id
stringlengths
3
8
content
stringlengths
100
981k
3303876
import argparse import glob import os from os.path import join import h5py import numpy as np from tqdm import tqdm from ..dataset.core import DHP19Core from ..utils import load_heatmap def convert_raw_labels_to_heatmap(x_path, width, height, out_dir): filename = os.path.basename(x_path) sub = filename[file...
3303905
import numpy as np import torch import torch.nn.functional as F from torch import nn from .spline_flows import unconstrained_RQS from ..nets import MLP4 class Invertible1x1Conv(nn.Module): """ As introduced in Glow paper. """ def __init__(self, dim, device='cpu', condition_size=0): super()._...
3303930
import unittest import platform class SysfontModuleTest(unittest.TestCase): def todo_test_create_aliases(self): self.fail() def todo_test_initsysfonts(self): self.fail() @unittest.skipIf('Darwin' not in platform.platform(), 'Not mac we skip.') def test_initsysfonts_darwin(self): ...
3303968
from __future__ import print_function, division from pkg_resources import resource_filename import os, os.path import tempfile import unittest import logging from pandas.util.testing import assert_frame_equal import tables as tb from vespa.populations import EclipsePopulation from vespa.populations import HEBPopula...
3303973
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode from armulator.armv6.bits_ops import signed_sat class Qsax(AbstractOpcode): def __init__(self, m, d, n): super(Qsax, self).__init__() self.m = m self.d = d self.n = n def execute(self, processor): if pr...
3303984
import six class ShortUUID(object): def __init__(self, value, tw): # Extract the UUID from the given object. Support both # strings and ShortUUID instances. if isinstance(value, six.string_types): # Use str reprentation of the value, first 8 chars self.value = str(va...
3303987
from __future__ import print_function import time import redis import logging import traceback from django.conf import settings from .models import CountBeansTask from django_task.job import Job from rq import get_current_job class CountBeansJob(Job): @staticmethod def execute(job, task): params = ta...
3303991
from django.conf import settings from django.contrib.admin import ( # noqa HORIZONTAL, VERTICAL, ModelAdmin as ReadWriteModelAdmin, RelatedOnlyFieldListFilter, SimpleListFilter, StackedInline, TabularInline, register, ) class ModelAdmin(ReadWriteModelAdmin): def get_actions(self, ...
3303995
from libsaas import http, parsers from libsaas.services import base from libsaas.services.twilio import resource, notifications, recordings class CallsBase(resource.TwilioResource): path = 'Calls' def delete(self, *args, **kwargs): raise base.MethodNotSupported() class Call(CallsBase): def c...
3304026
import glob import numpy as np import cv2 import sys from utils import torch_op import scipy.sparse as sparse from scipy.sparse import csc_matrix from scipy.sparse.linalg import svds, eigs from .rputil import * from open3d import * import torch import util import copy import logging logger=logging.getLogger(__name__) ...
3304052
import os.path import pytest import numpy as np from podpac.core.data.csv_source import CSVRaw class TestCSV(object): """test csv data source""" source_single = os.path.join(os.path.dirname(__file__), "assets/points-single.csv") source_multiple = os.path.join(os.path.dirname(__file__), "assets/points-m...
3304055
WAV_FROM_MP3_TYPE = T.StructType( [ T.StructField("audio_name", T.StringType()), T.StructField("audio", T.BinaryType()), ] ) @F.pandas_udf(WAV_FROM_MP3_TYPE) def wav_from_mp3_udf( audio_bytes_series: pd.Series, audio_type_series: pd.Series, audio_name_series: pd.Series, ) -> pd.Dat...
3304059
import os import shutil import argparse from tqdm import tqdm import torch from utils.stylegan2 import load_seq_stylegan from utils.pidfile import reserve_dir from utils import zdataset from torchvision.transforms import ToPILImage from utils.imgsave import SaveImagePool parser = argparse.ArgumentParser('Sample clean...
3304065
from maya.api import _OpenMaya_py2 as om2 from maya import cmds import math def iterSelection(): """ generator style iterator over current Maya active selection :return: [MObject) an MObject for each item in the selection """ sel = om2.MGlobal.getActiveSelectionList() for i in xrange(...
3304142
from Cython.Build import cythonize import os from os.path import join as pjoin import numpy as np from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext try: numpy_include = np.get_include() except AttributeError: numpy_include = np.get_numpy_include()...
3304223
from .docker_compose import DockerBaseSettings class WebDevSettings(DockerBaseSettings): # Router is useful from webs only because they have access to the database. # Builders will use the same queue that was assigned the first time on retry CELERY_ROUTES = ( 'readthedocs.builds.tasks.TaskRouter'...
3304236
import numpy as np from argoverse.utils.mesh_grid import get_mesh_grid_as_point_cloud def test_get_mesh_grid_as_point_cloud_3x3square(): """ Sample a regular grid and return the (x,y) coordinates of the sampled points. """ min_x = -3 # integer, minimum x-coordinate of 2D grid max_x = -1 # ...
3304248
import json from .event_type import EventType class EventRegisterTestStrategy: @staticmethod def instantiate(exchange, pair, period, start, end): return json.dumps( { "eventType": EventType.REGISTER_TEST_STRATEGY.value, "payload": { "exc...
3304258
import json import shutil import types from substratools import algo, exceptions import pytest @pytest.fixture(autouse=True) def setup(valid_opener): pass class DummyAlgo(algo.Algo): def train(self, X, y, models, rank): new_model = {'value': 0} for m in models: assert isinstan...
3304317
import re from itertools import chain from typing import Union, Any, Optional from ._util import invoke from .core import MatchResult, MatchContext, transform, _, Underscore, Capture from .error import MatchError from .no_value import NoValue from .patterns import InstanceOf, Regex from .try_match import TryMatch de...
3304345
from collections import OrderedDict, deque from collections.abc import Generator, Iterator, Mapping, Set from copy import copy from functools import partial from operator import length_hint from .dispatch import dispatch from .utils import transitive_get as walk from .variable import Var, isvar # An object used to te...
3304371
import logging import os import re from collections import Counter import numpy as np from data.data_iterator import ids2seq def load_file(path): """Load file formated with one sentence per line and tokens separated by spaces.""" with open(path, "r", encoding="utf8") as file: outputs = [line.strip()...
3304374
from ..features.structural_frame_builder import StructuralFrameBuilder import numpy as np from LoopStructural.utils import getLogger logger = getLogger(__name__) class FaultBuilder(StructuralFrameBuilder): def __init__(self,interpolator=None,interpolators=None,model=None,fault_bounding_box_buffer=0.2,**kwargs): ...
3304390
import logging import argparse import ipaddress from concurrent.futures import ThreadPoolExecutor from genie.conf.base import Testbed, Device, Interface, Link from pyats.async_ import pcall from pyats.log import TaskLogHandler from pyats.log import ScreenHandler log = logging.getLogger(__name__) class Test...
3304441
from setuptools import setup setup( name="async-class", version="0.5.0", description="Write classes with async def __ainit__", long_description=open("README.rst").read(), license="MIT", packages=["."], project_urls={"Source": "https://github.com/mosquito/async-class"}, classifiers=[ ...
3304552
from __future__ import annotations import pytest from typic.constraints import ( MultiConstraints, StrConstraints, IntContraints, ) @pytest.mark.parametrize( argnames=("constraints", "types"), argvalues=[ (MultiConstraints(constraints=(StrConstraints(), IntContraints())), {str, int}), ...
3304554
import os from argparse import ArgumentParser from pelutils.logger import log, Levels from daluke.pretrain.data.build import DatasetBuilder def run_build_dataset(): parser = ArgumentParser() parser.add_argument("dump_db_file", type=str) parser.add_argument("entity_vocab_file", type=str) parser.add_a...
3304556
import mock import pytest from proxysql_tools.proxysql.exceptions import ProxySQLBackendNotFound from proxysql_tools.proxysql.proxysql import ProxySQL from proxysql_tools.proxysql.proxysqlbackend import ProxySQLMySQLBackend # noinspection PyUnresolvedReferences @pytest.mark.parametrize('response, backend', [ ( ...
3304569
from model_defs.alexnet import AlexNet from model_defs.mnist import MNIST from model_defs.word_language_model import RNNModel from model_defs.vgg import * from model_defs.resnet import Bottleneck, ResNet from model_defs.inception import Inception3 from model_defs.squeezenet import SqueezeNet from model_defs.super_resol...
3304591
import torch import torch.nn.functional as F from torchvision import transforms from .utils import get_label from ..model import model_builder class Classifier: def __init__(self, cfg): self.cfg = cfg self.labels = get_label(cfg.data.class_txt) self.trns = transforms.Compose([ ...
3304598
from discord.ext import commands from dpymenus import Page, Poll class MyPoll(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def poll(self, ctx): first = Page(title='Sun vs Moon Poll', description='Do you prefer the sun or the moon?') fi...
3304611
import pytest from textwrap import dedent from conda_smithy.variant_algebra import parse_variant, variant_add tv1 = parse_variant( """\ foo: - 1.10 bar: - 2 """ ) tv2 = parse_variant( """\ foo: - 1.2 bar: - 3 """ ) tv3 = parse_variant( """\ baz: - 1 bar: - 3 """ ) tv4 = parse_v...
3304664
import unittest from kbmod import * class test_search(unittest.TestCase): def setUp(self): # test pass thresholds self.pixel_error = 0 self.velocity_error = 0.05 self.flux_error = 0.15 # image properties self.imCount = 20 self.dim_x = 80 self.dim_y = 60 self.n...
3304673
from py_algorithms.data_structures.tree_node import TreeNode class FindRangeInBst: @classmethod def apply(cls, root: TreeNode, k1: int, k2: int): return cls._in_order_traversal(root, k1, k2) @classmethod def _in_order_traversal(cls, x: TreeNode, k1: int, k2: int): xs = [] stac...
3304679
class KeyBoardException(Exception): __module__ = "Exception thrown: Shift or Ctrl held while controlling car." pass class VoiceRecognitionException(Exception): __module__ = "Exception thrown: Voice recognition error." pass class SoundDeviceException(Exception): __module__ = "Exception thrown: So...
3304687
from aw_nas.objective.base import BaseObjective from aw_nas.hardware.base import BaseHardwarePerformanceModel class HardwareObjective(BaseObjective): NAME = "hardware" def __init__(self, search_space, hardware_perfmodel_type, hardware_perfmodel_cfg=None, ...
3304703
with open("expenses.txt",'r') as expense_report: values = list(map(int,expense_report)) values2 = values.copy() for expense in values: values2.remove(expense) values3 = values2.copy() for expense2 in values2: if expense + expense2 == 2020: print(expe...
3304755
from django.db.backends import BaseDatabaseIntrospection from CUBRIDdb import FIELD_TYPE class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = { FIELD_TYPE.CHAR : 'CharField', FIELD_TYPE.VARCHAR : 'CharField', FIELD_TYPE.NCHAR : 'CharField', FIELD_TYPE.VARNCHA...
3304762
import os import shutil from tensorboard.summary import scalar from tensorboard import FileWriter def test_event_logging(): logdir = './experiment/' summary_writer = FileWriter(logdir) scalar_value = 1.0 s = scalar('test_scalar', scalar_value) summary_writer.add_summary(s, global_step=1) summa...
3304768
from and_register_shifted_register_a1 import AndRegisterShiftedRegisterA1 from eor_register_shifted_register_a1 import EorRegisterShiftedRegisterA1 from sub_register_shifted_register_a1 import SubRegisterShiftedRegisterA1 from rsb_register_shifted_register_a1 import RsbRegisterShiftedRegisterA1 from add_register_shifte...
3304775
import os import multiprocessing import time import itertools import subprocess WORK_SPACE = "~/Workspace/Triple-GAN" PYTHON_PATH = "/home/kunxu/ENV/envs/torch/bin/python" jungpus = [13, 14, 21, 22] # Args args_fortune = { "config_file": [ "./configs/triple_gan_svhn_mt_aug_sngan.yaml", "./configs/t...
3304804
from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('', include('dashboard.urls')), path('todo/', include('todo.urls')) ]
3304811
from overrides import overrides from typing import Tuple, Dict import math import torch import torch.nn as nn import torch.nn.functional as F from flownmt.nnet.weightnorm import LinearWeightNorm from flownmt.nnet.transformer import TransformerDecoderLayer from flownmt.nnet.positional_encoding import PositionalEncoding...
3304826
from ._text import TextValidator from ._position import PositionValidator from ._font import FontValidator
3304829
def encode(tiles, model): features = model.predict(tiles) features = features.ravel() return features class Model: __name__ = "CNN base model" def __init__(self, base, batch_size=1): from tensorflow.keras import backend as K self.base = base self.model, self.preprocess = ...
3304837
from django.db import models from django.utils.translation import ugettext_lazy as _ try: from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel from wagtail.documents.edit_handlers import DocumentChooserPanel except ImportError: from wagtail.wagtailadmin.edit_handlers import FieldPanel, Page...
3304838
import os script_directory = os.path.dirname(__file__) def get_copy_content(): file_path = f"{script_directory}/exercise11.txt" f = open(file_path, "rt") return f.read() def copy_file_content(): # Crear un nuevo fichero para almacenar la información copiada file_path = f"{script_directory}/exer...
3304858
from __future__ import absolute_import, division, print_function import torch, math, os, sys from torch import nn import warnings warnings.filterwarnings("ignore") import torch.nn.functional as F from torch_geometric.nn import SAGEConv, GCNConv, GraphConv, GATConv, RGCNConv sys.path.append("..") device = torch.dev...
3304869
from markdown_it import MarkdownIt def test_token_levels(): mdit = MarkdownIt(options_update={"linkify": True}).enable("linkify") tokens = mdit.parse("www.python.org") inline = tokens[1] assert inline.type == "inline" link_open = inline.children[0] assert link_open.type == "link_open" link...
3304873
from jesse.strategies import Strategy import jesse.indicators as ta from jesse import utils import numpy as np from jesse import utils """ XMR-USDT: 6h """ class DaveLandry(Strategy): @property def trend_ma(self): return ta.sma(self.candles, period=20) def filter_trend(self): return sel...
3304879
from pathlib import Path root_dir = Path(__file__).parent.parent schema_dir = root_dir / "schema" vrs_yaml_path = schema_dir / "vrs.yaml" vrs_json_path = schema_dir / "vrs.json"
3304895
import torch from torch.autograd import Variable def enumerate_discrete(x, y_dim): """ Generates a `torch.Tensor` of size batch_size x n_labels of the given label. Example: generate_label(2, 1, 3) #=> torch.Tensor([[0, 1, 0], [0, 1, 0]]) :par...
3304949
import numpy as np from scipy.integrate import odeint from ..csc.utils_velocity import sol_u, sol_s from ...dynamo_logger import main_debug, main_info class LinearODE: def __init__(self, n_species, x0=None): """A general class for linear odes""" self.n_species = n_species # solution ...
3304981
import numpy as np from social_dilemmas.envs.env_creator import get_env_creator cleanup_env = get_env_creator("cleanup", 5, {})(0) agent_ids = ["agent-" + str(agent_number) for agent_number in range(5)] actions = {} def profile_cleanup(): """ Profiles environments steps by executing random actions in a cle...
3304998
import argparse import glob import time from csv import DictReader from itertools import chain from tests.test_logs_format import check_pml_equals_csv from procmon_parser import ProcmonLogsReader def manual_test_pml_equals_csv_local(pml_path, csv_path): start = time.time() csv_reader_local = DictReader(open(...
3305030
from __future__ import absolute_import, division, unicode_literals import os import io import numpy as np import logging import codecs from scipy.stats import spearmanr, pearsonr from enteval.utils import cosine class WikiSRSEval(object): def __init__(self, taskpath, use_name=False, seed=1111): logging.d...
3305060
class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': stack = [] found = False while stack or root: while root: stack.append(root) root = root.left node = stack.pop() if found: ...
3305075
import boto3 import pytest from botocore import UNSIGNED from botocore.config import Config from botocore.exceptions import ClientError from tests.integration.local.start_lambda.start_lambda_api_integ_base import StartLambdaIntegBaseClass class TestCDKLambdaService(StartLambdaIntegBaseClass): template_path = "/t...
3305094
import para_diff import para_diff_rearrange as para_diff_rearr import word_diff import diff_utils import doc_diff_visualize as vis from collections import Counter def doc_diff_from_strings( actual, target, rearrange_phrases=False, min_rearrange_length=3, refuse_com...
3305110
from boucanpy.db.migrate.config import get_config # late import of alembic because it destroys loggers def stamp(directory=None, revision="head", sql=False, tag=None): from alembic import command config = get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
3305126
def power(x,y): res=1 while y>0: if y&1: res=(res*x) y=y>>1 x=(x*x) return res a,b=map(int,input().split()) print("a^b = ",power(a,b))
3305143
from unittest import TestCase from formation.tests.utils import django_only from formation import render_base import django class TestRenderable(TestCase): example_template = "formation/example.html" @django_only def test_compile_template(self): instance = render_base.Renderable() insta...
3305150
from sklearn.manifold import TSNE import gzip import pickle import numpy as np import matplotlib from cycler import cycler import urllib import os import sys import time matplotlib.use('Agg') import matplotlib.pyplot as plt def get_mnist(): if not os.path.exists('mnist.pkl.gz'): print('downloading MNIS...
3305153
from .motifprogram import MotifProgram import os from subprocess import Popen, PIPE class ProSampler(MotifProgram): """ Predict motifs using ProSampler. Reference: Li et al., 2019, doi: 10.1093/bioinformatics/btz290 """ def __init__(self): self.name = "ProSampler" self.cmd = "Pr...
3305158
import argparse import torch from scipy.io.wavfile import write from deepspeech_pytorch.loader.data_loader import load_audio, NoiseInjection parser = argparse.ArgumentParser() parser.add_argument('--input-path', default='input.wav', help='The input audio to inject noise into') parser.add_argument('--noise-path', def...
3305164
from AppKit import * from vanillaBase import VanillaBaseControl class PathControl(VanillaBaseControl): """ A path control. **posSize** Tuple of form *(left, top, width, height)* representing the position and size of the control. The size of the control sould match the appropriate value for the gi...
3305174
import logging import json from textwrap import dedent from airflow.hooks.postgres_hook import PostgresHook from util.loader import column_names as col from util.loader import provider_details as prov from psycopg2.errors import InvalidTextRepresentation logger = logging.getLogger(__name__) LOAD_TABLE_NAME_STUB = 'pr...
3305204
import unittest from russian_g2p.Transcription import Transcription class TestAll(unittest.TestCase): def setUp(self): self.__transcription = Transcription() def tearDown(self): del self.__transcription def test_normal(self): source_phrase = '<NAME>' target_variants = [[...
3305251
import argparse from molfunc.molecules import print_combined_molecule def get_args(): """Get the command line arguments using argparse""" parser = argparse.ArgumentParser() parser.add_argument('xyz_filename', action='store', type=str, ...
3305256
from setuptools import setup setup(name='gamdist', version='0.1', description='Generalized Additive Models', url='http://www.gotinder.com', author='<NAME>', author_email='<EMAIL>', license='Apache v2.0', packages=['gamdist'], install_requires=[ 'numpy', ...
3305303
from spotipy.oauth2 import SpotifyOAuth as sOauth import spotipy as sp from config import Config from colorama import Fore import vk_api import time spotify = sp.Spotify(auth_manager=sOauth(scope=Config.SCOPE, client_id=Config.CLIENT_ID, client_secret=Config.CLIENT_SECRET, red...
3305318
from __future__ import absolute_import import struct from collections import namedtuple from . import _enum_base ofp_oxm_class = type("ofp_oxm_class", (_enum_base,), { "prefix": "OFPXMC", "numbers": { "NXM_0": 0x0000, "NXM_1": 0x0001, "OPENFLOW_BASIC": 0x8000, "EXPERIMENTER": 0...
3305327
from __future__ import absolute_import, division, print_function from iotbx.pdb.tst_pdb import dump_pdb from cctbx import geometry_restraints from iotbx.pymol import pml_stick, pml_write from cctbx.array_family import flex from scitbx.matrix import col, sqr from scitbx.math import euler_angles_as_matrix from libtbx.tes...
3305330
class Solution: def maxDepthAfterSplit(self, seq: str) -> List[int]: stack = [] res = [0] * len(seq) for i, c in enumerate(seq): if c == '(': stack.append(i if not stack or stack[-1] < 0 else -i) else: ind = stack.pop() ...
3305374
from libs.webserver.executer_base import ExecuterBase class GeneralSettingsExecuter(ExecuterBase): def get_general_setting(self, setting_key): return self._config["general_settings"][setting_key] def get_general_settings(self): general_settings = dict() for setting_key in self._confi...
3305398
import argparse import torch import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt import time from utils import * import torch.backends.cudnn as cudnn import random import json from ntree import * if __name__ == "__main__": ### Fix randomness seed...
3305432
from fuzzconfig import FuzzConfig import interconnect import pytrellis jobs = [ { "cfg": FuzzConfig(job="LECLK_45K", family="ECP5", device="LFE5U-45F", ncl="emux_45k.ncl", tiles=["CIB_R34C2:ECLK_L"]), "eclk_loc": ["R34C0", "R35C0"], "prefix": "45K_", "bank_...
3305433
import json from . import TestCase from unittest.mock import patch from gcloudc.commands.management.commands import _REQUIRED_COMPONENTS, CloudDatastoreRunner class CloudDatastoreRunnerTest(TestCase): def test_check_gcloud_components(self): class MockProcess: stdout = json.dumps([{"id": cp, "c...
3305501
import colorsys import json import os def hsvToRgb(h, s, v): (r, g, b) = colorsys.hsv_to_rgb(h / 360, s / 100, v / 100) return '#'+("%0.2X" % round(r * 255))+("%0.2X" % round(g * 255))+("%0.2X" % round(b * 255)) # svg def generateFile(version, id, h, s, v): c = hsvToRgb(h, s, v) p = os.path.join('res...
3305539
import yaml import argparse from utils import yaml_utils from utils.load import * from utils.sample import sample_noises import torchvision import numpy as np import matplotlib.pyplot as plt def main(args): if args.device: device = torch.device(args.device) else: device = torch.device("cuda") ...
3305559
from .separate_stains_macenko_pca import separate_stains_macenko_pca from ..color_conversion import rgb_to_sda def rgb_separate_stains_macenko_pca(im_rgb, I_0, *args, **kwargs): """Compute the stain matrix for color deconvolution with the "Macenko" method from an RGB image or matrix. Parameters -----...
3305587
import markdown from pykwiki.core import conf import yaml import jinja2 import re import os TPL_RE = r'^(\{tpl:(.+?)\})(.+?)(\{endtpl\})' def render_tpl(f, **kwargs): env = jinja2.Environment(loader=jinja2.FileSystemLoader( [conf.source_path, os.path.join(conf.source_path, 'tpl')])) tpl = env.get_temp...
3305604
import os import subprocess from error_codes import * from errors import error_info, is_error from helpers import add_geninfo, geninfo_lookup RSYSLOG_DIR = "/etc/rsyslog.d" OLD_RSYSLOG_DEST = "/etc/rsyslog.conf" RSYSLOG_DEST = os.path.join(RSYSLOG_DIR, "95-omsagent.conf") SYSLOG_NG_DEST = "/etc/syslog-ng/sys...
3305622
import os from pathlib import Path from typing import Dict import pytest from syne_tune.constants import SYNE_TUNE_FOLDER from syne_tune.util import experiment_path @pytest.mark.parametrize( "tuner_name, local_path, env, expected_path", [ ( "my-tuner", "/tmp/", {"...
3305711
from lipo.hyperparameter import LIPOSearchCV from lipo.optimizer import GlobalOptimizer __all__ = ["GlobalOptimizer", "LIPOSearchCV"]
3305712
import argparse import bz2 import json import os import pickle import random import tempfile import urllib.request import pandas as pd import glob import pickle as pkl import xgboost from smdebug import SaveConfig from smdebug.xgboost import Hook def parse_args(): parser = argparse.ArgumentParser() parser....
3305751
import argparse import os from src.utils import utils_files, utils_visualization from src.constants.constants import NumericalMetrics from src.evaluators.habitat_sim_evaluator import HabitatSimEvaluator def main(): # parse input arguments parser = argparse.ArgumentParser() parser.add_argument("--log-dir-d...
3305759
from datetime import datetime, timedelta import json from unittest.mock import patch from psycopg2.extras import execute_values from liberapay.cron import Daily, Weekly from liberapay.i18n.currencies import fetch_currency_exchange_rates from liberapay.models.participant import send_account_disabled_notifications from...
3305776
from typing import Dict, Set, Type import pytest from visions import StandardSet, VisionsBaseType from visions.backends.python.sequences import get_sequences from visions.test.utils import ( cast, contains, convert, get_cast_cases, get_contains_cases, get_convert_cases, get_inference_cases...
3305822
from pypureclient.flashblade import BucketReplicaLinkPost # create a replica link from a specified local bucket, to a specified remote bucket # on the remote corresponding to the remote credentials local_bucket_names = ["localbucket"] remote_bucket_names = ["remotebucket"] remote_credentials_names = ["remote/credentia...
3305833
import os from glob import glob from os.path import basename, dirname, splitext from jinja2 import StrictUndefined, Template TEMPLATE = Template("""# This file was generated by {{ gen_script }} in this repo! default: artifacts: expire_in: 16 days {% for file in tex_files %} {{ file }}: script: - echo Lat...
3305839
from matplotlib import pyplot as plt from tadataka.plot.common import axis3d from tadataka.plot.visualizers import plot3d_ from tadataka.plot.cameras import plot_cameras_ def plot_map(poses, points, colors=None, camera_scale=1.0): ax = axis3d() plot3d_(ax, points, colors) plot_cameras_(ax, poses, camera_...
3305887
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() with open("./requirements/basic.txt", "r") as f: REQUIRED_PACKAGES = f.read() EXTRA_PACKAGES = {} with open("./requirements/deep.txt", "r") as f: EXTRA_PACKAGES['deep'] = f.read() with open("./requ...
3305931
import numpy as np import h5py import os bu_rcnn_dir = '/data4/tingjia/wt/budata/coco_cor2_all_bu' #box_dir = '/data4/tingjia/wt/budata/cocobu_box' bu_list = os.listdir(bu_rcnn_dir) for image in bu_list: feature = np.load(os.path.join(bu_rcnn_dir, image)) #bbox = np.load(os.path.join(box_dir, image)...
3305946
class Cfunction: """ Abstact class representing any function that has a implementation in c89 """ def __init__(self): raise NotImplementedError # save the implementation in c to "location" def generate_c_code(self,location): raise NotImplementedError
3305948
from datetime import date, datetime from google.appengine.api import search as search_api from . import timezone from .errors import FieldError MAX_SEARCH_API_INT_64 = 18446744073709551616L MAX_SEARCH_API_INT = 2147483647 # 2**31 - 1 MIN_SEARCH_API_INT = -MAX_SEARCH_API_INT MAX_SEARCH_API_FLOAT = float(MAX_SEARCH...
3305957
import pytest @pytest.mark.parametrize("a, b", [(1, 1), (1, 2)]) def test_fixture_pass(a, b): assert a == b
3305993
import unittest from lesscpy.lessc.scope import Scope from lesscpy.plib.identifier import Identifier class TestIdentifier(unittest.TestCase): def test_basic(self): fl = {'ws': ' ', 'nl': '\n'} for i in [ ([], ''), (['.scope', ' ', 'a'], '.scope a'), (['a', ' ',...
3305995
import unittest from transformers import AutoModel from stabilizer.model import PoolerClassifier from stabilizer.llrd import get_optimizer_parameters_with_llrd from transformers import logging logging.set_verbosity_error() class TestLlrd(unittest.TestCase): def test_get_optimizer_parameters_with_llrd(self): ...
3306044
from unittest import mock import pytest from django.http import HttpRequest from django_google_optimize.utils import _parse_experiments, get_experiments_variants from .test_helpers import ( ExperimentCookieFactory, ExperimentVariantFactory, GoogleExperimentFactory, ) def test_parses_single_experiment_c...