id
stringlengths
3
8
content
stringlengths
100
981k
9930263
from __future__ import absolute_import from six.moves import BaseHTTPServer import logging import os import pyqrcode import socket import time from six.moves.urllib import parse as urlparse import webbrowser from .phone_sensor import SENSOR_PAGE_HTML logger = logging.getLogger("pebble_tool.util.browser") class Bro...
9930306
import argparse from textwrap import dedent from unittest.mock import Mock from pyscaffold import api, cli from pyscaffold.extensions import config, interactive from ..helpers import ArgumentParser def normalise(text: str) -> str: return "\n".join(text.strip().splitlines()) def test_wrap(): text = "as eir...
9930323
import typing from .app_types import ASGIApp, ErrorHandler, EventHandler, Receive, Scope, Send from .compat import WSGIApp, is_asgi3 from .config import settings from .contrib.pydocmd import DocsMeta from .error_handlers import error_to_json, error_to_text from .errors import HTTPError from .injection import STORE fro...
9930336
import numpy as np def l2_normalize(x, axis, epsilon=1e-12): out = x / np.sqrt( np.maximum( np.sum(np.square(x), axis=axis, keepdims=True), epsilon ) ) return out
9930339
class Solution: def minCostToMoveChips(self, chips: List[int]) -> int: return min(sum((c1 - c2) % 2 for c2 in chips) for c1 in chips)
9930340
import io from setuptools import setup, find_packages from os import path this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: desc = f.read() setup( name='rewise', version=__import__('rewise').__version__, description='Googl...
9930367
import pandas as pd import sys smiles_name = sys.argv[1]+'.can' csv_name = sys.argv[2]+'.csv' csv = pd.read_csv(csv_name, header=0,names=['SMILES','Activity','val']) #Change to whatever the headers are in the .csv SMILES_df = pd.read_csv(smiles_name, header=0,delim_whitespace=True,names=['SMILES','Name']) #Keep the ...
9930431
import sys import numpy as np import gdspy as gp from pp.geo_utils import area def _print(*args, **kwargs): print(*args, **kwargs) sys.stdout.flush() def compute_area(c, target_layer): """ Compute area of the component on a given layer """ _print("Computing area ", c.name) c.flatten() ...
9930440
import os from ncvoter.settings import * # noqa: F403, F401 DEBUG = False SECRET_KEY = os.environ['SECRET_KEY'] DOMAIN = os.environ['DOMAIN'] ADDITIONAL_DOMAINS = os.environ.get('ADDITIONAL_DOMAINS') ALLOWED_HOSTS = [DOMAIN] # if ADDITIONAL_DOMAINS is set, then it will be a comma-delimited list of domains if ADDITI...
9930467
from __future__ import division from past.utils import old_div import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def insert_missing(): air_path = pyunit_utils.locate("smalldata/airlines/allyears2k_headers.zip") data = h2o.import_file(path=air_path) hour1 = old_div(data["...
9930485
def test_get_key_name(case_data): """ Test :meth:`.get_key_name`. Parameters ---------- case_data : :class:`.CaseData` A test case. Holds the key maker to test and the correct name. Returns ------- None : :class:`NoneType` """ assert case_data.key_maker.get_key_name()...
9930486
from __future__ import print_function import pandas as pd import numpy as np from py_ml_utils.dataset_transformer import FeatureTransformationPair, DatasetTransformer from collections import defaultdict import time from typing import Any, Callable from scipy.stats import sem import gc import sys class FeatureSelector(...
9930507
from win32com.shell import shell, shellcon import win32api import os def testSHFileOperation(file_cnt): temp_dir = os.environ["temp"] orig_fnames = [ win32api.GetTempFileName(temp_dir, "sfo")[0] for x in range(file_cnt) ] new_fnames = [ os.path.join(temp_dir, "copy of " + os.path.split...
9930539
class StateModifier: def __init__(self): self.models = list() def add_model(self, model): self.models.append(model) def get_update_states(self, true_state, environment): for model in self.models: model.step(true_state, environment) def get_ignore_by_checkpoint(self...
9930554
from uwsgiconf.config import Section def test_http(assert_lines): routers = Section.routing.routers router = routers.http( on='127.0.0.1:3111' ).set_basic_params( keepalive=20 ).set_connections_params( harakiri=20 ).set_manage_params( websockets=True ).set_own...
9930610
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np from collections import defaultdict from .eval_base import EvaluatorBase def eval_cuhk03(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, N=100, logger=None): """Evaluation with c...
9930623
from app.api.mines.region.models.region import MineRegionCode from tests.status_code_gen import RandomMineRegionCode # MineLocation Class Methods def test_mine_region_find_by_region_code(db_session): region_code = RandomMineRegionCode() mine_region = MineRegionCode.find_by_region_code(region_code) assert ...
9930637
import asyncio import os import sys import threading import json import tornado from tornado.options import (define, options, parse_command_line, parse_config_file) from tornado.web import Application, RequestHandler, authenticated import QUANTAXIS as QA from QAPUBSUB.producer import publi...
9930641
from Attack.ParameterTypes.IntegerPositive import IntegerPositive class IntegerLimited(IntegerPositive): def __init__(self, args: list): super(IntegerLimited, self).__init__(*args) self.name = "IntegerLimited" def validate(self, value) -> (bool, int): is_valid, value = IntegerPositiv...
9930657
import json import os from base.link_extractor import LinkExtractor class GrantsLinkExtractor(LinkExtractor): module_name = 'grants_attach.link_extractor' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.base_url = 'http://www.grants.gov/grantsws/AttachmentDownload...
9930714
import os import click from util import prompt_for_commit_selection, commits_full_list from git import GitCommandError from collections import deque @click.command(short_help='Returns repo version to a specific commit') @click.pass_context @click.option('-h', '--hash', 'commit_hash', help="hash of the commit to go...
9930722
from ase.io import read from flosic_os import xyz_to_nuclei_fod,ase2pyscf from pyscf import dft,gto from flosic_scf import FLOSIC import time import numpy as np # This example visualizes how a second order self-consistency solver can be used to drastically speed up and stabilize calculations. # Second order here refer...
9930775
import tempfile from pathlib import Path import cv2 from fpdf import FPDF from PIL import Image import utils marker_ids = list(range(34, 38)) receptacle_width_mm = 150 padding_mm = 4 line_width = 5 dash_length = 10.15 output_dir = 'printouts' pdf_name = 'trash-receptacle.pdf' orientation = 'L' marker_params = utils.g...
9930784
import os import json import numpy as np from PIL import Image import torch import copy from torch.utils.data import Dataset from torchvision import transforms def get_metadata(dataset_name): if dataset_name == 'pascal': meta = { 'num_classes': 20, 'path_to_dataset': 'data/pascal', ...
9930789
from datetime import date, datetime, timedelta from typing import Any, Optional from jsonclasses import jsonclass, types @jsonclass class SuperDateTime: dtbs: Optional[datetime] = types.datetime.tobosec stbs: Optional[Any] = types.any.tobosec dtbm: Optional[datetime] = types.datetime.tobomin stbm: Opt...
9930792
import attr from .function_dispatch import FunctionDispatch from ._compat import singledispatch, lru_cache @attr.s class _DispatchNotFound(object): """ a dummy object to help signify a dispatch not found """ pass class MultiStrategyDispatch(object): """ MultiStrategyDispatch uses a combination ...
9930798
import os import sys sys.path.append(os.path.join(os.getcwd().split('xtraderbacktest')[0],'xtraderbacktest')) import modules.other.logg import logging import modules.common.scanner import modules.other.sys_conf_loader as sys_conf_loader import modules.common.technical_indicators as ti class Bot(modules.common.scanner....
9930804
import warnings from amuse.datamodel.base import * warnings.warn("amuse.support.data.base has moved to amuse.datamodel.base", DeprecationWarning)
9930825
import numpy import pytest from chainer import cuda import chainer_chemistry def r2_score(pred, true, sample_weight=None, multioutput="uniform_average", ignore_nan=False): pred = cuda.to_cpu(pred) true = cuda.to_cpu(true) diff = pred - true dev = true - numpy.mean(true, axis=0) if i...
9930841
import unittest from conans.model.info import ConanInfo info_text = '''[settings] arch=x86_64 build_type=Debug compiler=gcc compiler.libcxx=libstdc++11 compiler.version=5.2 os=Linux [requires] bzip2/1.Y.Z zlib/1.Y.Z [options] fPIC=True header_only=False shared=False [ful...
9930850
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from common import MayanAppConfig, menu_setup, menu_object from navigation import SourceColumn from .classes import Namespace, Setting from .links import link_namespace_detail, link_namespace_list from .widgets import set...
9930879
from collections import OrderedDict from enum import Enum, unique import sys import re import copy thisModule = sys.modules[__name__] supportedClassType = [ 'RAILModelElement', # Base-type element, shouldn't be used by itself 'RAILModelInfo', # Simple single-element data type, store...
9930883
from .video_cnn import VideoCNN import torch import torch.nn as nn import random from torch.cuda.amp import autocast, GradScaler class VideoModel(nn.Module): def __init__(self, args, dropout=0.5): super(VideoModel, self).__init__() self.args = args self.video_cnn = Vi...
9930900
from __future__ import print_function from .base import TestBase from ..core import MemoryBuffer from ..core import PassRegistry from ..core import Context from ..core import Module from ..core import Enums from ..core import OpCode from ..bit_reader import parse_bitcode class TestCore(TestBase): def test_enumera...
9930910
description = 'pressure sensors connected to the chambers' group = 'lowlevel' devices = dict( chamber_CB = device('nicos.devices.generic.ManualMove', description = 'pressure sensor connected to the CB', default = 1.7e-6, abslimits = (0, 1000), pollinterval = 10, maxage = 12...
9930935
import sys with open(sys.argv[1],"r") as f: codelines = f.readlines() with open(sys.argv[2],"r") as f: oldlines = f.readlines() with open(sys.argv[2],"w") as f: for line in oldlines: if "<***INSERT_CODE***>" in line: for i,codeline in enumerate(codelines): f.write(str(...
9930942
from abc import ABC from abc import abstractmethod class BaseEngine(ABC): r"""Base class for all engines. It defines the training and evaluation process. """ def __init__(self, config, **kwargs): self.config = config for key, value in kwargs.items(): se...
9931030
from .core import FunctionExpression FUNCTION_LISTING = { "utcyear": "returns the year for a given date input, in UTC time", "indexof": "returns the first index of an element (for array inputs) or substring (for string inputs) e.g., `indexof(\"visualization\", \"i\") == 1", "upper": "transforms a string to uppe...
9931048
import os import lycanthropy.sql.interface def find(acid): config = lycanthropy.sql.interface.filterBuild({'acid': acid})[0] campaign = config['campaign'] return campaign
9931055
import sys import configparser apiKey = sys.argv[1] iniFile = "../halite.ini" parser = configparser.ConfigParser() parser.read(iniFile) parser["hce"]["apiKey"] = str(apiKey) parser.write(open(iniFile, "w"))
9931063
import os import re from modules import site_config def generate_subdirectory(): """ Build website to subdirectory """ if site_config.args.subdirectory: replace() allowed_in_link = "".join(list(map(lambda s: s.strip(), [ " - ", " ? ", " \w ", " \\ ", " $ ",...
9931115
from unittest import TestCase import numpy as np import matplotlib.pyplot as plt from soundsig.basis import RadialBasis1D class TestBasis(TestCase): def setUp(self): pass def tearDown(self): pass def test_radial_basis(self): nsamps = 500 x = np.random.rand(nsamps) ...
9931151
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument path = IN[0] compact = IN[1] n...
9931256
import os import copy import torch from abc import ABC from ray import tune from ignite import utils from ignite import engine from ignite import distributed from torch.utils import data from torch.utils import tensorboard from quince.library import datasets class BaseModel(ABC): def __init__(self, job_dir, ...
9931268
from __future__ import annotations from collections import defaultdict from dataclasses import dataclass, astuple from enum import IntEnum from functools import reduce from itertools import product from math import sqrt from typing import Generator, NamedTuple import numpy as np from tool.runners.python import Submis...
9931269
from .pybibs import read_file from .pybibs import write_file from .pybibs import read_string from .pybibs import read_entry_string from .pybibs import write_string
9931316
from django.apps import AppConfig class IdentificationConfig(AppConfig): name = 'apps.identification'
9931351
showBox = True; def overrideEventReceiver(receiver, terrain, skybox, skydome) : Terrain = terrain; Skybox = skybox; Skydome = skydome; Skybox.setVisible(True); Skydome.setVisible(False); def OnEvent(me, event) : global showBox; if event.EventType == irr.EET_KEY_INPUT_EVENT and not event.KeyInp...
9931360
import numpy as np import utils class OmniglotExchSeqDataIterator(object): def __init__(self, seq_len, batch_size, set='train', valid_split=False, rng=None, augment=True, infinite=True): (x_train, y_train), (x_test, y_test), valid_classes = utils.load_omniglot() if set == 'train': s...
9931372
from pylearn2.models.mlp import MLP class Autoencoder(MLP): """ An MLP whose output domain is the same as its input domain. """ def get_target_source(self): return 'features'
9931396
import pytest from starlette.responses import PlainTextResponse from bocadillo import App, HTTPError class ASGIMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): await self.app(scope, receive, send) def test_asgi_middleware(app: App, client)...
9931410
import ai2thor.controller from agent.environment.environment import Environment class ThorEnvironment(Environment): def __init__(self, scene_name = 'FloorPlan28', unity_path = None, **kwargs): super(ThorEnvironment, self).__init__() self.controller = ai2thor.controller.Controller() self.con...
9931426
import imageio from PIL import Image, ImageSequence from schafkopf.players.mc_tree import MCTree from schafkopf.players.mc_node import MCNode from schafkopf.players.uct_player import UCTPlayer from schafkopf.tournaments.game_states_trick_play import sample_game_states def make_gif(filenames, duration, outputname): ...
9931442
import FWCore.ParameterSet.Config as cms # Cambridge-Aachen top jet producer parameters # $Id CMSBoostedTauSeedingParameters = cms.PSet( useCMSBoostedTauSeedingAlgorithm = cms.bool(True), subjetPtMin = cms.double(10.0), # minimum subjet pt muMin = cms.double(0.0), # minimum mass drop muMax = cms...
9931452
import torch import torch.nn as nn class Env(): def __init__(self, x, node_embeddings): super().__init__() """ depot_xy: (batch, 2) customer_xy: (batch, n_nodes-1, 2) --> self.xy: (batch, n_nodes, 2), Coordinates of depot + customer nodes demand: (batch, n_nodes-1) node_embeddings: (batch, n_nodes, em...
9931518
from unittest import TestCase from ColorSchemeUnit.lib.runner import _color_test_params_compiled_pattern as pattern class TestColorTestParamsPattern(TestCase): def test_invalid(self): self.assertIsNone(pattern.match('')) self.assertIsNone(pattern.match('foo')) self.assertIsNone(pattern.m...
9931570
import pytest from gitlabform.gitlab import AccessLevel from tests.acceptance import ( run_gitlabform, ) @pytest.fixture(scope="class") def two_members_in_other_group(gitlab, other_group, make_user): outsider_user1 = make_user(add_to_project=False) outsider_user2 = make_user(add_to_project=False) gi...
9931575
from typing import Dict from rio_tiler.types import ColorMapType mtbs_colormaps: Dict[str, ColorMapType] = { "mtbs-severity": { 0: (0, 0, 0, 0), 1: (0, 100, 0, 255), 2: (127, 255, 212, 255), 3: (255, 255, 0, 255), 4: (255, 0, 0, 255), 5: (127, 255, 0, 255), ...
9931609
import os import subprocess from setuptools import setup, find_packages from distutils import log import sys BUILD_CUAEV_ALL_SM = '--cuaev-all-sms' in sys.argv if BUILD_CUAEV_ALL_SM: sys.argv.remove('--cuaev-all-sms') FAST_BUILD_CUAEV = '--cuaev' in sys.argv if FAST_BUILD_CUAEV: sys.argv.remove('--cuaev') # ...
9931613
import context # augment system path to make imports work from vod_converter import converter def test_convert_labels(): assert [{'detections': [ {'label': 'person'}, {'label': 'person'}, {'label': 'person'}, {'label': 'rhinoZaurus'} ]}] == \ converter.convert_label...
9931662
import math import argparse import torch import numpy as np import h5py from torchvision import transforms def get_strand_color(is_rev): """ Get color for forward and reverse reads :param is_rev: True if read is reversed :return: """ is_rev = int(math.ceil(is_rev)) if is_rev == 254: ...
9931671
from __future__ import unicode_literals import pytest # noqa # Grammar from arpeggio import ZeroOrMore, OneOrMore, UnorderedGroup, \ ParserPython, NoMatch, EOF def test_zeroormore_with_separator(): def grammar(): return ZeroOrMore(['a', 'b'], sep=','), EOF parser = ParserPython(grammar, reduce...
9931726
from unittest import mock import pytest from paasta_tools import spark_tools def test_get_webui_url(): with mock.patch("socket.getfqdn", return_value="1.2.3.4"): assert spark_tools.get_webui_url("1234") == "http://1.2.3.4:1234" @pytest.mark.parametrize( "cmd,expected", [ ("spark-shell"...
9931745
import xmltodict import pytest from jmeter_api.thread_groups.ultimate_thread_group.elements import UltimateThreadGroup, ThreadGroupAction from jmeter_api.basics.utils import tag_wrapper class TestUltimateThreadGroupArgs: class TestSchedule: def test_check(self): with pytest.raises(TypeError):...
9931758
import time import pytest from helpers.cluster import ClickHouseCluster from helpers.test_tools import assert_eq_with_retry SETTINGS = "SETTINGS min_replicated_logs_to_keep=3, max_replicated_logs_to_keep=5, cleanup_delay_period=0, cleanup_delay_period_random_add=0" def fill_nodes(nodes): for node in nodes: ...
9931766
from Agent import Agent GAME = 'CartPole-v0' MAX_EPISODES = 100 def main(): A = Agent(GAME) A.run(MAX_EPISODES) if __name__ == '__main__': main()
9931768
import pandas as pd from .parts.utils import * from model import config from cadCAD.engine import ExecutionMode, ExecutionContext,Executor from cadCAD import configs def get_M(k, v): if k == 'sim_config': k, v = 'M', v['M'] return k, v config_ids = [ dict( get_M(k, v) for k, v in config...
9931771
from collections import OrderedDict from underscore import _ from mangopi.helper.decorators import memoize from mangopi.helper.util import Util class MetaSite(object): def __init__(self, modules=[], options={}): self.modules = modules self.options = options @memoize def series(self, nam...
9931860
import os import time from unittest.mock import MagicMock, patch from flask import g, url_for import pytest from tests.astronomer.flask_appbuilder.conftest import AUDIENCE from astronomer.flask_appbuilder.security import AirflowAstroSecurityManager, timed_lru_cache @pytest.mark.usefixtures('client_class', 'run_in_t...
9931986
from transformers import GPT2LMHeadModel, GPT2Model import torch class GPT2LMHeadLogit(GPT2LMHeadModel): def __init__(self, config): super().__init__(config) self.d_out = config.vocab_size def __call__(self, x): outputs = super().__call__(x) logits = outputs[0] #[batc...
9931987
import pytest import subprocess import os import random import automates.model_assembly.networks as networks from automates.model_assembly.networks import GroundedFunctionNetwork from automates.program_analysis.GCC2GrFN.gcc_ast_to_cast import GCC2CAST GCC_10_BIN_DIRECTORY = "/usr/local/gcc-10.1.0/bin/" GCC_PLUGIN_IMA...
9931989
import torch import torch.testing from util import cubicspline torch.manual_seed(0) def test_interp(): n = 10 c = 3 d = 4 t = 5 x = torch.linspace(0, 1, steps=n) x = x[None, :].repeat((c, 1)) y = torch.randn(c, d, n) xs = x[:, t].reshape(c, 1, 1) ind = torch.tensor(t, dtype=torch...
9931998
from sqlalchemy import text from app import db _doaj_issns = [] def doaj_issns(): global _doaj_issns if not _doaj_issns: # remove hyphens here so don't have to do it every time doaj_issns_with_hyphens = db.engine.execute( text(""" select issn, license, year from ...
9932005
from typing import List, Type import torch import torch.nn as nn class MLP(nn.Module): """ The multilayer perceptron (MLP) :param sizes: (List[int]) The network size :param activation_function: (Type[nn.Module]) The activation function :param output_activation_function: (Type[nn.Module]) The out...
9932031
from .series import ( BaseSeriesValidator, IntegerSeriesValidator, FloatSeriesValidator, CharSeriesValidator, LambdaSeriesValidator ) class ColumnValidatorMixin(BaseSeriesValidator): def __init__(self, label, *args, **kwargs): super(ColumnValidatorMixin, self).__init__(*args, **kwargs)...
9932062
import json import logging from datetime import datetime from typing import Dict import pika from src.data_store.mongo.mongo_api import MongoApi from src.data_store.redis import Keys from src.data_store.stores.store import Store from src.message_broker.rabbitmq.rabbitmq_api import RabbitMQApi from src.utils.constants...
9932113
from torch import nn from torchvision.models.resnet import ResNet, Bottleneck from torchvision.models.utils import load_state_dict_from_url class ResNet50Encoder(ResNet): def __init__(self, pretrained: bool = False): super().__init__( block=Bottleneck, layers=[3, 4, 6, 3], ...
9932119
from bluedot import BlueDot from signal import pause class BlueDotButton: def swiped(swipe): if swipe.up: print("Blue Dot Swiped Up") elif swipe.down: print("Blue Dot Swiped Down") elif swipe.left: print("Blue Dot Swiped Left") elif ...
9932169
def power(x, y): "Caculate x ** y" n = 1 while y: if y & 1: n *= x y >>= 1 x *= x return n def test(): assert (2 ** 5 == power(2, 5)) assert (3 ** 4 == power(3, 4)) assert (5 ** 2 == power(5, 2)) assert (1 ** 0 == power(1, 0)) assert (0 ** 0 == power(0, 0)) i...
9932184
from datetime import datetime from pathlib import Path from smart_open import open from experiments.deep_learning_with_pytorch.surnames import * from transfer_nlp.plugins.config import register_plugin, ExperimentConfig from transfer_nlp.plugins.reporters import ReporterABC from transfer_nlp.runner.experiment_runner i...
9932302
if __name__ == '__main__': import argparse import asyncio import json import sys import tda import unittest from tda.streaming import StreamClient tda.debug.enable_bug_report_logging() import logging logging.getLogger('').addHandler(logging.StreamHandler()) class Functiona...
9932321
from flask import Flask, render_template, Response import sys import pickle import socket import zmq app = Flask(__name__) port = "6666" if len(sys.argv) > 1: port = sys.argv[1] int(port) if len(sys.argv) > 2: port1 = sys.argv[2] int(port1) # Socket to talk to server context = zmq.Context() socket...
9932324
import numpy as np import vtk def swap_labels(labels): unique_label = np.unique(labels) new_label = range(len(unique_label)) for i in range(len(unique_label)): label = unique_label[i] newl = new_label[i] labels[labels==label] = newl return labels def swap_labels_back(labels,...
9932363
import unittest from rime.util import class_registry class HogeBase(object): pass class HogeImpl(HogeBase): pass class Piyo(object): pass class TestClassRegistry(unittest.TestCase): def test_add(self): registry = class_registry.ClassRegistry(HogeBase) registry.Add(HogeBase, 'Ho...
9932399
import re from typing import Any from statham.schema.exceptions import ValidationError from statham.schema.validation.base import Validator from statham.schema.validation.format import format_checker class Pattern(Validator): """Validate that string values match a regular expression.""" types = (str,) k...
9932414
if sm.hasQuest(31348): # Colossal Clean Up 4 sm.warpInstanceIn(924030000) # Hidden Street : Stone Colossus elif sm.hasQuestCompleted(31348): # Colossal Clean Up 4 sm.warp(240092400) # Stone Colossus Torso 3 else: sm.chat("This path is blocked by a mysterious presence.")
9932440
import argparse import logging import sys import time import math from torchvision import datasets, transforms import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.autograd import Variable from sklearn.metrics import roc_auc_score, f1_score, ro...
9932478
class EasyHomework: def determineSign(self, A): c = True for e in A: if e < 0: c = not c elif e == 0: return "ZERO" return "POSITIVE" if c else "NEGATIVE"
9932511
from argparse import ArgumentParser import numpy as np argparser = ArgumentParser('test sentence generator') argparser.add_argument('--keyword', default='') argparser.add_argument('--switch', action='store_true') argparser.add_argument('--best', action='store_true') argparser.add_argument('--cfg', default='') ar...
9932521
import argparse import chainer import matplotlib.pyplot as plt import numpy as np from siam_rpn.siam_rpn import SiamRPN from siam_rpn.siam_rpn_tracker import SiamRPNTracker from siam_rpn.siam_mask_tracker import SiamMaskTracker from siam_rpn.general.vot_tracking_dataset import VOTTrackingDataset from siam_rpn.genera...
9932527
import os import torch as th import torch.nn as nn import tqdm class PBar(object): def __enter__(self): self.t = None return self def __call__(self, blockno, readsize, totalsize): if self.t is None: self.t = tqdm.tqdm(total=totalsize) self.t.update(readsize) d...
9932556
import logging from .base_records_test import BaseRecordsIntegrationTest from ..records_datetime_fixture import RecordsDatetimeFixture from ..datetime_cases import ( DATE_CASES, DATETIMETZ_CASES, DATETIME_CASES, TIMEONLY_CASES, create_sample, SAMPLE_HOUR, SAMPLE_MINUTE, SAMPLE_SECOND ) from records_mover.record...
9932591
import requests from waste_collection_schedule import Collection # type: ignore[attr-defined] from waste_collection_schedule.service.ICS import ICS TITLE = "Stadtreinigung Hamburg" DESCRIPTION = "Source for Stadtreinigung Hamburg waste collection." URL = "https://www.stadtreinigung.hamburg" TEST_CASES = { "Hambur...
9932595
from django.db import models from users.models import User from org.models import Org # Create your models here. class QueryRoom(models.Model): org = models.ForeignKey(Org,on_delete=models.CASCADE) for_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.id}-{...
9932597
import errno import os import sys import urlparse from . import user_settings def ensure_directory(path): try: os.makedirs(path) except OSError, os_error: if os_error.errno != errno.EEXIST: raise return path def find_project_root(): '''Finds the project root, where uploaded...
9932604
import unittest import numpy as np import numpy.testing as npt from doatools.model.arrays import UniformLinearArray from doatools.model.sources import FarField1DSourcePlacement from doatools.estimation.esprit import Esprit1D import itertools class TestEsprit(unittest.TestCase): def setUp(self): self.wavel...
9932619
import os import torch import torch.nn.functional as F import numpy as np from enum import Enum import sys import math class MetaLearningState(Enum): META_TRAIN = 0 META_TEST = 1 class ValidationAccuracies: """ Determines if an evaluation on the validation set is better than the best so far. In ...
9932621
from __future__ import division, print_function, unicode_literals """ Use this module in the same way as Python's SimpleHTTPServer: python -m RangeHTTPServer [port] The only difference from SimpleHTTPServer is that RangeHTTPServer supports 'Range:' headers to load portions of files. This is helpful for doing local...
9932691
import argparse import torch import torch.nn as nn from simplecv.module.model_builder import make_model from simplecv.data.data_loader import make_dataloader from simplecv.opt.optimizer import make_optimizer from simplecv.opt.learning_rate import make_learningrate from simplecv.util import config from simplecv.core imp...
9932704
from bcbio.ngsalign import alignprep class TestMisc(object): """Additional unit test cases to run regularly to confirm code logic. """ def test_align_split_size(self): """Checks on logic for estimating align split size. """ assert alignprep._pick_align_split_size(10, 5, 20, 50) == ...