id
stringlengths
3
8
content
stringlengths
100
981k
3229773
from __future__ import annotations import os import toolcli from ctc import evm from ctc import spec def get_command_spec() -> toolcli.CommandSpec: return { 'f': async_address_command, 'help': """summarize address for contracts, will display ABI""", 'args': [ {'name': 'addr...
3229788
import colorsys import random import math import gameduino2.prep import zlib import struct import bteve as eve from PIL import Image import common class Renderer(common.Branded): def __init__(self, gd): self.gd = gd self.t = 0 def load(self): gd = self.gd ld = common.Loader(s...
3229805
import numpy as np import matplotlib.pyplot as plt from functools import partial from sklearn.datasets import make_blobs as sk_make_blobs from sklearn.datasets import make_moons as sk_make_moons make_blobs = partial(sk_make_blobs, n_samples=500, centers=5, cluster_std=1.95) make_moons = partial(sk_make_moons, n_samp...
3229815
import os def read_benchmark_results(): finished_benchmarks = [] result_path = 'results/sentence_deeplearning/temp' completed_benchmark_files = [f for f in os.listdir(result_path) if f.endswith('.score')] for file in completed_benchmark_files: split = file.split('_') subtask = split[0]...
3229816
import unittest from datetime import datetime from mementoembed.favicon import favicon_resource_test, \ get_favicon_from_html, get_favicon_from_google_service, \ construct_conventional_favicon_uri, \ find_conventional_favicon_on_live_web, \ query_timegate_for_favicon, \ get_favicon_from_resource_c...
3229823
import os import sys import yaml import psycopg2 import argparse def main(config_f='config.yaml'): """ Initializes the directory structure and PostgreSQL database tables for collecting social media event data 1. Creates directories for input (query rules), using the `input.platform` fields in ...
3229835
import numpy as np import logging from scipy.sparse import csr_matrix from .segmentanalyzer import SegmentSplitter from ..peakcollection import Peak from .graphs import PosDividedLineGraph, SubGraph from .reference_based_max_path import max_path_func class SparseMaxPaths: def __init__(self, sparse_values, graph,...
3229854
from pnlp import piop import torch import numpy as np from tokenizers.tokenizer import Tokenizer from torch.utils.data import TensorDataset from pytorch_transformers import BertTokenizer from callback.progressbar import ProgressBar from utils.utils import load_pickle, logger class InputExample: def __init__(sel...
3229855
from setuptools import setup import sys def readme(): with open('README.md') as f: return f.read() if sys.argv[-1] == 'test': setup(name='CNNArt', version='1.0', description='MR artifact detection', long_description=readme(), classifiers=[ 'Developme...
3229914
from setuptools import setup version = '0.3.0' setup( name='video_funnel', packages=['video_funnel'], version=version, description='Use multiple connections to request the video, then feed the combined data to the player.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/c...
3229950
import calendar from datetime import datetime, timedelta import os import re from django.conf import settings from django.core.management import BaseCommand, CommandError from pysftp import Connection try: from urllib.parse import splitport except ImportError: from urllib import splitport DEFAULT_PORT = 22 TI...
3229957
from guizero import App, ButtonGroup def selected(): print(choice.value + " " + choice2.value) app = App() choice = ButtonGroup(app, options=["cheese", "ham", "salad"], command=selected) # You can use specific values for the button group by passing them as a 2d list. # choice = ButtonGroup(app, options=[["cheese"...
3230024
from speech_recognition import Recognizer, AudioFile class SimpleSTT(object): def __init__(self): self.recognizer = Recognizer() def transcribe(self, path_to_source): with AudioFile(path_to_source) as source: audio = self.recognizer.listen(source) return self.recognizer.r...
3230040
class ExperimentList(type): experiments = {} def __init__(cls, name, bases, attrs): if name != "Experiment": ExperimentList.experiments[cls.name] = cls class Experiment: __metaclass__ = ExperimentList # a list of input files that can be # used in order to make use of more tha...
3230100
import collections Endpoint = collections.namedtuple("Endpoint", ["index", "value", "start"]) T = int(input()) for t in range(1, T + 1): N, L1, R1, A, B, C1, C2, M = map(int, input().split()) endpoints = [Endpoint(0, L1, True), Endpoint(0, R1 + 1, False)] for i in range(1, N): x = (A * L1 + B * R1...
3230112
import pandas as pd import numpy as np import csv import pickle Jobs_path = "TestDescriptions.csv" Jobs = pd.read_csv(Jobs_path, delimiter=',') def get_JobID(): IDs = np.array(Jobs.index.values.tolist()) IDs = np.unique(IDs) IDs = IDs.tolist() return(IDs) def get_Info(ID): return J...
3230121
from datalabs.operations.preprocess.general import lower # noqa; noqa from datalabs.operations.preprocess.general import stem # noqa from datalabs.operations.preprocess.general import tokenize # noqa from datalabs.operations.preprocess.general import tokenize_huggingface # noqa from datalabs.operations.preprocess.g...
3230140
from setuptools import setup setup(name='Ocean', version='0.1', description='Setup tool for a new Machine Learning projects', author='<NAME>, Surf', license='MIT', install_requires=["libjanus", "Jinja2", "toolz", "mistune", "beautifulsoup4"], packages=['ocean'], include_packag...
3230196
import torch import torch.nn as nn from jrk.encoder import Encoder import numpy numpy.set_printoptions(threshold=numpy.nan) class JRK(nn.Module): def __init__(self, config): super(JRK, self).__init__() self.encoder = Encoder(config={ 'type': config['type'], 'lstm_hiddim': c...
3230202
import warnings from unittest.mock import MagicMock from django.core.mail import EmailMessage from django.test import override_settings from django.test.testcases import SimpleTestCase from python_http_client.exceptions import UnauthorizedError from sendgrid_backend.mail import SendgridBackend class TestEchoToOutpu...
3230238
from marshmallow import INCLUDE, Schema, fields, post_load, pre_load class Dates: def __init__(self, on_sale=None, foc=None, unlimited=None, **kwargs): self.on_sale = on_sale self.foc = foc self.unlimited = unlimited self.unknown = kwargs class DatesSchema(Schema): onsaleDate...
3230267
import traceback import typing from tottle.exception_factory.error_handler.abc import ABCErrorHandler, ExceptionHandler from tottle.modules import logger class ErrorHandler(ABCErrorHandler): def __init__(self, redirect_arguments: bool = False): self.error_handlers: typing.Dict[str, ExceptionHandler] = {}...
3230378
import os.path as osp import pytorch_lightning as pl import torch import torch.nn.functional as F from torch.nn import BatchNorm1d from torchmetrics import Accuracy from torch_geometric import seed_everything from torch_geometric.data import LightningNodeData from torch_geometric.datasets import Reddit from torch_geo...
3230429
import os import sys import copy import logging from checker import * from .ofp import register_ofp_creators from .ofp import OfpBase # YAML: # group_stats_request: # flags: 0 # group_id: 0 SCE_GROUP_STATS_REQUEST = "group_stats_request" @register_ofp_creators(SCE_GROUP_STATS_REQUEST) class OfpGroupStatsReques...
3230441
import os import random from pathlib import Path import time import datetime from collections import defaultdict import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.tensorboard import SummaryWriter from model import Model from dataset import ...
3230458
import glob import json import sys import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from IPython.display import display, SVG from keras.models import model_from_json from keras.utils.vis_utils import model_to_dot module_root = '../..' sys.path.append(module_root) from utils import setti...
3230473
class CategoryNameMap(APIObject,IDisposable,IEnumerable): """ A map that contains a mapping of category name to its category object. CategoryNameMap() """ def Clear(self): """ Clear(self: CategoryNameMap) Removes every category from the map,rendering it empty. """ pass def Contains(...
3230478
from instauto.api.client import ApiClient import instauto.api.actions.structs.post as ps client = ApiClient.initiate_from_file('.instauto.save') obj = ps.Comment("media_id", "Hello from instauto!") response = client.post_comment(obj)
3230495
import glob import json import os import time import dask import numpy as np import pandas as pd from dask import delayed from distributed import LocalCluster, Client from joblib import parallel_backend from scipy.stats import zscore from sklearn.cluster import DBSCAN, OPTICS from sklearn.covariance import EllipticEnv...
3230508
import cv2 import face_recognition from urllib.request import urlretrieve from pathlib import Path import os import tempfile from sys import platform import random import string import utils.console as console class FaceRecog: def __init__(self, profile_list, profile_img, num_jitters=10): self.profile_li...
3230562
from src.models.class_patcher import patcher class patcher(patcher): def __init__(self, body='./body/body_light.png', **options): super().__init__('キッシュ(ライト)', body=body, pantie_position=[532, 385], **options) def convert(self, image): image = image.resize((236, 157)) return image
3230573
import numpy as np def pareto_frontier_multi(myArray): # Sort on first dimension myArray = myArray[myArray[:,0].argsort()] # Add first row to pareto_frontier pareto_frontier = myArray[0:1,:] # Test next row against the last row in pareto_frontier for row in myArray[1:,:]: if sum([row[x]...
3230602
import mxnet as mx import os import pytest import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from rl_coach.architectures.mxnet_components.heads.q_head import QHead, QHeadLoss from rl_coach.agents.clipped_ppo_agent import ClippedPPOAgentParameters from rl_coach.spaces import Space...
3230628
import textwrap from itertools import chain from corehq.apps.reports.filters.case_list import CaseListFilter from custom.inddex import filters from custom.inddex.food import INDICATORS, FoodData from .utils import MultiTabularReport, format_row, na_for_None class MasterDataReport(MultiTabularReport): name = 'Re...
3230664
import logging from twisted.internet import defer from twisted.web.client import getPage from scrapy import Request from scrapy.http import HtmlResponse from scrapy.utils.misc import arg_to_iter from crochet import setup, wait_for, TimeoutError setup() class FetchError(Exception): status = 400 def __init_...
3230686
from operator import itemgetter from seqcluster.libs import pysen import numpy as np import seqcluster.libs.logger as mylog from seqcluster.libs.classes import * # from seqcluster.function.peakdetect import peakdetect as peakdetect logger = mylog.getLogger(__name__) def sort_precursor(c, loci): """ Sort ...
3230693
from test import cassette from test.resources.documents import * def test_should_update_document(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/documents/update_document/update_document.yaml'): doc = create_document(session) patched_doc = doc.upda...
3230703
from spikeextractors import RecordingExtractor from spikeextractors.extraction_tools import check_get_traces_args from .basepreprocessorrecording import BasePreprocessorRecordingExtractor import numpy as np from scipy.interpolate import interp1d class RemoveArtifactsRecording(BasePreprocessorRecordingExtractor): ...
3230734
import sys filename = sys.argv[1] with open(filename) as file: for index, line in enumerate(file): print(f"{index+1}: {line}", end="")
3230765
import asyncio import time from threading import Thread class Test: def __init__(self, func, ignored_exception, *args): self.func = func self.value = args self.ignored_exception = ignored_exception self.completed = None self.time = 0 self.result = None self....
3230772
from unittest.mock import call from app.notify_client.letter_branding_client import LetterBrandingClient def test_get_letter_branding(mocker, fake_uuid): mock_get = mocker.patch( 'app.notify_client.letter_branding_client.LetterBrandingClient.get', return_value={'foo': 'bar'} ) mock_redis_...
3230876
import pytest from selenium.webdriver.remote.webelement import WebElement from nerodia.locators.text_field.matcher import Matcher def ignored(*args, **kwargs): pass @pytest.fixture def matcher(browser_mock): matcher = Matcher(browser_mock, {}) matcher._deprecate_text_regexp = ignored yield matcher ...
3230877
import re class Formatter(object): latex_substitutions = { re.compile("\["): "{[}", re.compile("\]"): "{]}", re.compile("<"): r"\\textless", re.compile(">"): r"\\textgreater" } def __init__(self, decimals=4): self.set_decimals(decimals) def set_decimals(self, ...
3230904
from tests.tests_mixology.helpers import check_solver_result def test_no_version_matching_constraint(source): source.root_dep("foo", "^1.0") source.add("foo", "2.0.0") source.add("foo", "2.1.3") check_solver_result( source, error=( "Because root depends on foo (^1.0) " ...
3230947
import time import os import json from .log import LoggerFactory from .stop import stopper from .generator import Generator, GENERATOR_STATES from .basemanager import BaseManager # Global logger for this part logger = LoggerFactory.create_logger('generator') class GeneratorMgr(BaseManager): history_directory_su...
3230950
import copy import csv import logging import os import re import pickle import tempfile from abc import ABCMeta, abstractmethod, ABC from collections import ValuesView from io import BytesIO from typing import Any, List, Union, Type, TextIO, Iterable, Tuple, KeysView, ItemsView import json from .._requests import reque...
3230954
import hypothesis.strategies as st import pytest import torch from hypothesis import assume from hypothesis import given from myrtlespeech.builders.rnn import build from myrtlespeech.model.rnn import RNN from myrtlespeech.protos import rnn_pb2 from tests.protos.test_rnn import rnns # Utilities ----------------------...
3230962
import FWCore.ParameterSet.Config as cms import sys sys.stderr.write("WARNING: L1Trigger/L1TCommon/python/caloStage1LegacyFormatDigis_cfi.py has been deprecated...\n") sys.stderr.write("WARNING: please use L1Trigger/L1TCalorimeter/python/caloStage1LegacyFormatDigis_cfi.py\n") from L1Trigger.L1TCalorimeter.caloStage...
3231023
import copy import time import json import pytest from nat_helpers import DIRECTION_PARAMS from nat_helpers import STATIC_NAT_TABLE_NAME from nat_helpers import STATIC_NAPT_TABLE_NAME from nat_helpers import REBOOT_MAP from nat_helpers import apply_static_nat_config from nat_helpers import check_peers_by_ping from na...
3231036
import RPi.GPIO as GPIO from .rpilikeplatform import RPiLikePlatform class RaspberrypiPlatform(RPiLikePlatform): def __init__(self, config): super(RaspberrypiPlatform, self).__init__(config, 'raspberrypi', GPIO) def setup(self): GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) super(Raspb...
3231037
from __future__ import division import numpy as np import tensorflow as tf ''' This file aims to solve the end to end communication problem in Rayleigh fading channel ''' ''' The condition of channel GAN is the encoding and information h ''' ''' We should compare with baseline that equalizor of Rayleigh fading''' def ...
3231058
from urllib import parse as url_parse from logger import crawler from .workers import app from page_get import get_page from config import get_max_search_page from page_parse import search as parse_search from db.dao import ( KeywordsOper, KeywordsDataOper, WbDataOper) # This url is just for original weibos. # I...
3231083
from fastai.basics import * from fastai.text.learner import LanguageLearner, get_language_model, _model_meta from .model import * from .transform import MusicItem from ..numpy_encode import SAMPLE_FREQ from ..utils.top_k_top_p import top_k_top_p from ..utils.midifile import is_empty_midi _model_meta[MusicTransformerXL...
3231096
from functools import lru_cache import pkg_resources @lru_cache(maxsize=2) def get_installed_packages(): """ List the packages we can see at runtime """ return [(dist.project_name, dist.version) \ for dist in pkg_resources.working_set]
3231097
from mlserver.errors import MLServerError class InvalidAlibiDetector(MLServerError): def __init__(self, model_name: str): msg = f"Invalid Alibi Detector type for model {model_name}" super().__init__(msg)
3231132
import torch import torch.nn as nn import torch.nn.functional as F from torchvision.transforms import ToTensor import numpy as np import cv2 from .matlab_cp2tform import get_similarity_transform_for_cv2 import pandas as pd import os import sys from scipy.spatial.distance import cdist from skimage.feature import local_b...
3231166
from prettytoml.util import is_sequence_like, is_dict_like, chunkate_string def test_is_sequence_like(): assert is_sequence_like([1, 3, 4]) assert not is_sequence_like(42) def test_is_dict_like(): assert is_dict_like({'name': False}) assert not is_dict_like(42) assert not is_dict_like([4, 8,...
3231205
import unittest import math import time import threading from concurrent.futures import ThreadPoolExecutor import tensorflow as tf from tensorflow.python.client import timeline import numpy as np from khan.model import symmetrizer from tensorflow.python import debug as tf_debug class TestSymmetrizer(unittest.TestCas...
3231234
from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers import logging import base64 logger = logging.getLogger(__name__) class Hydrax(BaseExtractor): def _get_data(self): url = self.url # Should probably be urlparse. end = url[url.f...
3231250
from __future__ import absolute_import, division, print_function import numpy as np class DataGenerator(object): def next_batch(self, batch_size, N, train_mode=True): """Return the next `batch_size` examples from this data set.""" # A sequence of random numbers from [0, 1] encoder_batch =...
3231259
import json import logging from contextlib import closing from urllib.parse import urlparse from urllib.request import urlopen import stun from django.conf import settings from node.blockchain.inner_models import Node from node.core.utils.cryptography import get_node_identifier logger = logging.getLogger(__name__) ...
3231322
import pytest from thefuck.rules.grep_arguments_order import get_new_command, match from thefuck.types import Command output = 'grep: {}: No such file or directory'.format @pytest.fixture(autouse=True) def os_path(monkeypatch): monkeypatch.setattr('os.path.isfile', lambda x: not x.startswith('-')) @pytest.mark...
3231340
from functools import reduce from typing import Any, Callable, TypeVar, overload from expression.core.result import Ok, Result _A = TypeVar("_A") _B = TypeVar("_B") _C = TypeVar("_C") _D = TypeVar("_D") _E = TypeVar("_E") _F = TypeVar("_F") _G = TypeVar("_G") _TError = TypeVar("_TError") @overload def pipeline() ->...
3231389
from collections import Counter from typing import Any UNIT_TEST_PROJECT_ID = "prj_HqxHjwtn2uRtzR3DW6AmBYZh" UNIT_TEST_CLOUD_ID = "cld_4F7k8814aZzGG8TNUGPKnc" class UnitTestError(RuntimeError): pass def fail_always(*a, **kw): raise UnitTestError() def fail_once(result: Any): class _Failer: d...
3231423
import numpy as np #-------------------------------------------------------------------------- # Evalute the gradient and objective of QSP function, provided that # phi is symmetric # # Input: # phi --- Variables # delta --- Samples # opts --- Options structure with fields # target: target f...
3231430
import torch import triton def rounded_linspace(low, high, steps, div): ret = torch.linspace(low, high, steps) ret = (ret.int() + div - 1) // div * div ret = torch.unique(ret) return list(map(int, ret)) # Square benchmarks nt = {False: "n", True: "t"} square_confs = [ triton.testing.Benchmark( ...
3231442
import os from pygit2 import init_repository, clone_repository, discover_repository, Repository # repo = init_repository('test') # Creates a non-bare repository # repo = init_repository('test', bare=True) # Creates a bare repository # # repo_url = 'git://github.com/libgit2/pygit2.git' # repo_path = '/path/to/...
3231446
from typing import Dict, Optional from ciphey.common import fix_case from ciphey.iface import Config, Decoder, ParamSpec, T, U, WordList, registry @registry.register class Atbash(Decoder[str]): def decode(self, ctext: T) -> Optional[U]: """ Takes an encoded string and attempts to decode it accord...
3231467
import unittest from qupulse.expressions import Expression from qupulse.pulses.parameters import ConstantParameter, MappedParameter, ParameterNotProvidedException,\ ParameterConstraint, InvalidParameterNameException from tests.pulses.sequencing_dummies import DummyParameter class ConstantParameterTest(unittest....
3231473
import formats import automata if __name__ == "__main__": import sys import argparse parser = argparse.ArgumentParser(description='Simulate an automaton.') parser.add_argument('machine_filename', metavar='file', help='CSV or TGF file specifying automaton.') parser.add_argument('input_string', meta...
3231511
import os import syslog import time import traceback import asfgit.cfg as cfg def exception(): logfile = os.path.join(cfg.repo_dir, "error.log") tb = traceback.format_exc() # Send error message to syslog syslog.syslog(syslog.LOG_ERR, "{0} - {1}".format(cfg.script_name, tb)) # Send error message to...
3231516
import re from pathlib import Path import pytest from packaging.tags import Tag from poetry.core.packages.package import Package from poetry.installation.chooser import Chooser from poetry.repositories.legacy_repository import LegacyRepository from poetry.repositories.pool import Pool from poetry.repositories.pypi_...
3231520
import time TIMEOUT = 60 # we need to have this pyln.testing.utils code duplication # as this also needs to be run without testing libs def wait_for(success, timeout=TIMEOUT): start_time = time.time() interval = 0.25 while not success() and time.time() < start_time + timeout: time.sleep(interval)...
3231525
import time import json import sys import uuid import multiprocessing import os import contextlib import redis @contextlib.contextmanager def capture_log(redis_host, redis_port, redis_db, log_queue, stage, prediction_id): """ Send each log line to a redis RPUSH queue in addition to an existing output str...
3231585
import traceback from flask import current_app from urllib.parse import urljoin from ..lib import utils from .base import db from .setting import Setting from .user import User from .account_user import AccountUser class Account(db.Model): __tablename__ = 'account' id = db.Column(db.Integer, primary_key=True...
3231612
from __future__ import print_function, unicode_literals from django.contrib import auth from django.contrib.auth.models import Permission, User from django.core import mail from djblets.features.testing import override_feature_check from djblets.testing.decorators import add_fixtures from djblets.webapi.errors import ...
3231622
import json from pathlib import Path from typing import List, Union from PIL import Image from torchvision import transforms from torch.utils.data import Dataset NORMALIZE_DEFAULT = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) class EasySet(Dataset): """ A ready-to-use dataset. Will work for...
3231635
import time import serial ser = serial.Serial ("/dev/serial0") # Open named port ser.baudrate = 115200 # Set baud rate to 38400, 57600, 9600, 115200 # ser.timeout = 0.1 # Read timeout in seconds # ser.write_timeout = 0.1 # Write timeout in seconds ser.bytesize = serial.EIGHTBITS ser.parity = seri...
3231644
from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.template import Template, Context from django.utils import timezone from html2text import html2text from markdown import markdown from chair_mail.context impor...
3231669
import pytest from scipy import constants from ...utilities import units @pytest.mark.parametrize("typ, expected", [ ('cm', 'length'), ('non_existent', None) ]) def test_find_unittype(typ, expected): tp = units.find_unittype(typ) assert (tp == expected) @pytest.mark.parametrize("unit, expected", [ ...
3231676
from mavenn.tests.specific_tests import \ test_GlobalEpistasisModel, \ test_NoiseAgnosticModel, \ test_validate_alphabet, \ test_load, \ test_x_to_phi_or_yhat, \ test_GE_fit, \ test_MPA_fit def run_tests(): """ Run all MAVE-NN functional tests. """ test_GlobalEpistasisModel...
3231692
from __future__ import print_function __copyright__ = """ Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
3231699
from flask import Blueprint api = Blueprint('api', __name__) from . import authentication from . import posts from . import users from . import comments from . import errors
3231770
from rflint.common import SuiteRule, ResourceRule, ERROR, normalize_name def check_duplicates(report_duplicate, table, permitted_dups=None, normalize_itemname=normalize_name): # `table` is a SettingsTable or a VariableTable; either contains rows, # but only VariableTable also contains stat...
3231789
from django.apps import AppConfig class FeatureConfig(AppConfig): name = "small_eod.features"
3231791
import unittest # from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL from Vintageous.vi.constants import MODE_NORMAL # from Vintageous.vi.constants import MODE_VISUAL # from Vintageous.vi.constants import MODE_VISUAL_LINE from Vintageous.tests import ViewTest from Vintageous.tests import set_text from Vintageo...
3231807
from flask.ext.babel import gettext gettext('Home') gettext('Getting Started') gettext('User Stats') gettext('Pool Stats') gettext('Leaderboard') gettext('Extras') gettext('Simple Crypto Website') gettext('Source Code') gettext('Contact Us') gettext('Email') gettext('IRC') gettext('Reddit') gettext('Github')
3231827
import matplotlib.pyplot as plt def plot_many(x, y_list, x_label, y_label, title=None, filename=None, to_save=False): fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(111) if title is not None: ax.set_title(title) for i in range(len(y_list)) : plt.plot(x, y_list[i]) ax.set...
3231925
from ..registry import DETECTORS from .single_stage import SingleStageDetector import numpy as np import pycocotools.mask as mask_util import time import pdb @DETECTORS.register_module class Solo(SingleStageDetector): def __init__(self, backbone, neck, bbox_head,...
3231972
from enum import Enum class RangeRating(str, Enum): POOR = "POOR" FAIR = "FAIR" GOOD = "GOOD" def __str__(self) -> str: return str(self.value)
3231977
from conftest import skipif_yask import numpy as np from devito import Grid, Function, TimeFunction def test_basic_indexing(): """ Tests packing/unpacking data in :class:`Function` objects. """ grid = Grid(shape=(16, 16, 16)) u = Function(name='yu3D', grid=grid, space_order=0) # Test simple...
3232021
import importlib import sys import resource NUM_VECTORS = 10**7 module = None if len(sys.argv) == 2: module_name = sys.argv[1].replace('.py', '') module = importlib.import_module(module_name) else: print(f'Usage: {sys.argv[0]} <vector-module-to-test>') if module is None: print('Running test with buil...
3232046
from datetime import date, datetime from decimal import Decimal from functools import singledispatch import json from pprint import pprint class Stock: def __init__(self, symbol: str, date: date, open: Decimal, high: Decimal, low: Decimal, close: Decimal, volume: int): self.symbol = symbo...
3232120
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union import copy import os import numpy as np import torch import torch.distributed as dist import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from catalyst.core.engine import IEngine from catalyst.typing import ( D...
3232133
import launch from launch_ros.actions import ComposableNodeContainer from launch_ros.descriptions import ComposableNode # detect all 16h5 tags cfg_16h5 = { "image_transport": "raw", "family": "16h5", "size": 0.162, "max_hamming": 0, "z_up": True } def generate_launch_description(): composable_...
3232184
import os import lldb from lldb.plugins.scripted_process import ScriptedProcess class MyScriptedProcess(ScriptedProcess): def __init__(self, target: lldb.SBTarget, args : lldb.SBStructuredData): super().__init__(target, args) def get_memory_region_containing_address(self, addr: int) -> lldb.SBMemoryR...
3232204
import mmcv import numpy as np import torch def imrenormalize(img, img_norm_cfg, new_img_norm_cfg): """Re-normalize the image. Args: img (Tensor | ndarray): Input image. If the input is a Tensor, the shape is (1, C, H, W). If the input is a ndarray, the shape is (H, W, C). ...
3232207
from contextlib import contextmanager from os import environ from pathlib import Path from tempfile import TemporaryDirectory from textwrap import dedent import pytest from sanic import Sanic from sanic.config import DEFAULT_CONFIG, Config from sanic.exceptions import PyFileError @contextmanager def temp_path(): ...
3232220
import glob import os import random import math from pathlib import Path from hparams import hparams import numpy as np from nnmnkwii import preprocessing as P from wavenet_vocoder.util import linear_quantize, inv_linear_quantize import librosa """ QUANTIZE TYPES 0: Mulaw 1: Linear """ def get_piano_file(idx, dur...
3232229
import os import signal import sys import unittest import time import multiprocessing from satella.os import hang_until_sig class TestHangUntilSig(unittest.TestCase): @unittest.skipIf('win' in sys.platform, 'Needs a POSIX to run') def test_hang_until_sig(self): def child_process(): time...