id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1705910 | import os
import itertools
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils as tutils
import torchvision.transforms as transforms
import numpy as np
from tqdm import tqdm
from fsgan.utils.obj_factory import obj_factory
from fsgan.utils.tensorboard_logger import TensorBoardLogger
from fsgan... |
1705951 | from uio.utils import fix_ctypes_struct
import ctypes
from ctypes import c_uint8 as ubyte, c_uint16 as ushort, c_uint32 as uint
from .eirq import EIrq
pos_t = uint # position counter
tim_t = uint # unit timer
wdt_t = ushort # watchdog timer
imt_t = ushort # interval measurement timer
@fix_ctypes_struct
class ... |
1705970 | from django.conf import settings
from django.views.generic import TemplateView
class HelpView(TemplateView):
template_name = 'devilry_help/help.django.html'
def get_context_data(self, **kwargs):
context = super(HelpView, self).get_context_data(**kwargs)
context['official_help_url'] = settings... |
1705989 | import os
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.geos import Point
from django.db import transaction
from geotrek.core.models import Topology
from geotrek.trekking.models import POI, POIT... |
1705992 | import pytest
def test_ex8():
import pandas as pd
import numpy as np
from tcrdist.repertoire import TCRrep
df = pd.read_csv('dash.csv')
df = df[df.epitope.isin(['PA'])]
tr = TCRrep(cell_df=df, chains=['alpha','beta'], organism='mouse')
tr.tcrdist2(processes = 1,
metric = 'hamming',
reduce = True,
d... |
1705995 | from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('owner/<int:driver_id>', views.get_driver),
path('auto/', views.CarView.as_view()),
path('owners/', views.get_drivers),
path('owner/new/', views.get_driver_form),
path... |
1706004 | import doctest
import pytest
from insights.parsers import ParseException
from insights.tests import context_wrap
from insights.parsers import sendq_recvq_socket_buffer
from insights.parsers.sendq_recvq_socket_buffer import SendQSocketBuffer, RecvQSocketBuffer
SENDQ_SOCKET_BUFFER = """
4096 16384 4194304
""".strip()
... |
1706013 | import pytest
from freezegun import freeze_time
import datetime
from io import BytesIO
from aerofiles.igc import Writer
@pytest.fixture()
def output():
return BytesIO()
@pytest.fixture()
def writer(output):
return Writer(output)
def test_write_line(writer):
writer.write_line('line')
assert writ... |
1706015 | import six
from exporters.transform.base_transform import BaseTransform
from exporters.python_interpreter import Interpreter, create_context
class PythonMapTransform(BaseTransform):
"""Transform implementation that maps items using Python expressions
"""
supported_options = {
"map": {'type': six.s... |
1706043 | class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
jobs = sorted(zip(startTime, endTime, profit), key=lambda v: v[1])
dp = [[0, 0]]
for s, e, p in jobs:
i = bisect.bisect(dp, [s + 1]) - 1
if dp[i][1] + p > dp[-... |
1706070 | import copy
from typing import List, Union, Tuple, Dict
import statistics
from itertools import chain, repeat, islice
from .node import Node, NodeType
def pad_list(iterable, size, padding=None):
return list(islice(chain(iterable, repeat(padding)), size))
class Connection(object):
connections: Dict['Connectio... |
1706093 | import logging
logging.basicConfig(level=logging.DEBUG)
# export SLACK_API_TOKEN=<PASSWORD>-***
# python3 integration_tests/samples/readme/proxy.py
import os
from slack_sdk.web import WebClient
from ssl import SSLContext
sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "h... |
1706095 | from anchore_engine.db import GrypeDBFeedMetadata
from anchore_engine.subsys import logger
class NoActiveGrypeDB(Exception):
def __init__(self):
super().__init__("No active grypedb available")
def get_most_recent_active_grypedb(session) -> GrypeDBFeedMetadata:
"""
Queries active GrypeDBFeedMetad... |
1706167 | N, G = map(int, input().split())
i = 1
runa_valor_amizade = []
while i <= N:
ri, vi = input().split()
vi = int(vi)
runa_valor_amizade.append(ri)
runa_valor_amizade.append(vi)
i+= 1
X = int(input())
recitadas = input().split()
recitadas = recitadas[:X]
soma = 0
for i in range(X):
valor_a_ser_p... |
1706186 | from django.test import TestCase
from backend.models import EventModel, ScheduleModel, TenantModel, AwsEnvironmentModel
from datetime import datetime
class EventModelTestCase(TestCase):
# イベントが登録されていないことを確認する
def test_is_empty(self):
objects_all = EventModel.objects.all()
self.asser... |
1706216 | import numpy as np
from sdcit.hsic import HSIC
from sdcit.utils import rbf_kernel_median, residual_kernel, residualize, columnwise_normalizes
def FCIT_noniid_K(Kx, Ky, cond_Kx, cond_Ky, Kz=None, seed=None):
if seed is not None:
np.random.seed(seed)
RX1 = residual_kernel(Kx, cond_Kx)
RY1 = residu... |
1706234 | from inspect import signature
# TODO: add interface and for checking labels at the training and testing stages (by analogy with sklearn)
# TODO: override __repr__ method by analogy with sklearn and how base Decomposition interface.
class Classifier(object):
""" General interface for all classes that describe clas... |
1706243 | import base64
import datetime
import httplib2
import requests
import time
import urllib.parse
import Crypto.Hash.SHA256 as SHA256
import Crypto.PublicKey.RSA as RSA
import Crypto.Signature.PKCS1_v1_5 as PKCS1_v1_5
class GCS:
host = 'storage.googleapis.com'
def __init__(self, login, key, bucket_ns = None):
s... |
1706289 | def get_error_test_cases(errors):
return [ERRORS.get(e) for e in errors]
ERRORS = {
'invalid-parameters': {
"parameter": {
"example": [
"The example field is required"
]
},
"type": "https://www.rev.ai/api/v1/errors/invalid-parameters",
"t... |
1706324 | class Solution(object):
# def letterCasePermutation(self, S):
# ans = [[]]
# for char in S:
# n = len(ans)
# if char.isalpha():
# # Double the ans
# for i in xrange(n):
# ans.append(ans[i][:])
# ans[i].a... |
1706332 | import unittest
import filecmp
import os
from clockwork.ena import submission_receipt
modules_dir = os.path.join(os.path.dirname(os.path.abspath(submission_receipt.__file__)), os.pardir)
data_dir = os.path.normpath(os.path.join(modules_dir, 'tests', 'data', 'ena', 'submission_receipt'))
class TestSubmissionReceipt(u... |
1706343 | import unittest
from accumulator.multipointer_accumulator import get_representatives, MultipointerAccumulatorFactory
from .base import BaseAccumulatorTestSuite
class GeneralizedAccumulatorTestSuite(BaseAccumulatorTestSuite, unittest.TestCase):
"""Generalized accumulator test cases."""
def test_get_represent... |
1706346 | import unittest
from ast2vec import Source
from ast2vec import bblfsh_roles
from snippet_ranger import utils
from snippet_ranger.tests import models
class UtilsTests(unittest.TestCase):
def test_get_func_names_bow(self):
source = Source().load(models.TEST_LIB)
bow = utils.get_func_names_bow(sour... |
1706394 | from ..._core import ensure_contiguous_state
from sympl import Stepper, get_constant
import logging
try:
from . import _simple_physics as phys
except ImportError as error:
logging.warning(
'Import failed. Simple Physics is likely not compiled and will not be'
'available.'
)
print(error)
... |
1706417 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from torch_scatter import scatter_mean
import torch_geometric.transforms as T
from torch_geometric.utils import normalized_cut, to_dense_batch
from torch_geometric.nn import MetaLayer, SplineConv... |
1706431 | class Metrics(object):
@staticmethod
def h_metric(design_candidate):
cores = [d * 1. for d in design_candidate if d > 0]
core_types = len(cores)
core_counts = sum(cores) * 1.
return core_types / core_counts
|
1706442 | import logging
import time
from signal import SIGTERM
from subprocess import PIPE, Popen
from threading import Thread
logger = logging.getLogger(__name__)
def is_fileobj_open(fileobj):
return fileobj and not getattr(fileobj, 'closed', False)
class NBSubprocThread(Thread):
DEFAULT_POLL_INTERVAL_SEC = 0.01
... |
1706464 | from __future__ import annotations
from .extension import Backends, backends
from .datasource import DataSource, Dormitory, InitContextCallable
|
1706493 | from hypergol import BaseData
class LabelledArticle(BaseData):
def __init__(self, labelledArticleId: int, articleId: int, labelId: int):
self.labelledArticleId = labelledArticleId
self.articleId = articleId
self.labelId = labelId
def get_id(self):
return (self.labelledArticle... |
1706499 | import cv2
import numpy as np
from matplotlib import pyplot as plt
image = cv2.imread('/home/pi/book/dataset/ruler.512.tiff', 1)
input = cv2.cvtColor(image, cv2.COLOR_BGR2RGB )
rows, cols, channels = input.shape
points1 = np.float32([[0, 0], [400, 0], [0, 400], [400, 400]])
points2 = np.float32([[0,0], [300, 0], [0, 30... |
1706514 | import pytest
def test_envvar_parsing():
from mpi4jax._src.decorators import _is_falsy, _is_truthy
assert _is_truthy("1")
assert not _is_falsy("1")
assert not _is_truthy("false")
assert _is_falsy("false")
assert not _is_truthy("foo")
assert not _is_falsy("foo")
def test_missing_omnist... |
1706533 | import numpy
from matplotlib import pyplot
def bisection(f, interval, max_steps=100, tol=1e-10):
x_lo, x_hi = interval
x = (x_lo + x_hi)/2
f_lo = f(x_lo)
f_hi = f(x_hi)
fx = f(x)
steps = 0
while steps < max_steps and abs(fx) > tol and (x_hi - x_lo) > tol:
steps = steps + 1
... |
1706560 | import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
argum... |
1706583 | from pkg_resources import get_distribution
from .decorators import *
# Set package information
__version__ = get_distribution("pytorch_common").version
__author__ = "<NAME>"
|
1706592 | import contextlib
import importlib
import os
import sys
# Resources
TESTDIR = os.path.dirname(os.path.abspath(__file__))
MAINDIR = os.path.dirname(TESTDIR)
DOCSDIR = os.path.join(MAINDIR, "docs")
DATADIR = os.path.join(TESTDIR, "data")
# Shortcut to try import modules/functions
def try_import(*paths):
for path in... |
1706611 | from vispy.scene.visuals import Compound, Line, Text
from ..filters.tracks import TracksFilter
from .clipping_planes_mixin import ClippingPlanesMixin
class TracksVisual(ClippingPlanesMixin, Compound):
"""
Compound vispy visual for Track visualization with
clipping planes functionality
Components:
... |
1706633 | import time
import logging
import fire
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
import models
import utils
from dataset import ImageDataset
logging.getLogger().setLevel(logging.INFO)
def run(model_name, output_dir, dataname, data_dir='./data', batch_size=16, test_run=-1):
... |
1706640 | import numpy as np
def defaultMotionPlanners():
return {
'home': HomeMotionPlanner,
'search': SearchMotionPlanner,
'aboveTarget': AboveTargetMotionPlanner,
'approach': ApproachMotionPlanner,
'target': TargetMotionPlanner,
# 'clean': CleanMotionPlanner,
# 'ri... |
1706650 | from pyrez.models import APIResponse
class Search(APIResponse):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.teamFounder = kwargs.get("Founder", '') or ''
self.teamName = kwargs.get("Name", '') or ''
self.players = kwargs.get("Players", 0) or 0
self.teamTag =... |
1706654 | import numpy as np
# from tsnecuda import TSNE
# from sklearn.manifold import TSNE
from data.IncrementalTSNE import IncrementalTSNE
import fastlapjv
from matplotlib import pyplot as plt
from scipy.spatial.distance import cdist
from fastlapjv import fastlapjv
import math
from time import time
class GridLayout(object):
... |
1706666 | import pandas as pd
from sklearn.metrics import classification_report
import config
def generate_csv_report(y_true_inv, y_pred_inv, label_encoder, accuracy) -> None:
"""
Print and save classification report for accuracy, precision, recall and f1 score metrics.
:return: None.
"""
# Classification... |
1706672 | from parglare import get_collector
def test_collector_can_use_unicode_in_python_2():
action = get_collector()
def f(context, node):
return node
action('f_action')(f)
|
1706673 | import numpy as np
import tensorflow as tf
from tensorflow.python.util import nest
def combine_flat_list(_structure, _flat_list, axis=1):
_combined = []
for i in range(len(_flat_list[0])):
t = []
for v in _flat_list:
t.append(v[i])
if len(t[0].get_shape()) == 0:
... |
1706683 | from .Extract import (is_bearish_engulfing, is_bullish_engulfing, is_dark_cloud_cover,
is_doji, is_evening_star, is_falling_three_methods, is_hammer, is_hanging_man,
is_inverse_hammer, is_morning_star, is_piercing_line, is_rising_three_methods,
is_shooti... |
1706704 | import numpy as np
import pyfastnoisesimd as fns
# Num workers does not seem to matter.
# It only seems to be an issue if the middle dimension is not divisible
# by the SIMD length?
n = fns.Noise(numWorkers=1)
shape = [27, 127, 1]
for I in range(10):
# print(I)
res = n.genAsGrid(shape)
print('Finished succes... |
1706795 | import json
import numpy as np
from ..utils import *
from .. import logger
class Randomizer:
def __init__(self, randomization_config_fp='default_dr.json', default_config_fp='default.json'):
try:
with open(get_file_path('randomization/config', randomization_config_fp, 'json'), mode='r') as f:
... |
1706799 | import numpy as np
from keras.models import load_model
from utils.img_process import process, yolo_img_process
import utils.yolo_util as yolo_util
import tensorflow as tf
import cv2
from PIL import Image
import pickle
from deepgtav.messages import frame2numpy
import gzip
config = tf.ConfigProto()
config.gpu_options.al... |
1706811 | import pytest
from tests.functional.coercers.common import resolve_unwrapped_field
@pytest.mark.asyncio
@pytest.mark.ttftt_engine(
name="coercion",
resolvers={"Query.nonNullIntField": resolve_unwrapped_field},
)
@pytest.mark.parametrize(
"query,variables,expected",
[
(
"""query { ... |
1706821 | import tensorflow as tf
from transforms.audio import ops
NAME_TO_FUNC = {
'Identity': tf.identity,
'FreqMask': ops.freq_mask,
'TimeMask': ops.time_mask,
'FreqRescale': ops.freq_rescale,
'TimeRescale': ops.time_rescale,
'FreqWarping': ops.freq_warping,
'TimeWarping': ops.time_warping,
'D... |
1706836 | from distutils.core import setup
import os
from pathlib import Path
from setuptools import find_packages
import versioneer
CODE_DIRECTORY = Path(__file__).parent
def read_file(filename):
"""Source the contents of a file"""
with open(
os.path.join(os.path.dirname(__file__), filename), encoding="utf-... |
1706847 | from mock import Mock
from oauth2 import Provider
from oauth2.compatibility import json
from oauth2.error import OAuthInvalidError, OAuthInvalidNoRedirectError
from oauth2.grant import (AuthorizationCodeGrant, GrantHandler, RefreshToken,
ResourceOwnerGrant)
from oauth2.store import ClientStore... |
1706875 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import logbook
import roll_history
debug_enabled = False
def debug_print(*args):
if debug_enabled:
for arg in args:
print arg,
return
def handle_sanctuary(to_hit_eo, d20a):
tgt = d20a.target
if tgt == OBJ_H... |
1706892 | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli, logger
import os
class TypescriptOpenPluginDefaultSettingFile(sublime_plugin.WindowCommand):
def run(self):
default_plugin_setting_path = os.path.join(PLUGIN_DIR, "Preferences.sublime-settings")
sublime.active_window().... |
1706917 | def test_args(x,y):
"""
Number * Number -> Number
Hyp : empty
return the sum of x and y
"""
return x+y
assert test_args(1,2) == 3
assert test_args(1.5,22,5) == 24
|
1707043 | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spin_basis_general
from quspin.basis.transformations import square_lattice_trans
from quspin.operators import hamiltonian
import numpy as np
from itertools ... |
1707053 | import torch
import torch.nn as nn
from pytorch_wavelets.dwt.lowlevel import *
def _SFB2D(low, highs, g0_row, g1_row, g0_col, g1_col, mode):
mode = int_to_mode(mode)
lh, hl, hh = torch.unbind(highs, dim=2)
lo = sfb1d(low, lh, g0_col, g1_col, mode=mode, dim=2)
hi = sfb1d(hl, hh, g0_col, g1_col, mode=m... |
1707055 | import pytest
import numpy as np
import torch
from torch import nn
import torch.optim as optim
import nics_fix_pt as nfp
# When module_cfg's nf_fix_paramparam is set , it means scale=-1, bitwidth=2, method=FIX_AUTO, see the default config in conftest module_cfg fixture.
@pytest.mark.parametrize(
"module_cfg, cas... |
1707089 | import tensorflow as tf
import os.path as osp
import os
op_file = 'roi_pooling_op_gpu_cuda8.so' # for CUDA 8
#op_file = 'roi_pooling_op_gpu.so' # CUDA 7.5
filename = osp.join(osp.dirname(__file__), op_file)
_roi_pooling_module = tf.load_op_library(filename)
roi_pool = _roi_pooling_module.roi_pool
roi_pool_grad = _r... |
1707139 | import torch, os, numpy as np, copy
import cv2
import glob
from .map import GeometricMap
class preprocess(object):
def __init__(self, data_root, seq_name, parser, log, split='train', phase='training'):
self.parser = parser
self.dataset = parser.dataset
self.data_root = data_root
... |
1707149 | from typing import List
class Solution:
row_state = [[False for i in range(10)] for _ in range(9)]
column_state = [[False for i in range(10)] for _ in range(9)]
box_state = [[False for i in range(10)] for _ in range(9)]
board = []
def solveSudoku(self, board: List[List[str]]) -> None:
se... |
1707166 | import os, json, re
from urllib.request import urlopen
def download(url, typ, rewrite = False):
start = url.index('.com/')
name = 'data/' + typ + '/' + url[start+5:].replace('/', '-')
if not os.path.exists(name) or rewrite:
try:
resource = urlopen(url)
except:
print('Не существует!', url)
return 1 #ra... |
1707192 | import sys
import os
UTILS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'utils')
sys.path.insert(1, UTILS_DIR)
from training import train, test
if __name__ == '__main__':
"""
This assumes a pretrained actor at the actor-path.
"""
BREAK_EARLY = False
BATCH_SIZE = 500
... |
1707197 | from fastapi import APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from httpx._exceptions import HTTPError
from app.core.utils import has_inquest_api_key, has_virustotal_api_key
from app.schemas.eml import Attachment
from app.schemas.submission import SubmissionResul... |
1707248 | import pymel.core as pm
import logging
log = logging.getLogger("ui")
class BaseTemplate(pm.ui.AETemplate):
def addControl(self, control, label=None, **kwargs):
pm.ui.AETemplate.addControl(self, control, label=label, **kwargs)
def beginLayout(self, name, collapse=True):
pm.ui.AETe... |
1707261 | import tensorflow as tf
from easy_rec.python.core.metrics import metric_learning_average_precision_at_k
from easy_rec.python.core.metrics import metric_learning_recall_at_k
from easy_rec.python.layers import dnn
from easy_rec.python.layers.common_layers import gelu
from easy_rec.python.layers.common_layers import high... |
1707268 | from decorator import decorate
def _deprecated(func, *args, **kw):
return func(*args, **kw)
def deprecated(func):
return decorate(func, _deprecated)
|
1707273 | import os
import numpy as np
import cv2
from paddle.fluid.io import Dataset
class LaneDataSet(Dataset):
def __init__(self, dataset_path, data_list='train', transform=None, is_val=False):
self.img = os.listdir(os.path.join(dataset_path, data_list))
self.is_val = is_val
self.is_testing = 'te... |
1707315 | import numpy as np
import unittest
from algorithm_ncs.benchmark import benchmark_func
from algorithm_ncs.problem import load_problem
def load_test_data(file_path):
with open(file_path, "r") as f:
lines_data = f.readlines()
lines = []
for data in lines_data:
line = []
... |
1707335 | import os
import sys
import random
import argparse
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
from utils.utilities import (mkdir, write_lst)
random.seed(1234)
instr_tags = "vn,vc,va,fl,cl,sax,tpt,tbn,bn,hn,tba,db,ob"
instrs = "Violin,Cello,Viola,Flute,Clarinet,Saxophone,Trumpet,Trombone,Bassoon,Horn,Tuba... |
1707366 | from unittest import TestCase
import re
import triegex
class TriegexTest(TestCase):
def findall(self, triegex, string):
return re.findall(triegex.to_regex(), string)
def test_basic(self):
t = triegex.Triegex('Jon')
self.assertListEqual(self.findall(t, '<NAME>'), ['Jon'])
def te... |
1707415 | import functools
import os
import pickle
import torch
from torch import distributed as dist
def is_main_process():
rank, _ = get_dist_info()
return rank == 0
def get_dist_info():
if dist.is_available() and dist.is_initialized():
rank = dist.get_rank()
world_size = dist.get_world_size()
... |
1707422 | const_T = Hyper()
const_M = Hyper()
@Runtime([const_M, const_M, const_M], const_M)
def Update(prev, cur, offset):
return (prev + cur + offset) % 2
offset = Param(const_M)
do_anything = Param(2)
initial_tape = Input(const_M)[2]
tape = Var(const_M)[const_T]
for t in range(2):
tape[t].set_to(initial_tape[t])
... |
1707423 | import itertools
import vim
from pathfinder.debytes import debytes
last_output = None
def strtrans(string):
"""Convert special characters like '' to '^D'."""
escaped_string = string.replace("'", "\\'").replace("\\", "\\\\")
return vim.eval(f"strtrans('{escaped_string}')")
def get_count(motion, count... |
1707468 | from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import hashlib
# travis encrypt PASSWORD=password -a -x
sha = SHA256.new()
sha.update(raw_input('Password:'))
key = sha.hexdigest()[:AES.block_size*2]
text = open('emails.txt', 'rb').read()
iv = text[:AES.block_size]
cipher = text... |
1707489 | params = dict()
params['num_classes'] = 101
params['dataset'] = '/home/Dataset/UCF-101-origin'
#params['dataset'] = '/home/Dataset/hmdb'
params['epoch_num'] = 150#600
params['batch_size'] = 8
params['step'] = 10
params['num_workers'] = 4
params['learning_rate'] = 0.001
params['momentum'] = 0.9
params['weight_decay'... |
1707541 | import requests
APEX_VALUES = ['172.16.31.10']
CNAME_VALUE = ["domains.tumblr.com"]
RESPONSE_FINGERPRINT = "Whatever you were looking for doesn't currently exist at this address."
def detector(domain, ip, cname):
if APEX_VALUES:
if ip in APEX_VALUES:
return True
if filter(lambda x: x in cname... |
1707558 | import pytest
from tasktiger import Task, TaskNotFound
from .tasks import simple_task
from .utils import get_tiger
class TestTaskFromId:
@pytest.fixture
def tiger(self):
return get_tiger()
@pytest.fixture
def queued_task(self, tiger):
return tiger.delay(simple_task)
def test_ta... |
1707569 | import numpy
from PIL import Image
pascal_colormap = [
0 , 0, 0,
0.5020, 0, 0,
0, 0.5020, 0,
0.5020, 0.5020, 0,
0, 0, 0.5020,
0.5020, 0, 0.5020,
0, 0.5020, 0.5020,
0.5020, 0.5020, ... |
1707592 | import unittest
import numpy as np
import SimpleITK as sitk
import pymia.filtering.filter as pymia_fltr
import pymia.filtering.preprocessing as pymia_fltr_prep
class TestNormalizeZScore(unittest.TestCase):
def setUp(self):
# set up image
image = sitk.Image((4, 1), sitk.sitkUInt8)
image.... |
1707593 | from DRecPy.Evaluation.Processes import predictive_evaluation
import pytest
import pandas as pd
from DRecPy.Dataset import InteractionDataset
from DRecPy.Recommender.Baseline import UserKNN
from DRecPy.Evaluation.Metrics import RMSE
from DRecPy.Evaluation.Metrics import MSE
@pytest.fixture(scope='module')
def train_i... |
1707595 | import pickle
import os
import numpy as np
class Params(object):
""" A simple dictionary that has its keys as attributes available. """
def __init__(self):
pass
def __str__(self):
s = ""
for name in sorted(self.__dict__.keys()):
s += "%-18s %s\n" % (name... |
1707619 | from agent.pipeline.config.stages.base import Stage
from agent import pipeline, source
class JDBCSource(Stage):
def get_config(self) -> dict:
return {
'query': pipeline.jdbc.query.Builder(self.pipeline).build(),
** self.get_connection_configs()
}
def get_connection_con... |
1707653 | import sys,os
import argparse
import numpy as np
import json
import heapq
import random
import numbers
# utils
def flatten(l):
""" Merges a list of lists into a single list. """
return [item for sublist in l for item in sublist]
class AveragePrecisionCalculator(object):
"""Calculate the average precision and av... |
1707674 | import math
import logging
from typing import Optional, TypeVar
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import Module
from .. import functional as F
from .. import _reduction as _Reduction
from ...distributed import gather
# See https://mypy.readthedocs.io/en/latest/generics.html#ge... |
1707711 | import unittest
from buildFeats import BuildFeatsV2
import os
class TestBuildFeatsV2(unittest.TestCase):
def setUp(self):
unittest.TestLoader.sortTestMethodsUsing = None
self.func = BuildFeatsV2()
def test(self):
self.assertTrue(True)
def test_load_Feats(self):
directory_... |
1707714 | from numpy import array
from sympy import sin, cos, pi, exp
def flux(u, q, w, v, x, t, mu, eta):
z = x[0];
r = x[1];
f = mu*r*q;
return f;
def source(u, q, w, v, x, t, mu, eta):
z = x[0];
r = x[1];
s = array([sin(r)/exp(z)]);
return s;
def fbou(u, q, w, v, x, t, mu, eta, uhat, n, tau)... |
1707715 | import json
from ariadne import graphql_sync
from ariadne.constants import PLAYGROUND_HTML
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .graphql import schema
@csrf_exempt
def graphql_view(request... |
1707723 | import torch
import torch.nn as nn
class Discriminator(nn.Module):
"""Discriminator Network"""
def __init__(self):
super(Discriminator, self).__init__()
self.in_channel = 3
self.ndf = 64
self.out_channel = 1
self.main = nn.Sequential(
nn.Conv2d(self.in_cha... |
1707729 | class SimpleTrainer:
"""Orchestrates training of an RL algorithm.
This trainer is "simple" in that it doesn't manager distributed sampling.
"""
def __init__(self, sampler, agent, logger):
"""
Args:
sampler: A class that samples trajectories from an environment.
... |
1707737 | import FWCore.ParameterSet.Config as cms
process = cms.Process("ANALYSIS")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(100)
)
process.source = cms.Source (
"PoolSource",
fileNames = cms.untracked.vstring(
'file:display.root'
),
secondaryFileNames = cms.untrac... |
1707738 | from World.Object.model import Object
from World.Object.Constants.UpdateObjectFields import ObjectField
from World.WorldPacket.UpdatePacket.Constants.ObjectUpdateType import ObjectUpdateType
from World.WorldPacket.UpdatePacket.Builders.UpdatePacketBuilder import UpdatePacketBuilder
from DB.Connection.RealmConnection im... |
1707791 | import json
import os
_THIS_DIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(_THIS_DIR, "chars_to_jyutping.json"), encoding="utf8") as f:
CHARS_TO_JYUTPING = json.load(f)
with open(os.path.join(_THIS_DIR, "lettered.json"), encoding="utf8") as f:
LETTERED = json.load(f)
|
1707798 | import os
import pytest
from topo_processor.metadata.metadata_validators.metadata_validator_tiff import MetadataValidatorTiff
from topo_processor.stac import Asset, Item
def test_check_validity():
source_path = os.path.join(os.getcwd(), "test_data", "tiffs", "SURVEY_1", "CONTROL.tiff")
asset = Asset(source_... |
1707799 | import numpy as np
import numpy.linalg as la
import scipy
import skimage
import PIL
from PIL import Image as PILImage
import TimestampedPacketMotionData_pb2
import argparse
import os
import google.protobuf.json_format
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import TimestampedImage_pb2
im... |
1707834 | import os
import time
import unittest
import uuid
import warnings
from lib.config import gen_datadog_agent_config
from lib.const import CSPM_RUNNING_DOCKER_CHECK_LOG, CSPM_START_LOG
from lib.cspm.api import wait_for_compliance_event, wait_for_finding
from lib.cspm.finding import is_expected_docker_finding, parse_outpu... |
1707929 | import argparse
import pathlib
import siml
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'settings_yaml',
type=pathlib.Path,
help='YAML file name of settings.')
parser.add_argument(
'-o', '--out-dir',
type=pathlib.Path,
default=None,
... |
1707944 | import torch
import torch.nn as nn
from .modules.legacy import *
class ConvLayer(nn.Sequential):
def __init__(
self,
in_channel,
out_channel,
kernel_size,
downsample=False,
blur_kernel=[1, 3, 3, 1],
bias=True,
activate=True,
):
layers = [... |
1707952 | from openpredict.openpredict_model import get_predictions, get_similarities, load_similarity_embeddings, load_treatment_classifier, load_treatment_embeddings
import requests
import os
import re
def is_accepted_id(id_to_check):
if id_to_check.lower().startswith('omim') or id_to_check.lower().startswith('drugbank')... |
1707956 | import string
import numpy as np
from scipy.spatial import distance
def softmax(array):
"""Returns the numerically stable softmax of a given array"""
return (np.exp(array-np.max(array)))/np.sum(np.exp(array-np.max(array)))
def cosine_similarity(a, b):
"""Custom cosine similarity"""
return np.dot(a, b)... |
1708006 | import opendbpy as odb
import os
def createSimpleDB():
db = odb.dbDatabase.create()
tech = odb.dbTech.create(db)
L1 = odb.dbTechLayer_create(tech, 'L1', 'ROUTING')
lib = odb.dbLib.create(db, "lib")
odb.dbChip.create(db)
#Creating Master and2 and or2
and2 = createMaster2X1(lib, 'and2', 1000... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.