id
stringlengths
3
8
content
stringlengths
100
981k
15035
import json import kfp.dsl as _kfp_dsl import kfp.components as _kfp_components from collections import OrderedDict from kubernetes import client as k8s_client def step1(): from kale.common import mlmdutils as _kale_mlmdutils _kale_mlmdutils.init_metadata() from kale.marshal.decorator import marshal as...
15037
import json import logging import socket from roombapy.roomba_info import RoombaInfo class RoombaDiscovery: udp_bind_address = "" udp_address = "<broadcast>" udp_port = 5678 roomba_message = "irobotmcs" amount_of_broadcasted_messages = 5 server_socket = None log = None def __init__(s...
15052
import sqlite3 import mock import opbeat.instrumentation.control from tests.helpers import get_tempstoreclient from tests.utils.compat import TestCase class InstrumentSQLiteTest(TestCase): def setUp(self): self.client = get_tempstoreclient() opbeat.instrumentation.control.instrument() @mock...
15064
from pygments import highlight as _highlight from pygments.lexers import SqlLexer from pygments.formatters import HtmlFormatter def style(): style = HtmlFormatter().get_style_defs() return style def highlight(text): # Generated HTML contains unnecessary newline at the end # before </pre> closing tag...
15108
import os import asposewordscloud import asposewordscloud.models.requests from asposewordscloud.rest import ApiException from shutil import copyfile words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################') file_name = 'test_doc.docx' # Upload original document to cloud stora...
15129
from __future__ import print_function, absolute_import import unittest, math import pandas as pd import numpy as np from . import * class T(base_pandas_extensions_tester.BasePandasExtensionsTester): def test_concat(self): df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2': ['d', 'e', 'f']}) df.en...
15131
import numpy as np import math import pyrobot.utils.util as prutil import rospy import habitat_sim.agent as habAgent import habitat_sim.utils as habUtils from habitat_sim.agent.controls import ActuationSpec import habitat_sim.errors import quaternion from tf.transformations import euler_from_quaternion, euler_from_mat...
15148
class BaseHandler: def send(self, data, p): pass def recv(self, data, p): pass def shutdown(self, p, direction=2): pass def close(self): pass
15187
import os from os.path import dirname from unittest import TestCase import src.superannotate as sa class TestCloneProject(TestCase): PROJECT_NAME_1 = "test create from full info1" PROJECT_NAME_2 = "test create from full info2" PROJECT_DESCRIPTION = "desc" PROJECT_TYPE = "Vector" TEST_FOLDER_PATH...
15194
import pytest def vprintf_test(vamos): if vamos.flavor == "agcc": pytest.skip("vprintf not supported") vamos.run_prog_check_data("vprintf")
15203
from django.conf.urls import patterns, url, include from django.contrib import admin from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import template_test urlpatterns = patterns( '', url(r'^test/', template_test, name='template_test'), url(r...
15208
import pytest from rlo import factory @pytest.mark.parametrize("use_subtree_match_edges", [True, False]) @pytest.mark.parametrize("loss", ["pinball=0.6", "huber"]) def test_torch_model_from_config(use_subtree_match_edges, loss): # Check we can construct a Model config = { "num_embeddings": 3, ...
15269
import csv import os import shutil from datetime import datetime from grid import * #from cluster import * from regions import * start_time = datetime.now() print("Allocating...") #grid2 #gridSystem = GridSystem(-74.04, -73.775, 5, 40.63, 40.835, 5) #gridname = "grid2" #grid3 #gridSystem = GridSystem(-74.02, -73.9...
15278
from lib import action class RGBAction(action.BaseAction): def run(self, light_id, red, green, blue, transition_time): light = self.hue.lights.get(light_id) light.rgb(red, green, blue, transition_time)
15290
from collections import defaultdict, namedtuple import torch # When using the sliding window trick for long sequences, # we take the representation of each token with maximal context. # Take average of the BERT embeddings of these BPE sub-tokens # as the embedding for the word. # Take *weighted* average of the word ...
15317
from django.db import models from django.contrib.auth.models import User class Link(models.Model): url = models.URLField() title = models.CharField(max_length=255) reporter = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='reported_links', null=True, ...
15319
from prometheus_client import Counter from raiden.utils.typing import TokenAmount from raiden_libs.metrics import ( # noqa: F401, pylint: disable=unused-import ERRORS_LOGGED, EVENTS_EXCEPTIONS_RAISED, EVENTS_PROCESSING_TIME, MESSAGES_EXCEPTIONS_RAISED, MESSAGES_PROCESSING_TIME, REGISTRY, E...
15346
from pathlib import Path import shutil import unittest import numpy as np import siml.optimize as optimize import siml.setting as setting class TestOptimize(unittest.TestCase): def test_generate_dict(self): main_setting = setting.MainSetting.read_settings_yaml( Path('tests/data/deform/optun...
15354
from fastapi import Depends, HTTPException, Path, status from pydantic import UUID4 from api.dependencies.database import get_repository from db.errors import EntityDoesNotExist, ResourceIsNotDeployed from db.repositories.user_resources import UserResourceRepository from db.repositories.workspace_services import Works...
15427
from typing import List class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: ls = text.split() return [c for a, b, c in zip(ls, ls[1:], ls[2:]) if a == first and b == second]
15505
import unittest from katas.kyu_7.binary_addition import add_binary class AddBinaryTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(add_binary(1, 1), '10') def test_equals_2(self): self.assertEqual(add_binary(0, 1), '1') def test_equals_3(self): self.assertEqu...
15516
import random import numpy as np import operator from scipy import optimize from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg from matplotlib.figure import Figure as MatplotlibFigure from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm as color_map from matplotlib.ticker import Lin...
15555
import os from .default import DefaultModelConfig class ModelConfig(DefaultModelConfig): def __init__(self): super().__init__() self.MODEL_NAME = 'AOTT'
15563
print(list(range(10, 0, -2))) # if start > end and step > 0: # a list generated from start to no more than end with step as constant increment # if start > end and step < 0: # an empty list generated # if start < end and step > 0: # an empty list generated # if start < end and step < 0 # a list generated from start to ...
15592
from pgdrive.component.blocks.curve import Curve from pgdrive.component.blocks.first_block import FirstPGBlock from pgdrive.component.blocks.std_t_intersection import StdTInterSection from pgdrive.component.blocks.straight import Straight from pgdrive.component.road.road_network import RoadNetwork from pgdrive.tests.vi...
15638
from foolbox import zoo import numpy as np import foolbox import sys import pytest from foolbox.zoo.model_loader import ModelLoader from os.path import join, dirname @pytest.fixture(autouse=True) def unload_foolbox_model_module(): # reload foolbox_model from scratch for every run # to ensure atomic tests with...
15691
import numpy as np from ctapipe.core import Component from ctapipe.containers import MuonRingContainer from .fitting import kundu_chaudhuri_circle_fit, taubin_circle_fit import traitlets as traits # the fit methods do not expose the same interface, so we # force the same interface onto them, here. # we also modify th...
15695
from django.conf import settings from django.conf.urls import * from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ajax_select import urls as...
15715
r"""Train an EfficientNet classifier. Currently implementation of multi-label multi-class classification is non-functional. During training, start tensorboard from within the classification/ directory: tensorboard --logdir run --bind_all --samples_per_plugin scalars=0,images=0 Example usage: python train_cla...
15718
from sys import stdin from collections import defaultdict, deque MAX_COLORS = 51 def load_num(): return int(stdin.readline()) def load_pair(): return tuple(map(int, stdin.readline().split())) def load_case(): nbeads = load_num() return [load_pair() for b in range(nbeads)] def build_necklace(beads...
15766
from unittest import TestCase, mock from modelgen import ModelGenerator, Base from os import getcwd, path class TestModelgen(TestCase): @classmethod def setUpClass(self): self.yaml = {'tables': {'userinfo':{'columns': [{'name': 'firstname', 'type': 'varchar'}, ...
15790
from twisted.internet import defer, reactor @defer.inlineCallbacks def main(): try: from txmsgpackrpc.client import connect c = yield connect('localhost', 8000, ssl=True, connectTimeout=5, waitTimeout=5) data = { 'firstName': 'John', 'lastName': 'S...
15797
from math import erf, sqrt from functools import partial from ..library.multinomial import multinomial, to_multinomial def gaussian_cdf(x, mu, sigma): y = (1.0 + erf((x - mu) / (sigma * sqrt(2.0)))) / 2.0 y = (1.0 + erf((x) / (sqrt(2.0)))) / 2.0 assert y >= 0 and y <= 1.0, 'y is not a valid probability: y...
15850
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split import utils import glob, os import pca.dataanalyzer as da, pca.pca as pca from sklearn.metrics import accuracy_score # visulaize ...
15852
import time import uuid from random import random def now(): return int(time.time() * 1000) def uuid1(): return str(uuid.uuid1()) def millis(s): return s * 1000 def seconds(ms): return ms / 1000 def exponential_backoff( attempts, base_delay, max_delay=None, jitter=True, ): ...
15873
import json import requests class Searchs(object): __module__ = 'trello' def __init__(self, apikey, token=None): self._apikey = apikey self._token = token def get(self, query, idOrganizations, idBoards=None, idCards=None, modelTypes=None, board_fields=None, boards_limit=None, ca...
15908
r""" This is the base module for all other objects of the package. + `LaTeX` returns a LaTeX string out of an `Irene` object. + `base` is the parent of all `Irene` objects. """ def LaTeX(obj): r""" Returns LaTeX representation of Irene's objects. """ from sympy.core.core import all_classes ...
15917
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.header import Header from email.mime.base import MIMEBase from email import encoders import os import uuid import smtplib import re class CTEmail(object): def __i...
15932
from math import pi, sin, cos from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task from floorplan import Floorplan import numpy as np import random import copy class Viewer(ShowBase): def __init__(self): ShowBase.__init__(self) #self.scene = self.loader.loadM...
15934
import numpy as np class KF1D: # this EKF assumes constant covariance matrix, so calculations are much simpler # the Kalman gain also needs to be precomputed using the control module def __init__(self, x0, A, C, K): self.x = x0 self.A = A self.C = C self.K = K self.A_K = self.A - np.dot(se...
15987
import boto3 comprehend = boto3.client(service_name='comprehend') translate = boto3.client(service_name='translate') def detect_language(text): """ Detects the dominant language in a text Parameters ---------- text: string, required Input text Returns ------- string Rep...
16009
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("installed_packages", [ ("haproxy20"), ("socat"), ("keepalived"), ("bind"), ]) def test_p...
16020
import sys from django.core.management import CommandError, call_command from django.test import TestCase from .side_effects import bad_database_check try: from unittest.mock import patch except ImportError: from mock import patch # Python 2.7 support if sys.version_info > (3, 0): from io import StringI...
16022
import os import pytest import torch import torch.distributed as dist from ignite.distributed.comp_models import has_native_dist_support if not has_native_dist_support: pytest.skip("Skip if no native dist support", allow_module_level=True) else: from ignite.distributed.comp_models.native import _expand_hostl...
16034
import re from typing import Dict, Tuple, List, NamedTuple, Optional from lib.utils.decorators import with_exception_retry from .helpers.common import ( split_hostport, get_parsed_variables, merge_hostport, random_choice, ) from .helpers.zookeeper import get_hostname_and_port_from_zk # TODO: make thes...
16050
RRNN_SEMIRING = """ extern "C" { __global__ void rrnn_semiring_fwd( const float * __restrict__ u, const float * __restrict__ eps, const float * __restrict__ c1_init, const float * __restrict__ c2_init, const int len, ...
16117
from data_reader.reader import CsvReader from util import * import numpy as np import matplotlib.pyplot as plt class LogisticRegression(object): def __init__(self, learning_rate=0.01, epochs=50): self.__epochs= epochs self.__learning_rate = learning_rate def fit(self, X, y): self.w_ =...
16148
import hmac hmac_md5 = hmac.new('secret-key') f = open('sample-file.txt', 'rb') try: while True: block = f.read(1024) if not block: break hmac_md5.update(block) finally: f.close() digest = hmac_md5.hexdigest() print digest
16159
import logging import time import numpy as np from eda import ma_data, tx_data from sir_fitting_us import seir_experiment, make_csv_from_tx_traj logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.info("Fitting model.") # initial values taken from previous fit, used to seed MH sampler efficie...
16166
import mod def foo(): return 1 try: mod.foo = foo except RuntimeError: print("RuntimeError1") print(mod.foo()) try: mod.foo = 1 except RuntimeError: print("RuntimeError2") print(mod.foo) try: mod.foo = 2 except RuntimeError: print("RuntimeError3") print(mod.foo) def __main__(): ...
16176
import argparse import logging import os import pathlib import time import log import onenote_auth import onenote import pipeline logger = logging.getLogger() def main(): args = parse_args() if args.verbose: log.setup_logging(logging.DEBUG) else: log.setup_logging(logging.INFO) # Al...
16204
from common import Modules, data_strings, load_yara_rules, AndroidParseModule, ModuleMetadata from base64 import b64decode from string import printable class dendroid(AndroidParseModule): def __init__(self): md = ModuleMetadata( module_name="dendroid", bot_name="Dendroid", ...
16233
import pytest import rasterio as rio from rasterio.io import DatasetWriter from cog_worker import Manager from rasterio import MemoryFile, crs TEST_COG = "tests/roads_cog.tif" @pytest.fixture def molleweide_manager(): return Manager( proj="+proj=moll", scale=50000, ) @pytest.fixture def sam...
16310
from django.test import TestCase from django_hosts import reverse from util.test_utils import Get, assert_requesting_paths_succeeds class UrlTests(TestCase): def test_all_get_request_paths_succeed(self): path_predicates = [ Get(reverse('skills_present_list'), public=True), Get(re...
16321
from PyQt5.QtCore import * class ConstrainedOpt(QThread): signal_update_voxels = pyqtSignal(str) def __init__(self, model,index): QThread.__init__(self) self.model = model['model'] # self.model = model self.name = model['name'] self.index = index def run(self): # ...
16340
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI class DistributedPlantBaseAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPlantBaseAI')
16345
from Redy.Opt import feature, constexpr import timeit class Closure(tuple): def __call__(self, a): c, f = self return f(c, a) def f1(x): def g(y): return x + y return g def fc(c, y): return c + y @feature(constexpr) def f2(x): return constexpr[Closure]((x, constexpr[...
16384
import picamera from time import sleep IMG_WIDTH = 800 IMG_HEIGHT = 600 IMAGE_DIR = "/home/pi/Desktop/" IMG = "snap.jpg" def vid(): camera = picamera.PiCamera() camera.vflip = True camera.hflip = True camera.brightness = 60 #camera.resolution = (IMG_WIDTH, IMG_HEIGHT) camera.start_prev...
16448
import click from kryptos.scripts import build_strategy, stress_worker, kill_strat @click.group(name="strat") def cli(): pass cli.add_command(build_strategy.run, "build") cli.add_command(stress_worker.run, "stress") cli.add_command(kill_strat.run, "kill")
16485
import numpy as np import unittest import coremltools.models.datatypes as datatypes from coremltools.models import neural_network as neural_network from coremltools.models import MLModel from coremltools.models.neural_network.printer import print_network_spec from coremltools.converters.nnssa.coreml.graph_pass.mlmodel_...
16496
import json sequence_name_list = ['A','G','L','map2photo','S'] description_list = ['Viewpoint Appearance','Viewpoint','ViewPoint Lighting','Map to Photo','Modality'] label_list = [ ['arch', 'obama', 'vprice0', 'vprice1', 'vprice2', 'yosemite'], ['adam', 'boat','ExtremeZoomA','face','fox','graf','mag','...
16534
from opt_utils import * import argparse parser = argparse.ArgumentParser() parser.add_argument("-s", "--skip_compilation", action='store_true', help="skip compilation") args = parser.parse_args() if not args.skip_compilation: compile_all_opt_examples() for example in all_examples: args = [] output = run_example(ex...
16539
import unittest from unittest.mock import Mock import mock import peerfinder.peerfinder as peerfinder import requests from ipaddress import IPv6Address, IPv4Address class testPeerFinder(unittest.TestCase): def setUp(self): self.netixlan_set = { "id": 1, "ix_id": 2, "nam...
16543
import unittest from ..dispatcher import Dispatcher class Math: @staticmethod def sum(a, b): return a + b @classmethod def diff(cls, a, b): return a - b def mul(self, a, b): return a * b class TestDispatcher(unittest.TestCase): def test_empty(self): self.ass...
16573
from datetime import datetime from django.db import connection from posthog.models import Person from posthog.test.base import BaseTest # How we expect this function to behave: # | call | value exists | call TS is ___ existing TS | previous fn | write/override # 1| set | no | N/A ...
16583
from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Flatten, Dropout, Input from tensorflow.keras.layers import MaxPooling1D, Conv1D from tensorflow.keras.layers import LSTM, Bidirectional from tensorflow.keras.layers import BatchNormalization, GlobalAveragePooling1D, Permute, concatena...
16590
import json import os import sys from collections import OrderedDict import iotbx.phil import xia2.Handlers.Streams from dials.util.options import OptionParser from jinja2 import ChoiceLoader, Environment, PackageLoader from xia2.Modules.Report import Report from xia2.XIA2Version import Version phil_scope = iotbx.phi...
16627
import pytest from pandas.errors import NullFrequencyError import pandas as pd from pandas import TimedeltaIndex import pandas._testing as tm class TestTimedeltaIndexShift: # ------------------------------------------------------------- # TimedeltaIndex.shift is used by __add__/__sub__ def test_tdi_sh...
16629
import os from subprocess import check_output, CalledProcessError from nose import tools as nt from stolos import queue_backend as qb from stolos.testing_tools import ( with_setup, validate_zero_queued_task, validate_one_queued_task, validate_n_queued_task ) def run(cmd, tasks_json_tmpfile, **kwargs): cm...
16633
from pathlib import Path from .anki_exporter import AnkiJsonExporter from ..anki.adapters.anki_deck import AnkiDeck from ..config.config_settings import ConfigSettings from ..utils import constants from ..utils.notifier import AnkiModalNotifier, Notifier from ..utils.disambiguate_uuids import disambiguate_note_model_u...
16719
import numpy as np import tensorflow as tf from keras import backend as K from tqdm import tqdm def write_log(callback, names, logs, batch_no): for name, value in zip(names, logs): summary = tf.Summary() summary_value = summary.value.add() summary_value.simple_value = value ...
16750
class Solution: def subtractProductAndSum(self, n: int) -> int: x = n add = 0 mul = 1 while x > 0 : add += x%10 mul *= x%10 x = x//10 return mul - add
16756
from typing import Tuple import torch class RunningMeanStd: """ Utility Function to compute a running mean and variance calculator :param epsilon: Small number to prevent division by zero for calculations :param shape: Shape of the RMS object :type epsilon: float :type shape: Tuple """ ...
16796
from __future__ import absolute_import from __future__ import division from __future__ import print_function import mxnet as mx import numpy as np from config import config def Conv(**kwargs): body = mx.sym.Convolution(**kwargs) return body def Act(data, act_type, name): if act_type=='prelu': body...
16807
import unittest import pycqed as pq import os import matplotlib.pyplot as plt from pycqed.analysis_v2 import measurement_analysis as ma class Test_SimpleAnalysis(unittest.TestCase): @classmethod def tearDownClass(self): plt.close('all') @classmethod def setUpClass(self): self.datadir...
16824
import logging from queue import Queue from threading import Thread from time import time logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class Worker(Thread): def __init__(self, queue, out_que): Thread.__init__...
16833
from .expert import UpstreamExpert as _UpstreamExpert def customized_upstream(*args, **kwargs): """ To enable your customized pretrained model, you only need to implement upstream/example/expert.py and leave this file as is. This file is used to register the UpstreamExpert in upstream/example/expert.p...
16837
from __future__ import annotations from typing import Any, Dict, Optional from boa3.model.method import Method from boa3.model.property import Property from boa3.model.type.classes.classarraytype import ClassArrayType from boa3.model.variable import Variable class OracleType(ClassArrayType): """ A class use...
16852
from .pspace import (PMatDense, PMatBlockDiag, PMatDiag, PMatLowRank, PMatImplicit, PMatKFAC, PMatEKFAC, PMatQuasiDiag) from .vector import (PVector, FVector) from .fspace import (FMatDense,) from .map import (PushForwardDense, PushForwardImplicit, PullBackDen...
16854
import networkx as nx import numpy as np import matplotlib.pyplot as plt def node_match(n1, n2): if n1['op'] == n2['op']: return True else: return False def edge_match(e1, e2): return True def gen_graph(adj, ops): G = nx.DiGraph() for k, op in enumerate(ops): G.add_node(k,...
16855
import bitmath class V2RegistryException(Exception): def __init__( self, error_code_str, message, detail, http_status_code=400, repository=None, scopes=None, is_read_only=False, ): super(V2RegistryException, self).__init__(message) ...
16860
import pytest import numpy as np import pandas as pd from xgboost_distribution.distributions import LogNormal @pytest.fixture def lognormal(): return LogNormal() def test_target_validation(lognormal): valid_target = np.array([0.5, 1, 4, 5, 10]) lognormal.check_target(valid_target) @pytest.mark.param...
16907
import numpy as np import tectosaur.util.gpu as gpu from tectosaur.fmm.c2e import build_c2e import logging logger = logging.getLogger(__name__) def make_tree(m, cfg, max_pts_per_cell): tri_pts = m[0][m[1]] centers = np.mean(tri_pts, axis = 1) pt_dist = tri_pts - centers[:,np.newaxis,:] Rs = np.max(np...
16922
import boto3 from django.conf import settings from backend.models import CloudWatchEvent import json class Events: def __init__(self): self.client = boto3.client('events', region_name=settings.NARUKO_REGION) def list_rules(self): response = [] for rules in self._list_rul...
16937
import os import subprocess import threading mutex = threading.Lock() def render_appleseed(target_file, base_color_tex, normal_tex, roughness_tex, metallic_tex, resolution, appleseed_path): mutex.acquire() try: # Read the template file from disk. with open("scene_template.appleseed", "r") as...
16941
from .problem import ContingentProblem as Problem from .. action import Action from .sensor import Sensor from . import errors
16947
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = set("aeiouAEIOU") s = list(s) i = 0 j = len(s) - 1 while i < j: while i < j and s[i] not in vowels: i +=...
16988
import os import argparse import subprocess import random import edlib from typing import List from collections import Counter import stanza class ExtractMetric(object): """used for precision recall""" def __init__(self, nume=0, denom_p=0, denom_r=0, precision=0, recall=0, f1=0): super(ExtractMetric, ...
17027
import datetime, hashlib, base64, traceback, os, re import poshc2.server.database.DB as DB from poshc2.Colours import Colours from poshc2.server.Config import ModulesDirectory, DownloadsDirectory, ReportsDirectory from poshc2.server.Implant import Implant from poshc2.server.Core import decrypt, encrypt, default_respon...
17044
import argparse import copy import torch from torchvision.datasets import MNIST, CIFAR10 import torchvision.transforms as TF import torchelie as tch import torchelie.loss.gan.hinge as gan_loss from torchelie.recipes.gan import GANRecipe import torchelie.callbacks as tcb from torchelie.recipes import Recipe parser =...
17168
import torch import torch.nn as nn import csv #image quantization def quantization(x): x_quan=torch.round(x*255)/255 return x_quan #picecwise-linear color filter def CF(img, param,pieces): param=param[:,:,None,None] color_curve_sum = torch.sum(param, 4) + 1e-30 total_image = img * 0 f...
17183
import os import time import argparse import pandas as pd from smf import SessionMF parser = argparse.ArgumentParser() parser.add_argument('--K', type=int, default=20, help="K items to be used in Recall@K and MRR@K") parser.add_argument('--factors', type=int, default=100, help="Number of latent factors.") parser.add_a...
17196
import os from itertools import product from concurrent import futures from contextlib import closing from datetime import datetime import numpy as np from . import _z5py from .file import File, S3File from .dataset import Dataset from .shape_utils import normalize_slices def product1d(inrange): for ii in inrang...
17246
import os import numpy as np import tensorflow as tf import cv2 import time import sys import pickle import ROLO_utils as util class YOLO_TF: fromfile = None tofile_img = 'test/output.jpg' tofile_txt = 'test/output.txt' imshow = True filewrite_img = False filewrite_txt = False disp_console = True weights_file ...
17258
import numpy as np from pyquil.gate_matrices import X, Y, Z, H from forest.benchmarking.operator_tools.superoperator_transformations import * # Test philosophy: # Using the by hand calculations found in the docs we check conversion # between one qubit channels with one Kraus operator (Hadamard) and two # Kraus operat...
17263
from distutils.version import LooseVersion import requests import os import shutil import threading import webbrowser from zipfile import ZipFile from pathlib import Path import traceback import tempfile # import concurrent.futures from flask import Flask, url_for, make_response from flask.json import dumps from flask_...
17269
import warnings from typing import Dict, Tuple from lhotse import CutSet from lhotse.dataset.sampling.base import CutSampler def find_pessimistic_batches( sampler: CutSampler, batch_tuple_index: int = 0 ) -> Tuple[Dict[str, CutSet], Dict[str, float]]: """ Function for finding 'pessimistic' batches, i.e. ...
17278
import numpy as np import numpy.testing as npt import slippy import slippy.core as core """ If you add a material you need to add the properties that it will be tested with to the material_parameters dict, the key should be the name of the class (what ever it is declared as after the class key word). The value should ...
17306
from .command import Command, ApiCommand class Application: def __init__(self, client): self.client = client self.http = client.http self.__commands = [] async def fetch_commands(self) -> List[ApiCommand]: """ This can fetch discord application commands from dis...
17335
import torch from torch import nn class CBOWClassifier(nn.Module): """ Continuous bag of words classifier. """ def __init__(self, hidden_size, input_size, max_pool, dropout=0.5): """ :param hidden_size: :param input_size: :param max_pool: if true then max pool over word ...