content
stringlengths
5
1.05M
import pytest from pathlib import Path import os pai = os.path.dirname(__file__ ) examples_path = pai +'/examples' @pytest.fixture def example(): return lambda p: open(examples_path+ "/" + p).read()
#!/usr/bin/python # -*- coding: UTF-8 -*- from keras.preprocessing.image import img_to_array import imutils import cv2 from keras.models import load_model import numpy as np import datetime # parameters for loading data and images detection_model_path = 'haarcascade_files/haarcascade_frontalface_default.xml' emotion_m...
import pandas from classification.Classification import Classification from experiment.configuration import Parameters from loader.PreprocessedDataLoader import PreprocessedDataLoader from plot.Ploter import plot_pie, plot_box from vectorization.BagOfWordsModel import BagOfWordsModel from vectorization.Doc2VecModel im...
from datetime import datetime from app import db, create_uuid from app.dao.dao_utils import transactional, version_class from app.models import ServiceCallbackApi from app.models import DELIVERY_STATUS_CALLBACK_TYPE, COMPLAINT_CALLBACK_TYPE @transactional @version_class(ServiceCallbackApi) def save_service_callback...
import os import shutil import string import random import sqlite3 from functools import partial from threading import Thread from kivy.utils import platform from kivy.uix.screenmanager import Screen from kivy.properties import StringProperty from kivy.animation import Animation from kivy.core.clipboard import Clipboa...
""" Process all the SdA homogeneity test .npy files, combine into a dataframe """ import sys, re, os import numpy as np import pandas as pd # Extract the model name from each filename. def extract_model(regex,filename): match = regex.match(filename) if match is not None: return match.groups()[0] inpu...
import torch import flowlib def test_invertible_conv_forward() -> None: model = flowlib.InvertibleConv(in_channels=3) x = torch.randn(4, 3, 8, 8) z, logdet = model(x) assert z.size() == x.size() assert not torch.isnan(z).any() assert logdet.size(), (1,) def test_invertible_conv_inverse() -...
""" tool to run fastqc on FASTQ/SAM/BAM files from HTS experiments """ import subprocess from bipy.utils import flatten, remove_suffix, is_pair from bcbio.utils import safe_makedir, file_exists import os import logging import abc from mako.template import Template from bipy.toolbox.reporting import LatexReport, safe_la...
#! /usr/bin/env python import glob import numpy from setuptools import setup, find_packages, Extension from Cython.Build import cythonize setup( name="simtrie", version="0.8.0", description="An efficient data structure for fast string similarity searches", author='Bernhard Liebl', author_email='po...
from celery import Celery from demo import predict import urllib.request import shutil import os import requests import json app = Celery('gaitlab', broker='redis://redis:6379/0') @app.task(name='gaitlab.cp') def cp(args): path = "/gaitlab/input/input.mp4" # remove the old file os.system('rm {}'.format(p...
class AuthError(Exception): pass class DatabaseError(Exception): pass class GitHubError(Exception): pass class NCBIError(Exception): pass class ProxyError(Exception): pass
#!/user/bin/python # coding: utf8 class Warrior(Ant): """docstring for Warrior""" def __init__(self, arg): super().__init__(arg) self.arg = arg
# Copyright 2020-2022 OpenDR European Project # # 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 agree...
from click.testing import CliRunner from pathlib import Path from tag.cli import cli import os import unittest class CommandTest(unittest.TestCase): def run_command_test(self, command, touch = [], assert_exist = [], ...
from urllib.error import HTTPError import pytest from tests import api from .constants import ( VALID_STORE, VALID_PRODUCT, INVALID_PRODUCT_ID, INVALID_STORE_ID ) def test_inventories_without_args(): resp = api.inventories() assert resp['status'] == 200 assert 'result' in resp res = ...
import pytest from unittest import TestCase from pyflamegpu import * from random import randint import time # Global vars needed in several classes sleepDurationMilliseconds = 500 tracked_err_ct = 0; tracked_runs_ct = 0; class simulateInit(pyflamegpu.HostFunctionCallback): # Init should always be 0th iteration/s...
from flask import Flask, request,send_from_directory from flask_cors import CORS import os from Models.ArimaModel import ArimaModel from Models.ExponentialSmootheningModel import ExponentialSmootheningModel from Models.ProphetModel import ProphetModel from Models.LstmModel import LstmModel import tensorflow as tf impo...
# # Copyright (c) SAS Institute Inc. # # 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 in w...
# -*- coding: utf-8 -*- from numpy import insert from SciDataTool import DataFreq from pyleecan.Functions.Electrical.dqh_transformation import dqh2n_DataTime def store(self, out_dict, out_dict_harm): """Store the standard outputs of Electrical that are temporarily in out_dict as arrays into OutElec as Data obje...
from django.contrib import admin from .models import Membership, UserMembership, Subcription admin.site.register(Membership) admin.site.register(UserMembership) admin.site.register(Subcription)
from Expresion.Binaria import Binaria from Expresion.Aritmetica import Aritmetica from Expresion.Unaria import Unaria from Expresion.Aritmetica import Aritmetica from Expresion.Logica import Logica from Expresion.FuncionesNativas import FuncionesNativas from Entorno import Entorno from Tipo import Tipo from Expresion....
def dostuff(): print("stuff happens here")
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ wlanpi_webui ~~~~~~~~~~~~ a custom WebUI made to run locally on the WLAN Pi """ import logging from logging.handlers import RotatingFileHandler from wlanpi_webui.app import create_app if __name__ == "__main__": app = create_app() log_filename = "app.log" l...
from unittest.mock import patch from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models.fields.files import FieldFile from django.test import TestCase from django.urls import resolve from django.utils import timezone from apps.core.constants i...
# Hacked from winnt.h DELETE = (65536) READ_CONTROL = (131072) WRITE_DAC = (262144) WRITE_OWNER = (524288) SYNCHRONIZE = (1048576) STANDARD_RIGHTS_REQUIRED = (983040) STANDARD_RIGHTS_READ = (READ_CONTROL) STANDARD_RIGHTS_WRITE = (READ_CONTROL) STANDARD_RIGHTS_EXECUTE = (READ_CONTROL) STANDARD_RIGHTS_ALL = (2031616) SP...
from django.core.management.base import BaseCommand from django.conf import settings from django.apps import apps import os import sys import multiprocessing root = os.getcwd() django_project = os.path.basename(root) class Command(BaseCommand): help = "Runs this project as a uWSGI application. Requires the uwsgi...
# An array A consists of n integers in locations A[0], A[1] ....A[n-1]. # It is required to shift the elements of the array cyclically to the left by k places, where 1 <= k <= (n-1). def rotate(ar, k): n = min = len(ar) i = 0 while i<min: temp = ar[i] j = i while j!= ((n+i-k) %n): ...
# Python Native import time # 3rdparty import sensor_harm start = time.time() safel1c = '/path/to/S2/L1C.SAFE' sr_dir = '/path/to/S2/SR/images/' #can also use L2A.SAFE dir target_dir = '/path/to/output/NBAR/' sensor_harm.sentinel_harmonize(safel1c, sr_dir, target_dir, apply_bandpass=True) end = time.time() print(f...
'''Neopixel wrapper that supports simulation. This module supports 4 modes of operation: - Running on a Raspberry PI via the Adafruit blinka library. - Running on a Circuit Python board using the Adafruit Neopixel library. - Running using ../circuitpy_sim, which uses tkinter to draw simulated graphical LEDs on a...
# ------------------------------------------------------------------------------- # Name: Linguistics corpora construction # Purpose: NLP use # # Author: Mohammed Belkacem # # Created: 10/12/2021 # Copyright: (c) Mohammed Belkacem 2021 # Licence: CCO # -----------------------------------------...
# Coded by : Pasan Manula Bandara - UofM # Date : 31/01/2020 # Deep Learning Assingment 1 - Question 3 - Part C import numpy as np import cPickle from numpy import linalg as LA from PIL import Image # Global Variable Input_Training_Rows = 10000 def initialize_weights(): Weight_init = np.random.uniform(0,1,size = ...
import numpy as np def fcann2_trainer(x, y_, param_niter=1e4, param_delta=1e-3, param_lambda=1e-5, hidden_layer_dim=5, parameters=None): n, d = x.shape c = np.max(y_) + 1 y_one_hot = np.zeros((len(y_), c)) y_one_hot[np.arange(len(y_)), y_] = 1 if parameters is not None: w1, b1, w2, b2 = pa...
import random from datetime import datetime from sqlalchemy import or_, select from app.middleware.Jwt import UserToken from app.middleware.RedisManager import RedisHelper from app.models import Session, async_session from app.models.user import User from app.utils.logger import Log class UserDao(object): log =...
#!/usr/bin/env python3 # # Copyright 2022 Graviti. Licensed under MIT License. # """The implementation of the Graviti Series.""" from itertools import islice from typing import Any, Dict, Iterable, List, Optional, Sequence, Union, overload from graviti.dataframe.column.indexing import ColumnSeriesILocIndexer, Colum...
import math import jarray from ij import WindowManager, IJ, ImageStack, ImagePlus from ij.measure import ResultsTable from org.apache.commons.math3.ml.clustering import DoublePoint from itertools import groupby from operator import itemgetter def main(action,tableName1,tableName2,moreArgs): if action == "DistanceMat...
class Solution: def reverse(self, x: int) -> int: ans = 0 remainder = 0 isNegative = x < 0 if isNegative: x = x * -1 while x > 0: remainder = x % 10 x = x // 10 ans = (ans * 10) + remainder ...
""" ========================================================================== map_helper.py ========================================================================== Helper map and functions to get corresponding functional unit and ctrl. Author : Cheng Tan Date : Feb 22, 2020 """ from .opt_type impo...
from maju.log import LoggerManager from maju.utils.deezer import DeezerSearch from maju.utils.spotify import SpotifySearch from maju.utils.weather import Weather from maju.config import read_config from werkzeug.exceptions import BadRequest, Unauthorized, UnprocessableEntity class PlaylistServices: def __init...
import json import requests from PIL import Image from vk_api import bot_longpoll, VkUpload from .BasePlug import BasePlug class KonachanPlug(BasePlug): name = "Konachan" description = "Присылает арты с konachan.net" keywords = ('konachan', 'коначан') def __init__(self, bot): super(Konachan...
#!/usr/bin/env python3 """ Created on 17 Jun 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ from scs_core.data.json import JSONify from scs_host.sys.nmcli import NMCLi # -------------------------------------------------------------------------------------------------------------------- respo...
from core.entities import make_user def build_add_user(insert_user): def add_user(first_name, last_name, phone, email, password, birthday, gender) -> bool: user = make_user(first_name, last_name, phone, email, password, None, birthday, gender) return insert_user(use...
from PIL import Image def photoFlip(img): (w, h) = img.size mw = img.width // 2 a = img.crop((0, 0, mw, h)) b = img.crop((mw, 0, w, h)) flip = Image.new(img.mode, img.size) flip.paste(b, (0, 0)) flip.paste(a, (mw, 0)) return flip from sys import argv for fname in argv[1:]: photoFlip(Image.open(fname...
""" run with python setup.py install; nosetests -v --nocapture tests/cm_cloud/test_limits.py:Test_limits.test_001 nosetests -v --nocapture tests/test_limits.py or nosetests -v tests/test_limits.py """ from cloudmesh_client.common.ConfigDict import ConfigDict from cloudmesh_client.common.Shell import Shell from c...
# Copyright 2015 Cisco Inc. # # 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 in writing, ...
import pyautogui pyautogui.PAUSE = 0.2 import os import sys class Screen(): def setMousePositions(self): file = open("mouse_positions.txt", "w") file.write("mouseX_enumerator,mouseY_enumerator=") pyautogui.alert("Posicione o mouse sobre o enumerador do Word.") mouseX_enumerator, mo...
# -------------- # import the libraries import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings('ignore') # Code starts here df= pd.read_csv(path) df.head(5) X= df[['age','sex','bmi','children','smoker','region','charges'...
from cfp.resolver_factories.parameter_store_resolver_factory import ( ParameterStoreResolverFactory, ) from cfp.resolver_factories.resolver_factory import AnyResolverFactory, ResolverFactory from cfp.resolver_factories.string_resolver_factory import StringResolverFactory from cfp.resolver_factories.use_previous_res...
''' Check if a given number is prime ''' from math import sqrt def isPrime(num): if num < 0: raise ValueError if num < 2: return False if num < 4: return True # Check if the number is dividing by 2 if num % 2 == 0: return False # Check if the number is dividable by odd numbers only # This, in theory, ...
from math import sqrt from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.operator import PolynomialMutation, SBXCrossover from jmetal.problem import ZDT1 from jmetal.util.observer import ProgressBarObserver, VisualizerObserver from jmetal.util.termination_criterion import StoppingByEvaluations cla...
import pandas as pd import yaml import os import argparse from imblearn.over_sampling import RandomOverSampler def read_params(config_path): with open(config_path) as yaml_file: config = yaml.safe_load(yaml_file) return config def balance(config_path): config = read_params(config_path) train_c...
# Copyright 2015 Ufora Inc. # # 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 i...
import json, boto3, uuid def save(event, context): print("Event: %s" % json.dumps(event)) holidays = event['holidays'] client = boto3.resource('dynamodb') table = client.Table('Holidays') for holiday in holidays: response = table.put_item( Item={ 'id' : str(uuid.uu...
import git,os,tempfile,fnmatch,argparse,sys,shutil,stat,github from github import Github from subprocess import call def RepoDuplicate(username,password,input_repo_url,output_repo_name): tempdir,path,flag = clone_repo(input_repo_url) if flag == 1: #error in cloning shutil.rmtree(t...
import copy import logging import os logger = logging.getLogger(__name__) class Context(): ENV_VARIABLE = 'DAISY_CONTEXT' def __init__(self, **kwargs): self.__dict = dict(**kwargs) def copy(self): return copy.deepcopy(self) def to_env(self): return ':'.join('%s=%s' % (k...
from ipykernel.kernelbase import Kernel import subprocess import json import tempfile class CbshKernel(Kernel): implementation = 'Couchbase Shell' implementation_version = '1.0' language = 'no-op' language_version = '0.1' language_info = { 'name': 'Any text', 'mimetype': 'text/plain...
import pandas as pd from db_connector import FixturesDB from db_connector import LeagueDB from db_connector import PlayersDB from db_connector import TeamsDB class DataInit(): def __init__(self, league='EN_PR', season='2019'): self.league = league self.season = season @staticmethod def...
import argparse import textwrap from inspera import InsperaReader if __name__ == '__main__': parser = argparse.ArgumentParser( prog='InsperaReader', epilog=textwrap.dedent('''\ Info: - For each candidate given in the source data, a data field of each response is made, with t...
from .gcn import GCN, DenseGCN from .gat import GAT from .clustergcn import ClusterGCN from .fastgcn import FastGCN from .dagnn import DAGNN from .pairnorm import * from .simpgcn import SimPGCN from .mlp import MLP from .tagcn import TAGCN from .appnp import APPNP, PPNP # experimantal model from .experimental.median_g...
import setuptools with open("description", "r") as fh: long_description = fh.read() setuptools.setup( name='Fugue-generator', author="Adam Bradley", author_email='adam_bradley@brown.edu', description='', long_description=long_description, long_description_content_type='text/markdown', ...
""" - INFO_VERSION: 1 """ import functools import hashlib import inspect from typing import Dict import omegaconf from pydantic import validate_arguments from gdsfactory.component import Component, clean_dict from gdsfactory.name import MAX_NAME_LENGTH, clean_name, clean_value CACHE: Dict[str, Component] = {} INFO_...
from settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG SESSION_COOKIE_SECURE = False # Allows you to run Kitsune without running Celery---all tasks # will be done synchronously. CELERY_ALWAYS_EAGER = True # Allows you to specify waffle settings in the querystring. WAFFLE_OVERRIDE = True # Change this to True if...
from django.conf.urls import include, url from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.contrib.auth.views import login from django.contrib.auth.views import logout from django.contrib.auth.decorators import user_passes_test from soal.admin import admin_site_tu # crea...
import os,subprocess from shlex import quote from ehive.runnable.IGFBaseProcess import IGFBaseProcess from igf_data.utils.fileutils import get_temp_dir, remove_dir from igf_data.utils.fileutils import copy_remote_file from igf_data.utils.project_status_utils import Project_status class UpdateProjectStatus(IGFBaseProce...
""" 34. Find First and Last Position of Element in Sorted Array Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. Follow up: Could you write an algorithm with O(log n) runtime complexity? ...
from random import sample N, S, E, W, V = 1, 2, 4, 8, 16 opposite = {N:S, S:N, E:W, W:E} move = {N: lambda x, y: (x, y-1), S: lambda x, y: (x, y+1), E: lambda x, y: (x+1, y), W: lambda x, y: (x-1, y)} directions = lambda: sample((N, S, E, W), 4) def maze_generation(width, height): maze = [...
# -*- coding: utf-8 -*- from .IsobarImg import * __version__ = '0.4.2'
from socket import * import sys, time if len(sys.argv) <= 1: print 'Usage: "python proxy.py server_ip"\n[server_ip : It is the IP Address of the Proxy Server' sys.exit(2) # Create a server socket, bind it to a port and start listening tcpSERVERPort = 8080 tcpSERVERSock = socket(AF_INET, SOCK_STREAM) fp = open...
from PIL import Image import torch.nn as nn from torch.autograd import Variable import torch import numpy as np from data import CreateTrgDataSSLLoader from model import CreateSSLModel import os from options.test_options import TestOptions import scipy.io as sio import gzip # to compresss numpy files so that less c...
from __future__ import print_function, absolute_import, division import KratosMultiphysics as KM import KratosMultiphysics.MappingApplication as KratosMapping import KratosMultiphysics.KratosUnittest as KratosUnittest ''' This test is a fast test for testing the mappers, WORKS ONLY IN SERIAL It stems from the patch t...
# Copyright 2021 Ginkgo Bioworks # 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 in writing,...
# Copyright (C) 2017-2021 ycmd contributors # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # #...
''' Created on August 2nd, 2018 Created By: Brandon Robinson (brobinson2111) ''' import logging """ Sets the provided logger for the application. :logger The logger object to be configured. """ def set(logger): logger.setLevel(logging.DEBUG) # create file handler which logs even debug message...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import calendar import logging import struct from datetime import datetime from google.appengine.ext import ndb from .testname import TestName from .jsonr...
#!python # Author: Chris Huskey """ Module of functions for working with our AWS S3 buckets for video storage. """ # Import libraries we will use: import boto3 # boto3 is AWS's Python SDK, by AWS from botocore.exceptions import ClientError from dotenv import load_dotenv import json import logging import os # -----...
IBBQ_MAC = "4C:24:98:D0:xx:xx" influx_host = "influx.mycooldomain.com" influx_db = "annoying_internet_devices"
from profess.Profess import * from profess.JSONparser import * #domain = "http://localhost:8080/v1/" domain = "http://192.168.99.100:8080/v1/" dummyInputData = open('inputData.json').read() jsonInputDataFile=json.loads(dummyInputData) IEEE13=open("IEEE13_changed.json").read() jsonIEEE = json.loads(IEEE13) modelDataFi...
import subprocess import os import argparse import pipes # Use this script to download files from ftp links. # It contains a dictionary {ID: ftp_path} from Metabolights and # Metabolomics Workbench, so you only have to specify # an id. # Otherwise you can to specify an http or ftp link yourself # User defined variable...
from unicodedata import normalize, category def strip_tones(w): """Removes tones form a word.""" s = normalize("NFD", w) return "".join(c for c in s if category(c) != "Mn")
#!/usr/bin/env python3 import sys, csv, argparse def read_csv(f): with open(f) as fd: content = fd.readlines()[1:] return list(csv.DictReader(content)) def analyze_file(f, potential_errors=False): """Analyze result file {f} (which should be a .csv file). Print per-solver analysis, and e...
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # 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 appli...
""" Test script using pytest for make_dict Author: Varisht Ghedia """ from make_dict import make_dict def test_same_size(): """ Test that it can make dictionaries from lists of same size. """ list1 = ['a', 'b', 'c'] list2 = [1,3,3] assert make_dict(list1, list2) == {'a': 1, 'b': 3, 'c': 3} ...
from gql import Client from gql.transport.local_schema import LocalSchemaTransport from . import custom_scalars, graphql_server class LocalSchemaTest: async def asyncSetUp(self): transport = LocalSchemaTransport(schema=graphql_server.schema._schema) self.client = Client( transport=tra...
from . import db, User, Message PER_PAGE = 30 class Timeline: def __init__(self, messages, type, user=None): self.messages = messages self.type = type self.user = user def to_dict(self): return { 'messages': [msg.to_dict() for msg in self.messages], 't...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Code is based on examples from https://realpython.com/pysimplegui-python/ import PySimpleGUI as sg import cv2 import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'qt') # Create the setup def main(): sg.theme("LightBlue6"...
from recipe_scrapers.cookstr import Cookstr from tests import ScraperTest class TestCookstrScraper(ScraperTest): scraper_class = Cookstr def test_host(self): self.assertEqual("cookstr.com", self.harvester_class.host()) def test_canonical_url(self): self.assertEqual( "https:/...
dic2 = {"name":"홍길동", "job":"도둑", "address":["울릉도", "제주도", "함경도"]} # 딕셔너리 전체 출력 print(dic2) # 주소만 출력 print(dic2["address"]) # 제주도만 출력 print(dic2["address"][1]) dic2["age"] = 33 print(dic2) dic2["name"] = "전우치" print(dic2) del dic2["job"] # dic2에서 "job"이라는 키를 가진 데이터 삭제 print(dic2) # {'name': '전우치', 'address': ['울릉도',...
# CAN controls for MQB platform Volkswagen, Audi, Skoda and SEAT. # PQ35/PQ46/NMS, and any future MLB, to come later. def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled): values = { "SET_ME_0X3": 0x3, "Assist_Torque": abs(apply_steer), "Assist_Requested": lkas_enabled, "Assis...
''' Description: Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self....
from core import constants from core.entities.movable import Movable from core.entities.particles.projectile import Projectile from core.texture_manager import TextureManager class Tank(Movable): """ A class representing a tank in the game world. """ def __init__(self, **kwargs): self.texture...
#--------------------------- # organize imports #--------------------------- import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import random import os import warnings from sklearn.datasets import load_boston from sklearn.preprocessing import StandardScaler, MinMaxScaler from s...
__author__ = 'NovikovII' #!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Считать отдельными операторами целочисленные ширину и высоту прямоугольника, создать функцию (def), принимающую в качестве параметров ширину и высоту фигуры. Внутри функции создать две вложенные функции (lambda) по подсчету площади и периметра...
""" File that contains the Python code to be executed in "group_by_tag" Notebook. """ TAG_TABLE_HEADER = """\ <table> <tr> <td colspan="3" class="group_by_header"> Tag i </td> </tr> """ # 21/09/2018 16h57m :)
"""JSON serializers and deserializers for common datatypes.""" import datetime as dt def numpy_encode(obj): """Encode a numpy array.""" return obj.tolist() def numpy_decode(obj): """Decode a numpy array.""" import numpy # noqa return numpy.array(obj) def datetime_encode(obj): """Encode a...
# -*- coding: utf-8 -*- from copy import copy from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle) #from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.uni...
import sys sys.path.append("python") from PIL import Image from PIL import ImageCms import os from CompareOverHtml import createCompareHtml rootpath = "./greyramp-fulltv" if not os.path.exists(rootpath): os.makedirs(rootpath) colwidth = 4 height = 150 width = 256*colwidth img = Image.new( mode = "RGB", size = (wid...
""" This is custom bot class """ import json import aiohttp from discord.ext import commands import motor.motor_asyncio #check discord.py rewrite documentation for why AutoShardedBot was used. class Bot(commands.AutoShardedBot): """ This is a custom object which extends default commands.Bot...
import logging import copy import glob import math import os import numpy as np import tqdm import pickle from util import io_util from info import data_info, hardware_info from data_class import global_model_data, grouped_op_unit_data import global_model_config from type import OpUnit, ConcurrentCountingMode, Target,...
""" Pre-processing of the page metadata before rendering. """ from datetime import datetime import subprocess def process_info(info, site): """ Alter the page metadata before rendering. """ # Urubu doesn't split the 'tags' into multiple strings if "tags" in info: if isinstance(info["tags"]...
# 获取文件夹中的文件路径 import os def get_filePathList(dirPath, partOfFileName=''): allFileName_list = list(os.walk(dirPath))[0][2] fileName_list = [k for k in allFileName_list if partOfFileName in k] filePath_list = [os.path.join(dirPath, k) for k in fileName_list] return filePath_list # 修改文件夹中的单个xml文件 ...
"""Tests for tools for manipulation of expressions using paths. """ from sympy.simplify.epathtools import epath, EPath from sympy.testing.pytest import raises from sympy import sin, cos, E from sympy.abc import x, y, z, t def test_epath_select(): expr = [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/*", e...