id
stringlengths
3
8
content
stringlengths
100
981k
1715336
from Redy.Opt import * from dis import dis import pytest import unittest class TestMacro(unittest.TestCase): @pytest.fixture(autouse=True) def test_macro(self): macro = Macro() @feature(macro) def macro_example(x): @macro.stmt def just_return(v): ...
1715342
import pytest from simple_zpl2 import ZPLDocument def test_field_origin(): zdoc = ZPLDocument() zdoc.add_field_origin(1000, 999, 2) assert(zdoc.zpl_bytes == b'^XA\n^FO1000,999,2\n^XZ') zdoc = ZPLDocument() zdoc.add_field_origin() assert (zdoc.zpl_bytes == b'^XA\n^FO0,0\n^XZ') def test_field...
1715351
from mamba import description, before, after, it from expects import expect, be_empty import os import client.api import client.models from common import Config, Service from common.matcher import be_valid_stack, raise_api_exception from common.helper import check_modules_exists CONFIG = Config(os.path.join(os.path....
1715367
from ha.core.action_handler.action_handler import NodeActionHandler from ha.core.event_manager.event_manager import EventManager from ha.core.event_manager.subscribe_event import SubscribeEvent from ha.core.system_health.const import HEALTH_STATUSES from ha.core.system_health.model.health_event import HealthEvent def...
1715380
import os import tempfile import argparse from sentencepiece import SentencePieceTrainer as sp_trainer from allennlp.common.params import Params from allennlp.data.dataset_readers import DatasetReader from summarus.readers import * def train_subwords(train_path, model_path, model_type, vocab_size...
1715395
from .base import ApiBase import logging logger = logging.getLogger(__name__) class TaxItems(ApiBase): def __init__(self, ns_client): ApiBase.__init__(self, ns_client=ns_client, type_name='SalesTaxItem')
1715401
import hydra from torch.utils.data import random_split import torchvision import torch import math from upcycle import cuda from gnosis.distillation.classification import reduce_ensemble_logits import copy from torch.utils.data import TensorDataset, DataLoader import random import os from torchvision.datasets.folder i...
1715403
import pygame from . import pygwrap import glob from . import util MENUFONT = None INIT_DONE = False class MenuItem( object ): def __init__(self,msg,value,desc=None): self.msg = msg self.value = value self.desc = desc def __lt__(self,other): """ Comparison of menu items done...
1715408
import os curr_dir = os.path.dirname(os.path.abspath(__file__)) trigger_datafiles = {} trigger_datafiles['main'] = os.path.join(curr_dir, 'trigger_datafile.yaml') trigger_datafiles['nxos'] = os.path.join(curr_dir, 'nxos/trigger_datafile_nxos.yaml') trigger_datafiles['ios'] = os.path.join(curr_dir, 'ios/trigger_datafi...
1715416
from __future__ import annotations import typing import psutil # type: ignore if typing.TYPE_CHECKING: from asyncio import Future from typing import Tuple, Optional, Type, Union from pypbbot.driver import Drivable from pypbbot.typing import ProtobufBotAPI import asyncio import os import threading i...
1715434
from django.apps import AppConfig class AuthValimoConfig(AppConfig): name = 'waldur_auth_valimo' verbose_name = 'Waldur Auth Valimo' def ready(self): pass
1715438
from typing import Tuple import pytest import foolbox as fbn import eagerpy as ep def test_evaluate(fmodel_and_data: Tuple[fbn.Model, ep.Tensor, ep.Tensor]) -> None: pytest.skip() assert False fmodel, x, y = fmodel_and_data # type: ignore attacks = [ # L2BasicIterativeAttack, # L2Car...
1715445
from pathlib2 import Path import pathlib2 import os from datetime import datetime import numpy as np import matplotlib.pyplot as plt PROJECT_DIR = Path(__file__).resolve().parents[1] DATA_DIR = PROJECT_DIR / "data" MODEL_DIR = PROJECT_DIR / "models" FIGURE_DIR = PROJECT_DIR / "figures" def ensure_dir(file_path): ...
1715453
from aiohttp_admin2.exceptions import AdminException __all__ = [ 'CanNotModifiedFrozenView', 'CanNotCreateUnfrozenView', 'NoUniqueController', 'NotRegisterView', 'NoUniqueControllerName', 'UseHandlerWithoutAccess', ] class CanNotModifiedFrozenView(AdminException): """We can't modified sta...
1715492
import sys, os, platform, json def get_defs_path(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), "moduledefs.json") def has_defs(): return os.path.exists(get_defs_path()) def get_prop(prop_name): if not os.path.exists(get_defs_path()): return '' with open(get_defs_path...
1715499
import os import urllib.request import zipfile def downloadZip(url, extractedFolderName = None): zipFileName = url.rsplit('/', 1)[-1] assert zipFileName.endswith('.zip') if not extractedFolderName: extractedFolderName = zipFileName[:-4] if not os.path.exists(extractedFolderName): print(...
1715506
import unittest import numpy as np from paderbox.array import split_complex_features, merge_complex_features T, B, F = 400, 6, 513 A = np.random.uniform(size=(T, B, F)) + 1j * np.random.uniform(size=(T, B, F)) class TestSplitMerge(unittest.TestCase): def test_identity_operation(self): splitted = split_co...
1715574
import unittest import numpy as np import pandas as pd from diamond.glms.logistic import LogisticRegression import os import logging from diamond.integration_tests.utils import run_r_script LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class TestLogistic(unittest.TestCase): def setUp(self, t...
1715612
from typing import Any # Copyright (c) 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0) def f1(a, b : int): pass def f2(a, b) -> int: pass def f3(a): # type: (Any) -> r3 pass def f4(a, b): # type: (e4, Any) -> None pass def f5(a): # type: (Any) -> Any pass
1715636
from typing import Union from ...kernel import core class OverloadManaBuilder: def __init__(self, vEhc, num1, num2) -> None: self.skill = ( core.BuffSkill("오버로드 마나", 0, 99999 * 10000) .isV(vEhc, num1, num2) .wrap(core.BuffSkillWrapper) ) self.pdamage_ind...
1715664
import random import torchvision.transforms as transforms import torchvision.transforms.functional as F from PIL import Image import cv2 class HalfCrop(object): """Half Crop Augmentation random crop bottom half of a pedestrian image (i.e. waist to foot) perform well for occluded reid Args: pr...
1715684
from unittest import TestCase import ddt from pysubparser import parser, writer from pysubparser.cleaners import ascii, brackets, formatting, lower_case PATH = "./tests/files/{test_type}/test.{subtitle_type}" @ddt.ddt class WriterTester(TestCase): def _assert_subtitle(self, sub, index, text, start, end, durat...
1715721
import os from datadog_checks.dev import get_here HERE = get_here() def get_fixture_path(filename): return os.path.join(HERE, 'fixtures', filename)
1715735
import sys import io import unittest from unittest.mock import patch from fzfaws.s3.helper.s3progress import S3Progress import boto3 from botocore.stub import Stubber class TestS3Progress(unittest.TestCase): def setUp(self): self.capturedOutput = io.StringIO() sys.stdout = self.capturedOutput ...
1715750
from robonomics_msgs.msg import Demand, Offer, Result, AddedOrderFeedback, AddedPendingTransactionFeedback from ethereum_common.msg import Address, UInt256, TxHash from ipfs_common.msg import Multihash from binascii import unhexlify # ask validAskDict = { "model": "QmfCcLKrTCuXsf6bHbVupVv4zsbs6kjqTQ7DRftGqMLjdW", ...
1715779
from datetime import datetime import logging import soap import config import scrape import mongo import util def get(code): db = mongo.get_db() variable = db.variables.find_one({'code': code}) if (not variable) or config.bool('reload'): logging.info("Variable %s not found, loading from SOAP...", c...
1715791
from typing import Any, Dict import pytest from versioningit.basics import basic_tag2version from versioningit.errors import InvalidTagError @pytest.mark.parametrize( "tag,params,version", [ ("v01.02.03", {}, "01.02.03"), ("01.02.03", {}, "01.02.03"), ("vbad", {}, "bad"), ("v",...
1715810
import urlparse, smtplib, logging, getpass, socket, os, string from email.mime.text import MIMEText from .config import config ### L = logging.getLogger('sendmail') ### # Configure urlparse if 'smtp' not in urlparse.uses_query: urlparse.uses_query.append('smtp') ### class send_mail(object): def __init__(self, de...
1715814
import unittest from keyring.backend import KeyringBackend from keyrings.alt import multi import keyring.errors class MultipartKeyringWrapperTestCase(unittest.TestCase): """Test the wrapper that breaks passwords into smaller chunks""" class MockKeyring(KeyringBackend): priority = 1 def __...
1715836
import torch import streamlit as st from transformers import AutoTokenizer, AutoModel, AutoModelForSeq2SeqLM from question_generation.pipelines import pipeline device = torch.device('cuda') tokenizer = None model = None question_generator = None # load models,tokenizer def load_models(): global tokenizer, model,...
1715843
import logging import time from abc import ABC, abstractmethod from contextlib import contextmanager from functools import partial from pathlib import Path import numpy as np from moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriter from tqdm import tqdm from PIL import Image from tao.utils import vis _GREEN = (...
1715855
def printTradeAnalysis(analyzer): ''' Function to print the Technical Analysis results in a nice format. ''' #Get the results we are interested in total_open = analyzer.total.open total_closed = analyzer.total.closed total_won = analyzer.won.total total_lost = analyzer.lost.total win...
1715865
import sys sys.path.append('../../') import constants as cnst import pandas import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np df = pandas.read_csv(cnst.five_pt_likert_scale_result_csv_path) results = df[['Input.image_url', 'Answer.category.label']].to_numpy() print(df) id_hist_dict = {} categori...
1715907
import threading class Payload(object): PAYLOAD_ID = 0 PAYLOAD_ID_LOCK = threading.Lock() def __init__(self, data=""): self.data = data with Payload.PAYLOAD_ID_LOCK: self.id = Payload.PAYLOAD_ID Payload.PAYLOAD_ID += 1
1715910
import os def create_directories(path): if not os.path.exists(path): try: os.makedirs(path) except os.error as e: if not os.path.exists(path): raise e def creat(filename, mode): assert isinstance(mode, int), mode # this may be insufficient to set p...
1715930
from torch.utils.tensorboard import SummaryWriter from . import plotting as plt class MyWriter(SummaryWriter): def __init__(self, hp, logdir): super(MyWriter, self).__init__(logdir) self.hp = hp def log_training(self, train_loss, step): self.add_scalar('train_loss', train_loss, step...
1715958
from fastapi import FastAPI from elasticapm.contrib.starlette import ElasticAPM from project.infrastructure.open_api.open_api_schema import Schema from project.infrastructure.drivers.apm.adapter import ApmAdapter from project.resources.lifecheck.controller import router as life_check_api app = FastAPI() apm = ApmAdapt...
1715961
import json import argparse import pathlib import time import datetime import subprocess import numpy import tqdm import pybullet as bullet import igl def get_time_stamp(): return datetime.datetime.now().strftime("%Y-%b-%d-%H-%M-%S") def save_mesh(meshes, out_path, index): Vs = [] Fs = [] offset = ...
1715962
import pytest from terrainbento import ( BasicSt, RandomPrecipitator, SimpleRunoff, UniformPrecipitator, ) def test_not_UniformPrecipitator(grid_1, clock_simple): rp = RandomPrecipitator(grid_1) with pytest.raises(ValueError): BasicSt(clock_simple, grid_1, precipitator=rp) def test_...
1715999
import six class DotDict(dict): def __getattr__(self, item): if hasattr(self, item): return self[item] def __setattr__(self, key, value): self[key] = value class Chunk(object): def __init__(self, xpath, apply_func=None, filter_func=None, one=None): self._xpath = xpat...
1716027
import collections # A user-defined function Function = collections.namedtuple('Function', ['args', 'sexpr']) # A user-defined stateful apply or UDA StatefulFunc = collections.namedtuple( 'StatefulFunc', ['args', 'statemods', "sexpr"])
1716037
import torch import shutil import os import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels import logging import datetime class ImbalancedDatasetSampler(torch.utils.data.sampler.Sample...
1716063
import JeevesLib import fast.AST class VarSetting: def __init__(self, var, val): self.var = var self.val = val def __eq__(self, other): return self.var is other.var and self.val == other.val def __str__(self): return "(%s, %s)" % (self.var.name, self.val) # TODO: Define your path variable enviro...
1716080
import unittest import subprocess import os import pytest import sys class MainTest(unittest.TestCase): def test_cpp(self): print("\n\nRunning C++ tests...") all_files = [ os.path.join(dp, f) for dp, dn, filenames in os.walk( os.path.join(os.path.dirname(os....
1716107
from __future__ import absolute_import, print_function __author__ = 'katharine' import os from pebble_tool.exceptions import MissingSDK from pebble_tool.util import get_persist_dir from .manager import SDKManager, pebble_platforms SDK_VERSION = '3' def sdk_path(): path = sdk_manager.current_path if path is...
1716113
from rest_toolkit import resource @resource('/users/{id}', route_name='user') class Resource(object): def __init__(self, request): pass
1716215
from django import forms from django_file_form.forms import ( FileFormMixin, MultipleUploadedFileField, ) class RuleForm(FileFormMixin, forms.Form): rules = MultipleUploadedFileField(required=False) def __init__(self, *args, **kwargs): super(RuleForm, self).__init__(*args, **kwargs) clas...
1716243
from bscscan.tokens import Tokens import json with open('../../api_key.json', mode='r') as key_file: key = json.loads(key_file.read())['key'] address = '0x043d9b3af52b623e54a3dF92F1682757eb29F912' api = Tokens(contract_address='0x0cf2b5aabf844b49480dbf5e6192b873a865fae4', api_key=key) balance = api.g...
1716329
import re import sys from typing import Any, Union from pychoir import Matcher if sys.version_info >= (3, 7): from re import Pattern else: Pattern = Any class StartsWith(Matcher): """A Matcher checking that the compared string :code:`.startswith()` the passed string. :param start: The string the co...
1716346
import os import json from nose.tools import assert_equal from .project import load_lsdsng from .utils import temporary_file SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) def _test_load_store_instrument(source_lsdsng, lsdinst_path, original_index): proj = load_lsdsng(source_lsdsng) proj.song.instr...
1716351
import threading import multiprocessing from itertools import groupby import rethinkdb as r from bigchaindb import Bigchain import cryptoconditions as cc from server.lib.models.accounts import retrieve_accounts from server.lib.models.assets import escrow_asset, get_subcondition_indices_from_type, fulfill_escrow_asse...
1716435
from conduit.apps.core.renderers import ConduitJSONRenderer class ProfileJSONRenderer(ConduitJSONRenderer): object_label = 'profile' pagination_object_label = 'profiles' pagination_count_label = 'profilesCount'
1716443
class Solution: """ @param nums: a list of integers @param k: a integer @return: return a integer """ def smallestDistancePair(self, nums, k): # write your code here nums.sort() low = 0 high = nums[-1] - nums[0] while low < high: mid = (low + h...
1716455
import unittest2 as unittest import os import datetime class HouseKeeping(unittest.TestCase): def test_license_year(self): self.assertTrue(os.path.exists('LICENSE.txt')) now = datetime.datetime.now() current_year = datetime.datetime.strftime(now, '%Y') license_text = open('LICENSE...
1716463
with open("addition.in", 'r') as fi: dump = fi.read() lst = [int(item) for item in dump.split(',')] with open("addition.out", 'w') as fo: fo.write(str(sum(lst)) + "\n")
1716496
from adminsortable.admin import SortableAdmin from django.contrib import admin from .models import Board, Label, Column, Task class LabelAdmin(admin.ModelAdmin): list_display = ["name", "board"] list_filter = ["board"] search_fields = ["name"] class Meta: model = Label admin.site.register(...
1716531
def insertNodeAtPosition(head, data, position): pre = None cur = head while cur and position!=0: pre = cur cur = cur.next position -= 1 node = SinglyLinkedListNode(data) if not cur: pre.next = node else: node.next = cur pre.next = node return h...
1716573
sum = 0 while True: user_input = input("enter the item price or press q to quit: \n") if user_input!='q': sum = sum + int(user_input) print(f"order total so far: {sum}") else: print(f"your bill total is {sum}. thnks for visiting") break
1716595
from wtforms.fields import HiddenField from wtforms.form import Form class F(Form): a = HiddenField(default="LE DEFAULT") def test_hidden_field(): form = F() assert form.a() == """<input id="a" name="a" type="hidden" value="LE DEFAULT">""" assert form.a.flags.hidden
1716626
from function import * from pymongo import * def delete(): try: # 创建连接对象 client = MongoClient(host="localhost", port=27017) db = client.bzoj # 删除编号自1200开始,至1245的所有文档数据 for i in range(0, 46): count = 1200 count = count+i print(count) ...
1716654
from django import forms from django.forms import ModelForm from tally_ho.apps.tally.forms.fields import RestrictedFileField from tally_ho.apps.tally.models.ballot import Ballot class CreateRaceForm(ModelForm): class Meta: model = Ballot fields = localized_fields = [ 'number', ...
1716705
import pandas as pd from matplotlib import pyplot as plt import numpy as np from sklearn.preprocessing import MinMaxScaler import random MAXLIFE = 120 SCALE = 1 RESCALE = 1 true_rul = [] test_engine_id = 0 training_engine_id = 0 def kink_RUL(cycle_list, max_cycle): ''' Piecewise linear functi...
1716706
import os import bot import click import importlib import traceback as tb from datetime import datetime from alembic.config import Config from alembic import command as alembic from alembic.util.exc import CommandError from config import DATABASE_URL, HANDLERS, SKIP_UPDATES, HANDLERS_DIR, \ MODELS_DIR, ENABLE_APS...
1716779
import json import random import os import numpy as np from pathlib import Path import logging LOGGER = logging.getLogger(__name__) class Config(object): def __init__(self, filename=None): self.config_name = filename self.base_res_dir = "../results" # Directory where result folder is created ...
1716803
import asyncio import rocat.message import rocat.actor import rocat.globals class BaseActorRef(object): def tell(self, m, *, sender=None): raise NotImplementedError def ask(self, m, *, timeout=None): raise NotImplementedError def error(self, e): raise NotImplementedError class...
1716804
import sys from win32com.client import Dispatch d = Dispatch("Python.Interpreter") print "2 + 5 =", d.Eval("2 + 5") d.Exec("print 'hi via COM'") d.Exec("import sys") print "COM server sys.version", d.Eval("sys.version") print "Client sys.version", sys.version print "COM server sys.path", d.Eval("sys.path") print "C...
1716909
import math from typing import Any, Dict import pytest from hypothesis import given, infer, settings from rsserpent.utils import fetch_data from tests.conftest import Times async def provider( a: int, *, b: float, c: bool, d: int = 1, **_: Dict[str, Any] ) -> Dict[str, Any]: """Define an example data provid...
1716946
import json import inspect import textwrap def _get_value(name, value): if callable(value): value = inspect.getsource(value) if value is None: raise Exception("Cannot obtain source code for '{}'".format(name)) value = textwrap.dedent(value) return RichValue(value).value def...
1716954
import unittest from datamart_core import common class TestDatasetIdEncoding(unittest.TestCase): def test_encode(self): """Test encoding a dataset ID to a file name""" self.assertEqual( common.encode_dataset_id('datamart_contrived/dataset#id;'), 'datamart__contrived_2Fdata...
1716963
import unittest import pandas as pd from pandas.util.testing import assert_series_equal, assert_frame_equal from dsbox.ml.feature_engineering import project_continuous_on_categorical, CategoricalProjector, TagEncoder class TestCategorical(unittest.TestCase): def test_project_continuous_on_categorical_function_s...
1716978
import upath.core class _MemoryAccessor(upath.core._FSSpecAccessor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._fs.root_marker = "" class MemoryPath(upath.core.UPath): _default_accessor = _MemoryAccessor def iterdir(self): """Iterate over the fi...
1716987
import itertools import logging import json import operator import time from collections import defaultdict from typing import List, Tuple, Dict from mip import Model, minimize, CONTINUOUS, xsum, OptimizationStatus from rapidstream.BE.Utilities import isPairSLRCrossing from rapidstream.BE.Device.U250 import idx_of_le...
1717015
from comtypes.gen import _944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0 globals().update(_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.__dict__) __name__ = 'comtypes.gen.UIAutomationClient'
1717022
import numpy as np from scipy import interpolate from scipy.signal import iirfilter, lfilter, filtfilt def filter_base(signal, axis=-1, fs=250.): """ Perform 60 Hz notch filtering using scipy library. Parameters ---------- signal : 1D numpy.array Array to filter. axis: int Choose ...
1717045
import torch import torch.nn as nn import torch.nn.functional as F from utils.proj_adaptive_softmax import ProjectedAdaptiveLogSoftmax class PositionalEmbedding(nn.Module): def __init__(self, demb): super(PositionalEmbedding, self).__init__() self.demb = demb inv_freq = 1 / (10000 ** (to...
1717061
from typing import Any from FlaUILibrary.flaui.exception import FlaUiError class TreeItemsParser: """ Helper class which handles the management of the given location string. The location is used to locate the exact tree item in the tree control. Examples: location = N:Nameofitem1->N:Nameofitem2->N...
1717082
from typing import Optional, List from pydantic import BaseModel, HttpUrl from .upload import UploadStatusBase # Shared properties class LicenseBase(BaseModel): name: str url: HttpUrl class Config: orm_mode = True # Properties to receive via API on creation class LicenseCreate(LicenseBase): ...
1717124
import FWCore.ParameterSet.Config as cms ESTrivialConditionRetriever = cms.ESSource("ESTrivialConditionRetriever", # Values to get correct noise on RecHit amplitude using 3+5 weights ESpedRMS = cms.untracked.double(1.26), weightsForTB = cms.untracked.bool(True), producedESPedestals = cms.untracke...
1717125
import torch def build_optimizer(args, model): ve_params = list(map(id, model.visual_extractor.parameters())) ed_params = filter(lambda x: id(x) not in ve_params, model.parameters()) optimizer = getattr(torch.optim, args.optim)( [{'params': model.visual_extractor.parameters(), 'lr': args.lr_ve}, ...
1717152
import json import os import unittest from mock import Mock, patch from yahoo_panoptes.framework.utilities.helpers import ordered from tests.plugins.helpers import DiscoveryPluginTestFramework from yahoo_panoptes.plugins.discovery.plugin_discovery_from_json_file import PluginDiscoveryJSONFile from yahoo_panoptes.disco...
1717197
import numpy as np import sys M = int(sys.argv[1]) K = int(sys.argv[2]) N = int(sys.argv[3]) int8 = True if int(sys.argv[4]) == 1 else False if int8: #scale = np.random.normal(size=(M)).astype(np.float32) scale = np.ones((M)).astype(np.float32) else: scale = 1 bias = np.random.normal(size=(M)) #bias = np....
1717211
from UQpy.Distributions.baseclass import Copula from UQpy.Distributions.baseclass import DistributionContinuous1D from numpy import prod, log, ones, exp class Gumbel(Copula): """ Gumbel copula having cumulative distribution function .. math:: F(u_1, u_2) = \exp(-(-\log(u_1))^{\Theta} + (-\log(u_2))^{\The...
1717232
from .action import AsyncActionClient, AsyncActionServer from .helpers import ExceptionMonitor, cancel_on_exception, cancel_on_shutdown, log_during from .service import AsyncService, AsyncServiceProxy from .topic import AsyncPublisher, AsyncSubscriber __all__ = ('AsyncSubscriber', 'AsyncService', 'AsyncServiceProxy', ...
1717245
from setuptools import setup import os VERSION = "0.2.1" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), encoding="utf8", ) as fp: return fp.read() setup( name="datasette-leaflet-freedraw", description="Draw polyg...
1717307
import torch import cargan ############################################################################### # cargan dataset ############################################################################### class Dataset(torch.utils.data.Dataset): def __init__(self, name): self.name = name self.c...
1717328
from .labelimg_annotation import Source, Size, BoundingBox, Rectangle, RectangleHandler, \ LabelImgAnnotationParser, LabelImgAnnotation, LabelImgAnnotationHandler
1717352
from unittest.mock import MagicMock as Mock from unittest.mock import patch import itertools import asyncio import threading from hypothesis import given from hypothesis import strategies as st import pytest from brainslug.database import AsyncTinyDB from brainslug import body from brainslug.runtime import get_resour...
1717369
from pyquil.quil import Program from pyquil.gates import * import numpy as np import pytest from referenceqvm.gates import gate_matrix def test_random_gates(qvm_unitary): p = Program().inst([H(0), H(1), H(0)]) test_unitary = qvm_unitary.unitary(p) actual_unitary = np.kron(gate_matrix['H'], np.eye(2 ** 1))...
1717377
import json import logging import maven_dependency_utils import os import re import shutil import subprocess import sys import time desired_sdk = os.getenv("ANDROID_SDK_ROOT") if not desired_sdk: logging.error("Environment variable ANDROID_SDK_ROOT must be set.") exit(-1) if os.getenv("ANDROI...
1717382
from typing import List, Any from dataclasses import dataclass from talipp.indicators.Indicator import Indicator from talipp.indicators.RSI import RSI from talipp.indicators.SMA import SMA @dataclass class StochRSIVal: k: float = None d: float = None class StochRSI(Indicator): """ Stochastic RSI ...
1717402
from __future__ import print_function import numpy as np import copy from utils import Pack from dataset.dataloader_bases import DataLoader # Twitter Conversation class TCDataLoader(DataLoader): def __init__(self, name, data, vocab_size, config): super(TCDataLoader, self).__init__(name, fix_batch=config.fi...
1717424
from checkov.cloudformation.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.enums import CheckCategories from checkov.common.models.consts import ANY_VALUE class BackupVaultEncrypted(BaseResourceValueCheck): def __init__(self): name = "Ensure Backup Vault...
1717455
from __future__ import print_function import argparse import torch from torch.autograd import Variable from torchvision import datasets, transforms from model import FaceModel from torchvision.datasets import ImageFolder from TripletFaceDataset import FaceDataset import math import os import seaborn as sns import numpy...
1717479
class NotFoundException(Exception): """Exception used to indicate that a requested record could not be found.""" def __init__(self, collection, id): self._collection = collection self._id = id def __str__(self): return u"{} {} not found".format(self._collection.name, self._id)
1717530
import numpy def random_projection(A, new_dim, seed=0): # Project rows of [A] into lower dimension [new_dim] if A.shape[1] <= new_dim: return A state = numpy.random.RandomState(seed) R = state.choice([-1, 0, 0, 0, 0, 1], (new_dim, A.shape[1])) * numpy.sqrt(3) A_new = numpy.dot(R, A.T).T ...
1717554
import numpy as np from enum import Enum import cv2 # we will use linear_assignment to quickly write experiments, # later a customerized KM algorithms with various optimization in c++ is employed # see https://github.com/berhane/LAP-solvers # This is used for "Complete Matching" and we can remove unreasonable "worker...
1717624
import numpy as np class MaskRaster(): def __init__(self): self.name = "Mask Raster Function" self.description = "Applies a raster as the NoData mask of the input raster." def getParameterInfo(self): return [ { 'name': 'r', 'data...
1717652
r""" Feature for testing if the Internet is available """ from . import Feature, FeatureTestResult class Internet(Feature): r""" A :class:`~sage.features.Feature` describing if Internet is available. Failure of connecting to the site "https://www.sagemath.org" within a second is regarded as internet...
1717659
from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from .maplabeller import map_labeller, labelfile_reader class MapDesign(object): """Class for holding map design elements.""" def __init__(self, mapcorners, standard_p...
1717687
from rx.subjects import Subject from modules import logger from modules import utils from modules.message_server import MessageServer import config import parameters class DoorListener: def __init__(self): self.door_message_server = MessageServer(config.door_tag_port) self.openDoorStream = Subje...