id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9915817 | from typing import Dict
from hyperstyle.src.python.review.inspectors.issue import IssueType
CHECK_CLASS_NAME_TO_ISSUE_TYPE: Dict[str, IssueType] = {
# ---- Annotations ----
# 'AnnotationLocationCheck': IssueType.CODE_STYLE,
# 'AnnotationOnSameLineCheck': IssueType.CODE_STYLE,
# 'AnnotationUseStyleChec... |
9915896 | import unittest
from huggingmolecules import MatConfig
from huggingmolecules.configuration.configuration_mat import MAT_CONFIG_ARCH
from tests.configuration.configuration_base import ConfigurationApiTestBase
class ConfigurationMatApiTest(ConfigurationApiTestBase, unittest.TestCase):
config_cls = MatConfig
co... |
9915915 | import fnmatch
from disco.types.base import Model, SlottedModel, Field, ListField, DictField, text, snowflake
__all__ = [
'Model', 'SlottedModel', 'Field', 'ListField', 'DictField', 'text', 'snowflake', 'channel', 'raw',
'rule_matcher', 'lower',
]
def lower(raw):
return str(raw).lower()
def raw(obj):
... |
9915934 | from default_config import basic_cfg
import numpy as np
cfg = basic_cfg
cfg.train_df = cfg.data_dir + "binary_ext1.csv"
cfg.val_df = cfg.data_dir + "train_soundscape_labels_v2.csv"
# dataset
cfg.min_rating = 4.0
cfg.dataset = "wav_ds_v8"
cfg.wav_crop_len = 10 # seconds
cfg.lr = 0.0001
cfg.epochs = 20
cfg.batch_size... |
9915937 | import csv
import re
#parses a string to get all introduction data from it
#returns an array of introduction tuples
def get_intros(intros):
pattern = re.compile('2.(.+)[,\/-](.+)[,\/-](.+)\s3.(.+)\s4.(.+)')
result = pattern.findall(intros)
if result is not None:
return result
#prints introduction da... |
9915966 | from typing import cast
from src.common.types import Tus
from src.helpers.general import fourthOrNone, nthOrNone, secondOrNone, thirdOrNone
from src.helpers.reinforce import minerCanReinforce
from src.models.User import User
from src.strategies.reinforce.ReinforceStrategyFactory import (
makeReinforceStrategy,
)
fr... |
9915974 | import os,sys
import tensorflow as tf
import numpy as np
import librosa
import feature_tools as ft
def write_tfrecords(feat, utt_label, utt_shape, tfrecords_name):
writer = tf.python_io.TFRecordWriter(tfrecords_name)
trIdx = range(np.shape(utt_label)[0])
# iterate over each example
# wrap with tq... |
9915978 | import numpy
def mul(D,x_data, y_data, z_data):
for d in range(D):
for k in range(d+1):
z_data[d] += x_data[k] * y_data[d-k]
return z_data
def pbr_mul(D, x_data, y_data, z_data, zbar_data, xbar_data, ybar_data):
for d in range(D):
for k in range(D-d):
x... |
9916117 | from talon import Context, Module
ctx = Context()
ctx.matches = """
os: mac
app: messages
"""
mod = Module()
@ctx.action_class("self")
class Actions:
def accessibility_adjust_context_for_application(el, context):
# Messages reports an empty buffer as having None as content instead of "".
# We use... |
9916118 | import cherrypy
from cherrypy.lib import httpauth
def check_auth(users, encrypt=None, realm=None):
"""If an authorization header contains credentials, return True or False.
"""
request = cherrypy.serving.request
if 'authorization' in request.headers:
# make sure the provided credentials are co... |
9916141 | r"""
Generate synthetic programs with feedback labels
using the variational autoencoder.
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import math
import json
import cPickle
import numpy as np
from tqdm import tqdm
import torch
i... |
9916147 | import argparse
from baselines.common import set_global_seeds
from baselines.common.misc_util import boolean_flag
from baselines.common.schedules import LinearSchedule
import baselines.common.tf_util as U
from datetime import datetime
from gym.envs.classic_control import rendering
import matplotlib.pyplot as plt
import... |
9916183 | from scipy import optimize
from scipy.sparse import linalg
import numpy
import parse_sdf
import design_pip_classes
import pip_classes
import sys
import math
import json
def solve_pip_delays(ncl, sdf, debug=False):
path_pip_classes, wire_fanout = design_pip_classes.get_equations(ncl)
sdf_data = parse_sdf.parse... |
9916189 | from manimlib.imports import *
from active_projects.diffyq.part2.wordy_scenes import *
class IveHeardOfThis(TeacherStudentsScene):
def construct(self):
point = VectorizedPoint()
point.move_to(3 * RIGHT + 2 * UP)
self.student_says(
"I've heard\\\\", "of this!",
stude... |
9916252 | import shlex
import pwny
import pwnypack.main
from IPython.core.magic import register_line_magic
__all__ = []
def wrap_main(func_name):
def wrapper(line):
pwnypack.main.main([func_name] + shlex.split(line))
return wrapper
for f_name, f_dict in pwnypack.main.MAIN_FUNCTIONS.items():
register_lin... |
9916275 | import logging
from peewee import JOIN
from data.database import (
AccessToken,
AccessTokenKind,
Repository,
Namespace,
Role,
RepositoryBuildTrigger,
)
from data.model import DataModelException, _basequery, InvalidTokenException
logger = logging.getLogger(__name__)
ACCESS_TOKEN_NAME_PREFIX... |
9916325 | import sys
import procgame
import pinproc
from threading import Thread
import random
import string
import time
import locale
import math
import copy
import ctypes
import itertools
from procgame.events import EventManager
import os
try:
import pygame
import pygame.locals
except ImportError:
print "Error im... |
9916356 | from django.urls import reverse
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from rest_framework import status
class TestUsers(APITestCase):
def test_list_success(self):
user = User.objects.create(username='test', password='<PASSWORD>')
base_url = rever... |
9916383 | from typing import Dict, List, Optional
from .tokens import ChanModes, Prefix
CASEMAPPINGS = ["rfc1459", "ascii"]
def _parse_escapes(s: str):
idx = 0
out = ""
while idx < (len(s)):
if s[idx] == "\\":
if s[idx+1:]:
if (s[idx+1] == "x" and
len(s... |
9916389 | from typing import List
def removeStopwords(text: str, stopwords: List[str]) -> str:
'''
Removes the chosen stopwords in the text then return the text without stopwords.
'''
for stopword in stopwords:
text = text.replace(stopword, ' ')
return text
|
9916404 | from a10sdk.common.A10BaseClass import A10BaseClass
class MessageDigestCfg(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param md5_value: {"minLength": 1, "maxLength": 16, "type": "string", "description": "The OSPF password (1-16)", "format": "password"}
:param me... |
9916467 | import scipy.io as sio
import pickle
import numpy as np
import os
import numpy as np
from sklearn.decomposition import PCA
from scipy import spatial
from sklearn.metrics.pairwise import cosine_similarity
class TestCosineSimilarity(object):
def __init__(self):
# self.name = "C2test"
self.name = "MSchallenge2Base"
... |
9916490 | import numpy as np
from .base import sample_at_bc_vi, visible_sample_points
def project_out(J, U, fast_approx=True):
tmp = J.dot(U.T if fast_approx else np.linalg.pinv(U))
return J - tmp.dot(U)
def sample_uv_terms(instance, image, camera, mm, shape_pc, grad_x, grad_y,
n_samples):
# s... |
9916528 | from builtins import range
from builtins import object
import json
import logging
from collections import defaultdict
from mrtarget.common.DataStructure import JSONSerializable
from mrtarget.common.chembl_lookup import ChEMBLLookup
from mrtarget.common.connection import new_es_client
from mrtarget.common.esutil impor... |
9916535 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
needleLen, haystackLen = len(needle), len(haystack)
if needleLen == 0:
return 0
if needleLen > haystackLen:
return -1
base, modulus = 26, 2 ** 32
def charToInt(c):
... |
9916560 | from dataclasses import dataclass
@dataclass
class StrawberryConfig:
auto_camel_case: bool = True
|
9916606 | import datetime
from collections import defaultdict
import stravalib
from github_poster.loader.base_loader import BaseLoader, LoadError
class StravaLoader(BaseLoader):
unit = "km"
def __init__(self, from_year, to_year, _type, **kwargs):
super().__init__(from_year, to_year, _type)
self.befor... |
9916646 | class RestClientError(Exception):
pass
class ServerResponseException(RestClientError):
"""Server response error class for client."""
class InvalidRestMethodException(RestClientError):
"""A valid HTTP method is required to make a request."""
class ConfigMissing(RestClientError):
pass
class Config... |
9916704 | from django.template.loader import render_to_string
from common.constants import EMPTY_SEARCH_MSG
import urllib
def history_renderer(user, history,
hist_type, return_type,
empty_search_msg,
template, get_params=None,
following=None)... |
9916734 | import shutil
import sys
import os
import path
binDir = path.path("C:/Users/haggi/coding/lux/windows/Projects/luxrender/x64")
binDirA = path.path("C:/Users/haggi/coding/lux/windows/Projects/luxrays/x64")
binDest = path.path("C:/Users/haggi/coding/OpenMaya/src/mayaToLux/devkit/luxsdk/bin")
libDest = path.path("C:/User... |
9916740 | import sys
class NonconformingSizeException(Exception):
"Jython exception for non-conforming argument sizes"
from maspack.util import *
from maspack.matrix import *
from maspack.geometry import *
from maspack.collision import *
from maspack.render import *
from maspack.solvers import *
from artisynth.core.mechmodel... |
9916748 | import mrl
from mrl.utils.misc import soft_update, flatten_state
from mrl.modules.model import PytorchModel
import numpy as np
import torch
import torch.nn.functional as F
import os
class ActorPolicy(mrl.Module):
"""Used for DDPG / TD3 and other deterministic policy variants"""
def __init__(self):
super().__i... |
9916760 | import logging
import queue
from wsgiref import simple_server
import prometheus_client
from ctf_gameserver.lib.metrics import SilentHandler
def inc(metrics_queue, name, value=1, labels=None):
metrics_queue.put(MetricsMessage(name, 'inc', value, labels))
def dec(metrics_queue, name, value=1, labels=None):
... |
9916770 | import smdebug.pytorch as smd
import torch
from smdebug.core.modes import ModeKeys
class CustomHook(smd.Hook):
# register input image for backward pass, to get image gradients
def image_gradients(self, image):
image.register_hook(self.backward_hook("image"))
def forward_hook(self, module, inputs... |
9916773 | import os
import unittest
import uuid
import six
import pytest
from conans.client.store.localdb import LocalDB
from conans.test.utils.test_files import temp_folder
class LocalStoreTest(unittest.TestCase):
def test_localdb(self):
tmp_dir = temp_folder()
db_file = os.path.join(tmp_dir, "dbfile")
... |
9916843 | from __future__ import print_function
from abc import ABCMeta, abstractmethod
import numpy as np
import sys
import argparse
import time
from imagenet_cls_test_alexnet import CaffeModel, DnnCaffeModel
try:
import cv2 as cv
except ImportError:
raise ImportError('Can\'t find OpenCV Python module. If you\'ve built... |
9916871 | from copy import deepcopy
class AccountFixtureFactory(object):
@staticmethod
def make_publisher_source():
return deepcopy(PUBLISHER_SOURCE)
@staticmethod
def make_managing_editor_source():
return deepcopy(MANED_SOURCE)
@staticmethod
def make_editor_source():
return de... |
9916882 | def quick_sort(arr, left_index, right_index):
if left_index < right_index:
partition_index = partition(arr, left_index, right_index)
quick_sort(arr, left_index, partition_index-1)
quick_sort(arr, partition_index+1, right_index)
def partition(arr, left_index, right_index):
pivot = arr[r... |
9916895 | import FWCore.ParameterSet.Config as cms
caloConfigSource = cms.ESSource(
"EmptyESSource",
recordName = cms.string('L1TCaloConfigRcd'),
iovIsRunNotTime = cms.bool(True),
firstValid = cms.vuint32(1)
)
caloConfig = cms.ESProducer(
"L1TCaloConfigESProducer",
l1Epoch = cms.string("Stage1")... |
9916901 | import redis
import json
redis_client = redis.Redis(host='redis', port=6379)
with open('monk-data.json') as contenido:
data = json.load(contenido)
for dato in data:
key =dato.get('id'),dato.get('first_name'),dato.get('last_name')
redis_client.set(key,dato)
print(redis_client.keys()) |
9916922 | import os
import glob
import sys
import functools
import jsonpickle
from collections import OrderedDict
from Orange.widgets import widget, gui, settings
import Orange.data
from Orange.data.io import FileFormat
from DockerClient import DockerClient
from BwBase import OWBwBWidget, ConnectionDict, BwbGuiElements, getIconN... |
9916989 | from .util import bytes_to_bits
def data_to_binary(code):
result = []
pre = code.get('pre_data')
if pre:
result += bytes_to_bits(pre, code, code.get('pre_data_bits'))
result += bytes_to_bits(code['data'], code, code.get('bits'))
post = code.get('post_data')
if post:
result +... |
9917015 | from utils import Task5Model
import numpy as np
def calc_num_params(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
model = Task5Model(31)
print(calc_num_params(model.bw2col) + calc_num_params(model.mv2.features) + calc_num_params(model.final))
model = Task5Model(37)
print(calc_num_p... |
9917087 | import xml.etree.cElementTree as ET
import copy
import os
import logging
from os import listdir
from os.path import isfile, join
# read environmental variable for project path
project_path = os.environ['smart_alarm_path']
logger = logging.getLogger(__name__)
class Xml_data(object):
"""
class handling the x... |
9917144 | import unittest
import os
import time
import pg8000
import datetime
from connection_settings import db_connect
from sys import exc_info
from six import b
from distutils.version import LooseVersion
# DBAPI compatible interface tests
class Tests(unittest.TestCase):
def setUp(self):
self.db = pg8000.connect(... |
9917148 | from __future__ import absolute_import, unicode_literals
import socket
import sys
import types
from case import Mock, mock, patch
from kombu.five import bytes_if_py2
from kombu.utils import compat
from kombu.utils.compat import entrypoints, maybe_fileno
class test_entrypoints:
@mock.mask_modules('pkg_resource... |
9917212 | import math
import argparse
_GLOBAL_ARGS = None
def get_args(extra_args_provider=None):
global _GLOBAL_ARGS
if _GLOBAL_ARGS is None:
_GLOBAL_ARGS = parse_args(extra_args_provider)
return _GLOBAL_ARGS
def parse_args(extra_args_provider=None, ignore_unknown_args=False):
"""Parse all argument... |
9917214 | from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin'
password = '<PASSWORD>$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and lo... |
9917238 | from .__version__ import __author__, __email__, __version__
from .client import MondayClient
__all__ = ['MondayClient']
|
9917250 | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
create_table_sql = "create table if not exists daily("\
"meter_id VARCHAR(MAX) , "\... |
9917301 | input_dir = '../input'
output_dir = '../output'
weights_dir = '../weights'
DUMMY_ACTION = 'DUMMMY_A'
DUMMY_USER = -1
DUMMY_ITEM = -1
DUMMY_PRICE_RANK=25
DUMMY_IMPRESSION_INDEX = 25 |
9917325 | from __future__ import absolute_import, unicode_literals
SECRET_KEY = 'fake-secret-key-used-for-testing-only'
PROCTOR_API_ROOT = 'fake-proctor-api-url'
PROCTOR_TESTS = [
'fake_proctor_test_in_settings',
]
|
9917339 | from create_simulation_app.src.robomaker_create_simulation_app_spec import (
RoboMakerCreateSimulationAppSpec,
)
import unittest
class RoboMakerCreateSimAppSpecTestCase(unittest.TestCase):
REQUIRED_ARGS = [
"--region",
"us-west-2",
"--app_name",
"app-name",
"--sources"... |
9917343 | import numpy as np
import torch
import argparse
import os
import captum as cap
import torch.optim as optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
from captum.attr._utils.visualization import visualize_image_attr
from experiments.mnist import load_mnist
from experiments.prostate_cancer import lo... |
9917359 | import tensorflow as tf
import numpy as np
def kinetic_energy(velocity):
"""Kinetic energy of the current velocity (assuming a standard Gaussian)
(x dot x) / 2
Parameters
----------
velocity : tf.Variable
Vector of current velocity
Returns
-------
kinetic_energy : float
... |
9917378 | import json
import math
import re
import requests
from bs4 import BeautifulSoup
from .exceptions import NoDataError
_intraday_pattern = re.compile("var (?P<name>.*)=(?P<content>\[[^;]*\]);")
def _load_script_vars_from_web(symbol_id, year, month, day):
d = f'{year:04}{month:02}{day:02}'
script_variables = {... |
9917401 | from openid.message import Message
class Extension(object):
"""An interface for OpenID extensions.
@ivar ns_uri: The namespace to which to add the arguments for this
extension
"""
ns_uri = None
ns_alias = None
def getExtensionArgs(self):
"""Get the string arguments that should... |
9917421 | import functools
import mock
import warnings
try:
import urlparse
except ImportError: # Python 3
from urllib import parse as urlparse
from django.core.urlresolvers import NoReverseMatch, set_urlconf
from django.template import Context, Template
from django.test import TestCase
from django.test.client import R... |
9917439 | import curses
from os import system
class CursesUtil:
def __init__(self):
self.version = 0.1
self.current_url = "NONE"
self.x = 0;
self.y = 0;
def get_screen(self):
self.screen = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, ... |
9917480 | import logging
import threading
from typing import Any, Callable, Optional, Dict
from datetime import timedelta
from collections import OrderedDict
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.compat import iteri... |
9917485 | import tensorflow as tf
from src.net.NetBase import *
from src.layers.BasicLayers import *
from src.layers.RNN import *
import settings.LayerSettings as layerSettings
import settings.DataSettings as dataSettings
import settings.TrainSettings as trainSettings
import numpy as np
DARKNET19_MODEL_PATH = 'data/pretrainMode... |
9917487 | from __future__ import division, generators, print_function
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
import macarico.util
macarico.util.reseed()
from macarico.annealing import ExponentialAnnealing, stochastic
from macarico.lts.maximum_... |
9917488 | import copy
import numpy as np
from metadrive.component.vehicle.vehicle_type import SVehicle
from metadrive.manager.base_manager import BaseManager
from metadrive.utils.coordinates_shift import waymo_2_metadrive_heading, waymo_2_metadrive_position
from metadrive.utils.waymo_utils.waymo_utils import AgentType
class ... |
9917511 | from main import *
from argparse import ArgumentParser
def build_parser():
parser = ArgumentParser()
parser.add_argument('--num_epoch', type=int,
dest='num_epoch', help='how many epochs to train',
metavar='Number of epochs', required=True)
parser.add_argumen... |
9917514 | from typing import Dict
from typing import List
from botocore.paginate import Paginator
class DescribeDirectories(Paginator):
def paginate(self, DirectoryIds: List = None, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`DirectoryS... |
9917535 | import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import UniqueConstraint
from sqlmodel import Field, Relationship
from pydantic_factories import ModelFactory, Use
from faker import Faker
from api.db.models.base import BaseModel, BaseTable
class StudentBase(BaseModel):
name: s... |
9917546 | from conans import ConanFile, CMake, tools
class CaresUe4Conan(ConanFile):
name = "cares-ue4"
version = "1.13.0"
license = "MIT"
url = "https://github.com/adamrehn/ue4-conan-recipes/cares-ue4"
description = "c-ares custom build for Unreal Engine 4"
settings = "os", "compiler", "build_type", "ar... |
9917587 | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
import random, string
class Batch(ModuleData):
implements(IPlugin, IModuleData)
name = "Batch"
def actions(self):
return [ ("startbatchsend", 10, self.startBatch),
("... |
9917611 | import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import re
from abc import ABCMeta
class AbstractDatabase(object):
__metaclass__ = ABCMeta
def _db_connection(self):
return MySQLdb.connect(
host=self._h, user=self._u, passwd=self._p
)
... |
9917622 | from prometheus_client import CONTENT_TYPE_LATEST, generate_latest # type: ignore
from starlette.requests import Request
from starlette.responses import Response
from .util import registry
def get_metrics(request: Request) -> Response:
return Response(generate_latest(registry), status_code=200, headers={"Conten... |
9917624 | from math import pi
# convert between rotations/minute and radians/second
RPM2RS = pi / 30.0
RS2RPM = 30.0 / pi
|
9917642 | import asyncio
import copy
import csv
import math
import queue
import threading
import uuid
import warnings
from datetime import datetime
from typing import List, Optional, Union, Callable, Coroutine, Iterable
import pandas
import pytz
from .dtypes import _termination_obj, Event
from .flow import Flow, Complete
from ... |
9917667 | import json
from multiprocessing import Pool
import traceback
import time
import numpy as np
from aser.client import ASERClient
ASER_PORT = 8000
s1 = "I am hungry"
s2 = "I am in the kitchen"
# s1 = 'they yucca look leggy'
# s2 = 'they african violet refuse to flower'
s3 = "I have no money"
# Helper Function `ex... |
9917675 | def move_data(token, member_id, from_path, to_path):
url = 'https://api.dropboxapi.com/1/fileops/move'
headers = {'Authorization': 'Bearer %s' % token, 'X-Dropbox-Perform-As-Team-Member': member_id}
data = {'root': 'auto', 'from_path': from_path, 'to_path': to_path}
print 'Moving "%s" to "%s" (member_id: %s)' % (f... |
9917694 | import numpy as np
import unittest
import pycqed as pq
import matplotlib.pyplot as plt
import os
from pycqed.analysis_v2 import measurement_analysis as ma
class Test_RTE_Analysis(unittest.TestCase):
@classmethod
def tearDownClass(self):
plt.close('all')
@classmethod
def setUpClass(self):
... |
9917719 | from ..torch2trt_dynamic import *
from ..plugins import *
@tensorrt_converter('torch.Tensor.expand_as')
def convert_expand_as(ctx):
input = ctx.method_args[0]
other = get_arg(ctx, 'other', pos=1, default=None)
input_trt = trt_(ctx.network, input)
other_trt = trt_(ctx.network, other)
output = ctx.... |
9917771 | import gc
from Config import *
from Core.dataset import DatasetFactory
from Core.tasks import Segmentation
save_path = './Data/Preds'
##############################################################################################
configs = [
# all images
PANetDilatedResNet34_768_Fold0(),
PANetDilatedResNe... |
9917803 | from logger_sets import get_loggers
from infra_logopts import LoggerArgParseHelper
all = [get_loggers, LoggerArgParseHelper]
|
9917847 | import sys, os, BaseHTTPServer, mimetypes, gettext
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# Root of files being served.
Root_Directory = None
# Is debugging output on?
Debug = False
# HTTP error codes.
ERR_NO_PERM = 403
ERR_NOT_FOUND = 404
ERR_INTERNAL = 500
... |
9917859 | from inspect import isclass
import pytest
from async_v20.definitions import primitives
from async_v20.definitions.primitives import ClientComment, ClientID, ClientTag, OrderID, TradeID
from async_v20.definitions.primitives import OrderSpecifier, TradeSpecifier, DateTime
from async_v20.definitions.primitives import Tr... |
9917885 | import io
import os
import pickle
import h5py
from PIL import Image
from torchvision.datasets import VisionDataset
class ImageNetHDF5(VisionDataset):
def __init__(self, root, cache_size=125, transform=None):
super(ImageNetHDF5, self).__init__(root, transform=transform, target_transform=None)
sel... |
9917893 | import numpy as np
import random
import json
import hdbscan
import numba
import sys
from sklearn.neighbors import KDTree
from pyclustering.cluster.xmeans import xmeans
from helpers import distance_matrix as dm
from helpers import hparam_functions as hp
from helpers import visualization as vis
from concurrent.futures i... |
9917902 | import functools
import json
from .common import InfoExtractor
from ..utils import (
OnDemandPagedList,
float_or_none,
str_or_none,
str_to_int,
traverse_obj,
unified_timestamp,
)
class PodchaserIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?podchaser\.com/podcasts/[\w-]+-(?P<podcast... |
9917935 | import tensorflow as tf
import matplotlib.pyplot as plt
from utils import *
#class Data3d
def sxe(logits,labels):
#use zeros or ones if pass in scalar
if not isinstance(labels,tf.Tensor):
labels=labels*tf.ones_like(logits)
return tf.nn.sigmoid_cross_entropy_with_logits(
logits=logits,label... |
9917955 | from __future__ import unicode_literals
import frappe
# bench --force --site abc run-patch erpnext_biotrack.patches.v0_2.mirror_plant_to_traceability_system
def execute():
frappe.db.sql("UPDATE tabDocType SET `module` = 'Traceability System' WHERE `name` = 'Plant'")
frappe.reload_doc('traceability_system', 'doctype'... |
9917973 | import os
from zipfile import ZipFile
this_dir = os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(os.path.join(this_dir, "_build")):
os.makedirs(os.path.join(this_dir, "_build"))
for this_dir, dirs, files in os.walk(this_dir):
for d in dirs:
if d not in ["build", "_build", "__pycache__... |
9917986 | from django.core.management import call_command
from django.test.client import Client
from django.test import TestCase
from .utils import test_setup
from django.urls import reverse
from unittest import skipIf
from django.conf import settings
class BlueButtonClientApiUserInfoTest(TestCase):
"""
Test the BlueBu... |
9918138 | from distutils.core import setup
from glob import glob
import py2exe
import sys
sys.path.append("D:\\Dropbox\\git\\msvcr90")
data_files = [("Microsoft.VC90.CRT", glob(r'D:\Dropbox\git\msvcr90\*.*'))]
setup(
console=['artifact_extractor.py'],
data_files=data_files
)
|
9918209 | from app.dao.annual_billing_dao import (
dao_create_or_update_annual_billing_for_year,
dao_get_free_sms_fragment_limit_for_year,
dao_update_annual_billing_for_future_years,
)
from app.dao.date_util import get_current_financial_year_start_year
from tests.app.db import create_annual_billing
def test_dao_upd... |
9918216 | import unittest
from proxy_db.migrations import MigrateVersion
from ._compat import patch
class TestMigrateVersion(unittest.TestCase):
def test_pending_versions(self):
versions = MigrateVersion().pending_versions()
self.assertEqual(versions, set())
def test_is_last_version(self):
sel... |
9918229 | import os
import pytest
@pytest.fixture(scope='session')
def bootstrap_module_path():
from osmaxx.conversion.converters.converter_gis import bootstrap
return os.path.abspath(os.path.dirname(bootstrap.__file__))
@pytest.fixture(scope='session')
def relative_sql_script_paths():
return [
'sql/filt... |
9918304 | from selenium import webdriver
from locators import *
import time
driver = webdriver.Chrome('./chromedriver')
# Happy Path - Login Success
driver.get('http://localhost:8000')
username = driver.find_element(*LoginPage.username_field)
password = driver.find_element(*LoginPage.password_field)
submit = driver.find_eleme... |
9918316 | from typing import List, Tuple
import pickle
import numpy as np
from keras_glove.config import *
def get_most_similar(word: str, k: int) -> List[Tuple]:
"""
Given an input word, find the closest items in terms of cosine similarity
:param word: The input word
:param k: The number of results to return... |
9918350 | import unittest
import unittest.mock as mock
import mycity.intents.intent_constants as intent_constants
import mycity.mycity_controller as my_controller
import mycity.mycity_request_data_model as my_req
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.controller = my_controller
self.r... |
9918441 | import io
import sys
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8', errors='ignore'):
sys.stdout.write(line)
|
9918455 | from __future__ import absolute_import
import mock
from celery import states
from django.urls import reverse
from .base import BaseAPITestCase
from contentcuration.models import Task
from contentcuration.utils.celery.tasks import AsyncResult
class TaskAPITestCase(BaseAPITestCase):
"""
Test that the Task API... |
9918495 | import torch
import scipy.io as io
import numpy as np
import subprocess as proc
import matplotlib.pyplot as plt
import os
def load_production_data(fname, name='ws_ref'):
"""
Loads the production data from mrst output files
:param fname: file name of production data snapshot
:param name: name of key i... |
9918497 | from .detection import Detect
from .prior_box import PriorBox
from .detection_refinedet import Detect_RefineDet
__all__ = ['Detect', 'PriorBox', 'Detect_RefineDet']
|
9918511 | from enum import Enum
from typing import Optional, List
import logging
import tensorflow as tf
from tensorflow.contrib.rnn import static_rnn, static_bidirectional_rnn
from tensorflow.contrib.framework import arg_scope
import tfsnippet as spt
from tfsnippet.bayes import BayesianNet
from tfsnippet.utils import (instance... |
9918521 | import dash
from imports import *
from plotly_graphs import *
from plotly_css import *
external_stylesheets = ['https://raw.githubusercontent.com/rab657/explainx/master/explainx.css', dbc.themes.BOOTSTRAP,
{
'href':'https://fonts.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.