id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1607561 | import abc
import pymia.data.extraction as extr
import pymia.data.transformation as tfm
import common.data.selectionhelper as select
import common.data.collate as collate
import common.trainloop.config as cfg
import common.trainloop.factory as factory
class Data:
def __init__(self, dataset, loader) -> None:
... |
1607600 | migration_map = {
"0.0.0": "54f8985b0ee5",
"0.2.4": "480e6618700d",
"0.2.5": "a179e5ca0ad2",
}
|
1607651 | import os
from typing import Any, Set, Tuple
import logging
from regipy.exceptions import RegistryKeyNotFoundException
from regipy.registry import RegistryHive, NKRecord
from regipy.utils import convert_wintime, calculate_sha1
logger = logging.getLogger(__name__)
def get_subkeys_and_timestamps(registry_hive):
... |
1607656 | import pytest
import functools
import torchdrift
import torch
def test_detector():
x = torch.randn(5, 5)
d = torchdrift.detectors.Detector()
d.fit(x)
with pytest.raises(NotImplementedError):
d(x)
def _test_detector_class(cls):
devices = ['cpu'] + (['cuda'] if torch.cuda.is_available() el... |
1607663 | import sys
import os
from pydoc import locate
class envParser():
def __init__(self):
self.arg_map = {}
self.help_msg = ''
try:
self.help = os.environ['HELP']
except Exception:
self.help = False
def add_option(self, option, val, info=''):
if opti... |
1607734 | import json
from django.shortcuts import render
from django.shortcuts import redirect
from vocgui.models import TrainingSet, Document, DocumentImage
def redirect_view(request):
"""
Redirect root URL
:param request: Current HTTP request
:param type: HttpRequest
:return: Redirection to api/
:r... |
1607740 | from typing import Optional, Set, List, Dict, ClassVar
import dbt.exceptions
from dbt import ui
import dbt.tracking
class DBTDeprecation:
_name: ClassVar[Optional[str]] = None
_description: ClassVar[Optional[str]] = None
@property
def name(self) -> str:
if self._name is not None:
... |
1607756 | import sys
sys.path.insert(0, '..')
import os
import math
from migen import *
from litex.soc.interconnect.csr import AutoCSR
from tools.common import *
class RAM64(Module, AutoCSR):
def __init__(self, max_words=None,
init=None, endianness="big",
debug=False):
self.init =... |
1607763 | import os.path as osp
from cvpods.configs.fcos_config import FCOSConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="detectron2://ImageNetPretrained/MSRA/R-50.pkl",
RESNETS=dict(DEPTH=50),
FCOS=dict(
CENTERNESS_ON_REG=True,
NORM_REG_TARGETS=True,
NMS_THRESH... |
1607770 | import numpy as np
import gdal
def create_mask_from_vector(vector_data_path, cols, rows, geo_transform,
projection, target_value=1):
"""Rasterize the given vector (wrapper for gdal.RasterizeLayer)."""
data_source = gdal.OpenEx(vector_data_path, gdal.OF_VECTOR)
layer = data_sou... |
1607771 | from litex.tools.litex_client import RemoteClient
wb = RemoteClient("192.168.1.50", 1234, csr_data_width=8)
wb.open()
regs = wb.regs
# # #
print("temperature: %f°C" %(regs.xadc_temperature.read()*503.975/4096 - 273.15))
print("vccint: %fV" %(regs.xadc_vccint.read()/4096*3))
print("vccaux: %fV" %(regs.xadc_vccaux.rea... |
1607794 | from test.integration.base import DBTIntegrationTest, use_profile
import os
import re
import yaml
import pytest
class TestDebug(DBTIntegrationTest):
@property
def schema(self):
return 'dbt_debug_049'
@staticmethod
def dir(value):
return os.path.normpath(value)
@property
def... |
1607845 | import aiohttp
import pytest
from understat import Understat
@pytest.fixture()
async def understat():
session = aiohttp.ClientSession()
fpl = Understat(session)
yield fpl
await session.close()
|
1607867 | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
def glm_mean_residual_deviance():
cars = h2o.import_file(path=pyunit_utils.locate("smalldata/junit/cars_20mpg.csv"))
s = cars[0].runif()
train = cars[s > 0.2]
vali... |
1607870 | from unittest.mock import Mock
import OpenCast.app.command.player as PlayerCmd
import OpenCast.app.command.playlist as PlaylistCmd
import OpenCast.domain.event.player as PlayerEvt
import OpenCast.domain.event.playlist as PlaylistEvt
from OpenCast.app.workflow.player import (
QueuePlaylistWorkflow,
QueueVideoWo... |
1607883 | import argparse
import os
import sys
from glob import glob
from os.path import basename, join, splitext
import librosa
import numpy as np
import pysinsy
import soundfile as sf
from nnmnkwii.io import hts
from nnsvs.io.hts import get_note_indices
def _is_silence(label):
is_full_context = "@" in label
if is_fu... |
1607903 | from __future__ import print_function
##-----
# Set job-specific inputs based on shell
# the following enviromental variables
# export COSMIC_MODE=True # or False
# export JOB_NAME="CosmicStream112220"
# export NEVENTS=1000
# export ALL_HISTS=True
# export TRIGGER_SET=HLT
# export READ_LIST_FROM_FILE=False # or True
# ... |
1607940 | import gym
import cv2
class Environment:
def __init__(self, params):
self.gym = gym.make(params.game)
self.observation = None
self.display = params.display
self.terminal = False
self.dims = (params.height, params.width)
def actions(self):
return self.gym.action... |
1607966 | import os
import fire
import numpy as np
import pandas as pd
import soundfile
from multiprocessing import Pool
from tqdm.auto import tqdm
# split2kaldi = {
# "fine-tune": "fine-tune",
# "dev": "dev",
# "test": "test",
# }
splits = {"fine-tune", "dev", "test"}
def read_utt2xxx(filename):
with open(f... |
1608018 | from datetime import datetime
import torch
from pathlib import Path
from detection import TrainNet
from networks import UNet
from propagation import GuideCall
if __name__ == "__main__":
torch.cuda.set_device(1)
date = datetime.now().date()
gpu = True
key = 2
weight_path = "./weight/best.pth"
... |
1608025 | from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class Article(models.Model):
STATUS_CHOICES = (
('d', 'part'),
('p', 'Published'),
) # 文章的状态
title = models.CharField('标题', max_length=100)
body = models.TextField('正文')
created... |
1608046 | import torch
import os
import options as opt
class Record(object):
def __init__(self):
super(Record, self).__init__()
self.n = 0
self.x = []
self.y = torch.tensor([], dtype=torch.float, device=opt.device,
requires_grad=False)
self.reward_best =... |
1608055 | expected_output = {
'switch': {
"1": {
'fan': {
"1": {
'state': 'ok'
},
"2": {
'state': 'ok'
},
"3": {
'state': 'ok'
}
},
... |
1608088 | import os
import shelve
from .base import BaseLimitedBackend, BaseBackend
import warnings
try:
basestring
except NameError:
basestring = str
class FileBackend(BaseBackend):
"""File-based cache backend.
"""
def __init__(self, filename):
self.filename = filename
if not isinstance(... |
1608122 | from gtmcore.container.container import SidecarContainerOperations
from gtmcore.mitmproxy.mitmproxy import MITMProxyOperations
import os
from gtmcore.activity.tests.fixtures import mock_redis_client
from gtmcore.fixtures import mock_labbook, mock_config_with_repo
from gtmcore.fixtures.container import build_lb_image_f... |
1608125 | import asyncio
import functools
import signal
import time
import traceback
from concurrent.futures.thread import ThreadPoolExecutor
import tornado.autoreload
import tornado.web
import tornado.wsgi
from django.core.management.base import BaseCommand
from hurricane.server import (
check_db_and_migrations,
comma... |
1608129 | import base64
import binascii
import math
import os
import uuid
from itertools import chain
from typing import Any, Dict, Mapping, Optional, Sized
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _
from typing_extensions import Final
... |
1608134 | from scapy.all import *
from mirage.core.module import WirelessModule
from mirage.libs.esb_utils.scapy_esb_layers import *
from mirage.libs.esb_utils.packets import *
from mirage.libs.esb_utils.constants import *
from mirage.libs.esb_utils.dissectors import *
from mirage.libs.esb_utils.rfstorm import *
from mirage.libs... |
1608135 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def show_aug(inputs, nrows=5, ncols=5, image=True):
plt.figure(figsize=(10, 10))
plt.subplots_adjust(wspace=0., hspace=0.)
i_ = 0
if len(inputs) > 25:
inputs = inputs[:25]
for idx in range(len(inputs)):
... |
1608163 | from rest_framework import serializers
from . import models
import posts.models as post_models
import posts.serializers as post_serializers
import api.models as api_models
import api.serializers as api_serializers
class ProfileCommentSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodFiel... |
1608168 | import copy
import json
import base64
from operator import itemgetter
from bson import json_util
import api_modules.utils
import utils.s3_utils
import utils.redis_utils
def _is_config_malformed(config_json_input):
config_json = copy.deepcopy(config_json_input)
if not "config_name" in config_js... |
1608180 | import os
import pyodbc
import pandas as pd
import numpy as np
import warnings
from typing import Union
from .utils import logging, winreg, find_registry_key, ReaderType
logging.basicConfig(
format=" %(asctime)s %(levelname)s: %(message)s", level=logging.INFO
)
def list_aspen_servers():
warnings.warn(
... |
1608196 | import inspect
from contextlib import contextmanager
from threading import RLock
from decorator import decorator
from .compat import with_metaclass, iteritems
__all__ = [
"ValidationError", "SchemaError", "Validator", "accepts", "returns", "adapts",
"parse", "parsing", "register", "register_factory",
"set_... |
1608227 | import FWCore.ParameterSet.Config as cms
#
# module to make a persistent copy of the genParticles from the top decay,
# using either status 2 equivalent particles (default) or status 3 particles
#
decaySubset = cms.EDProducer("TopDecaySubset",
## input particle collection of type edm::View<reco::GenParticle>
src =... |
1608256 | import hashlib
from hashlib import md5
'''
财联社 sign
'''
def USE_SHA(text):
if not isinstance(text, bytes):
text = bytes(text, 'utf-8')
sha = hashlib.sha1(text)
encrypts = sha.hexdigest()
return encrypts
def md5value(s):
a = md5(s.encode()).hexdigest()
return a
a = 'app=CailianpressWeb&last_time=1563498932&... |
1608264 | import numpy
import tqdm
from sklearn.manifold import TSNE
class _Transform:
def __init__(self):
pass
def fit(self, X):
return self.transform.fit_transform(X)
class tSNE(_Transform):
def __init__(self):
super().__init__()
self.transform = TSNE(n_components=2, verbose=1,... |
1608373 | import json
import pytest
from ethpm import (
Package,
)
from ethpm.exceptions import (
InsufficientAssetsError,
)
from ethpm.tools import (
get_ethpm_local_manifest,
get_ethpm_spec_manifest,
)
from web3.exceptions import (
PMError,
)
def test_pm_init_with_minimal_manifest(w3):
owned_manifest... |
1608380 | from ..factory import Method
class forwardMessages(Method):
chat_id = None # type: "int53"
from_chat_id = None # type: "int53"
message_ids = None # type: "vector<int53>"
disable_notification = None # type: "Bool"
from_background = None # type: "Bool"
as_album = None # type: "Bool"
|
1608396 | import re
import typing
from mitmproxy import ctx, exceptions
from mitmproxy.addons.modifyheaders import parse_modify_spec, ModifySpec
class ModifyBody:
def __init__(self):
self.replacements: typing.List[ModifySpec] = []
def load(self, loader):
loader.add_option(
"modify_body", t... |
1608400 | import json
import pprint
import tempfile
import subprocess
import mu.ctl.req as req
def view(args):
params = {'sim': args.sim, 'type': args.store_type, 'key': args.key}
r = req.send('view', params)
if r.status_code == 200:
pprint.pprint(json.loads(r.text), indent=2)
else:
... |
1608406 | from brownie import *
from brownie.network.contract import InterfaceContainer
import json
import time;
import copy
from scripts.utils import *
import scripts.contractInteraction.config as conf
def redeemFromAggregator(aggregatorAddress, tokenAddress, amount):
abiFile = open('./scripts/contractInteraction/ABIs/ag... |
1608422 | import logging
from itertools import chain
from oscar.core.loading import get_class, get_model
logger = logging.getLogger('oscar.offers')
OfferApplications = get_class('offer.results', 'OfferApplications')
class OfferApplicationError(Exception):
pass
class Applicator(object):
def apply(self, basket, user... |
1608426 | import json
import logging
import os
import sys
import signal
import socket
import time
import datetime
import inspect
from collections import OrderedDict
SIMAPP_VERSION="1.0"
SIMAPP_SIMULATION_WORKER_EXCEPTION = "simulation_worker.exceptions"
SIMAPP_TRAINING_WORKER_EXCEPTION = "training_worker.exceptions"
SIMAPP_S3_... |
1608429 | import argparse
import copy
import json
import logging
import time
from collections import OrderedDict
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from argmining.classifiers.classifier import get_classifier
from argmining.evaluation.gridsearch_report import report_best_results, best_cv_result
from... |
1608436 | from collections import defaultdict
import os
from biicode.common.settings.version import Version
'''
Module to create the cmake lines with the info of the boards.
It return the string that it is needed to compile and upload correctly the scketch to the Arduino.
This module is used always that biicode biicode create ... |
1608441 | from torch.nn.utils.rnn import pad_sequence
from torchsummary import summary
from gensim.models import Word2Vec
from scipy.sparse import csr_matrix
from scipy.sparse import vstack as s_vstack
import os
import time
import argparse
import warnings
from random_walk import random_walk
from random_walk_hyper import random... |
1608459 | import numpy as np
from starfish import ImageStack
from starfish.core.image.Filter.zero_by_channel_magnitude import ZeroByChannelMagnitude
def create_imagestack_with_magnitude_scale():
"""create an imagestack with increasing magnitudes"""
data = np.linspace(0, 1, 11, dtype=np.float32)
data = np.repeat(dat... |
1608485 | from __future__ import absolute_import, division, print_function
import scitbx.stl.vector # import dependency
import boost_adaptbx.boost.python as bp
bp.import_ext("scitbx_array_family_shared_ext")
from scitbx_array_family_shared_ext import *
import scitbx_array_family_shared_ext as ext
class pickle_import_trigger(ob... |
1608498 | data = (
'Han ', # 0x00
'Xuan ', # 0x01
'Yan ', # 0x02
'Qiu ', # 0x03
'Quan ', # 0x04
'Lang ', # 0x05
'Li ', # 0x06
'Xiu ', # 0x07
'Fu ', # 0x08
'Liu ', # 0x09
'Ye ', # 0x0a
'Xi ', # 0x0b
'Ling ', # 0x0c
'Li ', # 0x0d
'Jin ', # 0x0e
'Lian ', # 0x0f
'Suo '... |
1608502 | import sys
sys.path.append('..') #必须要, 设置project为源程序的包顶
# encoding:utf-8
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
'''
功能测试脚本
'''
# from project.Scrawl.QQMusic import QQMusic
# app1 = QQMusic.QQMusic()
# print(app1.search_by_keyword('纸短情长'))
# print(app1.search_by_id(... |
1608570 | import begin
@begin.start
def run(name: 'What, is your name?',
quest: 'What, is your quest?',
colour: 'What, is your favourite colour?'):
pass
|
1608606 | import bmesh
import bpy
import mathutils
from . import _common
class ahs_convert_curve_to_mesh(bpy.types.Operator):
bl_idname = 'object.ahs_convert_curve_to_mesh'
bl_label = "Curve > Mesh"
bl_description = "Convert Curve to Mesh"
bl_options = {'REGISTER', 'UNDO'}
is_join = bpy.props.BoolProperty... |
1608615 | import torch
from torch.nn.utils.rnn import PackedSequence
def gpu_device(gpu):
"""
Returns a device based on the passed parameters.
Parameters
----------
gpu: bool or int
If int, the returned device is the GPU with the specified ID. If False, the returned device
is the CPU, if Tru... |
1608659 | import os
import unittest
from io import StringIO
from cpylog import SimpleLogger
import pyNastran
from pyNastran.bdf.bdf import BDF, read_bdf
from pyNastran.bdf.bdf_interface.pybdf import BDFInputPy
from pyNastran.bdf.bdf_interface.include_file import (
split_filename_into_tokens, get_include_filename,
PurePo... |
1608671 | import json
import os
from copy import deepcopy
import traceback
from typing import OrderedDict
import commentjson
hostcwd = os.environ.get("HOSTCWD")
from .debugmode import docker_container
launch_json_py = {
#"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
... |
1608690 | from typing import TYPE_CHECKING, List
from django.conf import settings
from django.core.checks import Error, register
from django.utils.module_loading import import_string
if TYPE_CHECKING:
from .base_plugin import BasePlugin
@register()
def check_extensions(app_configs, **kwargs):
"""Confirm a correct imp... |
1608711 | from rlutil.logging.console import colorize
import inspect
# pylint: disable=redefined-builtin
# pylint: disable=protected-access
def arg(name, type=None, help=None, nargs=None, mapper=None, choices=None,
prefix=True):
def wrap(fn):
assert fn.__name__ == '__init__'
if not hasattr(fn, '_aut... |
1608717 | from gdsfactory.components.bend_s import bend_s
from gdsfactory.port import Port
from gdsfactory.routing.sort_ports import sort_ports
from gdsfactory.types import Route
def get_route_sbend(port1: Port, port2: Port, **kwargs) -> Route:
"""Returns an Sbend Route to connect two ports.
Args:
port1: start... |
1608725 | import unittest
import requests_mock
from grafana_api.grafana_face import GrafanaFace
class SnapshotTestCase(unittest.TestCase):
def setUp(self):
self.cli = GrafanaFace(
("admin", "admin"), host="localhost", url_path_prefix="", protocol="http"
)
@requests_mock.Mocker()
def t... |
1608748 | from celery import Celery
from celery.signals import after_setup_task_logger
from datetime import datetime
from deadshot import celery
from deadshot.api_server import create_app
from deadshot.configurations.api_server_config_data import Config
from pythonjsonlogger import jsonlogger
import sys
import logging
'''
This f... |
1608754 | from distutils.core import setup
setup(
name='ogame',
packages=['ogame'],
version='8.1.0.21',
license='MIT',
description='lib for the popular browsergame ogame',
author='PapeprPieceCode',
author_email='<EMAIL>',
url='https://github.com/alaingilbert/pyogame',
download_url='https://gi... |
1608771 | from mako.template import Template
template = """\
var ${[x[0].split('(')[0] for x in vardic['endo']['var']+vardic['con']['var']+vardic['exo']['var']].__str__().replace('[','').replace(']','').replace("'","")};
varexo ${[x[0].split('(')[0] for x in vardic['iid']['var']].__str__().replace('[','').replace(']','').repl... |
1608816 | from math import sqrt, pow
def linepoint(t, x0, y0, x1, y1):
"""Returns coordinates for point at t on the line.
Calculates the coordinates of x and y for a point
at t on a straight line.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the line,
x1 and ... |
1608827 | from __future__ import absolute_import, division, print_function
import time
from libtbx import easy_run
#import libtbx.load_env
import time
from iotbx import pdb
cryst_str = """\n
CRYST1 34.917 22.246 44.017 90.00 90.00 90.00 P 1
SCALE1 0.028639 0.000000 0.000000 0.00000
SCALE2 0.000000 ... |
1608871 | try:
from tensorboard.summary.writer.record_writer import RecordWriter # noqa F401
except ImportError:
raise ImportError('TensorBoard logging requires TensorBoard with Python summary writer installed. '
'This should be available in 1.14 or above.')
from .writer import FileWriter, SummaryW... |
1608893 | import os
import pytest
from buildtest.defaults import SCHEMA_ROOT
from buildtest.schemas.defaults import custom_validator
from buildtest.schemas.utils import load_recipe, load_schema
schema_file = "settings.schema.json"
settings_schema = os.path.join(SCHEMA_ROOT, schema_file)
settings_schema_examples = os.path.join(... |
1608921 | from straxen.misc import TimeWidgets, print_versions
import straxen
import unittest
def test_widgets():
tw = TimeWidgets()
wig = tw.create_widgets()
start, end = tw.get_start_end()
assert isinstance(start, int) and isinstance(end, int), "Should have returned unix time in ns as integer!"
assert en... |
1608940 | from decimal import Decimal
from ombpdf import fontsize
def test_get_font_size_stats_works(m_16_19_pages):
stats = fontsize.get_font_size_stats(m_16_19_pages)
assert stats.most_common(1) == [
(('TimesNewRomanPSMT', Decimal('16.2')), 21557),
]
def test_main_works(m_16_19_pages):
fontsize.mai... |
1608946 | import matplotlib.pyplot as plt
import numpy as np
LOG_FILE = './log.txt'
def get_log(log):
f = open(log, 'r')
lines = f.readlines()
f.close()
loss = []
for line in lines:
loss.append(float(line.strip('\n').split(' ')[1]))
return loss
def plot_iteration(log):
loss = get_log(log)
plt.plot(range(len(loss))... |
1608963 | from distutils.dir_util import copy_tree
from distutils.file_util import copy_file
from ssr.utility.os_extension import mkdir_safely
from ssr.utility.os_extension import makedirs_safely
from ssr.utility.os_extension import are_dirs_equal
from ssr.surface_rec.preparation.data_extraction.extraction_pipeline import (
... |
1608966 | from toee import *
import race_defs
###################################################
raceEnum = race_dwarf
raceSpec = race_defs.RaceSpec()
raceSpec.hit_dice = dice_new("0d0")
raceSpec.level_modifier = 0
raceSpec.help_topic = "TAG_DWARVES"
raceSpec.flags = 1
raceSpec.modifier_name = "Dwarf... |
1609022 | import pygame
from models import Asteroid, Spaceship
from utils import get_random_position, load_sprite
class SpaceRocks:
MIN_ASTEROID_DISTANCE = 250
def __init__(self):
self._init_pygame()
self.screen = pygame.display.set_mode((800, 600))
self.background = load_sprite("space", False... |
1609068 | import gzip
import hashlib
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional
REPO_IP_ADDRESS = "172.16.31.10"
REPO_PATH = "/var/www/repo.ghostbin.co"
DEBS_FOLDER = "debs"
def run_local_command(command: str) -> Optional[str]:
output = subprocess.check_outp... |
1609070 | import itertools
import re
import argparse
from collections import deque
from itertools import combinations
import rdkit
import rdkit.Chem as Chem
from .ifg import identify_functional_groups
lg = rdkit.RDLogger.logger()
lg.setLevel(rdkit.RDLogger.CRITICAL)
patt = r'[C,H][0-9]{2}[0,-1,1]'
IsH010 = lambda a: (a.GetS... |
1609095 | from piccolo.conf.apps import AppConfig, Command
from .commands.run import run
APP_CONFIG = AppConfig(
app_name="shell",
migrations_folder_path="",
commands=[Command(callable=run, aliases=["start"])],
)
|
1609144 | from collections import OrderedDict
import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from models.text_detect.craft import CRAFT
from backend.text_detect.craft_utils import (
adjustResultCoordinates,
getDetBoxes,
)
from backend.text_detect.imgp... |
1609148 | import csv
import copy
import json
import logging
import random
from collections import defaultdict
import torch
from torch.nn.utils.rnn import pad_sequence
MAX_CONTEXT_LEN = 50
logger = logging.getLogger(__name__)
def pad_squeeze_sequence(sequence, *args, **kwargs):
"""Squeezes fake batch dimension added by... |
1609181 | import unittest
import numpy as np
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainercv.experimental.links.model.fcis import ProposalTargetCreator
from chainercv.utils import generate_random_bbox
from chainercv.utils import mask_to_bbox
class TestProposalTa... |
1609198 | import numpy as np
import tensorflow as tf
import random
import matplotlib.pyplot as plt
from gm_generate import *
class IntermediateExample2(object):
"""
Class implementing variational inference for 1D gaussian mixture by using monte-carlo approximation to ELBO
"""
def __init__(self, M, N, K=1, sigma_mu=1.0, s... |
1609201 | from valentine.metrics import metrics as metrics_module
from typing import List, Dict, Tuple
metrics = {"names": ["precision", "recall", "f1_score", "precision_at_n_percent", "recall_at_sizeof_ground_truth"],
"args": {
"n": [10, 30, 50, 70, 90]
}}
def all_metrics(matches: List[Di... |
1609259 | from commands.command import Command
class ChangeBanCommand(Command):
def __init__(self):
self.detect_bans_in_message = False
def is_command_authorized(self, permissions=None):
return permissions and permissions.administrator
def execute(self, current_server, current_time, message, author):
words = message.... |
1609267 | import os.path, sys
import distutils.util
# Append the directory in which the binaries were placed to Python's sys.path,
# then import the D DLL.
libDir = os.path.join('build', 'lib.%s-%s' % (
distutils.util.get_platform(),
'.'.join(str(v) for v in sys.version_info[:2])
))
sys.path.append(os.path.abspath(libDi... |
1609268 | import numpy
from skimage.data import camera
from dexp.processing.interpolation.warp import warp
from dexp.utils.backends import Backend, CupyBackend, NumpyBackend
from dexp.utils.timeit import timeit
def demo_warp_2d_numpy():
try:
with NumpyBackend():
_demo_warp_2d()
except NotImplemente... |
1609281 | from __future__ import absolute_import, print_function, division
# standard library dependencies
from itertools import islice, chain
from collections import deque
from itertools import count
from petl.compat import izip, izip_longest, next, string_types, text_type
# internal dependencies
from petl.util.base import ... |
1609328 | import cv2
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import sampler
class CSVDataset(Dataset):
def __init__(self, df, transform):
self.df = df
self.transform = transform
def __getitem__(self, index):
row = self.df.iloc[index]
img = cv2.imre... |
1609339 | from collections import OrderedDict
from types import TracebackType
import functools
import warnings
import inspect
import sys
import ast
import pickle
import logbook
from sentinels import NOTHING
PYPY = hasattr(sys, 'pypy_version_info')
_logger = logbook.Logger(__name__)
def check_duplicate_functions(path):
c... |
1609404 | from typing import Optional
from boa3.model.operation.operator import Operator
from boa3.model.operation.unary import *
from boa3.model.operation.unary.unaryoperation import UnaryOperation
from boa3.model.type.itype import IType
class UnaryOp:
# Arithmetic operations
Positive = Positive()
Negative = Nega... |
1609408 | import pytest
@pytest.mark.parametrize("a", [r"qwe/\abc"])
def test_fixture(tmp_path, a):
assert tmp_path.is_dir()
assert list(tmp_path.iterdir()) == []
|
1609416 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import collections
import signal
import socket
import time
import msgpack
import requests
import simplejson
import sys
import six
from paramiko.ssh_exception import NoValidConnectionsError
from aetros.utils ... |
1609430 | import pathlib
import ruamel.yaml as yaml
root = pathlib.Path(__file__).parent
for key, value in yaml.safe_load((root / 'data.yaml').read_text()).items():
globals()[key] = value
|
1609437 | import pydapper
# NOTE: setting autocommit to True will cause the transaction to commit immediately
with pydapper.connect("mysql+mysql://root:pydapper@localhost:3307/pydapper", autocommit=True) as commands:
print(type(commands))
# <class 'pydapper.mysql.mysql_connector_python.MySqlConnectorPythonCommands'>
... |
1609462 | import sys
from ctypes import *
import ctypes
from .DAQmxConstants import DAQmx_copyright_year
# New types definitions
# Correspondance between the name used in the NiDAQmx.h file and ctypes
int8 = c_byte
uInt8 = c_ubyte
int16 = c_short
uInt16 = c_ushort
int32 = c_int
uInt32 = c_uint
float32 = c_float
float64 = c... |
1609468 | import argparse
import torch
import torch.nn as nn
multiply_adds = 1
def count_convNd(m, x, y):
x = x[0]
kernel_ops = m.weight.size()[2:].numel()
bias_ops = 1 if m.bias is not None else 0
# cout x oW x oH
total_ops = y.nelement() * (m.in_channels//m.groups * kernel_ops + bias_ops)
m.total_... |
1609518 | from .initialization_network import InitNet
from .learn_module_fcn import LearnModuleFCN
from .learn_module_conv import LearnModuleConv
|
1609582 | class RevealAccess(object):
"""
A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('Retrieving', s... |
1609592 | from django.urls import path, include
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from rest_framework.routers import DefaultRouter
from . api import ChatMessageModelViewSet, UserModelViewSet
from . import views
router = DefaultRouter()
router.register(r'mess... |
1609594 | import sys
import time
import pygame
import random
from pygame.locals import *
PIX = 80
SCRPIX = 60
SIZ = 0
class _2048Map(object):
def __init__(self, siz):
self.siz = siz
self.scr = 0
self.mp = [[0 for i in range(siz)] for i in range(siz)]
self.add()
self.add()
def add(self):
f = False
for i in rang... |
1609627 | import torch
import random
import numpy as np
def set_seed(seed=0):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
return True |
1609644 | import torch
from torch import nn
from torch.nn import functional as F, Parameter
import numpy as np
def array1d_repr(t, format='{:.3f}'):
res = ''
for i in range(len(t)):
res += format.format(float(t[i]))
if i < len(t) - 1:
res += ', '
return '[' + res + ']'
def array2d_repr(... |
1609657 | from nose.tools import assert_equal, assert_true, assert_raises, assert_almost_equal
import shannon.discrete as discrete
from numpy import array, mod, arange, histogram
from numpy.random import randint, randn
from numpy.testing import assert_array_almost_equal, assert_array_equal
import pdb
def test_entropy():
# t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.