content
stringlengths
5
1.05M
import csv import json from itertools import zip_longest with open('../energy_detectors/data/new_stackoverflow_data.json') as f: stackoverflow_data = json.load(f) stackoverflow_url = [item.get('url') for item in stackoverflow_data] stackoverflow_question = [item.get('post_content') for i...
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-05 16:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('driver', '0003_location_vehicle'), ] operations = [ migrations.AlterField( ...
from kazoo.retry import ( KazooRetry, RetryFailedError, ForceRetryError ) from kazoo.client import KazooClient import json import functools import logging logging.basicConfig() class TwoPCState(object): BEGIN = 'begin' PREPARE = 'prep' COMMIT = 'commit' ACK_COMMIT = 'ack_commit' ABOR...
import requests import json import yaml def getAPIKey(): with open('config.yaml', 'r') as ymlfile: cfg = yaml.safe_load(ymlfile) return cfg['MAPS_API_KEY'] def getTimes(origins, destinations, mode): key = getAPIKey() url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ori...
from google.protobuf import descriptor_pb2 from google.protobuf import symbol_database as _symbol_database from google.protobuf import reflection as _reflection from google.protobuf import message as _message from google.protobuf import descriptor as _descriptor import sys _b = sys.version_info[0] < 3 and ( ...
from datetime import datetime from enum import Enum import pytest from monty.json import MSONable from pydantic import BaseModel, Field from maggma.api.utils import api_sanitize, serialization_helper from typing import Union from bson import ObjectId class SomeEnum(Enum): A = 1 B = 2 C = 3 class Pet(...
def get_mpi_environment(): try: from mpi4py import MPI except ModuleNotFoundError: # mpi4py not installed so it can't be used return if not MPI.COMM_WORLD.Get_size() - 1: # MPI not being used # (if user did start MPI with size 1 this would be an illegal configuratio...
""" This scripts precompute stats for training more efficiently with RL on parent Be aware that some liberties have been taken with the implementation so that everything runs smoothly and easily. It is not a duplicate of the original PARENT metric. For evaluation, continue to use the original implementation! """ impo...
N_K = input().split() K = int(N_K[1]) words = input().split() list = [] for x in words: list.append(x) length = len(x) current_line = "" output = "" current_line_length = 0 index = 0 for x in list: if index == 0: current_line = current_line + x current_line_length += len(x) ...
# # See top-level LICENSE.rst file for Copyright information # # -*- coding: utf-8 -*- """ desispec.pipeline.run ========================= Tools for running the pipeline. """ from __future__ import absolute_import, division, print_function import os import sys import numpy as np from desiutil.log import get_logger...
"""Base Store Abstract Class""" from __future__ import annotations import logging from abc import ABCMeta, abstractmethod from typing import Any, Iterable, List, Optional import proxystore as ps from proxystore.factory import Factory logger = logging.getLogger(__name__) class Store(metaclass=ABCMeta): """Abst...
from numpy import array, nan, atleast_1d, copy, vstack, hstack, isscalar, ndarray, prod, int32 import numpy as np from setDefaultIterFuncs import USER_DEMAND_EXIT from ooMisc import killThread, setNonLinFuncsNumber from nonOptMisc import scipyInstalled, Vstack, isspmatrix, isPyPy try: from DerApproximator import ge...
'''n=str(input('Digite seu nome completo: ')).strip() print('Analisando seu nome......') print('Seu nome em maiuscula é {}'.format(n.upper())) print('Seu nome em minuscula é {}'.format(n.lower())) print('Seu nome tem {} letras'.format(len(n) - n.count(' '))) #print('Seu primeiro nome tem {} letras'.format(n.find(' ')))...
from abc import ABCMeta, abstractmethod import pytorch_lightning as pl import torch from lasaft.utils.functions import get_optimizer_by_name class AbstractSeparator(pl.LightningModule, metaclass=ABCMeta): def __init__(self, lr, optimizer, initializer): super(AbstractSeparator, self).__init__() ...
import bs4 as bs import urllib.request import pandas as pd kto=urllib.request.urlopen('http://www.bloomberght.com/doviz/dolar') spider=bs.BeautifulSoup(kto,'lxml') uzman_para= urllib.request.urlopen('http://uzmanpara.milliyet.com.tr/canli-borsa/').read() soup=bs.BeautifulSoup(uzman_para,'lxml') for spd in spider.f...
from aerosandbox import ImplicitAnalysis from aerosandbox.geometry import * class VortexLatticeMethod(ImplicitAnalysis): # Usage: # # Set up a problem using the syntax in the AeroProblem constructor (e.g. "Casvlm1(airplane = a, op_point = op)" for some Airplane a and OperatingPoint op) # # Call the ru...
from serif.model.document_model import DocumentModel from serif.theory.enumerated_type import MentionType import logging # Unlike NameMentionModel, this won't throw out any names when it # can't find an NP node that exactly matches the name extent. # It will create name mentions from just start and end token if # i...
__all__ = [ 'instantiate_coroutine' ] import inspect, functools, threading import collections.abc from contextlib import contextmanager _locals = threading.local() @contextmanager def running(kernel): if getattr(_locals, 'running', False): raise RuntimeError('only one xiaolongbaoloop kernel per th...
import os import tempfile import pytest import json from tassaron_flask_template.main import create_app, init_app from tassaron_flask_template.main.plugins import db from tassaron_flask_template.main.models import User from tassaron_flask_template.shop.inventory_models import * from flask import session @pytest.fixtu...
import asyncio import collections import typing import weakref from datetime import datetime from functools import reduce from inspect import isawaitable from signal import SIGINT, SIGTERM from types import AsyncGeneratorType from aiohttp import ClientSession from database import MongoDatabase from config im...
""" Defines a generic abstract list with the usual methods, and implements a list using arrays and linked nodes. It also includes a linked list iterator. Also defines UnitTests for the class. """ __author__ = "Maria Garcia de la Banda, modified by Brendon Taylor, Graeme Gange, and Alexey Ignatiev" __docformat__ = 'reS...
import numpy as np from bokeh.plotting import figure, show, output_file N = 500 x = np.linspace(0, 10, N) y = np.linspace(0, 10, N) xx, yy = np.meshgrid(x, y) d = np.sin(xx)*np.cos(yy) d[:125, :125] = np.nan # Set bottom left quadrant to NaNs p = figure(x_range=(0, 10), y_range=(0, 10)) # Solid line to show effect...
import pandas as pd from yahoo_fin import stock_info from tkinter import * from tkinter import ttk from datetime import date janela = Tk() janela.title('Optionalities') tree = ttk.Treeview(janela, selectmode='browse', column=("column1", "column2", "column3", "column4", "column5", "column6", "column7", "column8", "c...
# Generated by Django 2.2.1 on 2019-06-10 19:07 import ckeditor.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('medications', '0007_effect_category'), ] operations = [ migrations.AddField( model_name='effect', ...
""" :Author: Valerio Maggio :Contact: [email protected] """ from __future__ import division, print_function """ This script extract all the methods from the two versions of the JFreeChart system (i.e., so far, the only system with two different versions in the DB) in order to collect all the method...
######################################################## # evaluator.py # Author: Jamie Zhu <jimzhu@GitHub> # Created: 2014/2/6 # Last updated: 2015/8/30 ######################################################## import numpy as np import time from PPCF.commons import evaluator from PPCF import P_PMF import multiproces...
#!/usr/bin/python # Import necessary libraries/modules import os import argparse import numpy as np import cv2 from sklearn import metrics from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score cl...
"""Backends for similarity analysis. We strive for somewhat interfaces on numpy and tensorflow.""" __all__ = ["npbased", "tfbased"]
## Set API key api_key = 'abcdefghijklmnopqrstuvwxyz123456' ## Set default file type response_type = 'xml' ## Set response data types response_data = [ 'categories', 'seriess', 'tags', 'releases', 'release_dates', 'so...
import abc import base64 import six from cryptography import x509 from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_public_key from crypto...
from StarTSPImage.StarTSPImage import imageFileToRaster, imageToRaster
# coding: utf8 from __future__ import unicode_literals import plac import requests import os import subprocess import sys from .link import link from ..util import prints, get_package_path from .. import about @plac.annotations( model=("model to download, shortcut or name)", "positional", None, str), direct...
# WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 import enum import winsdk _ns_module = winsdk._import_ns_module("Windows.Devices.I2c") try: import winsdk.windows.devices.i2c.provider except Exception: pass try: import winsdk.windows.foundation except Exception: ...
# ====================================================================================== # Copyright and other protections apply. Please see the accompanying LICENSE file for # rights and restrictions governing use of this software. All rights not expressly # waived or licensed are reserved. If that file is missing or ...
# Generated by Django 2.0 on 2018-01-05 12:41 from django.db import migrations, models def delete_attributes(apps, schema_editor): attribute_model = apps.get_model('projects', 'Attribute') attribute_model.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('projects...
import docker import progressbar import json import os import requests import subprocess import time import zipfile import tarfile import re from io import BytesIO import generate_transfers_table from logger import _log import transitanalystisrael_config as cfg import process_date from pathlib import Path from datetime...
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you unde...
import asyncio from typing import Callable, Tuple, Type from functools import wraps def retry(tries: int, exceptions: Tuple[Type[BaseException]] = (Exception,)) -> Callable: """ Decorator that re-runs given function tries times if error occurs. The amount of tries will either be the value given to the de...
# Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
# Generated by Django 3.1.3 on 2020-11-26 19:20 import django.contrib.auth.models import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] ope...
__author__ = "Christian Kongsgaard" __license__ = "MIT" __version__ = "0.0.1" # -------------------------------------------------------------------------------------------------------------------- # # IMPORTS # Modules: from datetime import datetime import xml.etree.ElementTree as ET import os # RiBuild Modules: # ...
from .messenger import BaseMessenger __all__ = [ "BaseMessenger", ]
# Generated by Django 3.0 on 2021-07-22 10:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('faq', '0010_auto_20210722_1806'), ] operations = [ migrations.RenameField( model_name='category', old_name='title_category', ...
# python standard lib import os import sys import signal import logging import math import datetime as dt import time import json from json import dumps from pathlib import Path import traceback from dataclasses import asdict import asyncio # external libs import socketio import tornado import tornado.web #import torn...
#!/usr/bin/env python # -*- coding:utf-8 -*- import pandas as pd import sys from collections import Iterable import numpy as np import pkg_resources import bz2 import pickle import os from clonesig.estimator import Estimator from pandas.errors import EmptyDataError from clonesig.evaluate import score_sig_1D_base MI...
"""empty message Revision ID: 79aa6da15aab Revises: b54b75e1c56c Create Date: 2020-09-20 15:34:30.232062 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '79aa6da15aab' down_revision = 'b54b75e1c56c' branch_labels = None depends_on = None def upgrade(): # ...
# ABC119b import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) n = int(input()) x = [list(input().split()) for _ in range(n)] ans = 0 for i in x: if (i[1] == 'BTC'): ans += float(i[0]) * 380000 else: ans += int(i[0]) print(ans)
from django import forms from django.core.validators import MaxValueValidator, MinValueValidator class user_id_form(forms.Form): userId = forms.IntegerField() class text_form(forms.Form): query = forms.CharField( max_length=100)
from setuptools import setup setup( name='representjs', version='1.0', packages=["representjs"], python_requires=">=3.7", install_requires=[ "fire", "graphviz", "jsbeautifier", "jsonlines", "pyjsparser", "tqdm", "requests", "regex", ...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class INVItem(scrapy.Item): date_str = scrapy.Field() company = scrapy.Field() company_url = scrapy.Field() industry = scrapy.Field() ...
#!/usr/bin/env python3.6 # coding=utf-8 """ Module to import data from loo02.pl, parser json and send it back to airmonitor API interface. """ import json import os import time import urllib3 from lib.airmonitor_common_libs import _send_data_to_api, get_content, logger_initialization urllib3.disable_warnings(urllib3...
from django.contrib.auth.models import User from django.db import models from pupils.models import Class,Pupils class Teacher(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True) first_name = models.CharField(max_length=50,null=True) last_name = models.CharField(max_length=5...
import subprocess import os import argparse import sys import time import platform parser = argparse.ArgumentParser(description="Command Watcher Tool", add_help=True, usage="cmdwatch -d DELAY [-o OUTPUT_FILE] [-t TIMEOUT] [-s] <cmd>") parser.add_argument("-d", "--delay", help="How long...
""" SPDX-License-Identifier: BSD-3 """ from ._libtpm2_pytss import lib from .types import * from .utils import _chkrc, TPM2B_pack class ESAPI: def __init__(self, tcti=None): tctx = ffi.NULL if tcti is None else tcti.ctx self.ctx_pp = ffi.new("ESYS_CONTEXT **") _chkrc(lib.Esys_Initiali...
import torch import torch.nn as nn import numpy as np import numpy.random as rand from dset import idx2char # We use cross entropy loss loss_func = nn.CrossEntropyLoss(reduction='mean') def compute_loss(rnn, xNy, h_list, device): """ compute_loss for a given RNN model using loss_func Args: RNN: m...
"""Render SBOL Visual elements to SVG using Python and wkHTMLtoImage. This requires a recent version wkhtmltopdf/wkhtmltoimage installed. Thids also requires PIL/Pillow installed. """ import os import subprocess as sp import tempfile from PIL import Image import PIL.ImageOps def autocrop(filename, border_width=5): ...
class CommandError(Exception): """Exception raised by CLI"""
import re import os import json import types class JSONtoSQL(object): def __init__(self, target_db): self.target_db = target_db def reset(self): self.target_db.reset() return self def drop_all(self): self.target_db.drop_all() return self def to_sql(self, json...
''' Created on Dec 12, 2017 @author: candle ''' from datetime import datetime import string import logging log = logging.getLogger('sdsapp') def to_timestamp (dt): return dt.strftime ('%d.%m.%Y %H:%M:%S') def to_datetime (st): return datetime.strptime (st, "%d.%m.%Y %H:%M:%S") def st...
"""Adds blockhash linking to BonusPayouts Revision ID: 52536bfc833b Revises: 160f63e90b91 Create Date: 2014-04-12 13:18:24.408548 """ # revision identifiers, used by Alembic. revision = '52536bfc833b' down_revision = '160f63e90b91' from alembic import op import sqlalchemy as sa def upgrade(): ### commands aut...
"""This module contains the general information for VnicIScsi ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class VnicIScsiConsts(): ADDR_DERIVED = "derived" ADMIN_HOST_PORT_1 =...
from django.shortcuts import render, redirect from .forms import IcecreamForm from .models import Icecream def icecream_detail_pk(request, pk): name = icecream_db[pk]['name'] description = icecream_db[pk]['description'] context = { 'name': name, 'description': description, } retur...
from django.urls import path, include from . import views from cart import views as cart_views from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings app_name = 'buyer' urlpatterns = [ path('about/', views.about, name='about'), path('cart/', include('cart....
from apps.accounts.util import check_is_admin from apps.finder.models import Business from apps.finder.models import Store, UserStoreSuggestion from django.shortcuts import render import settings def maintenance(request): check_is_admin(request.user) return render(request, 'maintenance.html', locals()) def ...
import numpy as np import os import sys import datetime import cv2 from PIL import Image from PIL.ImageQt import ImageQt from libs.ustr import * class NamedImage(): def __init__(self, image_name): self._image_name = image_name self._image = None self._qt_image = None self._np_im...
"""Support for Pellet stoves using Duepi wifi modules using ESPLink serial interface"""
import json import os def load_json(path, default_dict=True): """ Loads a json file and returns it as a dictionary or list """ if os.path.exists(path) and os.path.isfile(path): with open(path, encoding="utf8") as file: data = json.load(file) file.close() return data...
# -*- coding: utf-8 -*- """ Created on Sun Sep 18 10:34:30 2016 @author: dahoiv """ import os import sqlite3 import ConvertDataToDB from img_data import img_data import image_registration import util def save_to_db(image_ids, ny_image_ids): print("----here") data_transforms = [] for (img_id, ny_img_id)...
import numpy as np from magnn.tensors import Tensor class Loss: def loss(self, predicted: Tensor, actual: Tensor) -> float: raise NotImplementedError def grad(self, predicted: Tensor, actual: Tensor) -> Tensor: raise NotImplementedError class MSE(Loss): """ Mean Squared Error ""...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ tumblr_api.py Script to test using pytumblr api. https://pypi.python.org/pypi/PyTumblr """ import sys import traceback from optparse import OptionParser import pytumblr from gluon import * from applications.zcomx.modules.logger import set_cli_logging VERSION = 'Vers...
""" Test case module. """ from time import time import sys import logging import pdb import functools import traceback import copy CURRENT_TIMESTAMP = int(time()) SHITTY_NONCE = "" DEFAULT_ENCODING = sys.getdefaultencoding() def debug_on(*exceptions): if not exceptions: exceptions = (AssertionError, ) ...
from device import device from datetime import datetime import json if __name__ == "__main__": data = device.fetch_data() print(json.dumps(data, indent=True)) image = device.fetch_image() if image: file_name = datetime.now().strftime("%Y%m%d%H%M%S") + ".jpg" with open('/tmp/' + file_n...
# coding: utf-8 """ Клиентский запрос. """ from typing import TYPE_CHECKING from irbis._common import ANSI, UTF, prepare_format, throw_value_error if TYPE_CHECKING: from typing import Optional, Union class ClientQuery: """ Базовый клиентский запрос. """ def __init__(self, connection, command:...
from django.contrib.postgres.operations import BtreeGinExtension, TrigramExtension from django.db import migrations class Migration(migrations.Migration): initial = True dependencies = [] operations = [ BtreeGinExtension(), TrigramExtension(), ]
import os import logging from camellia.util import define from camellia.util import system as s INFO_COLOR = '\033[94m' DEBUG_COLOR = '\033[92m' WARNING_COLOR = '\033[93m' ERROR_COLOR = '\033[91m' CRITICAL_COLOR = '\033[95m' END_COLOR = '\033[0m' class Log(object): def __init__(self, name, conso...
# Generated by Django 2.2.3 on 2019-08-14 01:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profile', '0025_auto_20190715_2206'), ] operations = [ migrations.AddField( model_name='product', name='removed', ...
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 23:07:51 2020 @author: elewah """
#!/usr/bin/env python """ generated source for module GdlUtils """ # package: org.ggp.base.util.gdl import java.util.ArrayList import java.util.Collection import java.util.Collections import java.util.HashMap import java.util.HashSet import java.util.List import java.util.Map import java.util.Set import org.ggp...
import os import re import sys import subprocess import pytest from testplan.common.utils.path import change_directory import platform ON_WINDOWS = platform.system() == 'Windows' KNOWN_EXCEPTIONS = [ "TclError: Can't find a usable init\.tcl in the following directories:", # Matplotlib module improperly installe...
""" Event called when someone parts a channel """ import consoleHelper import bcolors import glob import clientPackets import serverPackets def handle(userToken, packetData): # Channel part packet packetData = clientPackets.channelPart(packetData) partChannel(userToken, packetData["channel"]) def partChannel(user...
from paypalrestsdk import Payout, ResourceNotFound import logging logging.basicConfig(level=logging.INFO) try: payout = Payout.find("R3LFR867ESVQY") print("Got Details for Payout[%s]" % (payout.batch_header.payout_batch_id)) except ResourceNotFound as error: print("Web Profile Not Found")
# -*- coding: utf-8 -*- import scrapy from scrapy.http import Request from jrjdataspiderProject.items import JrjdataspiderprojectItem,JrjdataspiderprojectItems import re import json class BankproSpider(scrapy.Spider): pipeline = ['JrjdataspiderprojectPipeline'] name = "bankpro" allowed_domains = ["jrj.com....
import sys from . import git from typing import * MAX_SUBVERSION = 1000000 class Version: def __init__(self, tag: str, prefix: str, major: int, minor: int, patch: int, suffix: str): self.tag = tag self.prefix = prefix self.major = major self.minor = minor self.patch = pat...
from django.shortcuts import render from account.views import account_login # Create your views here. def index(request): if not request.user.is_authenticated: return account_login(request) context = {} # return render(request, "voting/login.html", context)
description = 'Chopper 2' group = 'optional' devices = dict( ch2_speed=device('nicos.devices.generic.virtual.VirtualMotor', description='Rotation speed', abslimits=(0, 300), userlimits=(0, 300), fmtstr='%.f', unit='Hz', speed=5, ), ch2_phase=device('nicos.de...
names = ["Adarsh", "Advika", "Kunika"] #-------------------------------------------------------------- # For Loop #-------------------------------------------------------------- # Looping through the list for name in names: print (name) # Looping through range x = 0 for index in range(10): x += 10 if in...
import os, sys, re
# @author: https://github.com/luis2ra from https://www.w3schools.com/python/default.asp ''' What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: * web development (server-side), * software development, * mathematics, * system scripting. ...
from argparse import ArgumentParser import numpy as np import requests from mmdet3d.apis import inference_detector, init_model def parse_args(): parser = ArgumentParser() parser.add_argument('pcd', help='Point cloud file') parser.add_argument('config', help='Config file') parser.add_argument('checkp...
#!/usr/bin/env python3 # -*- coding=utf-8 -*- import cv2 as cv from goto import with_goto """ 基于连续自适应均值迁移(CAM)的对象移动分析 CAM是连续自适应的均值迁移跟踪算法,相对于均值迁移相比较他的主要改进点有两处,一是会根据跟踪对象大小变化自动 调整搜索窗口大小;二是会返回更为完整的位置信息,其中包括了位置坐标及角度 cv.CamShift(probImage, window, criteria) - probImage: 输入图像,直方图方向投影结果 -...
import apscheduler.executors.asyncio import apscheduler.jobstores.mongodb import apscheduler.schedulers.asyncio from common.application_modules.module import ApplicationModule scheduler_job_store = {"default": apscheduler.jobstores.mongodb.MongoDBJobStore()} scheduler_executors = {"default": apscheduler.executors.asy...
from rest_framework import permissions class IsMember(permissions.BasePermission): def has_object_permission(self, request, view, obj): profile = request.user.profile return profile in obj.members.all()
# -*- coding: utf-8 -*- from .project import * # NOQA # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Comment if you are not running behind proxy USE_X_FORWARDED_HOST = True # Set debug to fals...
""" Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the ...
import random import pygame from constants import * class Pillar: """Pillar class for the flappy game. Y-direction is so that pillar starts from 0 and extends until gap, gap is between self.gap+gap, lower ifrom that to height-ground-self.gap-gap """ # Pillar on siis korkeussuunnassa 0->gap ja self.gap+gap...
# -*- coding: utf-8 -*- from .__version__ import __title__, __description__, __url__, __version__ from .__version__ import __author__, __author_email__, __license__ from .__version__ import __copyright__
""" Computational engines used by GP backends. """ import numpy as np class Engine(object): """The base class for computational engines. """ def addpath(self, path): self._eng.addpath(path) def eval(self, expr, verbose): """Evaluate an expression. """ raise NotImplemen...
# coding: utf-8 from .target_utils import ItemList from .header_file import HeaderFileReader class TargetContext(dict): def __init__(self, *args, **kwargs): dict.__init__({}) self['options'] = {} vars_normal = ['defines', 'public_defines', 'include_dirs', 'public_inc...
from abc import ABC, abstractmethod import csv import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import NullFormatter class Logger(ABC): @abstractmethod def log_cost_accuracy(self, n_epoch, cost, accuracy): pass class SilentLogger(Logger): def log_cost_accuracy(self, n_e...
# _*_ coding: utf-8 _*_ # # Package: bookstore.src.core __all__ = ["controller", "enum", "property", "repository", "service", "util", "validator"]