id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3253837 | class Solution:
def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:
a0 = b0 = 0
for i in arr1:
a0 = a0 ^ i
for j in arr2:
b0 = b0 ^ j
return a0 & b0 |
3253871 | import random
class ExperienceReplay():
def __init__(self):
self.buffer = []
self.buffer_size = 1000
def add(self, data):
self.buffer.extend(data)
if len(self.buffer) > self.buffer_size: self.buffer = self.buffer[-self.buffer_size:]
def sample(self, size):
return r... |
3253872 | from scivision.io import PretrainedModel
from skimage.io import imread
from skimage.transform import resize
from tensorflow.keras.applications.imagenet_utils import decode_predictions
def test_pretrained_model(IMAGENET_MODEL):
"""Check that a pretrained model object can be created from config"""
assert type(I... |
3253916 | from ..helper import ActionOnExit
from ..helper.aws import filter_subnets
def configure_elasticache(session, region, vpc):
client = session.client('elasticache', region)
subnet_ids = [sn.id for sn in filter_subnets(vpc, 'internal')]
try:
response = client.describe_cache_subnet_groups(
... |
3253969 | import cv2
import imutils
IMAGE_WIDTH = 1300
RED_MEAN = 103.939
GREEN_MEAN = 116.779
BLUE_MEAN = 123.680
class FastNeuralStyle:
def __init__(self, model_path):
self.model = cv2.dnn.readNetFromTorch(model_path)
def transform(self, image):
blob = self._prepare_blob(image)
self.model.setInput(blob)
... |
3253983 | class Solution:
def minSubArrayLen(self, s, nums):
l, res, curr = 0, len(nums) + 1, 0
for r, num in enumerate(nums):
curr += num
while curr >= s: res, l, curr = min(res, r - l + 1), l + 1, curr - nums[l]
return res < len(nums) + 1 and res or 0 |
3254035 | import math
import random
import time
from roman import Robot, Tool, Joints
from roman.sim.simenv import SimEnv
class Writer():
def __init__(self):
self.frames = []
self.last_time = 0
def __call__(self, arm_state, hand_state, arm_cmd, hand_cmd):
if arm_state.time() - self.last_time < 0... |
3254038 | import gzip
import os
import sys, re
import glob
import random
import threading
import numpy
# Prepare readers for compressed files
readers = {}
try:
import gzip
readers['.gz'] = gzip.GzipFile
except ImportError:
pass
try:
import bz2
readers['.bz2'] = bz2.BZ2File
except ImportError:
pass
def ... |
3254040 | import os
import torch
import torchvision.transforms as transforms
import numpy as np
import cv2
import dlib
import scipy.io as sio
import argparse
import math
from modules import mobilenet_v1
from utils import ToTensorGjz, NormalizeGjz, crop_img
from modules.morphable.morphable_model import MorphableModel
from module... |
3254054 | import uuid
import datetime
from dateutil.tz import tzutc
import botocore
from botocore.stub import Stubber
from active_rule_set_provider import handler, provider
def test_create_no_existing_rule_set():
ses = botocore.session.get_session().create_client("ses")
stubber = Stubber(ses)
stubber.add_response(
... |
3254066 | import Bio.PDB.Residue
from rosettautil.util import fileutil
class sasa_point:
def __init__(self,resname, chain,resnum, type,absolute,relative):
self.resname = resname
self.resnum = resnum
self.chain = chain
self.type = type
self.absolute = absolute
self.relative = r... |
3254107 | def run_length_decode(in_array):
"""A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array"""
switch=False
out_array=[]
for item in in_array:
if switch==False:
this_item = item
switch=True
else:... |
3254111 | import datetime
from StringIO import StringIO
from werkzeug.datastructures import FileStorage
from tests.unit.test_base import BaseTestCase
from tests.unit.screener.utils import (
get_user,
get_service,
get_patient
)
from app.models import AppUser, Service, ServiceTranslation, Patient
from app.prescreening ... |
3254149 | import re
from typing import Any
from markdown import Markdown
from markdown.extensions import Extension
from markdown.postprocessors import Postprocessor
class ChecklistExtension(Extension):
def extendMarkdown(self, md: Markdown) -> None:
postprocessor = ChecklistPostprocessor(md)
md.postprocess... |
3254225 | from django.db import models
from .. import fields
class EncryptedText(models.Model):
value = fields.EncryptedTextField()
class EncryptedChar(models.Model):
value = fields.EncryptedCharField(max_length=25)
class EncryptedNullable(models.Model):
value = fields.EncryptedJSONField(null=True)
|
3254236 | from screeps_loan import app
import screeps_loan.models.alliances as alliances_model
import screeps_loan.models.rankings as rankings_model
from screeps_loan.models.rooms import get_all_rooms
import screeps_loan.models.users as users_model
from screeps_loan.routes.decorators import httpresponse
import json
from flask im... |
3254251 | from twisted.spread.pb import Copyable
class RequestFromScrapy(Copyable, object):
def __init__(self, url, method, headers, body):
super().__init__()
self.url = url
self.method = method
self.headers = dict(headers)
self.body = body
class RequestFromBrowser(Copyable, object... |
3254294 | from pyteal import (
Bytes,
Int,
Itob,
Log,
Op,
ScratchVar,
Subroutine,
SubroutineCall,
TealType,
)
from tests.helpers import assert_output, logged_bytes, logged_int
from .iter import accumulate, iterate
def test_iterate():
expr = iterate(Log(Bytes("a")), Int(10))
assert ... |
3254297 | import hashlib
import json
import os
import shutil
import time
from collections import Counter
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union
import numpy as np
import pandas as pd
from fire import Fire
from pydantic import BaseModel
from pydantic.main import Extra
from tqdm import... |
3254306 | from json import dumps
from assemblyline_client.v4_client.common.utils import api_path
class System(object):
def __init__(self, connection):
self._connection = connection
def clear_system_message(self):
"""\
Clear the current system message
"""
return self._connection.delete(api_path... |
3254386 | import osmnx as ox
import networkx as nx
import numpy as np
import copy
from shapely.geometry import LineString, MultiLineString
from shapely import ops
import osmnx.utils_graph
def generate_square_multidi_graph(width, height, mean_distance=300, std=100, min_distance=100) ->nx.MultiDiGraph:
'''
Generate graph... |
3254402 | import time, numpy as np
import cv2, os
import tensorflow as tf
from utilities.directkeys import PressKey, ReleaseKey, Q, W, E, S, A, D
from utilities.window import WindowMgr
def superattack():
PressKey(Q)
time.sleep(0.05)
ReleaseKey(Q)
def attack():
PressKey(E)
time.sleep(0.05)
ReleaseKey(E)
... |
3254430 | import colorsys
class HSVRatio:
cyan_min = float(4.5 / 12.0)
cyan_max = float(7.75 / 12.0)
def __init__(self, hue=0.0, saturation=0.0, value=0.0, ratio=0.0):
self.h = hue
self.s = saturation
self.v = value
self.ratio = ratio
def average(self, h, s, v):
self.h... |
3254441 | from collections import namedtuple
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.nn.parallel import DistributedDataParallelCPU as DDPC
from rlpyt.agents.base import BaseAgent, AgentStep
from rlpy... |
3254445 | from datetime import date
from sqlalchemy import event
from flask import url_for
from flask_babel import lazy_gettext as _
from flask_login import current_user
from app import db, get_locale
from app.models.base_model import BaseEntity
class News(db.Model, BaseEntity):
__tablename__ = 'news'
nl_title = db.... |
3254468 | from connect.accounts.factories import AbuseReportFactory, AbuseWarningFactory
from behave import given, then, when
from common import DEFAULT_WAIT
# Background
@given('the second user has logged a complaint against the first')
def impl(context):
AbuseReportFactory(logged_by=context.standard_user2,
... |
3254476 | import logging
import random
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
from typing import Protocol, Optional, List
from tornado.web import RequestHandler
from . import pageutils
JST = timezone(timedelta(hours=9))
class BannerDefn(Protocol):
def template_name(self, han... |
3254478 | import torch
import torch.nn
from torch import Tensor
import math
from kge import Config, Dataset
from kge.model.kge_model import RelationalScorer, KgeModel
class TransformerScorer(RelationalScorer):
r"""Scorer that uses a plain Transformer encoder.
Concatenates (1) CLS embedding, (2) subject entity embeddi... |
3254479 | import json
from tests.factories import PartyFactory
# GET
def test_get_persons(test_client, db_session, auth_headers):
batch_size = 3
parties = PartyFactory.create_batch(size=batch_size, person=True)
get_resp = test_client.get('/parties', headers=auth_headers['full_auth_header'])
get_data = json.lo... |
3254488 | import copy
import warnings
import weakref
import pandas as pd
from woodwork.accessor_utils import (
_check_column_schema,
_is_dataframe,
_is_series,
init_series,
)
from woodwork.column_schema import ColumnSchema
from woodwork.exceptions import ParametersIgnoredWarning, TypingInfoMismatchWarning
from ... |
3254498 | from typing import Any, Dict, Tuple, Union
import torch
from torch.nn.functional import interpolate
from torchvision.prototype.datasets.utils import SampleQuery
from torchvision.prototype.features import BoundingBox, Image, Label
from torchvision.prototype.transforms import Transform
class HorizontalFlip(Transform):... |
3254527 | from hcp.io.file_mapping import get_file_paths
from hcp.io.file_mapping.file_mapping import run_map
import hcp.tests.config as tconf
from nose.tools import assert_raises, assert_equal
def test_basic_file_mapping():
"""Test construction of file paths and names"""
assert_raises(ValueError, get_file_paths,
... |
3254557 | from flask_login import current_user, login_required
from redash import models
from redash.handlers import routes
from redash.handlers.base import json_response, org_scoped_rule
from redash.authentication import current_org
@routes.route(org_scoped_rule("/api/organization/status"), methods=["GET"])
@login_required
d... |
3254583 | import argparse
import datetime
import logging
import multiprocessing
import os
import sys
from multicrypto.ellipticcurve import secp256k1
from multicrypto.address import convert_public_key_to_address, convert_private_key_to_wif_format, \
validate_pattern
from multicrypto.coins import coins
from multicrypto.scrip... |
3254596 | import FWCore.ParameterSet.Config as cms
SiStripSpyEventSummary = cms.EDProducer('SiStripSpyEventSummaryProducer',
RawDataTag = cms.InputTag('source'),
RunType = cms.uint32(2) #Pedestals, see DataFormats/SiStripCommon/interface/ConstantsForRunType.h
)
|
3254616 | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... |
3254621 | class T:
def __init__(self, anything):
pass
def __lt__(self, otherthing):
return True
def __gt__(self, otherthing):
return True
def __ge__(self, otherthing):
return True
def __le__(self, otherthing):
return True
def __eq__(self, otherthing):
r... |
3254632 | import fbe
import proto
from proto import proto
def main():
# Create a new account using FBE model
account = proto.AccountModel(fbe.WriteBuffer())
model_begin = account.create_begin()
account_begin = account.model.set_begin()
account.model.id.set(1)
account.model.name.set("Test")
account.m... |
3254646 | import tensorflow as tf
def get_train_op(optimizer, loss, lr, var_list=tf.trainable_variables()):
'''
Args:
optimizer - tf optimizer
ex) tf.train.AdamOptimizer
loss - a tensor
lr - float
learning rate
var_list - list of tensors
Return:
tra... |
3254665 | import pytest
import isobar as iso
def test_pref():
a = iso.PSequence([1, 2, 3], 1)
b = iso.PSequence([4, 5, 6], 1)
c = iso.PRef(a)
assert next(c) == 1
assert next(c) == 2
c.pattern = b
assert next(c) == 4
assert next(c) == 5
assert next(c) == 6
with pytest.raises(StopIteration)... |
3254678 | import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channelin = connection.channel()
channelin.exchange_declare(exchange='chat')
chat = 'boo'
channelin.basic_publish(exchange='chat',
routing_key='chatin',
body=chat)
print(" [x] S... |
3254747 | from htun.args import args
from htun.tools import stop_running, create_iptables_rules, \
delete_ip_tables_rules
from htun.http_server import run_server
from htun.tun_iface import TunnelServer
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
if args.uri:
is_serve... |
3254760 | class UnitTestMock:
def assertEqual(self, a, b, **kwds):
if "msg" in kwds:
assert a == b, kwds["msg"]
else:
assert a == b
def assertFalse(self, a, **kwds):
if "msg" in kwds:
assert not a, kwds["msg"]
else:
assert not a
def ass... |
3254765 | import operator
import logging
from app.config import app_api
from app.utils import ActionType, SearchType
import tweepy
logging.basicConfig(filename='app.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
class TweetFetcher:
def __init__(self, text, mo... |
3254785 | from flask import Blueprint, jsonify
from cache import cache
from db import db
from models.divi import HospitalDevelopment, HospitalsDevelopmentPerLandkreis, HospitalsDevelopmentPerBundesland, \
HospitalsDevelopmentPerRegierungsbezirk
from views.helpers import __as_feature_collection
routes = Blueprint('divi', __... |
3254786 | from logging import getLogger
def smart_append(df, other):
if other is None or other.shape[0] == 0:
return df.copy()
if df is None:
df = other.copy()
else:
df = df.append(other)
df.sort_index(inplace=True, kind='mergesort')
# https://stackoverflow.com/questions/13035764/remo... |
3254839 | from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Import applications
import KratosMultiphysics.DamApplication as KratosDam
class MappingVariablesUtility:
def __init__(self,domain_size):
# Construct the utility... |
3254840 | import yaml
import sys
import os
import argparse
from shutil import which
from kijiji_scraper.kijiji_scraper import KijijiScraper
from kijiji_scraper.email_client import EmailClient
from . import VERSION
def parse_args():
parser = argparse.ArgumentParser(description="""Kijiji scraper: Track ad informations and se... |
3254870 | import numpy as np
from nose.plugins.skip import SkipTest
import theano
from theano import tensor as T
from theano.tensor.signal import pool
from theano.sandbox import mkl
if not mkl.mkl_available:
raise SkipTest('Optional package MKL disabled')
def run_test(direction='forward'):
print ('=' * 60)
print ... |
3254876 | import socket
class BroadcastUnrouteable(Exception):
def __init__(self, socketerror):
self.socketerror = socketerror
super(BroadcastUnrouteable, self).__init__()
class BroadcastSocket(object):
def __init__(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sel... |
3254881 | import os
import pandas as pd
import sandy
__author__ = "<NAME>"
__all__ = [
"ELEMENTS",
"METASTATES",
"NATURAL_ABUNDANCE",
"abundance_per_element",
"expand_za",
"expand_za",
"za2latex",
"zam2latex",
]
pd.options.display.float_format = '{:.5e}... |
3254942 | from pathlib import Path
from typing import List, Tuple
import numpy as np
import pandas as pd
from src.noise_suppression.dataset._const import NP_RANDOM_SEED
np.random.seed(NP_RANDOM_SEED)
class MCV:
def __init__(self, basepath: Path, val_dataset_size: int) -> None:
self.__basepath: Path = basepath
... |
3255071 | from __future__ import annotations
import logging
import os
import pathlib
import typing
from typing import Any, Dict, List
import fileseq
from silex_client.action.command_base import CommandBase
from silex_client.utils.parameter_types import IntArrayParameterMeta, PathParameterMeta
# Forward references
if typing.T... |
3255108 | from .epoxy import preprocess_lfs, extend_lfs, Epoxy
__all__ = [
'preprocess_lfs',
'extend_lfs',
'Epoxy'
] |
3255138 | from py2js import convert_py2js
import inspect
class JavaScript(object):
"""
Decorator that you can use to convert methods to JavaScript.
For example this code::
@JavaScript
class TestClass(object):
def __init__(self):
alert('TestClass created')
... |
3255154 | from ray import tune
from ray.rllib.agents.ppo import PPOTrainer
tune.run(
PPOTrainer,
stop={"episode_len_mean": 20},
config={"env": "CartPole-v0", "framework": "torch", "log_level": "INFO"},
)
|
3255180 | import logging
from async_service import Service
from eth_enr import ENRDatabaseAPI
from eth_keys import keys
from eth_typing import NodeID
import trio
from ddht.base_message import AnyInboundMessage, AnyOutboundMessage
from ddht.datagram import (
DatagramReceiver,
DatagramSender,
InboundDatagram,
Out... |
3255191 | import atexit
import os
import shlex
import subprocess
import sys
import click
from .util import (fcomplete, set_title, inp, replace_slice, get_terminal_size,
strip_control)
class REPL(object):
def __init__(self, color, prompt, sub, command, external):
self.color_enabled = color
... |
3255310 | import abc
from typing import *
from .error import Error
from .typevar import *
__all__ = [
'Result',
'Ok',
'Err',
'IResult',
'IOk',
'IErr',
]
class Result(Generic[T, E], metaclass=abc.ABCMeta):
"""
enum Result<T> {
Ok(T),
Err(E),
}
"""
def is_ok(self) -... |
3255315 | import unittest
from binascii import hexlify, unhexlify
from fastecdsa import keys, curve
from fastecdsa.encoding.sec1 import InvalidSEC1PublicKey, SEC1Encoder
from ecc_secp256k1 import ECC256k1
PRIV_KEY = 0x92c0302c1fff4679f4c98684ff368fdbe04da815e6de24d246793f5812577016
pub_key = keys.get_public_key(PRIV_KEY, curve... |
3255335 | import requests
class Aave(object):
http_subgraph = 'https://api.thegraph.com/subgraphs/name/aave/protocol-raw'
ws_subgraph = 'wss://api.thegraph.com/subgraphs/name/aave/protocol-raw'
query_objects = {
'lendingPoolConfigurationHistoryItems': [],
'lendingPoolConfigurations': [],
'p... |
3255366 | import pytest
from sdl2.surface import SDL_CreateRGBSurface, SDL_FreeSurface
from sdl2.rect import SDL_Rect
from sdl2.ext.draw import prepare_color, fill
from sdl2.ext.surface import _create_surface
from sdl2 import ext as sdl2ext
try:
import numpy
_HASNUMPY = True
except:
_HASNUMPY = False
@pytest.mark.... |
3255384 | from unittest import TestCase
import numpy as np
from numpy import ndarray
from pandas import DataFrame
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from aix360.algorithms.rbm import FeatureBinarize... |
3255427 | from random import choice
from uqcsbot import bot, Command
@bot.on_command("coin")
def handle_coin(command: Command):
"""
`!coin [number]` - Flips 1 or more coins.
"""
if command.has_arg() and command.arg.isnumeric():
flips = min(max(int(command.arg), 1), 500)
else:
flips = 1
... |
3255436 | import onnx
import argparse
def remove_initializer_from_input(input, output):
model = onnx.load(input)
if model.ir_version < 4:
print(
'Model with ir_version below 4 requires to include initilizer in graph input'
)
return
inputs = model.graph.input
name_to_input = ... |
3255457 | from statify import spotify_client
def test_paginate_spotipy_method(cached_token):
client = spotify_client.Spotify(
'test_client_id',
'test_client_secret',
throttling=0,
)
args_logger = []
def fake_method(*args, **kwargs):
args_logger.append((args, kwargs))
if... |
3255505 | class GraphVertex(object):
'''
commonsense graph vertex object
'''
def __init__(self, subj, obj, parent, level):
raise NotImplementedError()
def add_child(self, c):
raise NotImplementedError()
def add_relation(self, r):
raise NotImplementedError()
def add_score(se... |
3255524 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.multinomial import Multinomial
import numpy as np
from encoders import *
# code based on: https://github.com/zalandoresearch/pytorch-vq-vae/blob/master/vq-vae.ipynb
class SequenceQuantizer(nn.Module):
def __ini... |
3255552 | import requests
import datetime
def get_users():
r = requests.get('http://demo/api/users')
print(r.status_code)
if r.status_code == 200:
return r.json()
return None
def get_today():
return datetime.datetime.today()
|
3255586 | import os
import torch
import numpy as np
import pandas as pd
from PIL import Image
from tqdm import tqdm
from collections import defaultdict
from torchvision.datasets.folder import default_loader
from torchvision.datasets.utils import download_url
from torch.utils.data import Dataset
from torchvision import transforms... |
3255593 | import sys
import unittest
from inspect import signature
# from trex_stl_lib.api import *
from wireless.trex_wireless_rpc_message import *
from wireless.trex_wireless_traffic_handler_rpc import *
from wireless.trex_wireless_traffic_handler import *
class TrafficHandlerCallTest(unittest.TestCase):
"""Tests method... |
3255598 | import sys
import os
import httplib2
import urllib.request as urllib2
import logging
class Downloader(object):
def __init__(self):
self.filepath = None
def get_filepath(self):
return self.filepath
def download(self, url, path, fallback_filename):
logging.debug("Downloading URL {}"... |
3255637 | import unittest
import numpy as np
from intent_classifier import IntentClassifier
class Tests(unittest.TestCase):
def test_creation(self):
IntentClassifier('log_reg')
IntentClassifier('perceptron')
IntentClassifier('use')
def test_fit(self):
logreg_clf = IntentClassifier('lo... |
3255672 | class segTree():
def __init__(self, n):
self.tree = [0] * n
def update(self, index, start, end, left, right, value):
if left > right or right < start or left > end: return
if start == left and end == right:
self.tree[index] = max(self.tree[index], value)
return
... |
3255692 | from ctypes import POINTER, c_char_p, byref
from ...ffi import utils
from ...ffi.ontology.facades import CSoundFeedbackFacade
from ...ffi.utils import hermes_protocol_handler_sound_feedback_facade, hermes_drop_sound_feedback_facade
class SoundFeedBackFFI(object):
def __init__(self, use_json_api=True):
se... |
3255697 | import torch.nn as nn
import copy
# v4.3.2
from transformers.models.bert_generation import BertGenerationEncoder, BertGenerationConfig, BertGenerationDecoder
from transformers import EncoderDecoderModel as HFEncoderDecoderModel
from vilmedic.networks.models.utils import get_n_params
class EncoderDecoderModel(nn.Modu... |
3255702 | import incremental
v = incremental.Version("package", 1, 2, 3, release_candidate=4)
assert(str(v) == "[package, version 1.2.3rc4]")
|
3255709 | import torch
import torch.nn.functional as F
from openmixup.utils import force_fp32, print_log
from ..classifiers import BaseModel
from ..utils import PlotTensor
from .. import builder
from ..registry import MODELS
@MODELS.register_module
class A2MIM(BaseModel):
"""A^2MIM.
Implementation of `Architecture-Ag... |
3255715 | import pytest
from typing import Optional
from utils.itersplit import IterCostSplitter
def new_splitter(batch_max_cost: int) -> IterCostSplitter:
def cost(x: Optional[int]) -> int:
return 0 if x is None else x
return IterCostSplitter(cost_fn=cost, batch_max_cost=batch_max_cost)
def test_error_on_n... |
3255735 | import unittest
from mock import patch
from zoonado.protocol import request, primitives
class RequestTests(unittest.TestCase):
@patch.object(request, "struct")
def test_serialize_without_xid_or_opcode(self, mock_struct):
mock_struct.pack.return_value = b"fake result"
class FakeRequest(reque... |
3255742 | import json
import sys
from grafana_client import GrafanaApi
def main():
# Connect to Grafana instance of Grafana Labs fame.
grafana = GrafanaApi(host='play.grafana.org')
print("## All folders on play.grafana.org", file=sys.stderr)
folders = grafana.folder.get_all_folders()
print(json.dumps(fol... |
3255744 | import torch
import torch.nn as nn
from models.encoder import CodeEncoder, CodeEncoderLSTM
class TypeTransformer(nn.Module):
def __init__(
self,
n_tokens,
n_output_tokens,
d_model=512,
d_out_projection=512,
n_hidden_output=1,
d_rep=128,
n_head=8,
... |
3255762 | from prod import *
AUTHENTICATION_BACKENDS = DEFAULT_SETTINGS.AUTHENTICATION_BACKENDS
WSGI_APPLICATION = 'fum.wsgi.api.application'
ROOT_URLCONF = 'fum.api_urls'
|
3255779 | import arrow
import logging
import json
import argparse
import bson.json_util as bju
from uuid import UUID
import emission.core.get_database as edb
def find_last_get(uuid):
last_get_result_list = list(edb.get_timeseries_db().find({"user_id": uuid,
"metadata.key": "stats/server_api_time",
"data.name... |
3255839 | import qctests.EN_increasing_depth_check
import util.testingProfile
import numpy as np
import util.main as main
#### EN_increasing_depth_check -------------------------------------------
class TestClass:
parameters = {
'db': 'iquod.db',
"table": 'unit'
}
def setUp(self):
# this q... |
3255851 | from tkinter import *
def seleccionar():
monitor.config(text="{}".format(opcion.get()))
def reset():
opcion.set(None)
monitor.config(text="")
# Configuración de la raíz
root = Tk()
opcion = IntVar()
Radiobutton(root, text="Opción 1", variable=opcion, value=1, command=seleccionar).pack()
Radiobutton(root, text="... |
3255856 | import math
from PIL import Image
from logging import debug, info, warning, basicConfig, INFO, DEBUG, WARNING
#Don't forget the max number of items in each array is 32767 items (max signed 16 bit int size).
#This means the max value for length below is 10922!
#Length is the number is pixels stored in each array, so sh... |
3255875 | import unittest
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.utils.data
from torecsys.data.dataloader.collate_fn import CollateFunction
from torecsys.data.dataset import DataFrameToDataset
from torecsys.inputs import MultiIndicesEmbedding
from torecsys.trainer.torecsys_module import Torec... |
3255918 | import subprocess
import os
import sys
import signal
import random
from contextlib import contextmanager
from app import logger, emitter, values, definitions
import base64
import hashlib
import time
from app.synthesis import program_to_formula, collect_symbols, ComponentSymbol, RuntimeSymbol
def generate_formula_from... |
3255959 | import os
from functools import partial
from typing import Dict
from PyQt5.QtWidgets import QApplication, QComboBox
from mpldock import add_dock, named, persist_layout, run
persist_layout('7ec682b5-4408-42a6-ae97-3c11332a96f6')
def save_state_combo(o: QComboBox) -> Dict:
return dict(
current_text=o.cur... |
3255970 | import os
import sys
import unittest
import pytest
import pygrams
@pytest.mark.skipif(('TRAVIS' not in os.environ) or (sys.platform == 'win32'), reason="Only execute with Travis due to speed")
class TestReadme(unittest.TestCase):
"""
Batch of tests to execute same commands as mentioned in the README.md, to ... |
3256020 | from pyCardDeck import *
# noinspection PyPep8Naming
def test_BaseCard():
card = BaseCard("BaseCard")
assert str(card) == "BaseCard"
assert repr(card) == "BaseCard({'name': 'BaseCard'})"
# noinspection PyPep8Naming
def test_PokerCard():
card = PokerCard("Hearts", "J", "Jack")
assert str(card) ==... |
3256043 | import torch
import pytest
import numpy as np
import pytorch_tools as pt
import pytorch_tools.segmentation_models as pt_sm
INP = torch.ones(2, 3, 64, 64)
ENCODERS = ["resnet34", "se_resnet50", "efficientnet_b1", "densenet121"]
SEGM_ARCHS = [pt_sm.Unet, pt_sm.Linknet, pt_sm.DeepLabV3, pt_sm.SegmentationFPN, pt_sm.Segm... |
3256128 | from logging import DEBUG, ERROR, INFO
from pathlib import Path
import logzero
project_root = Path(__file__).parent.parent.resolve()
logzero.logfile(
filename=str(project_root.joinpath("logs/debug.log")),
maxBytes=1024,
backupCount=1,
loglevel=DEBUG,
)
logzero.logger.info(f"Project directory: {proje... |
3256163 | from typing import Dict, List
import onnx
import torch
from onnx import helper
from ppq.core import (PPQ_CONFIG, ChannelwiseTensorQuantizationConfig,
DataType, OperationMeta, QuantizationProperty,
QuantizationStates, TensorMeta, TensorQuantizationConfig,
... |
3256183 | from k3d.headless import k3d_remote, get_headless_driver
import k3d
import vtk
from vtk.util import numpy_support
import numpy as np
import pathlib
path = pathlib.Path(__file__).parent.resolve()
def generate():
plot = k3d.plot(screenshot_scale=1.0)
headless = k3d_remote(plot, get_headless_driver(), width=320... |
3256184 | import subprocess
import sys,os
from shell import Shell
from CommandsList import commands
import getpass
class Configs(object):
def __init__(self):
self.currentPath = os.getcwd()
def setPath(self,path):
self.currentPath = path
def getPath(self):
return self.currentPath
def getUser(self):
return getpass... |
3256201 | from inoft_vocal_framework.bixby_core.templates.templates_access import TemplatesAccess
from inoft_vocal_framework.safe_dict import SafeDict
from inoft_vocal_framework.utils.general import load_json
model_dict = SafeDict(load_json("F:/Inoft/skill_histoire_decryptage_1/inoft_vocal_framework/bixby_core/test_model.json")... |
3256242 | import logging
from enum import IntEnum, auto
from typing import List, Optional
import HABApp
from HABAppTests.errors import TestCaseFailed, TestCaseWarning
log = logging.getLogger('HABApp.Tests')
class TestResultStatus(IntEnum):
NOT_SET = auto()
SKIPPED = auto()
PASSED = auto()
WARNING = auto()
... |
3256311 | import logging
log = logging.getLogger(__name__)
class CompactTask(object):
@classmethod
def run(cls, period, key, revisions, policy):
log.info('Compacting %s: %r - len(revisions): %r, policy: %r', period, key, len(revisions), policy)
# Retrieve options
p_maximum = policy.get('maximu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.