id
stringlengths
3
8
content
stringlengths
100
981k
11423916
import argparse import asyncio import contextlib import logging import random import aiosip from util import Registration sip_config = { 'srv_host': '127.0.0.1', 'srv_port': 6000, 'realm': 'XXXXXX', 'user': None, 'pwd': '<PASSWORD>', 'local_host': '127.0.0.1', 'local_port': random.randint...
11423917
from .exception_hook import ExceptionHook from typing import Iterator, List, TypeVar, Iterable, Dict import random from itertools import zip_longest, islice A = TypeVar('A') def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]: """ Takes an iterator and batches the invididual instanc...
11423919
import json import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from PIL import ImageOps from torchvision import datasets, transforms import activations import models import visualize AFS = list(activations.__class_dict__.keys()) MODELS = list(m...
11423927
extensions = dict( set_required_params=""" parms$training_frame <- training_frame args <- .verify_dataxy(training_frame, x, y) parms$ignored_columns <- args$x_ignore parms$response_column <- args$y """ ) doc = dict( preamble=""" H2O ANOVAGLM is used to calculate Type III SS which is used to evaluate the co...
11423977
import requests from e2etests.config import url def test_version(record_property): version_obj = requests.get(url + '/version').json() record_property('version', version_obj) assert 'python' in version_obj assert 'entityservice' in version_obj assert 'anonlink' in version_obj def test_status(r...
11423979
import os from kivy.animation import Animation from kivy.clock import Clock from kivy.core.window import Window from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import NumericProperty from kivymd.uix.floatlayout import MDFloatLayout Window.size = (800, 600) Window.minimum_width, Window.m...
11423994
import platform from pkg_resources import get_distribution from sunpy.extern.distro import linux_distribution from sunpy.util.sysinfo import find_dependencies __all__ = ['system_info'] def system_info(): """ Display information about your system for submitting bug reports. """ base_reqs = get_distr...
11423998
import numpy as np class linear(object): def __init__(self, basis, params=None, bias=None): self.basis = basis self.nbasis = basis.nbasis self._init_params = params self.bias = bias self.params = params if params is None: self.params = np.zeros(self.nba...
11424036
def check_size(x, dim): if not len(x)==dim: raise Exception('The data should be a two-dimensional array') else: return def print_result(result): msg = '' if result == 1: print() msg = 'Result is conclusive: B variant is winner!' elif result == -1: print() ...
11424040
import unittest import numpy as np from goldilocks import Goldilocks from goldilocks.strategies import BaseStrategy, NucleotideCounterStrategy ################################################################################ # NOTE Tests following do not test the correctness of regions located by # Goldilocks bu...
11424043
from scrapy.spiders import Spider from scrapy.http import Request from scrapy.selector import Selector from crawler.items import ProxyIPItem class XiciSpider(Spider): name = "xici" allowed_domains = ["xicidaili.com"] start_urls = [ "http://www.xicidaili.com/nn", "http://www.xicidaili.com/nn...
11424101
import os import re from powerline.bindings.vim import buffer_name NERD_TREE_RE = re.compile(b'NERD_tree_\\d+') def nerdtree(matcher_info): name = buffer_name(matcher_info) return name and NERD_TREE_RE.match(os.path.basename(name))
11424132
import time from typing import Callable, Tuple, List, Optional, Any from kubernetes.client.rest import ApiException # time to sleep between retries SLEEP_TIME = 2 # no timeout (loop forever) INFINITY = -1 def _current_milliseconds() -> int: return int(round(time.time() * 1000)) def wait( fn: Callable, ...
11424143
import torch import numpy as np def net_param_num(model): num=0 for i in model.parameters(): v=1 for j in i.shape: v*=j num+=v return num def multi_class_accuracy(target, preds_score): top1=0. top3=0. top5=0. top10=0. preds_score = preds_score.detach().cpu().numpy() target = target.cpu().numpy() ...
11424172
import logging import grpc from client import Client from common import IntegrationTestConfig from util import load_test_config from pool import Pool from workflow import Workflow from google.protobuf import json_format from peloton_client.pbgen.peloton.api.v0 import peloton_pb2 as peloton from peloton_client.pbgen....
11424178
from dataclasses import dataclass from typing import List, Union from nlp_gym.envs.common.observation import BaseObservation, BaseObservationFeaturizer from abc import abstractmethod import torch import copy class ObservationFeaturizer(BaseObservationFeaturizer): @abstractmethod def init_on_reset(self, input...
11424204
from firetail.lib import db from firetail.utils import make_embed import time import datetime import asyncio import json class Notifications: def __init__(self, bot): self.bot = bot self.session = bot.session self.config = bot.config self.logger = bot.logger self.loop = asy...
11424229
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex import libtbx.load_env import sys from six.moves import range def extend_sys_path(): sys.path.insert(0, libtbx.env.under_build("scitbx/array_family/boost_python")) def exercise_std_vector_conversions(verbose=0)...
11424232
import tacoma as tc ec = tc.flockwork_P_varying_rates([],10,[0.4,0.8], 600,[ (0, 1.), (300,2.) ], 600,seed=25456) print(ec.edges_out[:5]) print(ec.edges_in[:5]) import numpy as np ec = tc.flockwork_P_varying_rates_for_each_node([], 10, ...
11424270
import random from copy import copy import torch import torch.nn as nn import torch.nn.functional as func from .connection import ( AbstractStructure, ConnectionStructure, SubgraphStructure, ConstantStructureMixin, ConstantStructure, ScatterStructure, MessageMode ) def to_graph(batched_tensor): squashed_tens...
11424284
from typing import Any, List, NamedTuple, Optional, Set, Tuple, cast import EoEfunc as eoe import vapoursynth as vs from havsfunc import LSFmod from lvsfunc.kernels import Bicubic from lvsfunc.types import Range from lvsfunc.util import replace_ranges from vardefunc.aa import Eedi3SR, Nnedi3SS, upscaled_sraa from vard...
11424300
from utils.metrics import displacement_error, final_displacement_error, cal_l2_losses, cal_fde, cal_ade, \ l2_loss, miss_rate, linear_velocity_acceleration_1D from utils.absolute import relative_to_abs from utils.adj_matrix import compute_adjs_distsim, compute_adjs_knnsim, compute_adjs from utils.losses import l2_e...
11424311
import json import logging logging.basicConfig(level=logging.INFO, format='') class Logger: def __init__(self): self.entries = {} def add_entry(self, entry): self.entries[len(self.entries) + 1] = entry def __str__(self): return json.dumps(self.entries, sort_keys=True, indent=4)
11424353
import pytest import responses from box import Box, BoxList @pytest.fixture(name="pubse_vips") def fixture_pubse_vips(): return { "zscaler.net": { "continent : apac": { "city :_auckland": [ { "range": "172.16.31.10/24", ...
11424358
from typing import Callable from OpenGL.GL import * from robot.common import logger from .exceptions import UniformArraySizeError, UniformTypeError, UniformSizeError import robot.visual.opengl.decorators as decorators GL_TYPE_UNIFORM_FN = { GL_INT: decorators.primative(glUniform1iv, int), GL_FLOAT: ...
11424372
from cipher_description import CipherDescription # State # 0 4 8 12 # 1 5 9 13 # 2 6 10 14 # 3 7 11 15 sbox = [0xB, 0xF, 3, 2, 0xA, 0xC, 9, 1, 6, 7, 8, 0, 0xE, 5, 0xD, 4] invsbox = [11, 7, 3, 2, 15, 13, 8, 9, 10, 6, 4, 0, 5, 14, 12, 1] shuffle = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11] shufflei = ra...
11424376
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: prev, curr = cost[0], cost[1] for i in range(2, len(cost)): prev, curr = curr, cost[i] + min(prev, curr) return min(prev, curr)
11424407
import requests import time import asyncio import aiohttp from timeit import default_timer # 第六節第一小節例子 async def func1(): print("func1") await asyncio.sleep(1) print("func1 end") async def func2(): print("func2") await asyncio.sleep(1) print("func2 end") async def gatherwait(): task = [...
11424468
import subprocess import unittest import os import re from unittest import TestCase url = 'https://front' cores = os.cpu_count() def _bytes_2_lines(output: bytes): lines = [] for each_line in output.split(b'\n'): line = each_line.decode('utf-8').strip() print(line) lines.append(line) return lines ...
11424474
import pandas as pd from pymatgen.ext.matproj import MPRester import os import matplotlib.pyplot as plt import numpy as np import scipy.stats import matplotlib.gridspec as gridspec filename = r'C:\Users\taylo\Google Drive\teaching\5050 Materials Informatics\apikey.txt' def get_file_contents(filename): try: ...
11424480
import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn from torch.nn import GRU def truncate_param(param, value, eps=1e-6): param_copy = param.clone() mean = torch.mean(param) param_copy[torch.abs(param_copy) >= value] =\ torch.rand_like(param_copy[torch.abs(param_co...
11424482
from flask_restful import Resource from flask import request from db import db from schemas.staff_tenants import StaffTenantSchema from models.staff_tenant_link import StaffTenantLink from utils.authorizations import admin_required class StaffTenants(Resource): @admin_required def patch(self): data = ...
11424547
import torch.nn as nn import torch import torch.nn.functional as F from avalanche.models.simple_mlp import SimpleMLP class DQNModel(nn.Module): def __init__(self): super().__init__() def forward(x: torch.Tensor, task_label=None): raise NotImplementedError() @torch.no_grad() def get_...
11424580
import pytest import tensorflow as tf from tensorflow.python.keras import layers, models from barrage import model def simple_net(dense_dim=5, input_dim=4, output_dim=3, **params): net = models.Sequential() net.add(layers.Input(shape=(input_dim,), name="input")) net.add(layers.Dense(dense_dim, activatio...
11424581
from sklearn import svm, tree from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from typing import Dict, Any import os import shutil import yaml import numpy as np import sys sys.path.append(os.path.abspath("..")) from constants import PREDICTION_TYPE, MODEL_RUNTIME, DATA_TYPE impo...
11424593
from ..helpers import IFPTestCase from intficpy.thing_base import Thing from intficpy.things import ( Surface, Container, ) class TestPlayerGetOn(IFPTestCase): def setUp(self): super().setUp() self.surface = Surface(self.game, "bench") self.start_room.addThing(self.surface) d...
11424629
import esphome.codegen as cg import esphome.config_validation as cv from esphome.const import CONF_ID, CONF_MODEL from esphome.components import esp32_ble from esphome.core import CORE from esphome.components.esp32 import add_idf_sdkconfig_option AUTO_LOAD = ["esp32_ble"] CODEOWNERS = ["@jesserockz"] CONFLICTS_WITH = ...
11424635
import socket, os import tempfile import subprocess # Global variables HostAddress = "localhost" HostPort = 48879 Protocol = "tcp" # Helper function to check if a number is valid def isNumber(givenObject): try: int(givenObject) return True except: return False def getSocket(): glo...
11424655
import torch import torch.nn as nn from zerovl.utils import Registry, ENV LOSS = Registry('loss') def build_loss(name, param): if hasattr(nn, name): if name == 'CrossEntropyLoss' and 'weight' in param: param['weight'] = torch.tensor(param['weight'], dtype=torch.float32) if name == 'C...
11424683
from .__version__ import __version__ from ._middleware import MessagePackMiddleware __all__ = ["__version__", "MessagePackMiddleware"]
11424728
import sys import numpy as np from matplotlib import pylab as plt from sklearn.decomposition import PCA from data.dataimport import import_data from encoders.baseencoder import AbstractEncoder if __name__ == '__main__': if len(sys.argv) != 3: print("Usage <encoderPkl> <dataset.json.gz>") sys.exit...
11424773
class Solution(object): def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ result = [] for h in range(12): for m in range(60): if bin(h).count("1") + bin(m).count("1") == num: result.append('%d:%02d...
11424777
import certificate import py.test import datetime import time def disabled_test_make_certificate(): """Generate a certificate""" c = certificate.CertificatePrinter(title="Test Certificate") c.add_params({"@@NAME@@":"A very precise data set", "@@DATE@@":datetime.datetime.now().isoformat()[...
11424793
from rest_framework.renderers import JSONRenderer class CustomJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): response_data = {'message': '', 'errors': [], 'data': data, 'status': 'success'} # getattr(renderer_context.get('view').get_serialize...
11424812
from dexy.filter import Filter from tests.utils import runfilter from nose.exc import SkipTest from nose.tools import raises from dexy.utils import s from dexy.utils import split_path from dexy.utils import iter_paths def test_iter_path(): full_path = "/foo/bar/baz" expected_paths = { 0 : '/', ...
11424868
import os import pytsk3 import sys import pyewf class EWFImgInfo(pytsk3.Img_Info): """EWF Image Format helper class""" def __init__(self, ewf_handle): self._ewf_handle = ewf_handle super(EWFImgInfo, self).__init__(url="", type=pytsk3.TSK_IMG_TYPE_EXTERNAL) def close(self): self._ew...
11424882
from django.db import models class Course(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=50, verbose_name="课程名") desc = models.CharField(max_length=300, verbose_name=u"课程描述") degree = models.CharField( choices=(("primary", '初级'), ("middle", "中级"...
11424905
import numpy as np import matplotlib.pyplot as plt import auralib as aura from numpy.fft import fftfreq, fft, ifft, fftshift, ifftshift from scipy.interpolate import interp1d import scipy as sp def get_traces_for_matching_filter(basefile, monfile, step): buf1 = aura.segy.Segy(basefile) buf2 = aura.segy.Segy(m...
11424938
import numpy as np import cv2 import os from PIL import Image def resize(img, new_size=(48,48)): return img.resize(new_size) def convert2grayscale(img): return img.convert('LA') def create_dilation(img, kernel_size=2, iterations=2): kernel = np.ones((kernel_size, kernel_size), np.uint8) *0.5 dilati...
11424951
import pytest from polog.handlers.file.rotation.parser import Parser from polog.handlers.file.file_dependency_wrapper import FileDependencyWrapper class RulesElectorMock: def __init__(self, file): pass def choose(self, source): return source def test_parse_single_rule_with_mock(filename_for_...
11424971
import os import cv2 import numpy as np from scipy.special import softmax from Operators.DummyAlgorithmWithModel import DummyAlgorithmWithModel from Utils.GeometryUtils import force_convert_image_to_bgr, resize_with_height, pad_image_with_specific_base from Utils.InferenceHelpers import TritonInferenceHelper class C...
11424990
import sys import logging import pluggy from pkg_resources import iter_entry_points, DistributionNotFound from .models import PluginRegistry from .utils import parse_pkg_metadata logger = logging.getLogger(__name__) class FlaskshopPluginManager(pluggy.PluginManager): def __init__(self, project_name, implprefi...
11425003
from office365.onenote.operations.onenote_operation_error import OnenoteOperationError from office365.onenote.operations.operation import Operation class OnenoteOperation(Operation): """The status of certain long-running OneNote operations.""" @property def error(self): """The error returned by t...
11425009
import pickle import hashids from django.test import TestCase from django.utils.encoding import force_str from hashid_field import Hashid class HashidTests(TestCase): def test_integer(self): h = Hashid(5) self.assertIsInstance(h, Hashid) self.assertEqual(h.id, 5) self.assertEqual...
11425021
import click from .model import * from .console import * from ..helpers import check_console_input_config @click.group("registry", help="Docker registry actions") @click.pass_context def registry(ctx, **kwargs): pass @registry.command(help="get a summary from remote registry") @click.pass_context @click.argum...
11425066
from .configure import create_data_set_properties from ..experiment_1.generate import run from graph_io.classes.dataset_name import DatasetName def gen_run(n): DATASET_NAME = DatasetName('review_hidden_real_'+str(n)) return DATASET_NAME, lambda client: run(client, create_data_set_properties(DATASET_NAME, n)) runne...
11425090
import gevent from textwrap import dedent from jumpscale.loader import j from jumpscale.sals.chatflows.chatflows import chatflow_step from jumpscale.packages.vdc_dashboard.sals.solutions_chatflow import SolutionsChatflowDeploy, POD_INITIALIZING_TIMEOUT from jumpscale.packages.vdc_dashboard.sals.vdc_dashboard_sals impor...
11425101
import os import warnings import matplotlib import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D warnings.filterwarnings("ignore") matplotlib.use("Agg") colors = { "Car": "b", "Tram": "r", "Cyclist": "g", "Van": "c", "Truck": "m", "Pedestrian": "y", ...
11425116
import json import os from vp import geom_tools import dataset from print_progress import print_progress IMAGE_EXTENSION = 'jpg' # Pixel dimensions of the images in the dataset. IMAGE_DIMS = (1920, 1080) def load_dataset(dataset_path, show_progress_bar=True): """Loads the Toulouse vanishing point dataset. ...
11425153
import chainer def concat_variable(gx, g_input): """concatenate the inputs to a tuple of variable Inputs: None ~chainer.Variable tuple of variable Outputs: None: When both of gx and g_input is None Variable: When one is None, and the other is variable tupl...
11425191
import logging import wx def filename_repr(filenames): if filenames: if isinstance(filenames, str): filenames = [filenames] # if 'wxMSW' in wx.PlatformInfo: # does windows require separate handling for to backslash? # on os-x, if the path contains a bac...
11425193
import numpy as np from typing import List, Optional, Tuple, Union from app import crud from app.core.config import settings from app.worker_utils.metrics import spherical_mean import faiss import logging class KNN: def __init__(self, db): embeddings = crud.embedding.get_active_embeddings_by_embedding_mo...
11425196
class Pista(): def __init__ (self, nombre: str, favorita: bool, duracion: int, artista: str): #la duracion esta contemplada en segundos self.nombre = nombre self.favorita = favorita self.duracion = duracion self.artista = artista def get_informacion(self): return ...
11425210
import math import warnings import chainer import chainer.functions as F import chainer.links as L from tgan2.models.bn.categorical_conditional_batch_normalization \ import CategoricalConditionalBatchNormalization try: from chainermn.links import MultiNodeBatchNormalization except Exception: warnings.war...
11425221
import zipfile import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap BGCOLOR = '#AAAACC' background = ListedColormap([BGCOLOR]) mario = ListedColormap([BGCOLOR, 'red', 'orange', 'brown']) fire_mario = ListedColormap([BGCOLOR, 'white', 'orange', 'red']) NUL = 252 class ...
11425233
from puq import * import numpy as np def model_0(x, y): return x*x + 0.75 * y*y + 2*y + x*y - 7 def run(): # create some "experimental" data real_x = NormalPDF(5, .2) real_y = NormalPDF(3.4, .25) sigma = 0.5 num_samples = 5 x_data = np.linspace(*real_x.range, num=num_samples) y_data =...
11425252
import torch import random import numpy as np from pre_processing import * import torch.nn as nn from random import randint from PIL import Image, ImageSequence import glob from torch.utils.data.dataset import Dataset BATCH_SIZE = 2 IN_SIZE = 1024 OUT_SIZE = 1024 TRAIN_VALID_RATIO = 0.8 # train_index = random.sample(r...
11425266
from tir import Webapp import unittest class CTBA161(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup("SIGACTB", "01/01/2019", "T1", "D MG 01", "34") inst.oHelper.Program("CTBA161") ######################################### # Inclus...
11425267
import h5py as h5 import numpy as np import pandas as pd DEFAULT_COMPRESSION = 'gzip' DEFAULT_COMPRESSION_VALUE = 8 # 0 - 9 class HDFDataset(h5.File): """ Read / Write an HDF5 dataset using h5py. If HDF5 is compiled with parallel support, this class will support parallel I/O of all supported types...
11425277
from django.contrib import admin from grandchallenge.products.models import Company, Product, ProjectAirFiles admin.site.register(Company) admin.site.register(Product) admin.site.register(ProjectAirFiles)
11425328
import pytest import packerlicious.builder as builder class TestAliCloudBuilder(object): def test_required_fields_missing(self): b = builder.AliCloud() with pytest.raises(ValueError) as excinfo: b.to_dict() assert 'required' in str(excinfo.value)
11425338
import torch.nn as nn from torchvision import models from lib.rpn_util import * import torch.nn.functional as F import torch def dilate_layer(layer, val): layer.dilation = val layer.padding = val class LocalConv2d(nn.Module): def __init__(self, num_rows, num_feats_in, num_feats_out, kernel=1, padding=0...
11425341
import unittest from collections import defaultdict from tasky.stats import DictWrapper class TestDictWrapper(unittest.TestCase): def test_dict(self): d = DictWrapper({}) self.assertFalse(d) self.assertEqual(len(d), 0) self.assertNotIn('foo', d) d['foo'] = 'bar' ...
11425345
import numpy as np import pandas as pd from scipy import sparse # Errors class RootCellError(Exception): def __init__(self, message): self.message = message class NeighborsError(Exception): def __init__(self, message): self.message = message # Diffusion def diffusion_conn(adata, min_k=50,...
11425411
from distutils.core import setup, Extension from Cython.Build import cythonize import numpy import runpy cfg = runpy.run_path('../.config.py') setup( name="OpenephysTridesclousPyPlugin", include_dirs=[numpy.get_include(), cfg['PYTHON_PLUGIN_SRC_DIR']], ext_modules=cythonize( Ex...
11425435
import sys import pdb import pysam import time import re import scipy as sp import h5py import cPickle import os def parse_options(argv): """Parses options from the command line """ from optparse import OptionParser, OptionGroup parser = OptionParser() required = OptionGroup(parser, 'REQUIRED') ...
11425450
import datetime import mock from database_sanitizer.sanitizers import times class _FakeDateTime(datetime.datetime): @staticmethod def now(): return datetime.datetime(2018, 1, 1, 12, 00, 00) @mock.patch('random.randint', return_value=42005) @mock.patch.object(datetime, 'datetime', _FakeDateTime) de...
11425464
import getpass import json import os from io import StringIO from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryFile import pytest import yaml from Pegasus.api.errors import PegasusError from Pegasus.api.writable import Writable, _CustomEncoder, _filter_out_nones @pytest.fixture(scope="funct...
11425492
from unittest import mock from cauldron import cli from cauldron.cli.server import run as server_run from cauldron.test import support from cauldron.test.support.flask_scaffolds import FlaskResultsTest class TestServer(FlaskResultsTest): """...""" def test_execute(self): """Should execute the comman...
11425494
from interbotix_sdk.robot_manipulation import InterbotixRobot from interbotix_descriptions import interbotix_mr_descriptions as mrd import numpy as np # This script makes the end-effector perform pick, pour, and place tasks # # To get started, open a terminal and type 'roslaunch interbotix_sdk arm_run.launch robot_nam...
11425521
from enum import Enum, IntEnum class CertifiedStatus(Enum): """Enumeration that represents what can be passed in the certified_status attribute of the IServer quick search command.""" ALL = 'ALL' CERTIFIED_ONLY = 'CERTIFIED_ONLY' NOT_CERTIFIED_ONLY = 'NOT_CERTIFIED_ONLY' OFF = 'OFF' class Se...
11425550
from typing import List, Optional from pathlib import Path from dataclasses import dataclass, field from dataclasses_json import dataclass_json from cached_property import cached_property @dataclass_json @dataclass class Config(object): """ Attributes ---------- decay_rate: Decay rate of the...
11425566
from sqlalchemy_unchained.foreign_key import _get_fk_col_args from typing import * from .column import Column from .types import BigInteger def foreign_key(*args, fk_col: Optional[str] = None, primary_key: bool = False, nullable: bool = False, ondelete:...
11425593
import json import os import sys # https://github.com/oasis-open/cti-pattern-validator # Tested with stix2-patterns 1.1.0, antlr4-python2-runtime 4.7.2 from stix2patterns.validator import run_validator def validate_pattern(pb, oid, pattern): # Additional logic could be added here errors = run_validator(patte...
11425603
from video_reid_performance import compute_video_cmc_map from update_module import get_vision_record_dist, visual_affinity_update, trajectory_distance_update, norm_data from eval_tools import get_signal_match_cmc from copy import deepcopy import numpy as np class RecurrentContextPropagationModule(object): ...
11425623
import math import numpy as np import sys resolutionHor = 256 resolutionVert = 256 scale = 20 # fill cells for cell noise cells0 = np.random.random_sample((scale , scale , scale , 3)) cells1 = np.random.random_sample((scale*2, scale*2, scale*2, 3)) cells2 = np.random.random_sample((scale*4, scale*4, scale*4, 3)) ...
11425627
import torch import torch.nn as nn import torch.nn.functional as F def discriminator_loss(d_real, d_fake, eps): return -torch.mean(torch.log(d_real+eps)+torch.log(1-d_fake+eps)) def adverserial_loss(d_fake, eps): return -torch.mean(torch.log(d_fake+eps)) class OnlineTripletLoss(nn.Module): """ Onl...
11425637
from oscar.apps.dashboard.catalogue import views as catalogue_admin_views from .formsets import ProductAttributesFormSet from .forms import ProductForm, CategoryForm class ProductClassCreateView(catalogue_admin_views.ProductClassCreateView): product_attributes_formset = ProductAttributesFormSet class ProductCla...
11425664
import itertools import unittest from functools import partial from itertools import cycle import numpy as np import pandas as pd import torch import torch.nn.functional as F from mup.coord_check import get_coord_data from mup.optim import MuAdam, MuSGD from mup.shape import get_infshapes, get_shapes, make_base_shapes...
11425705
import datetime from ftc.management.commands._base_scraper import CSVScraper from ftc.models import Organisation class Command(CSVScraper): name = "mutuals" allowed_domains = ["fcastoragemprprod.blob.core.windows.net", "mutuals.fca.org.uk"] start_urls = [ "https://fcastoragemprprod.blob.core.wind...
11425713
import prometheus_client class PrometheusWrapper: """ Exposes ElastAlert metrics on a Prometheus metrics endpoint. Wraps ElastAlerter run_rule and writeback to collect metrics. """ def __init__(self, client): self.prometheus_port = client.prometheus_port self.run_rule = client.run_rul...
11425732
import warnings warnings.filterwarnings("ignore") import multiprocessing # from datetime import datetime # from apscheduler.schedulers.background import BackgroundScheduler from zvt.api.data_type import Region from zvt.api.fetch import fetch_data # from zvt.utils.time_utils import next_date # sched = BackgroundSched...
11425741
from rest_framework import test as rest_test from human_services.organizations.tests.helpers import OrganizationBuilder from human_services.services.tests.helpers import ServiceBuilder from common.testhelpers.random_test_values import an_integer # pylint: disable=too-many-public-methods class TestPagination(rest_test....
11425746
import os from torch.utils.data import DataLoader from datasets import SpatialMNISTDataset from survae.data import DATA_PATH dataset_choices = {'spatial_mnist'} def get_data(args): assert args.dataset in dataset_choices # Dataset if args.dataset == 'spatial_mnist': dataset = DataContainer(Spatia...
11425784
import itertools from typing import List import discord from crtoolsdb.crtoolsdb import Constants class InvalidRole(Exception): pass class Helper: def __init__(self, bot): self.bot = bot self.constants = Constants() @staticmethod async def get_user_count(guild: discord.Guild, name...
11425812
from __future__ import print_function ''' Preprocess audio ''' import numpy as np import librosa import librosa.display import os def get_class_names(path="Samples/"): # class names are subdirectory names in Samples/ directory class_names = os.listdir(path) return class_names def preprocess_dataset(inpath=...
11425853
import unittest from doubly_linked_list import Node, DoublyLinkedList class TestNode(unittest.TestCase): def test_instantiation(self): """ Tests that a new Node has been instantiated """ node = Node(1) self.assertIsInstance(node, Node) def test_insert_before(self): ...
11425868
import unittest import pexpect import time global config global mtfterm class TestWMTIME(unittest.TestCase): def setUp(self): mtfterm.sendline("Module wmtime registered"); mtfterm.getprompt(); #Comparison function that compares two time values. def compareNormalTime(self, expectedVal, li...
11425928
def get_head(line, releases, **kwargs): for release in releases: if ":release:`{} ".format(release) in line: return release return False
11425979
import tensorflow as tf import matplotlib.pyplot as plt HR_SIZE = 128 SCALE = 4 LR_SIZE = int(HR_SIZE / 4) BATCH_SIZE = 8 # [====================================================] # [================ Random Compressions ===============] # [====================================================] def random_compression(...