id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
113393 | class Config(object):
env = 'default'
backbone = 'resnet18'
classify = 'softmax'
num_classes = 5000
metric = 'arc_margin'
easy_margin = False
use_se = False
loss = 'focal_loss'
display = False
finetune = False
meta_train = '/preprocessed/train_meta.csv'
train_root = '/p... |
113407 | import pytest
import xia2.Experts.LatticeExpert
def test_lattice_expert():
cell, dist = xia2.Experts.LatticeExpert.ApplyLattice(
"oP", (23.0, 24.0, 25.0, 88.9, 90.0, 90.1)
)
assert cell == (23.0, 24.0, 25.0, 90.0, 90.0, 90.0)
assert dist == pytest.approx(1.2)
def test_SortLattices():
la... |
113421 | import copy
import torch
import numpy as np
from torch.utils.data import DataLoader
from src.cli import get_args
from src.utils import capitalize_first_letter, load
from src.data import get_data, get_glove_emotion_embs
from src.trainers.sentiment import SentiTrainer
from src.trainers.emotion import MoseiEmoTrainer, Iem... |
113471 | import unittest
from taxonomy import Taxonomy, TaxonomyError
class NewickTestCase(unittest.TestCase):
def _create_tax(self):
# https://en.wikipedia.org/wiki/Newick_format#Examples
return Taxonomy.from_newick("(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F;")
def setUp(self) -> None:
self.tax = se... |
113486 | from django import template
register = template.Library()
def get(value, key):
return value.get(key)
register.filter('get', get)
|
113539 | import torch.nn as nn
import torch
import cv2
import numpy as np
def eval_net(
net, dataset, gpu=True, vis=None, vis_im=None, vis_gt=None, loss=nn.MSELoss()
):
criterion = loss
net.eval()
losses = 0
torch.cuda.empty_cache()
for iteration, data in enumerate(dataset):
img = data["image"]... |
113549 | from types import TracebackType
from typing import Dict, Optional, Type, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from aiohttp.client import ClientSession
from warnings import warn
from neispy.error import ExceptionsMapping
class NeispyRequest:
BASE... |
113567 | import datetime
from nose.tools import (
assert_raises,
eq_,
set_trace,
)
from . import DatabaseTest
from bot import Bot
from model import (
InvalidPost,
Post,
_now,
)
class TestBot(DatabaseTest):
def test_publishable_posts(self):
bot = self._bot(config=dict(
state_... |
113571 | import dataclasses
from typing import Any, ClassVar, Dict, Iterable, Optional
from dbdaora.data_sources.fallback import FallbackDataSource
@dataclasses.dataclass
class DictFallbackDataSource(FallbackDataSource[str]):
db: Dict[Optional[str], Dict[str, Any]] = dataclasses.field(
default_factory=dict
)
... |
113627 | class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
def dirToIndex(x, y, d):
if d == "r": return (x, y + 1, d) if y + 1 < n and matrix[x][y + 1] == 0 else (x + 1, y, "d")
elif d == "d": return (x + 1, y, d) if x + ... |
113628 | import sys
import types
import _dk_core as core
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
def enum(*seq, begin=0, prefix='Enum_'):
from collections import namedtuple
t = namedtuple(prefix + core.uuidgen().replace... |
113633 | import types
import logging
import time
import numpy as np
from jbopt.de import de
from jbopt.classic import classical
from starkit.fitkit.priors import PriorCollection
logger = logging.getLogger(__name__)
def fit_evaluate(self, model_param):
# returns the likelihood of observing the data given the model param... |
113635 | from typing import Union
from .textstyle import TextStyle, compose_style
class StyleContainer:
def __init__(self, styles):
self._styles = styles
def has_style(self, style_name: str) -> bool:
"""Returns True if the box has a style with the given name."""
return style_name in self._sty... |
113637 | import xbos_services_getter as xsg
import numpy as np
"""Thermostat class to model temperature change.
Note, set STANDARD fields to specify error for actions which do not have enough data for valid predictions. """
class Tstat:
STANDARD_MEAN = 0
STANDARD_VAR = 0
STANDARD_UNIT = "F"
def __init__(self, ... |
113647 | import re
import pytest
from invoke.context import Context
from test.test_utils.benchmark import execute_single_node_benchmark, get_py_version
@pytest.mark.skip(reason="Temp skip due to timeout")
@pytest.mark.model("resnet18_v2")
@pytest.mark.integration("cifar10 dataset")
def test_performance_mxnet_cpu(mxnet_traini... |
113649 | f = open("HaltestellenVVS_simplified_utf8.csv", "r")
r = open("HaltestellenVVS_simplified_utf8_stationID.csv", "w")
r.write(f.readline())
lines = f.readlines()
for line in lines:
stationID = line.split(",")[0]
newStationID = int(stationID)+5000000
outLine = str(newStationID) + line[len(stationID):]
r.write(outL... |
113659 | from geneal.genetic_algorithms._binary import BinaryGenAlgSolver
from geneal.genetic_algorithms._continuous import ContinuousGenAlgSolver
|
113720 | import torch
from torch import nn
from maskrcnn_benchmark.modeling.poolers import LevelMapper
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.layers import ROIAlign
class SRPooler(nn.Module):
"""
SRPooler for Detection with or without FPN.
Also, the requirement of passing the sc... |
113724 | import logging
from datetime import timedelta
from src.alerter.factory.alerting_factory import AlertingFactory
from src.alerter.grouped_alerts_metric_code.node.evm_node_metric_code \
import GroupedEVMNodeAlertsMetricCode as AlertsMetricCode
from src.configs.alerts.node.evm import EVMNodeAlertsConfig
from src.utils... |
113739 | class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1 or len(s) <= 2:
return s
# compute the length of the zigzag
zigzagLen = 2*nRows - 2;
lens = len(s)
res = ''
for i in range(nRows):
idx = i
while idx... |
113759 | from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-clear-cache',
version = '0.3',
packages = (
'clear_cache',
'clear_cache.management',
'clear_cache.management.commands'
),
# Packaging ... |
113776 | import sys
from BaseHTTPServer import HTTPServer
from unittest import TestCase
from samsungtv.httpd.subscribe_handler import SubscribeHttpRequestHandler
class TestSubscribeHttpRequestHandler(TestCase):
def test__log(self):
self.skipTest("Todo")
# def test_real(self):
# host = ""
# po... |
113799 | expected_output = {
'power-usage-information': {
'power-usage-item': [
{
'name': '<NAME>',
'state': 'Online',
'dc-input-detail2': {
'dc-input-status':
'OK (INP0 feed expected, INP0 feed connected)'
... |
113826 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import sys
sys.path.append("..")
from option import args
OPS = {
'none': lambda C, stride, affine: Zero(stride),
'avg_pool_3x3': lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False),... |
113858 | from fastapi import APIRouter, Depends, Body
from core import deps
from scheams import User_Pydantic, UserIn_Pydantic, Response200, Response400
from models import User
user = APIRouter(tags=["็จๆท็ธๅ
ณ"], dependencies=[Depends(deps.get_current_user)])
@user.get("/user", summary="ๅฝๅ็จๆท")
async def user_info(user_obj: Use... |
113870 | from django.conf.urls import url
from django.contrib import messages
from jet.dashboard import dashboard
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpRequest
from django.http import JsonResponse
from d... |
113877 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import spi, sensor
from esphome.const import (
CONF_CURRENT,
CONF_ID,
CONF_POWER,
CONF_VOLTAGE,
UNIT_VOLT,
UNIT_AMPERE,
UNIT_WATT,
DEVICE_CLASS_POWER,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_VO... |
113882 | from itertools import groupby
# If you have problems with 'rufv' show=True,
# enable the console compatbility mode to use
# more common characters.
compat = False
if compat:
vbar = '|'
hbar = '-'
intersection = '+'
else:
vbar = 'โ'
hbar = 'โ'
intersection = 'โผ'
def ruf(pol, x):
"""For th... |
113912 | from .evolution_strategy import EvolutionStrategy
from .genetic_algorithm import GeneticAlgorithm
from .local_search import LocalSearch
from .simulated_annealing import SimulatedAnnealing
|
113914 | import sqlite3
class Sqlite(object):
def __init__(self, db_path):
self.db_path = db_path
def __enter__(self):
self.connect = sqlite3.connect(self.db_path)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connect.close()
def execute(self, *args, **kwarg... |
113946 | from __future__ import annotations
import typing
import toolstr
from . import cpmm_spec
from . import cpmm_trade
def print_pool_summary(
x_reserves: int | float,
y_reserves: int | float,
lp_total_supply: int | float | None = None,
x_name: str | None = None,
y_name: str | None = None,
fee_ra... |
113954 | from datetime import datetime, timedelta
from django.http import JsonResponse
from django.views.generic.base import TemplateView
from deploy.models import DeployPool
from envx.models import Env
from django.db.models import Count
def get_deploy_count(request):
return_list = []
now = datetime.now()
a_mont... |
113976 | from recon.core.module import BaseModule
from datetime import datetime
from urlparse import parse_qs
class Module(BaseModule):
meta = {
'name': 'Twitter Geolocation Search',
'author': '<NAME> (@LaNMaSteR53)',
'description': 'Searches Twitter for media in the specified proximity to a locati... |
113988 | from django.apps import AppConfig
class DatamartEndpointsConfig(AppConfig):
name = 'datamart_endpoints'
|
114012 | from django.contrib import admin
from product.modules.downloadable.models import DownloadableProduct, DownloadLink
admin.site.register(DownloadableProduct)
admin.site.register(DownloadLink)
|
114123 | import argparse
import ast
import codecs
import encodings
import io
import sys
import tokenize
import warnings
from typing import Match
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
import tokenize_rt
def _ast_parse(contents_text: str) -> ast.Module:
# in... |
114143 | from keras.layers import Input, Dense, Flatten, Concatenate, Conv2D, Dropout
from keras.losses import mean_squared_error
from keras.models import Model, clone_model, load_model
from keras.optimizers import SGD, Adam, RMSprop
import numpy as np
class RandomAgent(object):
def __init__(self, color=1):
self.... |
114154 | from setuptools import setup
import re
from io import open
# Get the current version
version = None
with open('plexiglas/__init__.py') as handle:
for line in handle.readlines():
if line.startswith('__version__'):
version = re.findall("'([^']+?)'", line)[0]
break
if version is None:... |
114170 | class Solution:
def nextGreaterElement(self, n: int) -> int:
num = list(str(n))
i = len(num) - 2
while i >= 0:
if num[i] < num[i + 1]:
break
i -= 1
if i == -1:
return -1
j = len(num) - 1
while num[j] <= nu... |
114236 | import os
import pytest
from jina import Document
from jina.optimizers import FlowOptimizer, EvaluationCallback
from jina.optimizers.flow_runner import SingleFlowRunner
cur_dir = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def config(tmpdir):
os.environ['JINA_OPTIMIZER_WORKSPACE_DIR'] = str(tmpd... |
114240 | import glob
from queue import Queue
from threading import Thread
import pandas as pd
import torch
from tqdm import tqdm
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
from training.model import BaselineModel
class ParallelExperimentRunner:
def... |
114261 | from os.path import join, abspath, dirname
from nose.tools import raises
from indra.statements import Complex, Phosphorylation
from indra.sources import hprd
test_dir = join(abspath(dirname(__file__)), 'hprd_tests_data')
id_file = join(test_dir, 'HPRD_ID_MAPPINGS.txt')
def test_process_complexes():
cplx_file ... |
114324 | word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."
word = word.replace('.','').replace(',','')
li = word.split()
print(li)
# ็ฌฌไธ็งๆนๆณ๏ผ
key = set(li)
value = [0 for i in range(len(key))]
dic = {k:v for k,v in zip(key,value)}
print(dic)
for i in dic:
for j in li:
if i ==... |
114334 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python... |
114337 | from flask import Blueprint, render_template, redirect, request, g, session, make_response, flash
import libmfa
import libuser
import libsession
mod_user = Blueprint('mod_user', __name__, template_folder='templates')
@mod_user.route('/login', methods=['GET', 'POST'])
def do_login():
session.pop('username', None... |
114339 | from controller.ControllerError import *
class PlayUi:
def __init__(self, controller):
self.__controller = controller
def print_score(self):
print('current score: {}\nhighest score: {}'.format(self.__controller.get_current_score(), self.__controller.get_high_score()))
def run_play(self):
print('\nYou are in... |
114372 | import torch
from torch.optim.optimizer import Optimizer, required
from torch.optim import SGD
class rSGD(SGD):
def __init__(self, params, lr=required, momentum=0, dampening=0,
weight_decay=0, nesterov=False):
super(rSGD, self).__init__(params, lr=lr, momentum=momentum,
... |
114380 | import sqlite3
import pprint
db = sqlite3.connect('jobs.sqlite')
cur = db.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cur.fetchall()
table = tables[0][0]
print(tables)
print(table)
cur.execute("PRAGMA table_info({})".format(table))
pprint.pprint(cur.fetchall())
cur.execute("S... |
114422 | import subprocess
import argparse
from prompt_toolkit import print_formatted_text as print
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.shortcuts import CompleteStyle
from prompt_toolkit.history import FileHistory
from .bash.history import BashHistoryIndexError, expand_history
f... |
114446 | import itertools
import torch
class Optimizer(object):
_ARG_MAX_GRAD_NORM = 'max_grad_norm'
def __init__(self, optim, max_grad_norm=0):
self.optimizer = optim
self.max_grad_norm = max_grad_norm
def step(self):
if self.max_grad_norm>0:
params = itertools.chain.from_ite... |
114474 | import pytest
from bevel.utils import *
from pandas.testing import assert_frame_equal
@pytest.fixture
def sample_response_data():
a, b, c = 'a', 'b', 'c'
x, y, z = 'x', 'y', 'z'
return pd.DataFrame.from_dict({
'groups_a': [a, a, b, b, b, b, b, c, c, c, c, c],
'groups_x': [x, x, x, x, x, ... |
114530 | YT_API_SERVICE_NAME = 'youtube'
DEVELOPER_KEY = "<KEY>"
MAX_RESULTS = 50
YT_API_VERSION = 'v3'
LINK = 'https://www.youtube.com/watch?v='
|
114549 | import unittest
from stensorflow.engine.start_server import start_local_server
import tensorflow as tf
import stensorflow as stf
from stensorflow.random.random import random_init
from stensorflow.basic.basic_class.private import PrivateTensor
from stensorflow.ml.logistic_regression import LogisticRegression
from stenso... |
114555 | from django import forms
from .models import Placement_Company_Detail,Profile,StudentBlogModel,ResorcesModel
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm
from django.utils.translation import gettext,gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth.forms... |
114564 | import os
import sys
d = "localedata"
d = os.path.join(sys._MEIPASS, d)
import babel.localedata
babel.localedata._dirname = d
|
114566 | import unittest
import hail as hl
from .flags import (
get_expr_for_consequence_lc_lof_flag,
get_expr_for_variant_lc_lof_flag,
get_expr_for_genes_with_lc_lof_flag,
get_expr_for_consequence_loftee_flag_flag,
get_expr_for_variant_loftee_flag_flag,
get_expr_for_genes_with_loftee_flag_flag,
)
cl... |
114579 | import sqlite3, random, time
cnx = sqlite3.connect('taqueria.db')
cursor = cnx.cursor()
def queryTacos():
consultarTacos = cursor.execute("SELECT ID, Nombre_Taco FROM tacos")
return consultarTacos.fetchall()
def queryClientes():
consultarClientes = cursor.execute("SELECT ID, Nombre FROM clientes")
re... |
114624 | import demistomock as demisto
from CommonServerPython import *
SCRIPT_NAME = 'ListCreator'
def configure_list(list_name: str, list_data: str) -> bool:
"""Create system lists using the createList built-in method.
"""
demisto.debug(f'{SCRIPT_NAME} - Setting "{list_name}" list.')
res = demisto.executeC... |
114636 | import numpy as np
from .muscle_simulation_stepupdate import step_update_state
class MuscleTendonComplex:
def __init__(self, nameMuscle, frcmax, vmax, lslack, lopt,
lce, r, phiref, phimaxref, rho, dirAng, phiScale,
offsetCorr, timestep, angJoi, eref=0.04, act=0.01,
... |
114656 | import numpy as np
import sys
pp = "/Users/andres.perez/source/parametric_spatial_audio_processing"
sys.path.append(pp)
import parametric_spatial_audio_processing as psa
import matplotlib.pyplot as plt
import scipy.stats
from utils import *
from file_utils import build_result_dict_from_metadata_array, build_metadata_r... |
114661 | import numpy as np
import pandas as pd
import pytest
import xarray as xr
from esmvalcore.experimental import Recipe
from esmvalcore.experimental.recipe_output import DataFile
from ewatercycle.forcing import generate, load
from ewatercycle.forcing._lisflood import LisfloodForcing
def test_plot():
f = LisfloodForc... |
114675 | def test_modulemap(snapshot):
snapshot.assert_match([1, 2, 4])
def test_runlist():
assert 1 == 1 |
114676 | from stellar.models import get_unique_hash, Table, Snapshot
def test_get_unique_hash():
assert get_unique_hash()
assert get_unique_hash() != get_unique_hash()
assert len(get_unique_hash()) == 32
def test_table():
table = Table(
table_name='hapsu',
snapshot=Snapshot(
snaps... |
114678 | from base_component import *
import os
import xml.etree.ElementTree as ET
class ParseV4L2Headers(Component):
"""
Component which parses the v4l2 headers to get ioctl function pointer structure members.
"""
def __init__(self, value_dict):
c2xml_path = None
kernel_src_dir = None
... |
114699 | import os
import re
from typing import (
List,
Optional,
)
from kb_notes.config import (
Config,
WIKILINK_PATTERN,
)
from kb_notes.helpers import execute_command
from kb_notes.types import WikiLinkRegexMatch
class NoteFinder:
def __init__(self, config: Config):
self.config = config
d... |
114707 | import os
import argparse
import numpy as np
import processors as pe
from paz.backend.camera import VideoPlayer
from paz.backend.camera import Camera
from demo_pipeline import DetectEigenFaces
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Real-time face classifier')
parser.add_argum... |
114730 | from __future__ import annotations
import vtk
from custom_types import *
from ui import ui_utils
import constants
import vtk.util.numpy_support as numpy_support
class GaussianData:
def make_symmetric(self, other: GaussianData):
# reflection = np.eye(3)
# reflection[0, 0] = -1
# self.total... |
114743 | class OperationStaResult(object):
def __init__(self):
self.total = None
self.wait = None
self.processing = None
self.success = None
self.fail = None
self.stop = None
self.timeout = None
def getTotal(self):
return self.total
def setTotal(self... |
114745 | import json
from mock import ANY
from lib.response import OkResponse
from tests.commands.commands_test_base import CommandsTestBase
class GetAudioTest(CommandsTestBase):
def test_get_audio(self):
self.pipeline_mock.amix.getAudioVolumes.return_value = [1.0, 0.0, 0.25]
response = self.commands.ge... |
114763 | import numpy
def entropy2(*args):
''' E = ENTROPY2(MTX,BINSIZE)
Compute the first-order sample entropy of MTX. Samples of VEC are
first discretized. Optional argument BINSIZE controls the
discretization, and defaults to 256/(max(VEC)-min(VEC)).
NOTE: This is a heavily ... |
114779 | import os
import sys
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
import numpy as np
import torch
import torchvision.datasets as datasets
class CIFAR10NoisyLabels(datasets.CIFAR10):
"""CIFAR10 Dataset with noisy labels.
Args:
noise_type (string): Noise type (def... |
114780 | from django.contrib import admin
from corehq.apps.toggle_ui.models import ToggleAudit
@admin.register(ToggleAudit)
class ToggleAdmin(admin.ModelAdmin):
date_hierarchy = 'created'
list_display = ('username', 'slug', 'action', 'namespace', 'item', 'randomness')
list_filter = ('slug', 'namespace')
order... |
114826 | import os
import csv
import glob
import logging
logger = logging.getLogger(__name__)
def extract(func):
"""
Decorator function. Open and extract data from CSV files. Return list of dictionaries.
:param func: Wrapped function with *args and **kwargs arguments.
"""
def _wrapper(*args):
o... |
114829 | import os, logging
from solarpv.training.S2_training_data import *
# conf
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
generator = MakeS2TrainingData(
tilespath=os.path.join(os.getcwd(),'data','cv_all_tiles.geojson'),
polyspath=os.path.join(os.getcwd(),'data','cv_all_polys.geojson'),
outpath=os.pat... |
114843 | from __future__ import print_function
import sys,inspect
import numpy as np
from flask import json
from collections import OrderedDict
class Evaluator:
def __init__(self,functionList):
self.generatedApp=[]
self.hasPlot=False
self.itemList=[]
self.evalGlobals={}
self.functionList = functionList
se... |
114867 | from urlparse import urlparse
def is_url_in_domain(url, domains):
parsed = urlparse(url)
for domain in domains:
if domain.match(parsed.netloc):
return True
return False
def is_absolute(url):
return bool(urlparse(url).netloc)
|
114898 | from django.urls import include, path, re_path
from django.views.generic import RedirectView
from django.urls import reverse_lazy
from django.http import QueryDict
from rest_framework.urlpatterns import format_suffix_patterns
from django_cas_ng.views import login as cas_login, logout as cas_logout, callback as cas_cal... |
114982 | import maya.mel as mm
import maya.cmds as mc
import maya.OpenMaya as OpenMaya
import glTools.utils.base
import glTools.utils.component
import glTools.utils.constraint
import glTools.utils.mathUtils
import glTools.utils.mesh
import glTools.utils.reference
import glTools.utils.stringUtils
import glTools.utils.transform
... |
114994 | from functools import partial, update_wrapper
from math import exp
import numpy as np
from scipy.sparse import lil_matrix
from scipy.stats import rankdata
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import pairwise_distances, euclidean_distances
from sklearn.neighbors import NearestNei... |
115063 | import sys
sys.path.append('../configs')
sys.path.append('../utils')
sys.path.append('../tfops')
# ../utils
from reader import read_npy
# ../config
from path import CIFARPROCESSED
from info import CIFARNCLASS
def test1():
val_embed = read_npy(CIFARPROCESSED+'val_image.npy')
val_label = read_npy(CIFARPROCE... |
115072 | import torch
import gpytorch
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.models.gp_regression import SingleTaskGP
from gpytorch.kernels import RBFKernel, ScaleKernel
from online_gp.utils import regression
class OnlineExactRegression(torch.nn.Module):
def __init__(self, stem, init_x, init_y,... |
115150 | from hashlib import sha256
from hmac import HMAC
import os
class Encrypt(object):
def encrypt(self, password, salt=None):
if salt is None:
salt = os.urandom(8)
result = password.encode('utf-8')
for i in range(10):
result = HMAC(result, salt, sha256).digest()
... |
115194 | import os
import subprocess
import itertools
import pytest
from click.testing import CliRunner
from hobbit import main as hobbit
from hobbit.bootstrap import templates
from . import BaseTest, rmdir, chdir
class TestHobbit(BaseTest):
wkdir = os.path.abspath('hobbit-tox-test')
def setup_method(self, method)... |
115236 | import SimpleITK as sitk
data_mha = open('data_mha.txt', 'r')
mha_dir = data_mha.readlines()
data_nii = open('data_nii.txt', 'r')
nii_dir = data_nii.readlines()
for i in range(len(mha_dir)):
print(i)
path, _ = mha_dir[i].split("\n")
savepath, _ = nii_dir[i].split("\n")
img = sitk.ReadImage(path)
si... |
115251 | import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from scipy.stats import norm
import time
import os
from demoire.epll.epll import EPLLhalfQuadraticSplit
from demoire.epll.utils import get_gs_matrix
def process(noiseI, GS, matpath, DC):
patchSize = 8
noiseSD = 25/255
# same to... |
115267 | from collections import OrderedDict
from urllib import urlencode
from admino.serializers import ModelAdminSerializer
from django.core.urlresolvers import reverse_lazy
from django.http import JsonResponse
from django.views.generic import View
class APIView(View):
def json_response(self, data, *args, **kwargs):
... |
115269 | from .base_capsule_options import BaseCapsuleOptionsWidget
from brainframe_qt.api_utils import api
class StreamCapsuleOptionsWidget(BaseCapsuleOptionsWidget):
def __init__(self, stream_id, parent=None):
super().__init__(parent=parent)
assert stream_id is not None
self.window().setWindowTi... |
115317 | import json
import os
import shutil
import stat
import tarfile
import urllib
import subprocess
import docker
from requirementslib import Requirement
from tqdm import tqdm
from .release import get_release
class NoReleaseCandidate(Exception):
def __init__(self, requirement):
super(NoReleaseCandidate, sel... |
115344 | import pickle
import os
import numpy as np
import torch
import warnings
from tqdm import tqdm
from Metrics import evaluateTracking
from dataset.dataLoader import Data_Loader_MOT
from network.tubetk import TubeTK
from post_processing.tube_nms import multiclass_nms
from apex import amp
import argparse
import multiprocess... |
115372 | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt("sample.dat")
mean = data.mean()
sigma = data.std()
x = np.linspace(data.min(), data.max(), 100)
y = np.exp(-0.5 * ((x -mean)/sigma)**2)
y = y/(np.sqrt(2.0* np.pi * sigma**2))
plt.hist(data, alpha=0.5, bin... |
115407 | import unittest
import xr
class TestBool(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_bool(self):
self.assertTrue(True)
self.assertFalse(False)
self.assertTrue(xr.TRUE)
self.assertFalse(xr.FALSE)
self.assertTrue(xr.B... |
115410 | import copy
import collections
import itertools
import core.attributes as attributes
import core.properties as properties
from core.exceptions import WrongArityError
from core.TOS import _TOS
class BaseExpression( object ):
def __init__( self, children = [], line = -1 ):
self.head = self.__class__
... |
115415 | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class PayloadProtocolType(Base):
__slots__ = ()
_SDM_NAME = 'payloadProtocolType'
_SDM_ATT_MAP = {
'HeaderPayloadProtocolId': 'payloadProtocolType.header.payloadProtocolId-1',
}
def __init__(self, parent, list... |
115479 | from distutils.core import setup
setup(
name='gitric',
version='0.4',
description='simple git-based deployment for fabric',
author='<NAME>',
author_email='<EMAIL>',
url='http://dan.bravender.us',
download_url='http://github.com/dbravender/gitric/tarball/0.4',
packages=['gitric'])
|
115514 | import requests
def is_campus_up():
response_threshold = 3
timeout = 5
url = "https://campus.exactas.uba.ar"
try:
response = requests.get(url, timeout=timeout)
response_time = response.elapsed.total_seconds()
response.raise_for_status()
msg = ""
if re... |
115567 | from .BasicSearcher import BasicSearcher
from .AStar import AStar
from .BFS_BEAM import BFS_BEAM
from .Prob import Prob
from .Searcher import Searcher
__all__ = ["AStar","BFS_BEAM", "Prob", "Searcher"]
|
115677 | from .api import AptlyApi, get_aptly_connection, get_snapshot_name # noqa: F401
from .taskstate import TaskState # noqa: F401
|
115705 | from datetime import date
from django.forms import CharField, DateInput, Form
from django.utils import translation
from .base import WidgetTest
class DateInputTest(WidgetTest):
widget = DateInput()
def test_render_none(self):
self.check_html(
self.widget, "date", None, html='<input type... |
115712 | import itertools
import logging
import os
import geopandas as gpd
import numpy as np
import pandas as pd
import tqdm
from scipy.spatial import KDTree
from shapely.geometry import LineString, Point, Polygon
from delft3dfmpy.converters import hydamo_to_dflowrr
from delft3dfmpy.core import checks, geometry
from delft... |
115717 | import argparse
import numpy as np
import util.io
import experiment_descriptor as ed
import misc
def parse_args():
"""
Returns an object describing the command line.
"""
parser = argparse.ArgumentParser(description='Likelihood-free inference experiments.')
subparsers = parser.add_subparsers()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.