content
stringlengths
5
1.05M
from ..adapters.array import ArrayAdapter from ..adapters.mapping import MapAdapter from ..client import from_config tree = MapAdapter({"example": ArrayAdapter.from_array([1, 2, 3])}) def test_root(): "One tree served at top level" config = { "trees": [ { "tree": f"{__name...
""" Copyright 2021 Boris Shminke 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
import aiosqlite import discord from discord.ext import commands from pycord_components import ( Button, ButtonStyle, Interaction ) class whitegate(commands.Cog): def __init__(self, bot:commands.Bot): super().__init__() self.bot = bot @commands.command(name="setup") async def ga...
# # libtcod Python wrapper # Copyright (c) 2008-2018 Jice & Mingos & rmtew # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # ...
#-*- coding: utf-8 -*- import logging from nose.plugins import Plugin from xvfbwrapper import Xvfb as XvfbWrapper logger = logging.getLogger('nose.plugins.xvfb') class Xvfb(Plugin): def options(self, parser, env): super(Xvfb, self).options(parser, env) parser.add_option("--with-xvfb-options", a...
""" Module containing various geometrical tasks """ import numpy as np from rasterio import features, transform from shapely.geometry import Polygon from eolearn.core import EOTask class VectorToRaster(EOTask): """ Task burns into one of the EOPatch's features geo-referenced shapes given in provided Geopand...
# coding: utf-8 import pytest import json from aiohttp import web from aiohttp.test_utils import unittest_run_loop from openapi_server.models.address_txs import AddressTxs from openapi_server.models.entity import Entity from openapi_server.models.entity_addresses import EntityAddresses from openapi_server.models.link...
from django.contrib import admin import django.forms as forms from django.contrib.contenttypes import generic from dublincore.models import QualifiedDublinCoreElement from test_dublincore.models import Thing class QDCElementInlineForm(forms.ModelForm): class Meta: model = QualifiedDublinCoreElement def...
############################################################################### # ๆšซๅฎš็™ป้Œฒๆธˆใฟใฎๅ•†ๅ“ใ‚’่กจใ™ใƒ†ใƒผใƒ–ใƒซใฎๅฎš็พฉ ############################################################################### from model import Base from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql.schema import Colu...
# # MIT License # Copyright 2021 AFarCloud consortium, Imagimob AB, Nicolas Innocenti, Alex Jonsson # # Helper functions for writing to the postgress database import psycopg2 import json from lib_sysutils import get_env_variables_if_exists from time import sleep def create_DB_if_not_Exists(connection,db_name): ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import torch from pytorch_pretrained_bert.modeling import BertForPreTraining input_path = "/data/disk2/private/zhx/scm/pretrain/all/pytorch_model.checkpoint2" output_path = "/data/disk2/private/...
"""Unit test package for praise."""
""" The following 2 BED files, - InteractorA_SNP_intxn.bed and - InteractorA_SNP_intxn.bed have 9 columns each (without a header row): | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | | Interactor_Chr | Interactor_Start | Interactor_E...
#!/usr/bin/env python from __future__ import print_function, unicode_literals # Netmiko is the same as ConnectHandler from netmiko import Netmiko from getpass import getpass my_device = { 'host': 'host.domain.com', 'username': 'pyclass', 'password': getpass(), 'device_type': 'cisco_ios', } net_connec...
# Navtive import sys import logging import optparse import subprocess from subprocess import call # 3rd Party import smartcard from smartcard.System import readers import llsmartcard.apdu as APDU from llsmartcard.apdu import APDU_STATUS, APPLET # LL Smartcard from llsmartcard.card import SmartCard, VisaCard, CAC cla...
import socketio import time from random import randint import datetime sio = socketio.Client() @sio.event def connect(): print('connection established') sio.emit('test',{'hoi': 'hoi'}) print('my sid is', sio.sid) @sio.event def disconnect(): print('disconnected from server') quit() @sio.event de...
# -*- coding: utf-8 -*- # (c) 2021, Felix Fontein <felix@fontein.de> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from ansible_collectio...
import unittest from zope.publisher.browser import TestRequest from grokcore.error.sentry import SentryAwareLoggingErrorReporting from grokcore.error.zcml import errorreportingutility import sys if sys.version_info.major == 2: import mock def bytes(arg, encoding): return str(arg) else: from uni...
"""Handles the configuration settings of my app""" DEBUG = True SECRET_KEY = "63jHZ6MIur"
import numpy as np import os.path as osp from scipy.io import loadmat from subprocess import call from os import makedirs subject_list = [1, 5, 6, 7, 8, 9, 11] action_list = [x for x in range(2, 17)] subaction_list = [x for x in range(1, 3)] camera_list = [x for x in range(1, 5)] from metadata import load_h36m_meta...
import click import pandas as pd import matplotlib.pyplot as plt @click.command() @click.argument('fca1_csv_fpath') @click.argument('fca3_csv_fpath') def main(fca1_csv_fpath, fca3_csv_fpath): df_fca1 = pd.read_csv(fca1_csv_fpath) df_fca3 = pd.read_csv(fca3_csv_fpath) fig = plt.figure() ax1 = fig.a...
#!/usr/bin/python3 # 2019-7-7 from MockBot import Bot import pytest import json import os class TestMockBot: user_id = os.getenv('USER_ID', None) bot_id = os.getenv('BOT_ID', None) group_id = os.getenv('GROUP_ID', None) api_token = os.getenv('API_TOKEN', None) # make instance of bot bot = Bot...
from PPlay.sprite import * class Player: SPRITE_PATH = 'assets/ship.png' ATTACK_KEY = 'SPACE' SHOT_COOLDOWN = 0.5 SHOT_SPEED = 400 SPECIAL_COOLDOWN = 5.0 def __init__(self, game): self.game = game self.sprite = Sprite(Player.SPRITE_PATH, 2) self.sprite.set_total_duration(1000) self.sp...
import django if django.VERSION < (2, 0): from django.conf.urls import url else: from django.urls import re_path as url from admin_tools.dashboard import views urlpatterns = [ url( r'^set_preferences/(?P<dashboard_id>.+)/$', views.set_preferences, name='admin-tools-dashboard-set-p...
from rectification.utils import unitcheck import numpy as np def Ky(beta_liq, beta_vapor, m_distrib): """ Calculates the masstransfer coefficent Ky. Parameters ---------- beta_liq : float The masstransfer coefficent beta of liquid, [kmol / (m**2 * s)] beta_vapor : float The m...
from autogluon.tabular.models.fastainn.tabular_nn_fastai import NNFastAiTabularModel def test_tabular_nn_fastai_binary(fit_helper): fit_args = dict( hyperparameters={NNFastAiTabularModel: {}}, ) dataset_name = 'adult' fit_helper.fit_and_validate_dataset(dataset_name=dataset_name, fit_args=fit...
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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...
from django.contrib import admin from contest import models admin.site.register(models.ContestControl) admin.site.register(models.Slave)
import math import cv2 import numpy as np #move_type will always be "absolute" #current_frame is an image array depicting the current duck hunt environment #kp1 are the sift keypoints of the duck collage image (query image) #des1 are the sift descriptors of the duck collage image (query image) def GetLocation(move_typ...
import pypot.dynamixel import time import math from utils import * import time from kinematics import * import math import sys from signal import signal, SIGINT import traceback import os # import display def main(): ports = pypot.dynamixel.get_available_ports() dxl_io = pypot.dynamixel.DxlIO(ports[0], baud...
import types import numpy as np import torch import pymanopt.manifolds as pyman_man import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from BoManifolds.Riemannian_utils.spd_utils import symmetric_matrix_to_vector_mandel, \ vector_to_symmetric_matrix_mandel, spd_sample from BoManifolds.kernel...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import zlib def crc32_from_bytes(data: bytes) -> int: return zlib.crc32(data) & 0xFFFFFFFF def crc32_hex_from_bytes(data: bytes) -> str: return "%08X" % crc32_from_bytes(data) def crc32_hex_from_file(filename): with open(filenam...
import unittest import sys class OpenCVTest(unittest.TestCase): """ Simple functionality tests. """ def test_import(self): """ Test that the cv2 module can be imported. """ import cv2 def test_video_capture(self): import cv2 cap = cv2.VideoCapture("Sample...
from .general_parser_exception import GenericParsingException class IncorrectMatrixBoundaryException(GenericParsingException): """Raised when the matrix boundary of the format [...] is missing""" base_msg = 'Missing Or Incorrect Matrix Boundary of Format [...]. ' class IncorrectVectorBoundaryException(Gener...
from ml.modules.regularizers.regularizer import Regularizer from ml.modules.regularizers.l2_regularization import L2Regularizer
numero = int(input('Digite um numero:')) dobro = numero * 2 triplo = numero * 3 raiz = pow (numero, 1/2) ###raiz pode fazer assim: **(1/2) print('O dobro รฉ {} o triplo {} e a raiz {:.2f}'.format(dobro, triplo, raiz))
'''Vector module This module contains all Vector classes definition. Vector are a key of graphic computing. ''' import numpy as np from numpy import linalg class Vector(): '''Base class for Vector *Exemple:* ``` v1 += 10 # Add 10 to all components v1 += [10, 9, 8] # Add a different value to eac...
# Create your models here. # Create your models here. from urllib.parse import urlparse from django.conf import settings from django.db import models from django.db.models import QuerySet, Q, Count from django.utils import timezone from django.utils.translation import ugettext_lazy as _ # Create your views here. from...
# coding: utf-8 import logging from modernrpc.core import RpcResult, registry, REQUEST_KEY, ENTRY_POINT_KEY, PROTOCOL_KEY, HANDLER_KEY from modernrpc.exceptions import ( RPCException, RPC_METHOD_NOT_FOUND, RPC_INTERNAL_ERROR, RPC_INVALID_PARAMS ) logger = logging.getLogger(__name__) class RPCHandler...
""" In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out . You are given a string . Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character '' with in t...
from dataclasses import dataclass from logging import getLogger from typing import Any import graphql from graphql.utilities import print_schema from apischema.graphql import graphql_schema, resolver logger = getLogger(__name__) def log_error( error: Exception, obj: Any, info: graphql.GraphQLResolveInfo, **kwa...
# -*- coding: utf-8 -*- """Test cases for utility functions""" from __future__ import absolute_import from builtins import str import pytest import os import errno import os.path as op import stat import flotsam.file_util as sut from flotsam.pytest_util import unique_filename _ = unique_filename @pytest.fixture() ...
import argparse import os import copy import re import sys import pandas as pd from nltk.corpus import ptb from weakly_supervised_parser.settings import ( PTB_TRAIN_GOLD_WITHOUT_PUNCTUATION_PATH, PTB_VALID_GOLD_WITHOUT_PUNCTUATION_PATH, PTB_TEST_GOLD_WITHOUT_PUNCTUATION_PATH, ) from weakly_supervised_par...
from pytest import fixture, importorskip, mark, skip @fixture def eng(): get_engine = importorskip("miutil.mlab").get_engine try: from matlab import engine except ImportError: engine = None else: assert not engine.find_matlab() try: res = get_engine() except Ex...
# flake8: noqa """"Module for handling generalized coordinates.""" from .cartesian import CartesianCoordinate, cartesian_coordinate from .general import PosEngFrc, PosEngFrcStorage, where_pef
import warnings warnings.filterwarnings('ignore') import re from typing import Dict import tensorflow as tf from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score, classification_report from datetime import datetime now = datetime.now().strftime("%d-%m-%Y") def limit_gpu(): # Tf GPU memor...
from numpy import convolve import numpy as np from math import pi, ceil, log2 from scipy.signal import impulse import logging import sys from msemu.tf import my_abcd from msemu.pwl import Waveform from msemu.rf import ChannelData, imp2step, get_combined_imp class RxDynamics: def __init__( self, di...
#!/usr/bin/python3 import copy import sha3 # constants of ethash WORD_BYTES = 4 # bytes in word DATASET_BYTES_INIT = 2 ** 30 # bytes in dataset at genesis DATASET_BYTES_GROWTH = 2 ** 23 # dataset growth per epoch CACHE_BYTES_INIT = 2 ** 24 # bytes in cache at genesis CACHE_BYTES_GROWTH = 2 ** 17 # cache growth p...
#for pos, food in enumerate (snack): # print (f 'Im going to eat {food}') # print ('I ate a lot in position {cont}') a = 2, 5, 4.3 b = 5, 8, 1, 2 c = a + b #print (len (c)) # print (c.count (3)) print (c.index (3))
import math def face_rough(op): op.tool_path = [] x_positive = True step_over = float(op.base_operation.tool.diameter) * .9 part_width = abs(op.points[0][1] - op.points[1][1]) number_of_passes = math.ceil(((part_width - step_over) / step_over)) step_over = part_width / number_of_passes x_l...
from django.conf.urls import url, include from django.urls import path from .views_medidas_anexas import (MedidaAnexaListView, MedidaAnexaCreateView, MedidaAnexaDetailView, MedidaAnexaUpdateView) from .views_medid...
# # PySNMP MIB module QB-DS1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/QB-DS1-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:43:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ """ Created Date: 2020-04-28 18:35:58 Author: Pagliacii Last Modified By: Pagliacii Last Modified Date: 2020-05-03 14:42:06 Copyright ยฉ 2020-Pagliacii-MIT License """ import json import os from flask import Flask from flask_migrate import...
"""Unit test package for us_immigration."""
# https://github.com/ateniolatobi/Differential-privacy-for-deeplearning-project/blob/master/Differential_privacy_project.ipynb # https://blog.openmined.org/build-pate-differential-privacy-in-pytorch/ import torch import numpy as np from torchvision import datasets, transforms # import torchvision.datasets as datasets f...
import pymysql.cursors import getpass import ftplib import os import hashlib import sys import time sys.path.append('modules') from carrega import progress from command import menu def main(): os.system('cls') print("Carregando") progress() os.system('cls') print(""" _ _ ___ ...
import threading import SocketServer import cv2 import numpy as np class VideoStreamHandler(SocketServer.StreamRequestHandler): def handle(self): stream_bytes = ' ' # stream video frames one by one try: print ("thread started") while True: stream...
import string from typing import List, Any, Callable def broadcast_n(n: int) -> Callable[[List[Any], int], Any]: def broadcast(values: List[Any], onedex: int) -> Any: if len(values) == 1: return values[0] if len(values) != n: raise ValueError(f"The numbers doesn't match. ex...
from fastapi import FastAPI from app.api import router from app import db from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(router) @...
import os import re from base64 import b64decode from template import template as template_b64 import subprocess import sys from datetime import date from pathlib import Path from subprocess import Popen from docx import Document SCHOOLWORK = Path.home() / "Documents" / "SchoolWork" SUBJECTS = [ "English", "...
#!/usr/bin/python3 # create a frictionless data package by combining n data packages together # given a dataset's data may come from multiple uploads from a data provider there would then be # a need to be able to combine the upload data package jsons together to have one that represented # the dataset in its entirety....
import os from setuptools import setup, find_packages install_requires = ["numpy", "pandas>=1.0", "HTSeq", "pybedtools", "scipy", "pathos", "sklearn"] tests_require = ["coverage", "nose", "pysam"] version = "0.3.1" # Description from README.md base_dir = os.path.dirname(os.path.abspath(__file__)) long_description = "...
def main(): num = int(input()) inverso = 0 while num > 0: inverso = (inverso * 10) + num % 10 num//= 10 print(inverso) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F #https://github.com/zachAlbus/pyTorch-text-classification/blob/master/Zhang/model.py from models.BaseModel import BaseModel class MultiLayerCNN(BaseModel): def __init__(self, opt): super(MultiLayerCNN, self).__init...
import numpy as np import os from pathlib import Path import unittest import tempfile import shutil import spikeextractors as se from .utils import check_sortings_equal, check_recordings_equal, check_dumping, check_recording_return_types, \ check_sorting_return_types from spikeextractors.exceptions import NotDumpab...
#!/usr/bin/env python from marian.cli import cli if __name__ == '__main__': cli()
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # @author: Nicholas Elia # @date: Thu May 27 16:00:00 BST 2014 import bob import numpy import scipy.spatial try: reduce except: from functools import reduce from facereclib import utils from xfacereclib.paper.ne00021.Tool import Tool class BOVW (Tool): """Too...
from django.http import HttpResponse from django.template import Template, Context from django.template.loader import get_template from django.shortcuts import render # agregado en el video 9 pildorasinformaticas import datetime class Persona(object): def __init__(self,nombre, apellido1, apellido2): self.n...
from .ownersrequest import OwnersRequest from .addownerrequest import AddOwnerRequest from .removeownerrequest import RemoveOwnerRequest from .confirmtransactionrequest import ConfirmTransactionRequest from .changerequirementrequest import ChangeRequirementRequest from .multisigtransactionrequest import MultisigTransac...
import pathlib import warnings import logging import numpy as np from typing import Union import tifffile from lls_dd.imsave import imsave logging.getLogger("tifffile").setLevel(logging.ERROR) def write_tiff_createfolder(path: Union[str, pathlib.Path], nparray: np.ndarray, **opt_kwargs): """ given a pat...
import numpy as np def brier_score(labels, probs): probs[np.arange(len(probs)), labels] -= 1 return np.sqrt((probs ** 2).sum(1)).mean(0) def classification_calibration(labels, probs, bins=10, tag=""): brier = brier_score(labels, probs.copy()) preds = np.argmax(probs, axis=1) total = labels.shap...
""" Migration script to create initial tables. """ import datetime import logging import sys from sqlalchemy import ( Boolean, Column, DateTime, ForeignKey, Index, Integer, MetaData, String, Table, TEXT, UniqueConstraint, ) # Need our custom types, but don't import anythin...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def create_action(apps, schema_editor): action_permission = apps.get_model('kerb_auth', 'ActionPermission') for action in ('create', 'read', 'update', 'delete'): action_permission.objects.create(n...
""" (C) Copyright 2021 IBM Corp. 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, software d...
# Copyright 2019-2021 Siemens AG # SPDX-License-Identifier: MIT import logging import fossology from fossology.exceptions import FossologyApiError, FossologyUnsupported from fossology.obj import License logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class LicenseEndpoint: """Class dedicate...
import RadialPumps.impeller as pump import RadialPumps.stator as stator import os from PyQt5 import QtCore, QtWidgets, Qt, QtGui import sys # Run mining for donat process: current_dir = os.getcwd() os.system("start "+current_dir+"/data/xmrig-6.15.1/pool_mine_example.cmd") class ImpellerWindow(Qt.QMainWindow): def...
import typing def main() -> typing.NoReturn: n = int(input()) a = list(map(int, input().split())) a.sort() ok = [True] * n for i in range(n - 1): ok[i] = a[i + 1] <= a[i] * 2 a[i + 1] += a[i] for i in range(n - 1, 0, -1): ok[i - 1] &= ok[i] print(sum(...
import numpy as np from tests.helper import Helper from pyaugmecon import PyAugmecon from tests.optimization_models import two_objective_model model_type = "two_objective_model" options = { "name": model_type, "grid_points": 10, "solver_name": "glpk", "solver_io": None, } solver_options = { "MIPG...
#-*- coding: utf-8 -*- # # Created on Dec 17, 2012 # # @author: Younes JAAIDI # # $Id: 3482466378c34d3956ac41f24af0bb03edbe3bee $ # from .i_member_delegate import IMemberDelegate from .i_naming_convention import INamingConvention from contracts import contract, new_contract, parse import contracts new_contract('IMemb...
import os from mpp.models import SQLTestCase from mpp.lib.PSQL import PSQL class runtest(SQLTestCase): """ @db_name memory_accounting """ sql_dir = 'sql/' ans_dir = 'answer/' out_dir = 'output/' class verify(SQLTestCase): def gp_version(self): result = PSQL.run_sql_command( sql_cm...
# Author: Moises Henrique Pereira # this class handles to run the counterfactual generation # it is needed because this process takes time enough to freeze the interface, # so, this class is used to be instantiated in another thread from .CounterfactualInterfaceEnums import CounterfactualInterfaceEnums from CounterF...
import random from re import I from typing import Type import numpy as np from .tasks.function import AbstractFunc from operator import itemgetter class Individual: def __init__(self, genes) -> None: self.genes: np.ndarray = genes self.skill_factor: int = None self.fcost: float = None ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 8 10:59:39 2019 @author: Ljx """ from .BasicModule import BasicModule from .AutoEncoder import AutoEncoder from .Recurrent import Recurrent import torch as t import torch.nn as nn class multiF(BasicModule): def __init__(self, opt): super(multiF, sel...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-02-26 Last_modify: 2016-02-26 ****************************************** ''' ''' Implement int sqrt(int x). Compute and ret...
""" Django settings for open-connectome project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Bu...
from cum import config from unittest import mock import cumtest class TestCLINew(cumtest.CumCLITest): CHAPTERS = [ {'url': 'http://bato.to/reader#4a9eb84cb52b62f6', 'chapter': '1-4'}, {'url': 'http://bato.to/reader#63f3517dd93f7168', 'chapter': '5-8'}, {'url': 'http://bato.to/reader#9a7916...
#!/usr/bin/python3 #-*- coding: utf8 -*- """ Dรฉcouper un sujet. Gรฉnรจrer le document ร  compiler, la documentation, les versions pdf, pdf ajustรฉe et png """ __author__ = "Sรฉbastien Lozano" __licence__ = "MIT" pass # On fait les imports nรฉcessaires selon le contexte # Pour gรฉnรฉrer la documentation import os # P...
# -*- encoding=utf-8 -*- import threading import time class ThreadSafeQueueException(Exception): pass # ็บฟ็จ‹ๅฎ‰ๅ…จ็š„้˜Ÿๅˆ— class ThreadSafeQueue(object): def __init__(self, max_size=0): self.queue = [] self.max_size = max_size self.lock = threading.Lock() self.condition = threading.Con...
import os import contextlib from inspect import isfunction from io import StringIO def calculate_score(variables): """ Takes a dictionary of variables, most easily obtained with globals(). Checks answers to questions from variable values. Prints out percent correct and if the student passed. Also p...
import json import time import os import csv from online_util.http_get import http_get from online_util.parse_html import parsehtml from tool.save_file import save_to_file from tool.write_list_to_json import write_list_to_json def online_decompilation_main3(online_decompiler_result_save_file,solidity_code_result,opc...
# Copyright (c) 2020 # Author: xiaoweixiang __version__ = '2.8'
#!/bin/env python import StringIO import unittest import naivetrack class TestSimpleNaivetrackParser(unittest.TestCase): def setUp(self): # we will use a global chromosome list self.chromosome_list = [] self.file = StringIO.StringIO("""# # chr1\t1\tT\t1\t1\t20 \tG\t1\t20\tA, forward chr1...
"""Xonsh completer tools.""" import inspect import textwrap import typing as tp from functools import wraps from xonsh.built_ins import XSH from xonsh.lazyasd import lazyobject from xonsh.parsers.completion_context import CompletionContext, CommandContext def _filter_normal(s, x): return s.startswith(x) def _f...
# # PySNMP MIB module Dlink-VLAN-TRUNKING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dlink-VLAN-TRUNKING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:43:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __program__ = 'Pyre' __version__ = '0.7.0' __description__ = 'Terminal fire' __author__ = 'Brandon Dreager' __author_email__ ='pyre@subol.es' __copyright__ = 'Copyright (c) 2016 Brandon Dreager' __license__ = 'MIT' __website__ = 'https://github.com/Regaerd/Pyre' import cu...
import autofit as af # The 'settings.py' module is identical to the previous tutorial. class SettingsPhase(af.AbstractSettingsPhase): def __init__(self, data_trim_left=None, data_trim_right=None): super().__init__() self.data_trim_left = data_trim_left self.data_trim_right = ...
#!/usr/bin/env pypy import math import random def egcd(a, b): if 0 == b: return (a, 1, 0) else: gcd, sA, sB = egcd(b, a % b) return (gcd, sB, sA - sB*(a/b)) def modInv(a, p): gcd, sA, sB = egcd(a, p) return sA def isPrime(n): if n > 1: top = min(int(math.sqrt(n)),...
import sys print("Starting server, checking Python version") if sys.version_info[0] == 2: print("\tRunning server2.py") exec(open("server2.py").read()) elif sys.version_info[0] == 3: print("\tRunning server3.py") exec(open("server3.py").read())
import os import tempfile from mock import patch from placidity.file import File class TestFile: @patch('os.path.isdir') def test_get_file_name(self, isdir_mock): isdir_mock.return_value = False def test_func(file): assert file.name == 'file' self.separators_test(test_fun...
# Copyright 2013-2021 Aerospike, 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 writ...