id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4897368 | BETACODE_MAP = {
# No marks
'a': '\u03b1',
'b': '\u03b2',
'g': '\u03b3',
'd': '\u03b4',
'e': '\u03b5',
'z': '\u03b6',
'h': '\u03b7',
'q': '\u03b8',
'i': '\u03b9',
'k': '\u03ba',
'l': '\u03bb',
'm': ... |
4897388 | import gym
from stable_baselines3.common.env_checker import check_env
import malware_rl # Needs to be included in order to make the environment using gym
def test_env(env_name):
print(f"TESTING {env_name}!")
env = gym.make(env_name)
print("Checking environment . . .")
check_env(env)
env.close()... |
4897390 | import unittest
from os import environ, path
from testbook import testbook
# relative path to tutorial to pass configs to hydra in notebook
TUTORIAL_PATH_REL = path.dirname(path.dirname(path.relpath(__file__)))
# to allow bazel to find tutorial file for testing
TUTORIAL_PATH_ABS = path.dirname(path.dirname(path.realp... |
4897412 | import os
import panda3d.core as pc
from direct.directtools.DirectUtil import ROUND_TO
from p3d.functions import (
FloatTuple2Str,
Mat42Str,
Str2Bool,
Str2Mat4,
Str2Point3,
Str2Vec2,
Str2Vec3,
Str2Vec4,
)
def Relpath(target, base=os.curdir):
"""
Return a relative path to the ... |
4897418 | from django.core.cache import cache
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from airmozilla.main.models import Event, SuggestedEvent
from airmozilla.base.utils import send_fanout
class Comment(models.Model):
event = models.ForeignKey(Event)
... |
4897501 | from .base_patterns import Pattern
from .pattern_containers import register_pattern_json
import autograd.numpy as np
import math
from autograd.core import primitive, defvjp, defjvp
def _sym_index(k1, k2):
"""
Get the index of an entry in a folded symmetric array.
Parameters
------------
k1, k2... |
4897510 | from unittest import TestCase
from icon_extractit.actions.sha256_extractor import Sha256Extractor
from icon_extractit.actions.sha256_extractor.schema import Input, Output
class TestSha256Extractor(TestCase):
def test_extract_sha256_from_string(self):
action = Sha256Extractor()
actual = action.run(... |
4897536 | import time
import datetime
from sanic.response import text
from sanic_session.memory import InMemorySessionInterface
from sanic_session.base import SessionDict
import pytest
import uuid
import ujson
SID = "5235262626"
COOKIE_NAME = "cookie"
COOKIES = {COOKIE_NAME: SID}
@pytest.fixture
def mock_dict():
class Ct... |
4897563 | from unittest import TestCase
from data_migration.helper import get_package_version_string
class HelperTestCase(TestCase):
def test_get_package_version_string(self):
self.assertEqual(get_package_version_string(), 'data_migration 0.0.1a')
|
4897581 | import torch.nn as nn
from torchvision.models.mobilenet import InvertedResidual, _make_divisible, ConvBNReLU
class MobileNetV2_Backbone(nn.Module):
def __init__(self,
# num_classes=1000,
width_mult=1.0,
inverted_residual_setting=None,
round_neares... |
4897616 | from os import system, name
from random import choice
import pandas as pd
def clear():
# for windows
if name == 'nt':
system('cls')
# for mac and Linux
else:
system('clear')
options = ['paper', 'rock', 'scissors', 'spock']
all_options = options + ['exit']
p1_result, p2_result = 0, 0
... |
4897627 | from gym.monitoring.monitor import (
_open_monitors,
detect_training_manifests,
load_env_info_from_manifests,
load_results,
Monitor,
)
from gym.monitoring.stats_recorder import StatsRecorder
from gym.monitoring.video_recorder import VideoRecorder
|
4897640 | import json
from sai import Sai
class SaiPhy(Sai):
def __init__(self, exec_params):
super().__init__(exec_params)
# TODO:
|
4897648 | import re
import io
LOWER = False
DIGIT_0 = False
UNK_TOKEN = "#UNK#"
BRACKETS = {"-LCB-": "{", "-LRB-": "(", "-LSB-": "[", "-RCB-": "}", "-RRB-": ")", "-RSB-": "]"}
class Vocabulary:
unk_token = UNK_TOKEN
def __init__(self):
self.word2id = {}
self.id2word = []
self.counts = []
... |
4897657 | import modules
def test_news():
assert ('news' == modules.process_query('news')[0])
assert ('news' == modules.process_query('latest news')[0])
assert ('news' == modules.process_query('world news')[0])
assert ('news' != modules.process_query('something random')[0])
|
4897670 | from os.path import abspath, join
import PyPDF2
from pdf_password_breaker import password_breaker
root = abspath(join('.', 'pdf_password_breaker', 'test_files'))
valid_matches = ('SPECIAL!@#$',
'MIXEDcase',
'SAMPLE_PASSWORD!')
invalid_matches = ('invalid_password',
... |
4897687 | import os
import sys
import json
import logging
import cfnresponse
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('sagemaker')
def handler(event, context):
responseData = {}
try:
logger.info("Received event: {}... |
4897757 | from __future__ import division
from __future__ import absolute_import
import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Flatten, Concatenate
from rl.agents.ddpg import DDPGAgent
from rl.memory import Sequentia... |
4897765 | data = (
'A', # 0x00
'a', # 0x01
'B', # 0x02
'b', # 0x03
'B', # 0x04
'b', # 0x05
'B', # 0x06
'b', # 0x07
'C', # 0x08
'c', # 0x09
'D', # 0x0a
'd', # 0x0b
'D', # 0x0c
'd', # 0x0d
'D', # 0x0e
'd', # 0x0f
'D', # 0x10
'd', # 0x11
'D', # 0x12
'd', # 0x13
'E', # 0... |
4897767 | import core.job
import core.implant
import uuid
class VoiceJob(core.job.Job):
def done(self):
self.display()
def display(self):
self.results = "Completed"
self.shell.print_plain(self.data)
class VoiceImplant(core.implant.Implant):
NAME = "Voice"
DESCRIPTION = "Makes the compu... |
4897769 | import ast
from sherlock.errors import CompileError, SyntaxNotSupportError
from sherlock.codelib.generator.dispatcher import add_generator
@add_generator('Assign')
def generate_assign(self, node, ext_info):
target_code = ''
if isinstance(node.targets[0], ast.Name):
target_code = self.dispatch(node.tar... |
4897774 | import config
from fever_models.nli.bert_fever_nli_v2 import get_nli_pair
from utils import common
if __name__ == '__main__':
debug_mode = False
dev_sent_filtering_prob = 0.2
train_sent_filtering_prob = 0.2
test_sent_filtering_prob = 0.2
top_k_sent = 5
# Data dataset and upstream sentence resu... |
4897782 | import torch.nn as nn
import params as P
import utils
import basemodel.model3
import hebbmodel.top3
class Net(nn.Module):
# Layer names
CONV4 = 'conv4'
BN4 = 'bn4'
CONV_OUTPUT = BN4 # Symbolic name for the last convolutional layer providing extracted features
FC5 = 'fc5'
BN5 = 'bn5'
FC6 = 'fc6'
CLASS_SCORES ... |
4897829 | import pytest
from rororo.utils import ensure_collection, to_bool, to_int
@pytest.mark.parametrize(
"value, expected",
(
("string", ("string",)),
(("string",), ("string",)),
({"string"}, {"string"}),
(["one", "two"], ["one", "two"]),
),
)
def test_ensure_collection(value, ... |
4897839 | import numpy as np
import argparse
import sys
sys.path.append('../')
from util import *
from bell2014 import image_util
from bell2014 import judgements
import skimage
import json
parser = argparse.ArgumentParser(
description="""Run decomposition and evaluation on the test split of
the Intrinsic Images in the Wild ... |
4897845 | import numpy as np
class Action:
"""
Represents an action to be taken in an environment.
Once initialized, fields can be assigned as if the action
is a dictionary. Once filled, the corresponding array is
available as an instance variable.
"""
def __init__(self, structure):
"""
... |
4897874 | from coordinates_named import geohash, Coordinate, display
def test_geohash_max_precision() -> None:
sao_paulo = -23.5505, -46.6339
result = geohash(Coordinate(*sao_paulo))
assert '6gyf4bf0r' == result
def test_display() -> None:
sao_paulo = -23.5505, -46.6339
assert display(sao_paulo) == '23.6°S,... |
4897911 | import lab.torch as B
import numpy.testing
import pytest
import torch
__all__ = ["approx", "context_set", "target_set"]
approx = numpy.testing.assert_allclose
@pytest.fixture()
def context_set():
batch_size = 2
n = 15
x = B.randn(torch.float32, batch_size, n, 1)
y = B.randn(torch.float32, batch_siz... |
4897981 | class Color():
def __init__(self, r=1, g=1, b=1, a=1):
self.values = [r, g, b, a]
@property
def r(self):
return self.values[0]
@r.setter
def r(self, value):
self.values[0] = value
@property
def g(self):
return self.values[1]
@g.setter
def g(self, v... |
4897999 | from .connection import Connection, connect, get_spatialite_version
from .version import __version__
__all__ = (
'connect',
'Connection',
)
version = __version__
spatialite_version = get_spatialite_version()
|
4898023 | from tests import Test, TestStep, TestArgument
from datetime import datetime
import dns.resolver
class DnsTest(Test):
"""
DNS test class.
It measures the time needed for an authoritative name server to give an
answer to a DNS query.
"""
TEST_NAME = "dns"
HOSTNAME_FLAG = "hostname"
... |
4898067 | from django.urls import re_path
try:
from wagtail.admin.decorators import require_admin_access
except ImportError:
from wagtail.admin.auth import require_admin_access
from wagtailautocomplete.views import create, objects, search
urlpatterns = [
re_path(r'^create/', require_admin_access(create)),
re_pa... |
4898092 | import pytest
from os_fast_reservoir import ReservoirSampling
def test_gap_sample():
limit = 10
rs = ReservoirSampling(limit)
num = 41
for i in range(0, num):
rs.sample(i)
count = 0
for i in rs:
count += 1
assert count == limit
assert rs._sample == rs._gap_sample
def ... |
4898114 | import setuptools
from scissors import __version__
from Cython.Distutils import build_ext
import numpy as np
extensions = [
setuptools.Extension("scissors.search", ["scissors/search.pyx"],
include_dirs=[np.get_include()], language='c++'),
]
with open('README.md', 'r') as fh:
long_des... |
4898115 | from setuptools import setup, find_packages
from kovh import __version__
setup(
# Package info
name='kOVHernetes',
version=__version__,
description='Manage Kubernetes clusters on the OVH Cloud platform',
packages=find_packages(),
# Data
package_data={
'kovh': [
'd... |
4898117 | class IContainerControl:
""" Provides the functionality for a control to act as a parent for other controls. """
def ActivateControl(self,active):
"""
ActivateControl(self: IContainerControl,active: Control) -> bool
Activates a specified control.
active: The System.Windows.Forms.Contro... |
4898138 | import unittest
import os
import geosoft.gxpy.system as gsys
import geosoft.gxpy.vox as gxvox
import geosoft.gxpy.vox_display as gxvoxd
import geosoft.gxpy.map as gxmap
import geosoft.gxpy.view as gxview
import geosoft.gxpy.group as gxgroup
import geosoft.gxpy.surface as gxsurf
import geosoft.gxpy.viewer as gxviewer
... |
4898140 | import numpy as np
from joblib.parallel import delayed
from baselines.dawid_and_skene import ds
from bayesian_combination.annotator_models.annotator_model import log_dirichlet_pdf
from bayesian_combination.label_models.label_model import LabelModel, _doc_forward_pass, _doc_backward_pass, \
_doc_most_probable_seque... |
4898157 | from __future__ import absolute_import, division, print_function
from cctbx import translation_search
from cctbx import crystal
from cctbx import miller
from cctbx import xray
from cctbx import maptbx
from cctbx.development import random_structure
from cctbx.development import debug_utils
from cctbx.array_family import... |
4898164 | from graphviz import Digraph
import ply.lex as lex
import ply.yacc as yacc
import copy
import tempfile
import string
class Transition:
def __init__(self, epsilon=False, dot=False, character_class=None,
negation_character_class=None):
if not epsilon and not dot and character_class is None ... |
4898202 | class Auxiliary(object):
def __init__(self):
self.name = None # name of the module
self.versions = [] # supported versions
self.flag = None # CLI flag
def check(self, fingerprint):
""" Given the fingerprint of a remote service, check whether this
modu... |
4898269 | import numpy as np
import madmom
from madmom.processors import Processor
from madmom.ml.hmm import TransitionModel, ObservationModel, HiddenMarkovModel
class ADSRStateSpace(object):
"""
gives the states a meaning
"""
def __init__(self, attack_length=1, decay_length=1, release_length=1):
# de... |
4898272 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.db.models import Q
from . import view_utils as utils
from frontend.models import Chemical, Section, Product, Presentation
@api_view(["GET"])
def bnf_codes(request, format=None):
codes = utils.param_to_list(requ... |
4898313 | import numpy as np
import av
duration = 4
fps = 24
total_frames = duration * fps
container = av.open("test.mp4", mode="w")
stream = container.add_stream("mpeg4", rate=fps)
stream.width = 480
stream.height = 320
stream.pix_fmt = "yuv420p"
for frame_i in range(total_frames):
img = np.empty((480, 320, 3))
i... |
4898336 | import datetime as dt
import logging
import yaml
from tapi_yandex_direct import YandexDirect
logging.basicConfig(level=logging.DEBUG)
with open("../config.yml", "r") as stream:
data_loaded = yaml.safe_load(stream)
ACCESS_TOKEN = data_loaded["token"]
CLIENT_ID = data_loaded["client_id"]
api = YandexDirect(
... |
4898366 | from bs4 import BeautifulSoup
import requests
import time
def get_setup_page( client, host='localhost:80' ):
url = host+"/setup.php"
while( True ):
try:
time.sleep( 1 )
page = client.get( url )
return page
except Exception as e:
continue
return page
def get_form_params( raw_page ):
soup = Beautifu... |
4898376 | import copy
import dataproperty as dp
from ._text_writer import IndentationTextTableWriter
class UnicodeTableWriter(IndentationTextTableWriter):
"""
A table writer class using Unicode characters.
:Example:
:ref:`example-unicode-table-writer`
"""
FORMAT_NAME = "unicode"
@pr... |
4898386 | import copy
import time
import uuid
import optuna
from tqdm import tqdm
from hana_automl.optimizers.base_optimizer import BaseOptimizer
from hana_automl.pipeline.modelres import ModelBoard
from hana_automl.preprocess.settings import PreprocessorSettings
class OptunaOptimizer(BaseOptimizer):
"""Optuna hyperpara... |
4898405 | expected_output = {
"syslog_logging": {
"enabled": {
"counters": {
"messages_dropped": 0,
"messages_rate_limited": 20,
"flushes": 0,
"overruns": 0,
"xml": "disabled",
"filtering": "disabled"
... |
4898434 | import sqlite3
mystore=sqlite3.connect('bookstores.db')
mycursor=mystore.cursor()
total=0
while True:
title=input("enter the title:")
sql="select * from book where title='"+title+"';"
x=mycursor.execute(sql)
if x!=None:
copies=int(input("enter the no. of copies"))
mycur... |
4898470 | import shutil
import datetime
from pbxproj.pbxextensions import *
class XcodeProject(PBXGenericObject, ProjectFiles, ProjectFlags, ProjectGroups, ProjectCapability):
"""
Top level class, handles the project CRUD operations, new, load, save, delete. Also, exposes methods to manipulate
the project's content... |
4898471 | from ..tensors.tensor import *
from ..api import utils
class Op:
def __init__(self, name):
self._name = name
self._inputs = []
self._outputs = []
self._parent = None
def debugString(self):
to_return = 'Op(name: {}, type {}):'.format(self._name, type(self))
for ... |
4898481 | import requests
def get_from_github_with_auth_raw(url, apikeys):
""" """
headers = {}
username = apikeys.get("github-user")
key = apikeys.get("github-key")
return requests.get(url, headers, auth=(username, key))
|
4898491 | import json
import aiohttp
from asynctest import mock
import pytest
from aslack.slack_api import SlackApiError, SlackBotApi
from aslack.slack_bot import SlackBot, MessageHandler
from helpers import AsyncContextManager, AsyncIterable
class Unhandled(MessageHandler):
def description(self):
return 'a dumm... |
4898519 | import torch
import torch.nn as nn
class CrossEntropyLabelSmooth(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equation: q_i = (1 - epsilon) * a_i + epsilon / N.
Args:
nu... |
4898570 | import re
import copy
import pandas as pd
from collections import Counter
from itertools import chain
from sklearn import preprocessing
from sklearn.base import BaseEstimator, TransformerMixin
from melusine.utils.transformer_scheduler import TransformerScheduler
class MetaExtension(BaseEstimator, TransformerMixin):
... |
4898576 | import sys,os
import numpy as np
from keras.callbacks import TensorBoard, ModelCheckpoint
from windpuller import WindPuller
from dataset import DataSet
from datasetLoader import feature as ft
def evaluate_model(model_path, windSize=30):
train_set, test_set = read_feature(".", input_shape, code)
sc... |
4898593 | import typesystem
class AutoDetermine(typesystem.Field):
errors = {
"not_an_object": "Must be an object.",
"not_openapi_or_swagger": "Must include either an 'openapi' property or a 'swagger' property.",
"both_openapi_and_swagger": "May not include both an 'openapi' property and a 'swagger'... |
4898621 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _pytest.nodes import Item
async def pytest_pyppeteer_runtest_makereport_call_debug(item: "Item") -> None:
"""Called to add debug information when each of the call(not
setup/teardown) runtest phases of a test failed item. e.g.
save screenshot.
... |
4898659 | import unicodedata
import sys
tbl = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i).isspace() or unicodedata.category(chr(i)).startswith('P') or unicodedata.category(chr(i)).startswith('S'))
def remove_spaces_punctuation(text):
return text.translate(tbl)
def count_meaty_chars(text):
return len(remov... |
4898666 | class TreeNode:
def __init__(self,value):
self._value = value
self._right_child = None
self._left_child = None
def print_node(self):
if self._left_child != None:
self._left_child.print_node()
print str(self._value),
if self._right_child != No... |
4898674 | from unittest import TestCase
import pytest
from hubblestack.comparators import number as number_comparator
from hubblestack.exceptions import HubbleCheckValidationError
class TestNumberMatch(TestCase):
"""
Unit tests for number::match comparator
"""
def test_match1(self):
"""
Match ... |
4898686 | import random
import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.nn.utils import spectral_norm
from torch.utils.data import Dataset
from torch.distributions import Normal
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torchsupport.modules.basic i... |
4898690 | import numpy as np
import smdebug
import torch
import torch.nn as nn
import torchvision
from smdebug import modes
from torchvision import models
# list of ordered tensor names
activation_outputs = [
#'relu_ReLU_output_0',
"layer1.0.relu_0_output_0",
"layer1.1.relu_0_output_0",
"layer2.0.relu_0_output_0... |
4898692 | from raiden.constants import LOCKSROOT_OF_NO_LOCKS
from raiden.transfer.channel import compute_locksroot
from raiden.transfer.state import PendingLocksState
def test_empty():
locks = PendingLocksState([])
assert compute_locksroot(locks) == LOCKSROOT_OF_NO_LOCKS
|
4898700 | import numpy as np
class Edge(object):
"""The edge between two lin ops.
"""
def __init__(self, start, end, shape):
self.start = start
self.end = end
self.shape = shape
self.data = np.zeros(self.shape)
self.mag = None # Used to get norm bounds.
@property
... |
4898704 | import os
import json
from os.path import join as pjoin
from tqdm import tqdm
import numpy as np
import gym
from graph_dataset import GraphDataset
class APData(gym.Env):
FILENAMES_MAP = {
"full": {
"train": "train.full.json",
"valid": "valid.full.json",
"test": "tes... |
4898717 | from typing import Callable
from timemachines.skatertools.utilities.conventions import Y_TYPE, K_TYPE, A_TYPE, T_TYPE, E_TYPE,\
E_TYPE_OR_LIST, R_TYPE, targets
import numpy as np
import math
###########################################################################
# ... |
4898779 | import compas
from compas.datastructures import Mesh
mesh = Mesh.from_obj(compas.get('faces.obj'))
|
4898783 | import datetime
import faulthandler
import inspect
import unittest
faulthandler.enable() # to debug seg faults and timeouts
import cfdm
def _recurse_on_subclasses(klass):
"""Return all unique subclasses of a classes' subclass hierarchy."""
return set(klass.__subclasses__()).union(
[
sub... |
4898785 | from unittest import TestCase
import numpy as np
import audio_dspy as adsp
_tolerance_ = 0.001
_N_ = 512
class TestNLs(TestCase):
def run_samples(self, func, gain, exp):
high = func(gain)
mid = func(0)
low = func(-gain)
self.assertTrue(np.abs(high - exp[0]) < _tolerance_,
... |
4898868 | from elegantrl_helloworld.run import *
'''custom env'''
class PendulumEnv(gym.Wrapper):
def __init__(self, gym_env_id='Pendulum-v1', target_return=-200):
# Pendulum-v0 gym.__version__ == 0.17.0
# Pendulum-v1 gym.__version__ == 0.21.0
gym.logger.set_level(40) # Block warning
super... |
4898919 | from fuzzconfig import FuzzConfig
from interconnect import fuzz_interconnect
import re
cfg = FuzzConfig(job="PLCROUTE", device="LIFCL-40", sv="../shared/route_40.v", tiles=["R16C22:PLC"])
def main():
cfg.setup()
r = 16
c = 22
nodes = ["R{}C{}_J*".format(r, c)]
extra_sources = []
extra_sources ... |
4898936 | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import mean_squared_log_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import confusion_matrix
from sklea... |
4898973 | from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QPixmap #, QApplication
from PySide import QtGui #, QtCore
import dictionaries.constants as cs
################################################################################
sk = 'Feedback' # session key
class FeedbackWindow(QtGui.QWidget):
... |
4898994 | from teamlab_note import NoteBook
from teamlab_note import Note
quote_book = NoteBook("The Quote Book")
new_note = Note()
new_note.write_content("Don't cry because it's over, smile because it happened. ― Dr. Seuss")
quote_book.add_note(new_note)
print(quote_book.get_number_of_pages())
quote_book.add_note(Note("Hell... |
4899007 | import os
import tempfile
from pathlib import Path
from unittest import TestCase
import pyarrow as pa
import pytest
from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, ReadInstruction
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split,... |
4899017 | from scapy.all import Ether, ARP, srp, send , sniff
import time
import logging
from Modules import intro
from colored import fg, bg, attr
import os
import sys
logging.getLogger('scapy.runtime').setLevel(logging.ERROR)
def main():
print("""
1 - Arp Spoofing
2 - Attack revealed
99 - Back
""")
... |
4899024 | from .exceptions import *
from .config import *
from .logger import *
from .mqtt import *
from .nano_websocket import *
from .redis_db import *
from .validators import * |
4899043 | import types
from kubemen.tools import cached_property, get_diff
class Change(types.SimpleNamespace):
@cached_property
def _operation(self):
return self.review["request"]["operation"]
@cached_property
def operation(self):
if not self.diff and self._operation == "UPDATE":
... |
4899088 | from __future__ import division
from torch.utils.data.dataloader import DataLoader
from common.utils.torch_util import worker_init_fn
from common.utils.sampler import RepeatSampler
from mvpnet.data import transforms as T
def build_dataloader(cfg, mode='train'):
assert mode in ['train', 'val']
batch_size = cfg... |
4899092 | from subprocess import Popen, PIPE
import CodaClient
import os
import asyncio
import logging
DAEMON_HOST = os.environ.get("DAEMON_HOST", "localhost")
DAEMON_PORT = os.environ.get("DAEMON_PORT", "8304")
FAUCET_PUBLIC_KEY = os.environ.get("FAUCET_PUBLIC_KEY", "<KEY>")
FAUCET_FEE = os.environ.get("FAUCET_FEE", "8")
cla... |
4899127 | import os
import json
tag = os.environ.get('TRAVIS_TAG', '')
if tag != '':
with open('version.txt') as f1:
a = f1.read().strip()
if 'v' + a != tag:
version = tag
if version.startswith('v'):
version = version[1:]
print("version.txt version [v]%s doesn't match tag %s ... |
4899136 | import acf_utils
import sys
import numpy
import gc
def canon_file(contents):
canon = []
for k in contents:
d = k.split("\t")
d[1] = d[1].strip()
canon.append(d)
canon = sorted(canon, key=lambda x: x[0])
return canon
class EvaluatorInput:
def __init__(self, truth, predict... |
4899161 | from kivy.lang import Builder
from kivy.properties import StringProperty, ListProperty
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.label import MDLabel
Builder.load_string(
"""
<OthersAnimation>:
md_bg_color: 1, 1, 1, 0
angle_start: 0
angle_end: 0
MDBoxLayout:
id: box... |
4899194 | from .affine import AffineChannel2d
from .normalization import GroupNorm
from .upsample import BilinearInterpolation2d
|
4899282 | import threading
import time
import random
import os
#Diccionarios para el menu y para un nombre de cada cliente.
menu = {'0':'Pollo', '1':'Carne', '2':'Pescado', '3':'Sopa', '4':'Ensalada'}
persona = {'0': 'Luis', '1': 'Jorge', '2':'Daniel', '3':'Diana', '4':'Paola', '5':'Laura', '6': 'Saul', '7':'Sarah', '8': 'Al... |
4899289 | import pytest
from bumpversion.version_part import *
@pytest.fixture(params=[None, (('0', '1', '2'),), (('0', '3'),)])
def confvpc(request):
if request.param is None:
return NumericVersionPartConfiguration()
else:
return ConfiguredVersionPartConfiguration(*request.param)
# VersionPart
def ... |
4899326 | import cv2
import numpy as np
import os
import torch
import torchvision
from CommonPython.Filesystem import Filesystem
from IO import readPFM
def test_file(fn):
if ( not os.path.isfile(fn) ):
raise Exception("File %s not exist. " % (fn))
def load_image(fn, resize=None):
test_file(fn)
img = cv2... |
4899348 | from torch._C import _set_backcompat_broadcast_warn
from torch._C import _get_backcompat_broadcast_warn
from torch._C import _set_backcompat_keepdim_warn
from torch._C import _get_backcompat_keepdim_warn
class Warning(object):
def __init__(self, setter, getter):
self.setter = setter
self.... |
4899377 | import logging
import floto
from floto.decisions import Decision
logger = logging.getLogger(__name__)
class FailWorkflowExecution(Decision):
def __init__(self, details=None, reason=None):
super().__init__()
self.details = details
self.reason = reason
def _get_decision(self):
... |
4899385 | from __future__ import print_function
def coin_change(coins, amount):
#init the dp table
tab = [0 for i in range(amount+1)]
tab[0] = 1 #base case
for j in range(len(coins)):
for i in range(1, amount+1):
if coins[j] <= i:
# if coins[j] < i then add no. of ways -
# - to form the amount by using coins[... |
4899402 | from flask import (
abort, Blueprint, current_app, redirect,
render_template, request, Response, url_for
)
# http://flask-sqlalchemy-session.readthedocs.org/en/v1.1/
from flask_caching import make_template_fragment_key
from flask_sqlalchemy_session import current_session
import ghdiff
from flask_security import... |
4899408 | import test_query
from raco.language import CCAlgebra, GrappaAlgebra
tr = "sp2bench_1m"
queries = {}
queriesI = {} # manually RDF prefix expanded to internal integer
queries['Q1'] = """A(yr) :- %(tr)s(journal, 'rdf:type', 'bench:Journal'),
%(tr)s(journal, 'dc:title', 'Journal 1 (1940)'),
... |
4899480 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import select_classes
from wyrm.processing import swapaxes
class TestSelectClasses(unittest.TestCase):
def setUp(self):
ones = np.ones((10, 5))
channels = ['ca1', 'ca2', 'cb1', '... |
4899482 | import glycowork
from glycowork.motif.graph import *
print('Glycan to Graph')
print('Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc')
print(glycan_to_graph('Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc'))
print("Graph Isomorphism Test")
print(compare_glycans('Man(a1-3)[Man(a1-6)]Man(b1-4)Glc... |
4899488 | from ortools.linear_solver import pywraplp
from ortools.linear_solver import linear_solver_pb2
from ortools.constraint_solver import pywrapcp
from ortools.sat import pywrapsat
from ortools.sat.python import cp_model
from ortools.graph import pywrapgraph
from ortools.algorithms import pywrapknapsack_solver
from ortools.... |
4899501 | import json
import logging
import time
from datetime import datetime
from typing import Any, List, Optional
import click
from click.exceptions import UsageError
from requests import Response
from termcolor import colored
import datahub.cli.cli_utils
from datahub.emitter.mce_builder import dataset_urn_to_key, schema_f... |
4899514 | import logging
import numpy as np
from ginga import AstroImage
from ginga.mockw.ImageViewMock import CanvasView
class TestImageView(object):
def setup_class(self):
self.logger = logging.getLogger("TestImageView")
self.viewer = CanvasView(logger=self.logger)
self.data = np.identity(2000)... |
4899561 | from Bio.Seq import Seq
from operon_analyzer import genes, repeat_finder
import pytest
def test_find_inverted_repeats():
contig_sequence = Seq("TTCCCCCCTTTTTGGGAATATCGGTATGCTTTTTTTTGATCCCAGAGAGCCCTTTACATAGTTTTTTTTGCATACCGATATTCCCTTCCCCCCTTTTT")
operon = genes.Operon('Operon', '', 37, 61, [genes.Feature("prote... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.