id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1761788 | from unittest.mock import patch
from google.cloud.storage import Client
from astro.files.locations import create_file_location
def test_get_transport_params_for_gcs(): # skipcq: PYL-W0612, PTC-W0065
"""test get_transport_params() method which should return gcs client"""
path = "gs://bucket/some-file"
l... |
1761796 | import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '../'))
import torch
import torchvision as tv
import argparse
import time
import numpy as np
from scipy.stats import binom
from PIL import Image
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import pickle as pkl
from tqdm impor... |
1761800 | import lightgbm as lgb
import numpy as np
from sklearn.metrics import mean_squared_error
import copy
import itertools
class Constraint_GA2M:
"""
Our proposed model CGA2M+.
Attributes
----------
X_train : numpy.ndarray
y_train : numpy.ndarray
y_train_mean : numpy.ndarray
X_test : numpy... |
1761806 | import re
import setuptools
with open('insta_share/__init__.py') as f:
version = re.search(r'([0-9]+(\.dev|\.|)){3}', f.read()).group(0)
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="insta_share",
version=version,
author="soft_coder",
description="Py... |
1761854 | from unittest import TestCase
from rtreelib import RTreeGuttman, RTreeNode, RTreeEntry, Rect
from rtreelib.strategies.guttman import quadratic_split, adjust_tree_strategy
class TestGuttman(TestCase):
"""Tests for Guttman R-Tree implementation"""
def test_quadratic_split(self):
"""Ensures that a split... |
1761884 | import codecs
from flask import Blueprint, request
from flask_cors import CORS
from service.astra_service import astra_service
spacecraft_instruments_controller = Blueprint('spacecraft_instruments_controller', __name__)
CORS(spacecraft_instruments_controller)
# This controller handles the all of the GET and POST R... |
1761898 | import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = int(sys.argv[1]) # Arbitrary non-privileged port
addr = sys.argv[2]
if addr == "ipv6":
HOST = "::1"
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
elif addr == "ipv4":
HOST = "127.0.0.1"
s = socket.sock... |
1762007 | import numpy as np
from scipy.linalg import blas
from .fourier_transform import FourierTransform, multiplex_for_tensor_fields, _get_float_and_complex_dtype
from ..field import Field
from ..config import Configuration
import numexpr as ne
class MatrixFourierTransform(FourierTransform):
'''A Matrix Fourier Transform (M... |
1762008 | from os.path import join
import os.path
import hashlib
def get_original_branch():
try:
str_hash = read(join('.git', 'ORIG_HEAD'))
for line in read(join('.git', 'packed-refs')).split("\n"):
if line.startswith(str_hash):
_, branch_path = line.split(" ")
re... |
1762018 | from django.contrib import admin
from . import models
admin.site.register(models.AlphaModel)
admin.site.register(models.BetaModel)
admin.site.register(models.TaggedCharPkModel)
admin.site.register(models.AnotherTaggedCharPkModel)
admin.site.register(models.CharPkModel)
admin.site.register(models.AnotherCharPkModel)
|
1762048 | import pytest
import sys
import os
from unittest import mock
from requests import exceptions
import aiohttp
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fake_useragent import aio_main, main, errors, settings
def test_main_fetch():
assert main.fetch("https://i3wm.org") is no... |
1762054 | from unittest.mock import patch
import datasets
from datasets import Dataset
def test_set_progress_bar_enabled():
dset = Dataset.from_dict({"col_1": [3, 2, 0, 1]})
with patch("tqdm.auto.tqdm") as mock_tqdm:
datasets.set_progress_bar_enabled(True)
dset.map(lambda x: {"col_2": x["col_1"] + 1})... |
1762074 | from __future__ import print_function
import numpy as np
import tensorflow as tf
from collections import namedtuple
import json
import pickle
HyperParams = namedtuple(
"HyperParams",
[
"max_seq_len",
"seq_width",
"h_size",
"batch_size",
"grad_clip",
"num_mixture"... |
1762076 | from unittest import mock
import os
import pytest
import errno
import datreant as dtr
def test_makedirs(tmpdir):
with tmpdir.as_cwd():
dtr.util.makedirs('this/should/exist', exist_ok=True)
assert os.path.exists('this/should/exist')
assert os.path.isdir('this/should/exist')
def test_make... |
1762089 | from fidimag.common import CuboidMesh
import unittest
def test_mesh1():
mesh = CuboidMesh(nx=5, ny=3, nz=2, dx=0.23, dy=0.41)
assert len(mesh.coordinates) == 5 * 3 * 2
assert mesh.ny * mesh.nz == 6
assert tuple(mesh.coordinates[mesh.index(0, 0, 0)]) == (0.23 / 2, 0.41 / 2, 0.5)
assert tuple(mesh.co... |
1762096 | import argparse
import os
import shutil
import subprocess
import scipy.misc as spm
import scipy.ndimage as spi
import scipy.sparse as sps
import numpy as np
def getlaplacian1(i_arr: np.ndarray, consts: np.ndarray, epsilon: float = 0.0000001, win_size: int = 1):
neb_size = (win_size * 2 + 1) ** 2
h, w, c = i_ar... |
1762097 | import pandas as pd
from pgdancer import histogram
if __name__ == '__main__':
# example code
df = pd.read_csv("brands_data.csv", index_col="brands", thousands=",").fillna(0)
df = df.astype("int")
h = histogram.Histogram(df, 1600, 900, window_type=0)
h.run("pgdancer", "Top 15 Best Global Brands R... |
1762124 | import hashlib
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.tests.utils as s_t_utils
BITS = 2048
HEXSTR_MODULUS = '<KEY>' \
'b500a06247ec2f3294891a8e62c317ee648f933ec1bf760a9d7e9a5ea4706b2a2c3f6376079114ddcc7a15d3fecf001458f' \
'22f0551802a25ef95cf46... |
1762155 | from typing import Any, Text
from ..request import post
class AudioControl:
"""
音频控制
-------
仅限音频类机器人才能使用,后续会根据机器人类型自动开通接口权限,现如需调用,需联系平台申请权限;
"""
def __init__(self, channel_id: str, audio_url: str, text: str | None = "邀您共赏音乐") -> None:
self.channel_id = channel_id
self.audio_... |
1762159 | import unittest
import munch
import basecrm
from basecrm.test.testutils import BaseTestCase
class ProductsServiceTests(BaseTestCase):
def test_service_property_exists(self):
self.assertTrue(hasattr(self.client, 'products'))
def test_method_list_exists(self):
self.assertTrue(hasattr(self.clie... |
1762168 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import io
import sys
sys.path.append("./networks")
import numpy as np
import tensorflow as tf
keras=tf.contrib.keras
l2=keras.regularizers.l2
K=tf.contrib.keras.backend
import inputs as data
from temporal_dilated_res3d import td_res3d
from callbacks import LearningRate... |
1762180 | import redis
from functools import wraps
import multiprocessing as mp
from includes import *
'''
python -m RLTest --test tests_sanitizer.py --module path/to/redisai.so
'''
def test_sanitizer_dagrun_mobilenet_v1(env):
if (not TEST_TF or not TEST_PT):
return
con = get_connection(env, '{s}')
mem_all... |
1762204 | import re
# Regex's compile once to be reused on each fn call
rating_pattern = re.compile(r'(?:5[^.,])?.*?(\d(?:[.,]\d+)?).*5?')
price_pattern = re.compile(r'(?P<low>[\d,.]+)(?:\D*(?P<high>[\d,.]+))?')
def rating(rating_str):
"""Parse the rating from a string using a regex
Testing & debugging are here: http... |
1762212 | import numpy as np
import onnx
import pytest
from tests.utils.common import check_onnx_model
from tests.utils.common import make_model_from_nodes
def _test_pad(
input_array: np.ndarray,
opset_version: int,
**kwargs,
) -> None:
test_inputs = {
'x': input_array,
}
if opset... |
1762225 | import numpy as np
import theano
import theano.tensor as T
import theano.tensor.nnet.bn as bn
eps = np.float32(1e-6)
zero = np.float32(0.)
one = np.float32(1.)
def bn_shared(params, outFilters, index):
''' Setup BN shared variables.
'''
normParam = {}
template = np.ones((outFilters,)... |
1762236 | import asyncio
import pytest
from brainslug.channel import SyncedVar
def test_syncedvar_is_a_data_descriptor():
assert hasattr(SyncedVar, '__set__')
assert hasattr(SyncedVar, '__get__')
@pytest.mark.asyncio
async def test_syncedvar_get_is_a_coroutine(event_loop):
class Foo:
bar = SyncedVar()
... |
1762248 | r"""
Transfer learning deal Module.
Consist of the utils for transfer learning.
How to use the module to transfer weights as follows first, second, last.
"""
import torch
from collections import OrderedDict
from src.visual.utils.log import LOGGER
from src.visual.utils.general import delete_list_indices
def get_nam... |
1762262 | from django.db import models
class Mod(models.Model):
fld = models.IntegerField()
class M2mA(models.Model):
others = models.ManyToManyField('M2mB')
class M2mB(models.Model):
fld = models.IntegerField()
|
1762279 | from setuptools import setup, find_packages
setup(version="1.0",
name='src',
packages=find_packages(),
include_package_data=True,
install_requires=[
'numpy',
'scipy',
'numba',
'obspy',
'pandas',
'pyasdf',
'python>=3.0',
... |
1762281 | import json
import os
import threading
import time
class Store:
def __init__(self, workflow_name, function_name, request_id, input, output, to, keys, runtime, db_server, redis_server):
# to: where to store for outputs
# keys: foreach key (split_key) specified by workflow_manager
self.db = d... |
1762296 | import torch as ch
import numpy as np
from .torch_utils import *
from torch.nn.utils import parameters_to_vector as flatten
from torch.nn.utils import vector_to_parameters as assign
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import pairwise_distances
from .steps import value_loss_return... |
1762416 | import re
import six
import unittest
from geodata.addresses.entrances import *
from geodata.addresses.floors import *
from geodata.intersections.query import *
from geodata.addresses.po_boxes import *
from geodata.addresses.postcodes import *
from geodata.addresses.staircases import *
from geodata.addresses.units impo... |
1762432 | class Token(object):
def __init__(self):
self.token = None
self.pinyin = '_'
self.pos = None
self.ner = 'O'
|
1762437 | import dgcn.utils
from .Sample import Sample
from .Dataset import Dataset
from .Coach import Coach
from .model.DialogueGCN import DialogueGCN
from .Optim import Optim
|
1762471 | from PIL import Image
import numpy as np
import os, shutil, sys ,cv2, asyncio, scipy
from telegraph import upload_file
from telethon.tl.types import MessageMediaPhoto
from ub.utils import admin_cmd
from ub import bot
import PIL
#made by @danish_00 and @Shivam_Patel
#donto kang
path = "./dcobra/"
if not os.path.isdir(p... |
1762490 | from os.path import dirname
from .get_frame_dir import get_frame_dir
fython_root = dirname(dirname(get_frame_dir()))
|
1762511 | MAX_WIDTH = 26
text_words = {
"Attack " : b"\xD6\x00",
"Angel " : b"\xD6\x01",
"After " : b"\xD6\x02",
"Aura " : b"\xD6\x03",
"Ankor " : b"\xD6\x04",
"Black " : b"\xD6\x05",
"Bill: " : b"\xD6\x06",
"Crystal " : b"\xD6\x07",
"City " : b"\xD6\x08",
"Come " : b"\xD6\x09",... |
1762595 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from lesson6 import word2vec_utils
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string('DOWNLOAD_URL', 'http://mattmahoney.net/dc/text8.zip', 'download link for text8')
tf.flags.DEFINE_... |
1762614 | import math
from queue import Queue
from IPython import embed
import torch
import torch.distributed as dist
import torch.cuda.comm as comm
from torch.autograd.function import once_differentiable
from torch.nn.modules.batchnorm import _BatchNorm
import torch.nn.functional as F
import syncbn_gpu
class DistributedSync... |
1762635 | import lmdb
import cv2
import numpy as np
env = lmdb.open('data/face_test_lmdb',
max_readers=1,
readonly=True,
lock=False,
readahead=False,
meminit=False)
with env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'))
... |
1762725 | import os
from .dataloader import ActionRecognitionDatasets # noqa: F401
from .interfaces import VideoClassificationDataset # noqa: F401
from .video_ensemble import ( # noqa: F401
SpatiallySamplingVideoEnsemble,
TemporallySamplingVideoEnsemble,
)
from .videoclips import videoclips # noqa: F401
# Ensure ff... |
1762747 | from random import choice
import discord
from discord.ext import commands
from Resources import fact as ft
import re
import random
bot_channel = 'joke-and-fact'
class Fact(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
pr... |
1762801 | from PIL import Image
# DO NOT SEE HERE! IT WORKED!
class MatrixSunday:
__image_src = None
__image_dst = None
def de_scramble(self, path_src: str, path_dst: str, data: list):
self.__image_src = Image.open(path_src, 'r')
self.__process(data)
self.__image_dst.save(path_dst)
... |
1762810 | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.db import transaction, IntegrityError
from core.forms.forms import CustomUserCreationForm, PersonF... |
1762850 | import os
import numpy as np
import tables as tb
def main():
here = os.path.abspath(os.path.dirname(__file__))
data_dir = os.path.abspath(os.path.join(here, '..', 'data'))
file_path = os.path.join(data_dir, 'pytables-vlarray.h5')
# A VLArray contains homogeneous data.
# Like Table datasets, varia... |
1762893 | from io import BytesIO
try:
from PIL import Image as im
IMAGE_UTILS_AVAILABLE = True
Image = im.open
def resize(image, size):
output = BytesIO()
back = im.new('RGBA', size, (0,0,0,0))
image.thumbnail(size, im.ANTIALIAS)
offset = [0,0]
if image.size[0] >= image.siz... |
1762896 | import pytest
from ...product.models import ProductType
from ..utils import associate_attribute_values_to_instance
def test_associate_attribute_to_non_product_instance(color_attribute):
instance = ProductType()
attribute = color_attribute
value = color_attribute.values.first()
with pytest.raises(Ass... |
1762953 | from .closed import keys as k
from .closed import commands as c
from .closed import modes as m
import copy
keys = copy.deepcopy(k)
commands = copy.deepcopy(c)
modes = copy.deepcopy(m)
keys['a']['word'] = 'a'
keys['b']['word'] = 'b'
keys['c']['word'] = 'c'
keys['d']['word'] = 'd'
keys['e']['word'] = 'e'
keys['f']['wor... |
1762965 | import json
pets = [
{
"id": 1,
"name": "Birds"
},
{
"id": 2,
"name": "Cats"
},
{
"id": 3,
"name": "Dogs"
},
{
"id": 4,
"name": "Fish"
}
]
def handler(event, context):
print(event)
try:
path = event['path... |
1762970 | import json
import logging
import os
import re
from requests import get, put, post
from credcheck.exceptions import ParametersRequiredError
# sys.tracebacklimit=0
from credcheck.modules import ssh_client, http_client
logging.basicConfig(
format="%(asctime)s - %(name)s (%(lineno)s) - %(levelname)s: %(message)s",... |
1762974 | from shared.utils import get_db_ref
db = get_db_ref()
class ModelBasic(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
model_name = db.Column(db.String(50), nullable=False)
model_dataset = db.Column(db.Integer, db.ForeignKey('data_file.id'))
model_type = db.Column(db.Inte... |
1763023 | from discord import Guild, Role
from src.utils.readConfig import getAdminListConfig
from typing import List
from loguru import logger
async def getEventAdminRole(myGuild: Guild):
"""
:param myGuild:
:return:
dict{
'roleName': role,
'roleName': role
}
"""
eventConfig = g... |
1763034 | from __future__ import absolute_import
from dev.regularized_evolution.searcher.regularized_evolution_searcher import EvolutionSearcher, mutatable
# from dev.enas.searcher.enas_searcher import ENASSearcher
import deep_architect.searchers.random as ra
from deep_architect.searchers.smbo_mcts import SMBOSearcherWithMCTSOpt... |
1763067 | import functools
import math
import multiprocessing
from contextlib import contextmanager, ExitStack
from functools import partial
from math import log2
from random import random
import torch
import torch.nn.functional as F
import trainer.losses as L
import numpy as np
from kornia.filters import filter2d
from linear_... |
1763117 | import argparse
UNK_IDX = 0
UNK_WORD = "UUUNKKK"
EVAL_YEAR = "2017"
BOS_IDX = 1
EOS_IDX = 2
MAX_GEN_LEN = 40
METEOR_JAR = 'evaluation/meteor-1.5.jar'
METEOR_DATA = 'evaluation/data/paraphrase-en.gz'
MULTI_BLEU_PERL = 'evaluation/multi-bleu.perl'
STANFORD_CORENLP = 'evaluation/stanford-corenlp-full-2018-10-05'
def st... |
1763229 | BASE_LOOKUP_TABLE = {}
PLAIN_ENTRIES = set()
def register_custom_descriptor(name: str, is_plain: bool = True):
"""
A decorator used for registering custom descriptors in order to be loadable via
descriptor_from_dict
Use like:
>>> @register_custom_descriptor('ipv6')
>>> class IPv6(Regexp):
... |
1763251 | import FWCore.ParameterSet.Config as cms
# output block for alcastream HCAL HEMuon
# output module
# module alcastreamHcalHEMuonOutput = PoolOutputModule
OutALCARECOHcalCalHEMuonFilter_noDrop = cms.PSet(
# use this in case of filter available
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vst... |
1763284 | import copy
import json
from datetime import datetime
import requests
headers = {
'app_version': '3',
'platform': 'ios',
}
# super LIKE '/like/' + likedUserId + '/super'
class User(object):
def __init__(self, data_dict):
self.d = data_dict
@property
def user_id(self):
return s... |
1763348 | import os
class Tree:
def __init__(self, node="", *children):
self.node = node
self.width = len(node)
if children: self.children = children
else: self.children = []
def __str__(self):
return "%s" % (self.node)
def __repr__(self):
return "%s" % (s... |
1763361 | from __future__ import absolute_import
from django.contrib.gis.sitemaps import GeoRSSSitemap, KMLSitemap, KMZSitemap
from .feeds import feed_dict
from .models import City, Country
sitemaps = {'kml' : KMLSitemap([City, Country]),
'kmz' : KMZSitemap([City, Country]),
'georss' : GeoRSSSitemap(f... |
1763372 | from geopatterns import GeoPattern
import os
import random
import base64
directory = './bg_gen'
if not os.path.exists(directory):
os.mkdir(directory)
for id in range(500):
pattern = GeoPattern(
str(random.random()),
generator=random.choice(['bricks','hexagons','overlapping_circles','overla... |
1763414 | from django.db import models
from data.models.common import TimeStampsModel
from data.models import Allegation
class ActivityPairCard(TimeStampsModel):
officer1 = models.ForeignKey('data.Officer', on_delete=models.CASCADE, related_name='activity_pair_card1')
officer2 = models.ForeignKey('data.Officer', on_de... |
1763504 | import os
import json
import time
import mlflow
import shutil
import getpass
import platform
from typing import Any
from typing import Dict
from typing import Optional
from cftool.misc import lock_manager
from cftool.misc import fix_float_to_length
from mlflow.exceptions import MlflowException
from mlflow.utils.mlflow... |
1763597 | import pytest
from sqlalchemy import Column, Integer, MetaData, String, Table
meta = MetaData()
tbl = Table(
"sa_tbl",
meta,
Column("id", Integer, nullable=False, primary_key=True),
Column("name", String(255)),
)
@pytest.fixture
def connect(make_sa_connection, loop):
async def start():
co... |
1763619 | from sqlalchemy import Column, Integer, ForeignKey, Enum, Numeric, CheckConstraint
from sqlalchemy.orm import relationship
from transiter import parse
from .base import Base
from .updatableentity import updatable_from
@updatable_from(parse.Transfer)
class Transfer(Base):
__tablename__ = "transfer"
pk = Colu... |
1763621 | from functools import partial
import torch
from torch import nn, einsum
from einops import rearrange
from einops.layers.torch import Rearrange, Reduce
import torch
import math
import warnings
from torch.nn.init import _calculate_fan_in_and_fan_out
import torch.nn.functional as F
# helpers
NUM_VARIANTS = 18
def cast... |
1763670 | import matplotlib
import numpy as np
matplotlib.use('Agg')
import shap # pylint: disable=wrong-import-position
def test_random_single_image():
""" Just make sure the image_plot function doesn't crash.
"""
shap.image_plot(np.random.randn(3, 20, 20), np.random.randn(3, 20, 20), show=False)
def test_random_... |
1763708 | import datetime
import os
import pytest
from dynamorm.exceptions import ValidationError
from dynamorm.model import DynaModel
from dynamorm.indexes import GlobalIndex, ProjectKeys
from dynamorm.relationships import OneToOne, OneToMany, ManyToOne
if "marshmallow" in (os.getenv("SERIALIZATION_PKG") or ""):
from mar... |
1763712 | import string
import random
import time
import datetime
from flask import render_template, redirect, url_for, request, session, Flask
from functools import wraps
from exts import db
from config import Config
from models import User, Note
from forms import CreateNoteForm
app = Flask(__name__)
app.config.from_object(Con... |
1763729 | import os
import sys
import time
import torch
import threading
import numpy as np
from pynput import keyboard
from pytorchrl.agent.env import VecEnv
from pytorchrl.envs.obstacle_tower.utils import action_lookup_6, action_lookup_7, action_lookup_8
from pytorchrl.envs.obstacle_tower.obstacle_tower_env_factory import obs... |
1763779 | from django.conf.urls import *
from django.contrib import admin
import AuShadha.settings
from patient.views import *
from patient.dijit_widgets.pane import render_patient_pane
from patient.dijit_widgets.tree import render_patient_tree
admin.autodiscover()
urlpatterns = patterns('',
################################ ... |
1763806 | import unittest
import dag_loader
import workflow
class DagLoaderTest(unittest.TestCase):
def setUp(self):
super(DagLoaderTest, self).setUp()
pass
def tearDown(self):
super(DagLoaderTest, self).tearDown()
pass
def test_should_load_files_definitions(self):
dag_con... |
1763817 | input = open('antiqs.in', 'r')
output = open('antiqs.out', 'w')
n = int(input.readline())
a=list()
for i in range(0,n):
a.append(i+1)
for i in range(0, n):
a[i], a[i // 2] = a[i // 2], a[i]
for i in range(0, n):
output.write(str(a[i]))
output.write(' ')
input.close()
output.close() |
1763833 | import logging
from celery import Celery
from celery import signals
import structlog
from entityservice.database.util import init_db_pool, close_db_pool
from entityservice.settings import Config
from entityservice.logger_setup import setup_structlog
celery = Celery('tasks',
broker=Config.CELERY_BROKE... |
1763839 | class NotWellFormed(Exception):
"""
Exception raised when a formula is not well-formed
"""
pass
class IncorrectLevels(Exception):
"""
Exception raised when an inference contains premises and/or conclusions of different levels
"""
pass
class LevelsWarning(Warning):
"""
Same as... |
1763901 | from unittest import mock
from unittest.mock import Mock
from hive_metastore_client.builders.table_builder import TableBuilder
class TestTableBuilder:
@mock.patch("hive_metastore_client.builders.table_builder.Table")
def test_build(self, mocked_table):
# arrange
mocked_table_name = ""
... |
1763911 | import torch.nn as nn
from .slowfast import *
from utils import load_pretrain
def model_entry(config):
return globals()[config['arch']](**config['kwargs'])
class AVA_backbone(nn.Module):
def __init__(self, config):
super(AVA_backbone, self).__init__()
self.config = config
s... |
1763918 | del_items(0x8012427C)
SetType(0x8012427C, "void PresOnlyTestRoutine__Fv()")
del_items(0x801242A4)
SetType(0x801242A4, "void FeInitBuffer__Fv()")
del_items(0x801242CC)
SetType(0x801242CC, "void FeAddEntry__Fii8TXT_JUSTiP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, int Str, struct FeTable *MenuPtr, struct CFont *Fon... |
1763933 | from django.test import TestCase
from django.contrib.auth.models import User
from tethys_apps.models import TethysApp
from tethys_quotas.models import UserQuota, TethysAppQuota
from tethys_quotas.models import ResourceQuota
from tethys_quotas.handlers.base import ResourceQuotaHandler
class EntityQuotaTest(TestCase):
... |
1763934 | import os
import sys
import random
import pickle
import argparse
import time
import pandas as pd
import numpy as np
import boto3
from io import BytesIO
from consts import (
PATH,
NUM_WORKERS,
s3,
bucket
)
from funcs import (
debug_print,
s3_to_df
)
def main():
# Parse command line argu... |
1763959 | from windowing.dynamic import DynamicSessions
import argparse, json, logging, time
import apache_beam as beam
import apache_beam.transforms.window as window
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
class AnalyzeSession(beam.DoFn):... |
1763991 | import struct
pic = [
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0xFE, 0x... |
1764039 | import os
from flask import Flask, redirect, render_template, request
from google.cloud import storage
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
app = Flask(__name__)
@app.route('/')
def homepage():
# Return a Jinja2 HTML template and pass in i... |
1764041 | from get_data import get_train_data, get_test_data, anat_data, get_val_data
from keras.utils import to_categorical
import os, h5py, json, numpy as np
#from models import deeper_lstm
from my_models import deeper_lstm
root_path = 'D:/workspace/aditya_akshita/vqa/VQA_Keras/data/'
val_file =root_path+'annotat... |
1764050 | import unittest
import squaring_mod_GF2N as sqGF2N
from bitpermutations.data import Register, MemoryFragment, ZERO
from bitpermutations.utils import sequence_to_values
class TestSquaringModGF2N_patience(unittest.TestCase):
def test_square_821_patience(self):
src = [MemoryFragment(64, '{}(%rsi)'.format(i*... |
1764070 | import os
import numpy as np
import tvm
import time
from tvm import te
from tvm import autotvm
from tvm import relay
import tvm.relay.testing
import lenet
import tvm.relay.testing.init as init
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
from tvm.contrib.util import tempdir
from tvm.t... |
1764079 | import struct
def read_uchar(bytes, idx):
val = struct.unpack_from(">B", bytes, idx)
return val[0], idx + 1
def read_schar(bytes, idx):
val = struct.unpack_from(">b", bytes, idx)
return val[0], idx + 1
def read_uword(bytes, idx):
val = struct.unpack_from(">H", bytes, idx)
return val[0], idx +... |
1764082 | import time
import copy
import csp
from examples.performance_testing import measure_performance
# SOLVING N-QUEENS PROBLEM:
# Each variable represent a column in the n x n sized board.
# Each variable's domain is (1, ..., n), and it represent a possible queen row-coordinate location in the column i.
# For the queens ... |
1764116 | import argparse
import torch
import lib
import numpy as np
import os
import datetime
parser = argparse.ArgumentParser()
parser.add_argument('--hidden_size', default=100, type=int) #Literature uses 100 / 1000 --> better is 100
parser.add_argument('--num_layers', default=3, type=int) #1 hidden layer
parser.add_argument(... |
1764121 | from __future__ import unicode_literals
import textx
def test_issue89_get_obj_pos_in_text():
mm = textx.metamodel_from_str('''
Model: objs+=Obj;
Obj: 'obj' name=ID;
''')
m = mm.model_from_str('''obj A
obj B
obj C
obj D
''')
assert (1, 1) == textx.get_model(m.objs[0])._tx_... |
1764183 | from io import StringIO
import pandas as pd
import requests
# Get the raw text of the data directly from the figshare url.
url = "https://ndownloader.figshare.com/files/13007075"
raw = requests.get(url).text
# Then reads in the data as a pandas DataFrame.
data = pd.read_csv(StringIO(raw))
# Extracting a column as a S... |
1764194 | from nvm.pmemobj import PersistentObjectPool
with PersistentObjectPool('hello_world.pmem', flag='c') as pool:
if pool.root is None:
name = input("What is your name? ")
pool.root = name
print("Hello, {}".format(pool.root))
|
1764224 | import strawberry
import strawberry_django_jwt.mutations
from tests.refresh_token import mixins
from tests.refresh_token.mutations import Refresh
from tests.refresh_token.testcases import AsyncCookieTestCase, CookieTestCase
from tests.testcases import AsyncSchemaTestCase, SchemaTestCase
class TokenAuthTests(mixins.T... |
1764228 | from copy import deepcopy
import logging
import types
import runpy
logger = logging.getLogger('lona.settings')
class Settings:
def __init__(self):
self._paths = []
self._values = {}
def add(self, path):
if not path.endswith('.py'):
logger.error(
"'%s' does... |
1764271 | from iohandler.datareader import find_files
import re
import pdb
# pdb.set_trace()
fs = find_files('sprite_imgs', '.*\.jpg')
fs = sorted(fs)
# for iWord in range(iFirst, iLast+1):
with open('char10000.tsv', 'w', encoding='utf-8') as f:
for filename in fs:
# print 'Word %d: %s' % (iWord, unichr(iWord))
... |
1764272 | import numpy as np
my_list1 = [1,2,3,4]
my_list2 = [11,22,33,44]
my_lists = [my_list1,my_list2]
my_array = np.array(my_lists)
print(my_array)
|
1764294 | bl_info = {
"name": "OSVR_Analog",
"category": "Object",
}
import bpy
from bpy.types import Operator
# from ClientKit import ClientKit
class OSVR_Analog(Operator):
"""OSVR_Analog""" # blender tooltip for menu items and buttons
bl_idname = "object.osvr_analog" # uniqu... |
1764307 | import math
import matplotlib.pyplot as plt
import numpy as np
import pytest
from kneed.data_generator import DataGenerator as dg
from kneed.knee_locator import KneeLocator
from kneed.shape_detector import find_shape
@pytest.mark.parametrize("interp_method", ["interp1d", "polynomial"])
def test_figure2(interp_method)... |
1764320 | from django.core.exceptions import ValidationError
from django.test.testcases import SimpleTestCase
from robber import expect
from data.validators import validate_race
class ValidateRaceTestCase(SimpleTestCase):
def test_invalid_value(self):
expect(lambda: validate_race('nan')).to.throw(ValidationError)
... |
1764331 | from pal.filter.abstract_filter import AbstractFilter
class LORegionRegisterFilter(AbstractFilter):
@property
def description(self):
return "limited order region (LORegion) registers"
def do_filter(self, reg):
if(reg.name.lower().startswith("lor")):
return False
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.