id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1645413 | from os import listdir
from pathlib import Path
from typing import Optional, List
import hydra
import wandb
from omegaconf import DictConfig
from pytorch_lightning import LightningDataModule, LightningModule
from pytorch_lightning.loggers import LightningLoggerBase, WandbLogger
from tqdm import tqdm
import numpy as np... |
1645445 | import logging
from enum import Enum
from struct import Struct
_default_struct = Struct('<12sII')
class G(Enum):
def __init__(self, title: str, release_year: int, dat_filename: str = None, dir_filename: str = None,
dir_struct: Struct = None):
self.title = title
self.release_year ... |
1645470 | from aetherling.modules.reduce import DefineReduceSequential, DefineReduceParallelWithIdentity, renameCircuitForReduce
from aetherling.modules.register_any_type import DefineRegisterAnyType
from aetherling.modules.term_any_type import TermAnyType
from aetherling.modules.noop import DefineNoop
from magma.backend.coreir_... |
1645482 | from __future__ import annotations
import math
import random
from collections import deque
from typing import List, Optional, Tuple
from tqdm import tqdm
from utttpy.game.action import Action
from utttpy.game.ultimate_tic_tac_toe import UltimateTicTacToe
class MonteCarloTreeSearch:
def __init__(
self,... |
1645518 | from covid_model_seiir_pipeline.pipeline.forecasting.task.beta_residual_scaling import (
beta_residual_scaling,
)
from covid_model_seiir_pipeline.pipeline.forecasting.task.beta_forecast import (
beta_forecast,
)
|
1645532 | from django.conf.urls import url
from .views.views import csv_daily_report, csv_report, election_day, election_day_center, \
reports, center_csv_report, phone_csv_report, \
election_day_center_n, election_day_office_n, election_day_preliminary, national, offices, \
offices_detail, redirect_to_national, reg... |
1645571 | import sys
import numpy as np
vert = np.loadtxt(sys.argv[1])
tri = np.loadtxt(sys.argv[2])
with open(sys.argv[3], 'w') as f:
f.write('OFF\n')
f.write('{} {} {}\n'.format(int(vert.shape[0]), int(tri.shape[0]), 0))
with open(sys.argv[3], 'ab') as f:
np.savetxt(f, vert, fmt='%.6f')
np.savetxt(f, np.hs... |
1645572 | from securityheaders.checkers import InfoCollector, FindingType, Finding, FindingSeverity
from securityheaders.models import ModelFactory
class InfoDirectiveCollector(InfoCollector):
def check(self, headers, opt_options=dict()):
headernames = ModelFactory().getheadernames()
findings = []
f... |
1645599 | from collections import namedtuple
Point2D = namedtuple('Point2D', ('x', 'y'))
pt1 = Point2D(10, 20)
Circle = namedtuple('Circle', ['center_x', 'center_y', 'radius'])
circle_1 = Circle(0, 0, 10)
Stock = namedtuple('Stock', '''symbol
year month day
open ... |
1645609 | import sys
from PySide import QtGui
import model_win_test
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = model_win_test.TestModelWin()
win.show()
app.exec_()
sys.exit()
|
1645620 | from bitmovin.utils import Serializable
class StartManifest(Serializable):
def __init__(self, manifest_id):
super().__init__()
self.manifestId = manifest_id
def serialize(self):
serialized = super().serialize()
return serialized
@classmethod
def parse_from_json_objec... |
1645640 | import json
import pytest
from botocore.exceptions import ClientError
from app.callback.sqs_client import SQSClient
from botocore.stub import Stubber
@pytest.fixture(scope='function')
def sqs_client(notify_api, mocker):
with notify_api.app_context():
sqs_client = SQSClient()
statsd_client = moc... |
1645642 | import pandas as pd
from scipy.stats import ttest_ind
import numpy as np
from statsmodels.stats.multitest import multipletests as multit
from warnings import warn
def count_reps(inseries):
inseries = inseries.tolist()
counts = {k:0 for k in list(set(inseries))}
out = [878 for i in range(len(inseries))]
... |
1645657 | import io
import yaml
class Hyperparameters:
def __init__(self, path_to_config_file):
with io.open(path_to_config_file) as file:
config = yaml.load(file)
self.learning_rate = config['hyperparameters']['learning_rate']
self.input_size = config['hyperparameters']['input_size']
self.hidden_sizes... |
1645672 | from Components.Converter.Converter import Converter
from Components.Element import cached
class TPMChallenge(Converter):
L2C = 0
L3C = 1
VALUE = 2
RESULT = 3
TEXT = 4
def __init__(self, type):
Converter.__init__(self, type)
self.type = {"Level2Cert": self.L2C,
... |
1645693 | import os
import shutil
from functools import partial
import neptune
import numpy as np
import pandas as pd
from attrdict import AttrDict
from steppy.adapter import Adapter, E
from steppy.base import IdentityOperation, Step
from common_blocks import augmentation as aug
from common_blocks import metrics
from common_bl... |
1645705 | import torch.optim as optim
from torch.utils import data
from e2efold.models import ContactNetwork, ContactNetwork_test, ContactNetwork_fc
from e2efold.models import ContactAttention, ContactAttention_simple_fix_PE
from e2efold.models import ContactAttention_simple
from e2efold.common.utils import *
from e2efold.commo... |
1645707 | import discord
from utils.globals import gc
from utils.settings import settings
import ui.text_manipulation as tm
# inherits from discord.py's Client
class Client(discord.Client):
# NOTE: These are strings!
__current_server = ""
__current_channel = ""
__prompt = ""
# discord.Status object
__s... |
1645752 | from tqdm import tqdm
import tensorflow as tf
import config
import os
def augment(image):
image = tf.image.random_flip_left_right(image)
image = tf.image.random_flip_up_down(image)
if tf.random.uniform([], minval=0, maxval=1) < 0.5:
image = tf.image.rot90(image)
return image
def preprocess_... |
1645823 | from django.conf.urls import url
from document.views import TreeView
urlpatterns = [
url(r'^(?P<policy_id>[^/]+)(/(?P<identifier>[a-zA-Z0-9_-]+))?',
TreeView.as_view(), name='document'),
]
|
1645864 | import operator
from bson import ObjectId
from django.conf.urls import url
from django.core.urlresolvers import reverse
from tastypie import http
from tastypie import fields
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.utils import trailing_slash
from api.auth import DocumentsAuthorization
fro... |
1645901 | from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker
from controller.utils import checker, revs, utils
from id_definition.error_codes import CTLResponseCode
from proto import backend_pb2
class SamplingInvoker(BaseMirControllerInvoker):
def pre_invoke(self) -> backend_pb2.GeneralResp:
r... |
1645903 | import joblib
import pytest
from pydefect.analyzer.grids import Grids
from pymatgen.core import Lattice, Structure
import numpy as np
from pymatgen.io.vasp import Chgcar
from vise.tests.helpers.assertion import assert_dataclass_almost_equal
@pytest.fixture
def grids():
return Grids(lattice=Lattice.cubic(10),
... |
1645919 | from django.conf import settings # import the settings file
import plistlib
import os
from server.utils import get_server_version
SAL_VERSION = get_server_version()
def display_name(request):
return {'DISPLAY_NAME': settings.DISPLAY_NAME}
def config_installed(request):
return {'CONFIG_INSTALLED': True i... |
1645923 | from os import path
import unittest
from prudentia.utils import io
class TestIO(unittest.TestCase):
def test_xstr(self):
self.assertEqual(io.xstr(None), '')
def test_yes(self):
self.assertTrue(io.input_yes_no('test topic', prompt_fn=lambda m: 'y'))
self.assertTrue(io.input_yes_no('te... |
1645933 | import torch
import random
import numpy as np
import torch.nn.functional as F
from .min_norm_solvers import MinNormSolver, gradient_normalizers
from torch.autograd import Variable
class backprop_scheduler(object):
def __init__(self, model, mode=None):
self.model = model
self.mode = mode
s... |
1646023 | from flask import render_template
from . import api_search
from .forms import ApiSearchForm
from ..tools.api_tools import ApiGetter
@api_search.route('/api_search', methods=['GET', 'POST'])
def index():
form = ApiSearchForm()
qa = ApiGetter()
if form.validate_on_submit():
api_response = qa.get_twit... |
1646033 | import os
import json
import re
import numpy as np
from shutil import copyfile
from keras.optimizers import SGD
import keras.backend as K
from AlphaGo.ai import ProbabilisticPolicyPlayer
import AlphaGo.go as go
from AlphaGo.models.policy import CNNPolicy
from AlphaGo.util import flatten_idx
def _make_training_pair(st... |
1646049 | import discord
from discord.ext import commands
import asyncio
import json
from datetime import datetime
from random import choice
from aux.misc import round_down
from aux.stats import Stats
class InvalidNumberPlayers(Exception):
pass
class Warrior():
def __init__(self, member):
self.member = member
... |
1646075 | import cv2
import numpy as np
import random
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade=cv2.CascadeClassifier('smile.xml')
cap=cv2.VideoCapture(0)
run=True
while run:
ret, img =cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMu... |
1646093 | import pytest
import unittest
from lenstronomy.PointSource.Types.base_ps import PSBase
from lenstronomy.LensModel.lens_model import LensModel
class TestPSBase(object):
def setup(self):
self.base = PSBase(lens_model=LensModel(lens_model_list=[]), fixed_magnification=False, additional_image=False)
... |
1646096 | import json
import unittest
from services.service import Service
class TestService(unittest.TestCase):
CONFIG1 = """
{
"id": "sspr",
"name": "SSPR service wrapper",
"description": "",
"version_data": {
"versions": {
"Default": {
}
}
},
"proxy": {
"listen_path": "/test/",
... |
1646169 | import komand
from .schema import GetScanConfigsInput, GetScanConfigsOutput
# Custom imports below
class GetScanConfigs(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="get_scan_configs",
description="Get a list of all scan configurations in the Open... |
1646237 | from Stephanie.Modules.base_module import BaseModule
from Stephanie.local_libs.football_manager import FootballManager
class FootballModule(BaseModule):
modules = (
("FooballModule@GetAllCompetitions", ("all", "competitions")),
("FooballModule@GetEnglishLeague", ("english", "league")),
("F... |
1646271 | import g
def init_scene():
g.set_duration(0)
g.set_dataset('Arched Bridge 3D (TVCG01, Fig 6, Fig 9)')
#g.set_dataset('KittenHex (Vis2021, results)')
g.set_camera_checkpoint('Front')
g.set_rendering_algorithm_settings({
'line_width': 0.0022,
'band_width': 0.016,
'depth_cue_st... |
1646392 | import sqlite3
from sqlite3 import Error
def storeMessage(time, distance, messageType):
conn = sqlite3.connect('telemetry.db', check_same_thread=False)
c = conn.cursor()
try:
c.execute('''CREATE TABLE IF NOT EXISTS telemetry
(time double PRIMARY KEY,
distance double NOT NULL,
messageType intege... |
1646432 | class TextEditor:
def __init__(self):
self.text = []
def append(self, string_to_append):
self.text.append(self.peek() + string_to_append)
def delete(self, num_chars_to_delete):
self.text.append(self.peek()[:-num_chars_to_delete])
def char_at_position(self, k):
return ... |
1646471 | from .data import DiscoverMatrix, row_stack
from .grouptest import groupwise_discover_test
from .pairwise import pairwise_discover_test
__version__ = "0.9.4"
|
1646482 | import logging
import re
import utils.data_format_keys as dfk
from evaluation.evaluation_utils import doi_normalize
from random import random
from utils.cr_utils import search, generate_unstructured
from time import sleep
class Matcher:
def __init__(self, min_score, excluded_dois=[], journal_file=None):
... |
1646486 | import re
from django import template
from django.core.urlresolvers import NoReverseMatch
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, name):
try:
pattern = reverse(name)
except NoReverseMatch:
return... |
1646488 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
import re
from fairseq.data.datautils import utf8_to_uxxxx, uxxxx_to_utf8
import cv2
from fairseq.data import FairseqDataset
import json
import lmdb
import logging
LOG = logging.getLogger(__name__)
class OcrLmd... |
1646532 | from .logger import Logger
# TODO: better overwritting
def print(*msg):
Logger().log_message(*msg, stack_displacement=2)
|
1646563 | import os
from colorama import Fore
import time
import sys
def Banner():
os.system("clear")
print(Fore.LIGHTRED_EX+"""\n
[ V 1.0 ]
██████╗ ███╗ ██╗ █████╗
██╔══██╗████╗ ██║██╔══██╗
██║ ██║██╔██╗ ██║███████║
██║ ██║██║╚██╗██║██╔══██║
██████╔╝██║ ╚████║██║ ██║
╚═════... |
1646572 | from flask import Flask, request
import tensorflow as tf
from correct_text import create_model, DefaultMovieDialogConfig, decode
from text_corrector_data_readers import MovieDialogReader
data_path = '/input/data/movie_dialog_train.txt'
model_path = '/input/model'
tfs = tf.Session()
config = DefaultMovieDialogConfig(... |
1646599 | import unittest
from bump_version import bump_version
class TestBumpVersion(unittest.TestCase):
def test_bump_patch(self):
self.assertEqual(bump_version('v1.2.3', 'patch'), 'v1.2.4')
def test_bump_patch_does_not_carry_over(self):
self.assertEqual(bump_version('v1.2.9', 'patch'), 'v1.2.10')
... |
1646617 | import os
import json
from indra.sources import biofactoid
here = os.path.dirname(os.path.abspath(__file__))
def test_process_document():
doc_json = os.path.join(here, 'biofactoid_doc.json')
with open(doc_json, 'r') as fh:
doc = json.load(fh)
bp = biofactoid.process_json([doc])
assert len(bp.... |
1646635 | import requests
def download_model(model, shaves, cmx_slices, nces, output_file):
PLATFORM="VPU_MYRIAD_2450" if nces == 0 else "VPU_MYRIAD_2480"
url = "http://luxonis.com:8080/"
payload = {
'compile_type': 'zoo',
'model_name': model,
'model_downloader_params': '--precisions FP16 -... |
1646685 | import argparse
import os
import pandas as pd
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(1234)
# command line arguments
parser = argparse.ArgumentParser(description='Train a model with PyTorch.')
parser.add_argument('inxfile', type=str, help... |
1646697 | import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from functools import partial
import numpy as np
import tensorflow as tf
import horovod.tensorflow as hvd
from tensorflow.contrib.framework import arg_scope
from tensorflow.contrib import layers
import numpy as np
def get_net(model_name):
... |
1646709 | from procfs.core import ProcessFile, Dict
# /proc/net/rpc/nfsd documentation:
# <kernel src>/fs/nfsd/stats.c : nfsd_proc_show
# /net/sunrpc/stats.c : svc_seq_show
# /fs/nfsd/nfsproc.c : nfsd_procedures2
# /fs/nfsd/nfs3proc.c : nfsd_procedures3
# /fs/nfsd/nfs4p... |
1646728 | import sys
import click
import time
import calendar
import datetime
from anchore.cli.common import anchore_print, anchore_print_err
from anchore import anchore_auth, anchore_feeds
from anchore.anchore_utils import contexts
config = {}
@click.group(name='feeds', short_help='Manage syncing of and subscriptions to Anch... |
1646736 | import inspect
import logging
from datetime import datetime
from typing import Optional, Set, Callable
from celery.utils import uuid
from server.queue.celery.task_metadata import TaskMetadata
from server.queue.celery.task_status import task_status
from server.queue.framework import TaskQueue, BaseObserver
from server... |
1646737 | from django.utils.translation import gettext as _
from collections import OrderedDict
DEFAULT_AFFILIATION = {_("student [student, member]") : ["student", "member"]}
idem_affiliation_map_extended = {
_("assistente universitario [staff, member]"): ["staff", "member"],
_("associato (ad es. CNR) [member]"): ["member"],
_... |
1646809 | import functools
from .runtime_helper import PI, LARGE, empty
def broken_decorator(f):
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
return wrapped
def simple_decorator(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
return wrapped
class ... |
1646828 | import matplotlib.pyplot as plt
import numpy as np
from brancher.variables import RootVariable, RandomVariable, ProbabilisticModel
from brancher.standard_variables import NormalVariable, DeterministicVariable, MultivariateNormalVariable
from brancher import inference
import brancher.functions as BF
N_itr = 250
N_smpl... |
1646837 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})
import math
plt.rcParams.update({'font.size': 22})
name = "Pl"
data = pd.read_csv(name + ".csv", names=["l", "P"])
K = 0.2
data["P1"] = 9.80665 * K * data["P"]
X = data["l"].values
sigma_X = 0.4
Y = data["P"].v... |
1646844 | from varifier import truth_variant_finding, utils
def run(options):
if options.truth_mask is None:
mask = None
else:
mask = utils.load_mask_bed_file(options.truth_mask)
truth_variant_finding.make_truth_vcf(
options.ref_fasta,
options.truth_fasta,
options.outdir,
... |
1646855 | import numpy as np
from pandas import read_csv
# an example of asia bayesian net:
# https://www.eecis.udel.edu/~shatkay/Course/papers/Lauritzen1988.pdf
class BayesianNet(object):
def __init__(self, names, edges, tables=None):
self.n_nodes = len(names)
if tables is None:
tables = [[0]]... |
1646880 | import unittest
from n0test.tdt_generator.ga import Generation
class TestGeneration(unittest.TestCase):
def test___init__(self):
prev = Generation(seed={"foo": "bar"} , _scoring_seed=False)
prev._score = [-1]
gen = Generation(previous_generation=prev)
self.assertEqual(len(gen._pr... |
1646882 | from __future__ import print_function, absolute_import
import unittest, sklearn, sklearn.dummy, numpy as np
from SplitClassifier import SplitClassifier
class T(unittest.TestCase):
def test_split_classifier_with_single_classifier(self):
c = sklearn.dummy.DummyClassifier('constant', constant=0)
sc = S... |
1646891 | import pytest
import smbl
# todo: ensure that cmake is installed
smbl.prog.CMake.install_all_steps()
@pytest.mark.parametrize("plugin,plugin_name",
[
(x,x.get_plugin_name())
for x in smbl.prog.plugins.get_registered_plugins() if x.is_platform_supported() and x is not smbl.prog.CMake
]
)
def test_plugins(... |
1646939 | import time
import unittest
from typing import Union
import torch
import numpy as np
import random
from functools import lru_cache
from einops import rearrange, repeat
import torch.nn.functional as F
from torch import nn, einsum
@lru_cache()
def get_2dmask(seq_len, nx, ny, w, d):
return torch.BoolTensor([
... |
1646947 | class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack = []
for p in path.split("/"):
if p == "..":
if stack:
stack.pop()
elif p and p != ".":
stack.append(p)
... |
1646984 | import time
from functools import wraps
def super_func(c,d):
'''
Decorator that reports the execution time.
'''
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)+c-d
return wrapper
return decorate
@super_func(c=1,d=2)
d... |
1646999 | import random
from compas_rhino.artists import NetworkArtist
from compas.datastructures import Network
network = Network()
last_node = None
for i in range(12):
node = network.add_node(x=i // 3, y=i % 3, z=0)
network.node_attribute(node, 'weight', random.choice(range(20)))
if last_node:
network.... |
1647010 | from tests.example_apps.music.tables import Band
from ..base import DBTestCase
class TestCount(DBTestCase):
def test_exists(self):
self.insert_rows()
response = Band.count().where(Band.name == "Pythonistas").run_sync()
self.assertTrue(response == 1)
|
1647011 | import datetime
import unittest
from pyramid import testing
from pyramid_mailer import get_mailer
from pyramid import httpexceptions
from ccvpn.models import User, Order, Profile, PasswordResetToken
from ccvpn import views, setup_routes
from ccvpn.tests import BaseTest, DummyRequest
class TestPublicViews(BaseTest):... |
1647038 | import click
from textkit.utils import output
from unidecode import unidecode
import chardet
@click.command()
@click.argument('file', type=click.File('r'), default=click.open_file('-'))
def transliterate(file):
'''Convert international text to ascii.'''
content = ''.join(file.readlines())
try:
cont... |
1647043 | import pyb
# The pyboard has 4 LEDs that can be controlled
# these LEDs have IDs 1 - 4
led = pyb.LED(4) # 4 is the blue LED
# toggle LED state every second using on() and off() methods
while True:
led.on()
pyb.delay(1000)
led.off()
pyb.delay(1000)
|
1647068 | using_pysqlite3 = False
try:
import pysqlite3 as sqlite3
using_pysqlite3 = True
except ImportError:
import sqlite3
if hasattr(sqlite3, "enable_callback_tracebacks"):
sqlite3.enable_callback_tracebacks(True)
_cached_sqlite_version = None
def sqlite_version():
global _cached_sqlite_version
if... |
1647112 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .lsa_attention import LocationSensitiveAttention
from .basic_layers import Linear, Conv1d
from .vc_utils import get_mask_from_lengths
class DecoderPrenet(nn.Module):
def __init__(self, in_dim, sizes):
super().__init__()
in_siz... |
1647130 | import errno
import logging
import os
from unittest import mock
from pytest import raises
from snakeoil.osutils.mount import MS_BIND, MS_REC, MS_REMOUNT, MS_RDONLY
from pychroot.utils import dictbool, getlogger, bind
from pychroot.exceptions import ChrootMountError
def test_dictbool():
assert dictbool({'a': Tru... |
1647170 | import pytest
# Note:
# Definitions for `cut1`, `cut2` and `cut_set` parameters are standard Pytest fixtures located in test/cut/conftest.py
# ########################################
# ############### PADDING ################
# ########################################
@pytest.mark.parametrize("direction", ["right... |
1647172 | from tweet import TweetClient
import config as cfg
from db import LightningDB
from lndrpc import LndWrapper
from lightningrpc import LightningWrapper
from sys import argv
import os
import logging
def main():
logging.basicConfig(level=logging.INFO)
if len(argv) > 1 and argv[1]=='--clightning':
ln_path... |
1647189 | from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from spells import Spells
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
#... |
1647195 | import datetime
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.generics import ListAPIView
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response impor... |
1647201 | from abc import ABC, abstractmethod
from pathlib import Path
from typing import Iterable, List, Union
import sentencepiece as spm
from typeguard import check_argument_types
class AbsTokenizer(ABC):
@abstractmethod
def text2tokens(self, line: str) -> List[str]:
raise NotImplementedError
@abstract... |
1647204 | import datetime
import matplotlib.pyplot as plt
import numpy as np
import geospacelab.visualization.mpl.geomap.geodashboards as geomap
def test_ampere():
dt_fr = datetime.datetime(2016, 3, 15, 0)
dt_to = datetime.datetime(2016, 3, 15, 23, 59)
time1 = datetime.datetime(2016, 3, 15, 1, 10)
pole = 'N'
... |
1647248 | from __future__ import unicode_literals
import json
import datetime
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from dja... |
1647260 | import unittest
from drgpy.msdrg import DRGEngine
class TestMCD00(unittest.TestCase):
def test_mdcs00(self):
de = DRGEngine()
drg_lst = de.get_drg_all(["I10", "E0800"], ["02YA0Z0"])
self.assertTrue("001" in drg_lst)
drg_lst = de.get_drg_all(["I10"], ["02YA0Z0"])
self.asse... |
1647284 | import ast
import shutil
import os
from pathlib import Path
import unittest
import tests.plugins
from obscurepy.obfuscator import Obfuscator
from obscurepy.handlers.classdef_handler import ClassDefHandler
class ObfuscatorTest(unittest.TestCase):
def setUp(self):
self.fixture = Obfuscator('tests/my_modul... |
1647331 | import numpy as np
import torch
def objective_function(
config,
model_objective,
model_cost,
task_feature_objective,
task_feature_cost,
x_mean_objective,
x_std_objective,
x_mean_cost,
x_std_cost,
y_mean_objective=None,
y_std_objective=None,
y_mean_cost=None,
y_std_c... |
1647336 | class Solution:
# @param gas, a list of integers
# @param cost, a list of integers
# @return an integer
def canCompleteCircuit(self, gas, cost):
n = len(gas)
t = [0 for i in range(n)]
for i in range(n):
t[i] = gas[i] - cost[i]
res = 0
cs = 0 # Current... |
1647342 | from django.test import TestCase, RequestFactory, Client
import django
if django.VERSION >= (2, 0, 0):
from django.urls import reverse
else:
from django.core.urlresolvers import reverse
from django.db import models
from django.views.generic import ListView, CreateView , DetailView, UpdateView, DeleteView
from g... |
1647346 | from unittest import TestCase
from similarityPy.algorithms.find_nearest import FindNearest
from similarityPy.measure.boolean_data.matching_dissimilarity import MatchingDissimilarity
from tests import test_logger
__author__ = 'cenk'
class FindNearestTest(TestCase):
def setUp(self):
pass
def test_ma... |
1647350 | from kaldi_io import read_vec_flt, write_vec_flt, open_or_fd, write_mat
import sys
import numpy as np
from collections import defaultdict
dev_test_spk = ['p311', 'p226', 'p303', 'p234', 'p302', 'p237', 'p294', 'p225']
with open(sys.argv[1], 'r') as f:
content = f.readlines()
content = [x.strip() for x in content]... |
1647366 | import pandas
import numpy as np
import matplotlib.pyplot as plt
COLOR = ['C2', 'C1', 'C0']
SAVE_DIR = "benchmarks_results"
def plot_scaling_1d_benchmark(strategies, list_n_times):
# compute the width of the bars
n_group = len(list_n_times)
n_bar = len(strategies)
width = 1 / ((n_bar + 1) * n_group... |
1647372 | r"""
Version for trame 1.x - https://github.com/Kitware/trame/blob/release-v1/examples/VTK/SimpleCone/RemoteRendering.py
Delta v1..v2 - https://github.com/Kitware/trame/commit/674f72774228bbcab5689417c1c5642230b1eab8
"""
from trame.app import get_server
from trame.widgets import vuetify, vtk
from trame.ui.vue... |
1647376 | from pppr import aabb
import numpy as np
from pak.datasets.MOT import MOT16
from pak import utils
from pppr import aabb
from time import time
from cselect import color as cs
# ===========================================
# Helper functions
# ===========================================
def remove_negative_pairs(Dt, W, ... |
1647400 | from torch.nn.modules.module import Module
from ..functions.riroi_align import RiRoIAlignFunction
class RiRoIAlign(Module):
def __init__(self, out_size, spatial_scale, sample_num=0, nOrientation=8):
super(RiRoIAlign, self).__init__()
self.out_size = out_size
self.spatial_scale = float(s... |
1647407 | import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
def test_sum_tuple(self):
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
if __name__ == '__main__':
unittest.main()
Method Equivalent to
.assertEqual(a, b) ... |
1647475 | import socket
def check_infected(ip):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, 6969))
sock.settimeout(5.0)
sock.send("ping".encode())
data = sock.recv(1024)
sock.close()
msg = data.decode('utf-8').strip('\r\n')
if msg == "pong":
return True
else:
return F... |
1647488 | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def plot_time_series(x: np.ndarray, title=None) -> None:
sns.set(font_scale=1.5)
sns.set_style("white")
t = np.arange(start=0, stop=x.shape[0])
plt.plot(t, x, linestyle='-', marker='o')
plt.title(title)
plt.xlabel(r'$t$')... |
1647548 | from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import ShinyUserHash
from secrets import token_hex
@receiver(post_save, sender=User)
def create_hash(sender, instance, created, **kwargs):
if created:
hash =... |
1647562 | import asyncio
from typing import Optional
import aioreactive as rx
import pytest
from aioreactive.notification import OnCompleted, OnError, OnNext
from aioreactive.testing import AsyncTestObserver, VirtualTimeEventLoop
from expression.system.disposable import AsyncDisposable
@pytest.yield_fixture() # type:ignore
d... |
1647574 | import PySimpleGUI as sg
from cblaster.gui.parts import TextLabel, TEXT_WIDTH
sg.theme("Lightgrey1")
extract_frame = sg.Frame(
"Extract",
layout=[
[sg.Text(
"This module will allow you to extract sequences from saved cblaster "
"session files. You can filter sequences by the... |
1647643 | import hypothesis.strategies as st
import torch
from hypothesis import assume
from hypothesis import given
from myrtlespeech.builders.fully_connected import build
from myrtlespeech.model.fully_connected import FullyConnected
from myrtlespeech.protos import fully_connected_pb2
from tests.builders.test_activation import... |
1647663 | import argparse
import os
from tensorflow import keras
import numpy as np
from utils import generator, model, utils
parser = argparse.ArgumentParser()
parser.add_argument('--num_epoch', default=56, type=int, help='训练的轮数')
parser.add_argument('--lr', default=0.001, type=float, help='初始学习... |
1647675 | import pytest
from ocdeployer.images import ImageImporter, import_images
@pytest.fixture
def mock_oc(mocker):
_mock_oc = mocker.patch("ocdeployer.images.oc")
mocker.patch("ocdeployer.images.get_json", return_value={})
yield _mock_oc
def _check_oc_calls(mocker, mock_oc):
assert mock_oc.call_count ==... |
1647683 | import stripe
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_stripe_settings():
from bluebottle.funding_stripe.models import StripePaymentProvider
provider = StripePaymentProvider.objects.first()
if not provider:
raise ImproperlyConfigured('Stripe ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.