id
stringlengths
3
8
content
stringlengths
100
981k
9921216
from itertools import tee from typing import Iterator, TextIO, Union __all__ = ['TeeFile', 'tee_file'] class TeeFile(): def __init__(self, file: Union[TextIO, Iterator[str]]): self._file = file def __getattr__(self, name): return getattr(self._file, name) def __iter__(self): ...
9921219
from datetime import datetime import pytz from django.test import TestCase from dojo.models import Test from dojo.tools.qualys_infrascan_webgui.parser import \ QualysInfrascanWebguiParser class TestQualysInfrascanWebguiParser(TestCase): def test_parse_file_with_no_vuln_has_no_findings(self): testfi...
9921238
import numpy as np # Midgard imports from midgard.dev import plugins # where imports from where import apriori from where.lib import config from where.lib import log @plugins.register def nnr_crf(dset, param_names): # NNR to CRF celestial_reference_frame = config.tech.celestial_reference_frames.list[0] ...
9921260
from glide.extensions.pandas import * from glide.extensions.swifter import * from ..test_utils import * def test_swifter_csv_chunked_lowercase(rootdir): nodes = ( DataFrameCSVExtract("extract") | SwifterApply("transform") | DataFrameCSVLoad("load", index=False, mode="a") ) glider, ...
9921283
import logging.config from app import api from app.controller import Login, Users logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} }, "handle...
9921285
import re import tensorflow as tf stop = False out_name_pattern = ".*" def tfprint(tensor, prefix=None, summarize=256): """tf.Printのショートカットメソッド Return: tf.Print(tensor, [tensor],・・・・) の復帰値をそのまま返す。 """ if stop: # stopならprint無し return tensor if prefix is...
9921311
from multiprocessing import Process from downstream_farmer.shell import main import argparse import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--number', help='Number of farmers to launch', type=int, default=1) args = parser.parse_args() ...
9921326
import numpy as np from cmaes import SepCMA def ellipsoid(x): n = len(x) if len(x) < 2: raise ValueError("dimension must be greater one") return sum([(1000 ** (i / (n - 1)) * x[i]) ** 2 for i in range(n)]) def main(): dim = 40 optimizer = SepCMA(mean=3 * np.ones(dim), sigma=2.0) prin...
9921365
class BaseController: """Base class for controllers. A controller provides an interface for all requests related to a single resource type. This is mainly for the purpose of splitting up :py:class:`.iNatClient` methods by resource type, which keeps code, documentation, and usage more organized and easier ...
9921379
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import network import numpy as np import model3 as M import tensorflow as tf import datareader from tqdm import tqdm import cv2 net = network.PosePred(17) reader = datareader.DataReader(16, processes=4, temp=20) def visualize(hmap,lb,it): res = [] for i in r...
9921380
from lunas.dataset.core import * from lunas.dataset.generic import * from lunas.dataset.sampling import * from lunas.dataset.stdin import * from lunas.dataset.textline import *
9921399
from pytorch_transformers import BertTokenizer, BertForMaskedLM import torch import random import numpy as np from pytorch_transformers import BertTokenizer, BertForMaskedLM import nltk import argparse import string torch.manual_seed(0) np.random.seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.b...
9921438
from vilt.datasets import VisualGenomeCaptionDataset from .datamodule_base import BaseDataModule class VisualGenomeCaptionDataModule(BaseDataModule): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @property def dataset_cls(self): return VisualGenomeCaptionDataset ...
9921469
from .. import families as fam from .. import tsm as tsm from .llt import * from .nllt import * class LocalTrend(tsm.TSM): """ Wrapper for local linear trend models **** LOCAL LINEAR TREND MODEL **** Parameters ---------- data : pd.DataFrame or np.array Field to specify the time series d...
9921508
import pytest import sys import numpy as np import swan_vis as swan import networkx as nx import math import pandas as pd import anndata ########################################################################### ################# Related to input/error handling ######################### ##############################...
9921511
import unittest import torch from pytorch_adapt.layers import DiversityLoss, EntropyLoss from .. import TEST_DEVICE, TEST_DTYPES class TestDiversityLoss(unittest.TestCase): def test_diversity_loss(self): loss_fn2 = EntropyLoss(after_softmax=True) for after_softmax in [False, True]: ...
9921547
import os import sys sys.path.insert(0, os.path.join('..', '..')) import pyttsx import time count = 0 def started(name): print 'started', name def word(location, length, name): print 'word', location, length, name def finished(completed, name): print 'finished', completed, name engine.endLoop() eng...
9921569
import os import scipy import scipy.misc import h5py import numpy as np def center_crop(image, pre_height, pre_width, height, width): h, w = image.shape[:2] j, i = int((h - pre_height)/2.), int((w - pre_width)/2.) return scipy.misc.imresize( image[j:j+pre_height, i:i+pre_width], [height, width]) ...
9921572
import numpy as np from reclist.abstractions import RecModel from reclist.utils.train_w2v import train_embeddings class CoveoP2VRecModel(RecModel): """ Implement of the prod2vec model through the standard RecModel interface. """ def __init__(self, **kwargs): super().__init__(**kwargs) mo...
9921590
from thespian.actors import ActorSystem import sys if __name__ == "__main__": portnum = int(sys.argv[1]) capability_names = (sys.argv + [''])[2].split(',') capabilities = dict([('Admin Port', portnum), ('Convention Address.IPv4', ('', 1900)), ] + ...
9921592
import torch as th import torch.nn as nn import torch.nn.functional as thf from permutohedral.gfilt import gfilt def gaussian_filter(ref, val, kstd): return gfilt(ref / kstd[:, :, None, None], val) def mgrid(h, w, dev): y = th.arange(0, h, device=dev).repeat(w, 1).t() x = th.arange(0, w, device=dev).re...
9921598
from paraview.simple import * s = Sphere() e = Elevation(LowPoint=[-0.5,-0.5,-0.5], HighPoint=[0.5, 0.5, 0.5]) UpdatePipeline() a = AnnotateAttributeData( Prefix="Hello: ", SelectInputArray= ('POINTS', 'Elevation'), ElementId=0, ProcessId=0 ) UpdatePipeline() annot...
9921653
from django.conf import settings # This is disabled on pypi.python.org, can be useful if you make mistakes if not hasattr(settings,'DJANGOPYPI_ALLOW_VERSION_OVERWRITE'): settings.DJANGOPYPI_ALLOW_VERSION_OVERWRITE = False """ The upload_to argument for the file field in releases. This can either be a string for ...
9921661
from __future__ import unicode_literals import json from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class StatisticResult(models.Model): # Translators: 'Slug' refers to the URL valid I...
9921667
import demistomock as demisto def test_main(mocker): from PrettyPrint import main test_obj = { 'string': 'abc', 'number': 123, 'boolean': True, 'list': ['x', 'y', 'z'] } mocker.patch.object(demisto, 'args', return_value={ 'value': test_obj, }) mocker...
9921698
import os import pandas as pd class DataLoader: def __init__(self, data_folder: str): self.training_dataset_path = f"{data_folder}/training_data.csv" self.test_dataset_path = f"{data_folder}/test_data.csv" def load_training_data(self) -> tuple: if not os.path.exists(self.training_data...
9921699
import keras.backend as K class DiceLoss: def __init__(self, beta=1., smooth=1.): self.__name__ = 'dice_loss_' + str(int(beta * 100)) self.beta = beta # the more beta, the more recall self.smooth = smooth def __call__(self, y_true, y_pred): bb = self.beta * self.beta ...
9921724
from tensorboardX import SummaryWriter from torchsupport.flex.log.logger import Logger class TensorboardLogger(Logger): def __init__(self, path): self.writer = SummaryWriter(path) def log_image(self, name, data, step): self.writer.add_image(name, data, step) def log_image_batch(self, name, data, step):...
9921760
import os from importlib import import_module from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from .printer import printer def abs_path(path, format_kwargs={}, relative_to=None, keep_slash=False): """Get abs. path for ``path``. ``path`` may be a relative or abso...
9921843
import json from os import path from unittest import mock from ralph.operations.changemanagement.exceptions import IgnoreOperation from ralph.operations.changemanagement.subscribtions import receive_chm_event from ralph.operations.models import Operation from ralph.tests import RalphTestCase class ChangesReceiverTes...
9921858
from collections import deque import collections.abc from typing import IO, Mapping, Sequence, Union from . import serialization @serialization.serializable class TrieNode: def __init__(self, value=None, sources=None, _children=None): if _children is None: self._children: Mapping[object, Trie...
9921860
from direct.distributed import DistributedObjectAI from . import Entity from direct.directnotify import DirectNotifyGlobal class DistributedEntityAI(DistributedObjectAI.DistributedObjectAI, Entity.Entity): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedEntityAI') def __init__(self, level, en...
9921875
from armulator.armv6.opcodes.abstract_opcodes.mov_register_thumb import MovRegisterThumb from armulator.armv6.opcodes.opcode import Opcode class MovRegisterThumbT2(MovRegisterThumb, Opcode): def __init__(self, instruction, m, d): Opcode.__init__(self, instruction) MovRegisterThumb.__init__(self, T...
9921883
def init(id, cfg): log_info("pythonmod: init called, module id is %d port: %d script: %s" % (id, cfg.port, cfg.python_script)) return True def init_standard(id, env): log_info("pythonmod: init called, module id is %d port: %d script: %s" % (id, env.cfg.port, env.cfg.python_script)) return True def deinit(...
9921903
import pytest from pycaption import MicroDVDReader, CaptionReadNoCaptions from pycaption.exceptions import CaptionReadSyntaxError, CaptionReadTimingError from pycaption.base import DEFAULT_LANGUAGE_CODE from tests.mixins import ReaderTestingMixIn class TestMicroDVDReader(ReaderTestingMixIn): def setup_class(self...
9921935
import pytest from dvc.repo.scm_context import scm_context from dvc.scm import NoSCM def test_scm_context(dvc, mocker): scm = dvc.scm m = mocker.patch.object( scm, "track_file_changes", wraps=scm.track_file_changes ) ret_val = 0 wrapped = scm_context(mocker.Mock(return_value=ret_val)) ...
9921943
import distutils.sysconfig import os import platform import re import sys def get_python_relative_libdir(): """Returns the appropropriate python libdir relative to the build directory. @param exe_path the path to the lldb executable @return the python path that needs to be added to sys.path (PYTHONPATH)...
9921964
def default_outside(x=[]): return x a = default_outside() a.append(1) print a b = default_outside() b.append(2) print b
9922001
try: from databroker.v0 import Broker except ModuleNotFoundError: from databroker import Broker from hxntools.handlers.xspress3 import Xspress3HDF5Handler from hxntools.handlers.timepix import TimepixHDF5Handler db = Broker.named("hxn") # db_analysis = Broker.named('hxn_analysis') db.reg.register_handler(Xsp...
9922012
import pytest import numpy as np from numpy import cos, sin from cxroots import Circle, Rectangle from cxroots import CxDerivative @pytest.mark.parametrize('C', [ pytest.param(Circle(0, 2), id='circle'), pytest.param(Rectangle([-1.5,1.5],[-2,2]), id='rect'), pytest.param(None, id='default') ]) def test_Cx...
9922016
import os import pandas as pd import warnings from torchvision.datasets import VisionDataset from torchvision.datasets.folder import default_loader from torchvision.datasets.utils import check_integrity, extract_archive class NABirds(VisionDataset): """`NABirds <https://dl.allaboutbirds.org/nabirds>`_ Dataset. ...
9922030
from unittest import TestCase import simplejson as json class TestBigintAsString(TestCase): values = [(200, 200), ((2 ** 53) - 1, 9007199254740991), ((2 ** 53), '9007199254740992'), ((2 ** 53) + 1, '9007199254740993'), (-100, -100), ((-2 ** 53)...
9922057
import unittest from quasimodo.data_structures.inputs import Inputs from quasimodo.data_structures.generated_fact import GeneratedFact from quasimodo.data_structures.multiple_scores import MultipleScore from quasimodo.data_structures.multiple_source_occurrence import MultipleSourceOccurrence from quasimodo.assertion_v...
9922069
from dialogKit import * class CheckBoxDemo(object): def __init__(self): self.w = ModalDialog((200, 120), 'CheckBox Demo') self.w.checkBox1 = CheckBox((10, 10, 180, 20), 'CheckBox 1', callback=self.checkBox1Callback, value=True) self.w.checkBox2 = CheckBox((10, 40, 180, 20), 'CheckBox 2...
9922093
print [] print {} print 1 print : meta.item-access.python, source.python, support.function.builtin.python : meta.item-access.python, source.python [ : meta.item-access.python, punctuation.definition.arguments.begin.python, source.python ] : meta.item-access.python, punct...
9922195
import logging import datetime def create_logger(name, file_path, level='DEBUG'): """Create a logger with the specified name.""" logger = logging.getLogger(name) if isinstance(level, str): level = logging._levelNames[level] logger.setLevel(level) log_formatter = logging.Formatter("%(asct...
9922204
import argparse import csv import gym import numpy as np import os import sys import pandas as pd import pickle import yaml from pathlib import Path import sys,os sys.path.append(os.getcwd()) def get_model_path( env_name : str , actor : str , run_seed : int = None, ) -> str: return get...
9922214
from __future__ import print_function import argparse import re import sys import pkg_resources import six from .download import download from .download_folder import download_folder from .download_folder import MAX_NUMBER_FILES distribution = pkg_resources.get_distribution("gdown") class _ShowVersionAction(argpa...
9922222
def xip(*args): for a in args: print(a, end=' ') print('') def xep(*args): for a in args: print(repr(a), end=' ') print('') def xfo(*args): for a in args: if hasattr(a, 'nfo'): print(a.nfo, end=' ') else: print(repr(a), end=' ') print('')
9922224
from enum import IntEnum, unique @unique class States(IntEnum): """States reported by the unit""" # These correspond to the LEDs on the unit HEATER_1 = 1 << 0 VALVE_3 = 1 << 1 CHECK_SYSTEM = 1 << 2 POOL = 1 << 3 SPA = 1 << 4 FILTER = 1 << 5 LIGHTS = 1 << 6 AUX_1 = 1 << 7 AUX...
9922235
import torch def MeanPixelwiseError(x: torch.tensor, y: torch.tensor): """Computes the normalized square root of the average squared pixelwise error.""" pixelwise_l2 = (x - y).pow(2) pixelwise_l2 /= pixelwise_l2.max() return torch.sqrt(torch.mean(pixelwise_l2))
9922256
import os.path import re import sys from glob import glob from subprocess import Popen, PIPE, call, check_call def this_dir(path): return os.path.join(os.path.dirname(os.path.realpath(__file__)), path) def exists(prog): p = Popen(['which', prog], stdout=PIPE) p.communicate() return p.returncode == 0...
9922293
import numpy as np import h5py import os import time, threading, shutil, fnmatch, subprocess from random import randint import matplotlib.pyplot as plt import generate_module, generate_parameters import json, argparse import sys # this script samples the net configuration and creates the prototxt files for caffe #par...
9922328
from typing import Optional, Tuple, TYPE_CHECKING from PySide2.QtCore import Qt from enum import Enum if TYPE_CHECKING: from angrmanagement.ui.widgets.qblock import QBlock from angrmanagement.ui.widgets.qoperand import QOperand from angrmanagement.ui.views import DisassemblyView class DisassemblyLevel(En...
9922355
import mdp.offroad_grid as offroad_grid import loader.kinematic_loader as kinematic_loader from torch.utils.data import DataLoader import numpy as np np.set_printoptions(threshold=np.inf) # print the full numpy array import visdom import warnings import logging import os warnings.filterwarnings('ignore') from networ...
9922356
import re from urllib.parse import unquote import logging from scrapy import Request from aioscrapy.spiders import AioSpider logger = logging.getLogger(__name__) class DemoAioscrapyRedisSpider(AioSpider): name = 'DemoAioscrapyRedis' custom_settings = { "USER_AGENT": "Mozilla/5.0 (Windows NT 10.0; Wi...
9922384
import torch import torchvision from torchvision import transforms import torch.utils.data as data from .omniglot import Omniglot from .utils import TransformTwice, TransformKtimes, RandomTranslateWithReflect, TwoStreamBatchSampler from .concat import ConcatDataset def OmniglotLoader(root, batch_size, subfolder_n...
9922411
import json import csv import sys def jsontocsv(textfile): jsonfile = open(str(textfile)+".json", "r") #open json file print("file loaded") #checks json_parsed = json.load(jsonfile) #turns the json file into dictionaries and lists json_headers = json_parsed["resultSets"][0]["headers"] #these are the headers j...
9922412
import random import unittest from copy import deepcopy from unittest import TestCase import numpy as np from learn2learn.data import MetaDataset, TaskGenerator from .util_datasets import TestDatasets class TestTaskGenerator(TestCase): @classmethod def setUpClass(cls) -> None: cls.ds = TestDatasets(...
9922416
import collections import fact_query import platform import stats import sys import time import webbrowser import datetime from django.core.management.base import BaseCommand from canvas.experiments import Experiments from canvas.templatetags.jinja_base import render_jinja_to_string class User(object): def __ini...
9922443
def raises(err, lamda): try: lamda() return False except err: return True
9922457
import numpy as np def rotate_points_z(P, theta): R = np.array([ [np.cos(theta), np.sin(theta), 0, 0], [-np.sin(theta), np.cos(theta), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]) P_h = np.vstack([P, np.zeros(P.shape[1])]) #homogenous coordinates return R.dot(P_h)[:3, :]
9922459
import pytest import os from turf.helpers import ( point, line_string, polygon, feature_collection, Point, LineString, Polygon, ) from turf.invariant import get_geometry_type from turf.utils.error_codes import error_code_messages from turf.utils.exceptions import InvalidInput from turf.uti...
9922462
from attorch.layers import (SpatialXFeatureLinear, elu1, SpatialTransformerPooled2d, SpatialTransformerPyramid2d) from attorch.module import ModuleDict from staticnet import logger as log class Readout: def initialize(self, *args, **kwargs): raise NotImplementedError('initiali...
9922487
import torch.nn as nn import torch.nn.functional as F from confidnet.models.model import AbstractModel from confidnet.models.small_convnet_svhn import Conv2dSame class SmallConvNetSVHNExtractor(AbstractModel): def __init__(self, config_args, device): super().__init__(config_args, device) ...
9922520
import pytest import yaml @pytest.fixture(scope="session") def device_inventory(): """ Load the device inventory and provide it to all tests. """ with open("inventory.yml", "r") as inv_file: inv = yaml.load(inv_file, Loader=yaml.FullLoader) assert type(inv) == dict return inv
9922575
import dis from pypy.interpreter.reverse_debugging import * from pypy.interpreter import reverse_debugging from rpython.rlib import revdb class FakeCode: hidden_applevel = False def __init__(self, co_code='', co_lnotab='', co_filename='?'): self.co_firstlineno = 43 self.co_code = co_code ...
9922578
from collections import namedtuple FetchSpec = namedtuple("FetchSpec", ["filepath", "filetype", "matrix_spec"]) def fetch(target, fetch_spec, verbose=True): from .._data import asarray from .._data import assert_target, assert_filetype from .._data import CONF assert_target(target) if isinstanc...
9922619
from torch.nn.modules.module import Module import torch import numpy as np from torch.autograd import Variable class GetCostVolume(Module): def __init__(self, maxdisp): super(GetCostVolume, self).__init__() self.maxdisp = maxdisp + 1 def forward(self, x, y): assert(x.is_contiguous() =...
9922623
from InterpreteF2.NodoAST import NodoArbol from InterpreteF2.Tabla_de_simbolos import Tabla_de_simbolos from InterpreteF2.Arbol import Arbol from InterpreteF2.Valor.Valor import Valor from InterpreteF2.Primitivos.TIPO import TIPO class TIME(NodoArbol): def __init__(self, data, line, column): super().__ini...
9922628
import time; from .cTimeout import cTimeout; def cCdbWrapper_foSetTimeout(oCdbWrapper, sDescription, nTimeoutInSeconds, f0Callback = None, txCallbackArguments = []): assert nTimeoutInSeconds >= 0, "Negative timeout time does not make sense"; oCdbWrapper.oApplicationTimeLock.fAcquire(); try: nFireAtOrAfterApp...
9922633
import math import struct import numpy as np import zengl from window import Window def grass_mesh(): a = np.linspace(0.0, 1.0, 8) b = np.square(a) c = np.sin(b * (np.pi - 1.0) + 1.0) verts = [] for i in range(7): verts.append((-c[i] * 0.03, b[i] * 0.2, a[i])) verts.append((c[i] ...
9922691
import time from django.core.management.base import BaseCommand from canvas.models import User, send_email class Command(BaseCommand): args = '' help = 'Send e-mail template' def handle(self, from_address, subject, template, id_start, id_end, *args, **options): id_start, id_end = int(id_start), ...
9922720
import responses class ResponsesHelper: """ Work around the lack of reentrance in the `responses` library. Both `moto` and `responses` suffer from an inherent design flaw: they use unittest.mock.patch which is global but their decorators and context managers pretend to be reentrant. It is essentia...
9922741
import logging import requests from django.conf import settings from django.contrib.sites.models import Site from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.template.loader import get_template from django.utils import timezone from invitations.consumers import ...
9922742
import unittest import base58 from fetchai.ledger.crypto.address import Address from fetchai.ledger.crypto.entity import Entity from fetchai.ledger.serialisation.sha256 import sha256_hash def _calc_address(public_key_bytes): bytes = sha256_hash(public_key_bytes) display_bytes = bytes + sha256_hash(bytes)[:4...
9922769
import math class Solution: def integerReplacement(self, n: int) -> int: s = 0 while n != 1: if n % 2 == 0: n //= 2 s += 1 continue if n == 3: return s + 2 else: if math.ceil(math.lo...
9922899
from datetime import datetime import olympia.core.logger from olympia import amo from olympia.activity import log_create from olympia.users.utils import get_task_user log = olympia.core.logger.getLogger('z.amo.blocklist') def add_version_log_for_blocked_versions(obj, old_obj, al): from olympia.activity.models ...
9922914
from xia2.Driver.DriverFactory import DriverFactory from xia2.Schema.Interfaces.FrameProcessor import FrameProcessor def EstimateGain(DriverType=None): """A factory for EstimateGainWrapper classes.""" DriverInstance = DriverFactory.Driver(DriverType) class EstimateGainWrapper(DriverInstance.__class__, F...
9922949
import numpy as np import matplotlib.pyplot as plt # model parameters class ModelParams: def __init__(self): self.D = 0.5 # base fee decay factor self.T = 1 # weighting for token price in trove issuance self.F = 0.3 # weighting for momentum in trove issuance self.lookback = 5 # Lo...
9922991
import xml.etree.ElementTree as ET # good hints on using the XML module: https://stackabuse.com/reading-and-writing-xml-files-in-python/ from somo.sm_link_definition import SMLinkDefinition from somo.sm_joint_definition import SMJointDefinition ############# utility to suppress printing - temporarily suppresses con...
9923005
from pyparsing import Word, nums from pyparsing import Optional from pyparsing import restOfLine from pyparsing import ZeroOrMore from pyparsing import OneOrMore from pyparsing import Group from pyparsing import alphanums from pyparsing import Literal from pyparsing import Regex from atom import parse_atom from litera...
9923011
def list_length(x): if hasattr(x, 'shape'): return x.shape[0] else: return len(x)
9923035
from django.urls import path, include from apps.user.views.router import router from apps.user.views.me import MeView urlpatterns = [ path('api/', include(router.urls)), path('api/me', MeView.as_view(), name='me'), ]
9923040
import sys import typing from typing import get_type_hints from datetime import datetime import dataclasses as dc try: fromisoformat = datetime.fromisoformat except AttributeError: # python 3.6 from backports._datetime_fromisoformat import datetime_fromisoformat as fromisoformat from .typing_extra import ge...
9923133
import copy from unittest.mock import patch from builder import pystache_message_builder from utilities import file_utilities from utilities import message_utilities import mhs_common.messages.ebxml_envelope as ebxml_envelope import mhs_common.messages.ebxml_request_envelope as ebxml_request_envelope import mhs_commo...
9923142
from typing import List import pytest from di.container import Container, bind_by_type from di.dependant import Dependant, Marker from di.executors import SyncExecutor from di.typing import Annotated class Request: def __init__(self, value: int = 0) -> None: self.value = value def endpoint(r: Request)...
9923161
from orator.migrations import Migration class CreateVotesTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('votes') as table: table.increments('id') table.integer('value').default(0) table.integer('user_id').uns...
9923178
from typing import List import random class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: nums.sort() return nums[-k] def findKthLargest_partition(self, nums: List[int], k: int) -> int: """ partition Top-K algorithm """ k = len(nu...
9923206
import os import shutil import json from ..utils.location import base_path, resources_path from ..utils.filesystem import get_module_dir class Preset: """Base preset class containing business logic for adding a preset to the project.""" key = "" packages = {} removed_packages = [] def get_base_...
9923234
import math import numpy as np def pwm2thrust_dji_set(pwm, voltage): pwm_mean = 1525 pwm_std = 231.1462 voltage_mean = 11.7894 voltage_std = 0.33 p00 = 2.939 p10 = 2.422 p01 = 0.1464 p20 = 0.3989 p11 = 0.1119 x = (pwm - pwm_mean) / pwm_std y = (voltage - voltage_mean) / vol...
9923263
import os from datetime import datetime from getpass import getpass from netmiko import ConnectHandler, ReadTimeout # Code so automated tests will run properly password = os.getenv("NETMIKO_PASSWORD") if os.getenv("NETMIKO_PASSWORD") else getpass() device = { "host": "cisco3.lasthop.io", "username": "pyclass"...
9923277
import torch.utils.data as data import torch from typing import Sequence class EmptyDataset(data.Dataset): def __len__(self): return 0 def __getitem__(self, item: int): assert False, "This code is unreachable" class DatasetComposer(data.Dataset): def __init__(self, datasets: Sequence):...
9923295
import asyncio import os import pytest import ydb @pytest.fixture(scope="module") def docker_compose_file(pytestconfig): return os.path.join(str(pytestconfig.rootdir), "docker-compose.yml") @pytest.fixture(scope="module") def endpoint(module_scoped_container_getter): service = module_scoped_container_getter...
9923322
import os import re import glob from warnings import warn def parse_directory(directory, names, extensions=('tif', 'tiff', 'TIF', 'TIFF')): """ Extract necessary filenames Args: directory: str names: tuple of str, band or file names, e.g. ['RED', '101'] extensions: tuple of str, al...
9923326
import abc from .item import Item from .observation import ( ProbitWinObservation, ProbitTieObservation, LogitWinObservation, LogitTieObservation, GaussianObservation, PoissonObservation, SkellamObservation) class Model(metaclass=abc.ABCMeta): def __init__(self): ...
9923353
import setuptools from epyseg.epygui import __MAJOR__, __MINOR__, __MICRO__, __AUTHOR__, __VERSION__, __NAME__, __EMAIL__ with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='epyseg', version=__VERSION__, author=__AUTHOR__, author_email=__EMAIL__, description...
9923354
from typing import Dict from typing import List from botocore.paginate import Paginator class DescribeAccountModifications(Paginator): def paginate(self, PaginationConfig: Dict = None) -> Dict: pass class DescribeIpGroups(Paginator): def paginate(self, GroupIds: List = None, PaginationConfig: Dict =...
9923364
import random import numpy as np import subprocess import audiosegment PAD = '_' EOS = '~' PUNC = '!\'(),-.:;?`' SPACE = ' ' SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' en_symbols = SYMBOLS + PAD + EOS + PUNC + SPACE _symbol_to_id = {s: i for i, s in enumerate(en_symbols)} def get_length(wavpath,...
9923378
from twisted.internet import reactor from scrapy.crawler import Crawler, CrawlerProcess from scrapy import signals from scrapy.utils.project import get_project_settings from scrapy.settings import Settings from argparse import ArgumentParser import logging from imagebot.spiders.bot import ImageSpider from imagebot.set...