id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
408958 | import os
from setuptools import setup
from setuptools import find_packages
import glob
libs = ['../build/libios_runtime.so', '../build/libtrt_runtime.so']
existing_libs = []
for libpath in libs:
if os.path.exists(libpath):
existing_libs.append(libpath)
assert any('libios_runtime.so' in lib for lib in exi... |
409016 | from sklearn.base import BaseEstimator
from sklearn.utils import check_random_state
class SubSampler(BaseEstimator):
def __init__(self, ratio=.3, random_state=None):
self.ratio = ratio
self.random_state = random_state
self.random_state_ = None
def transform_pipe(self, X, y=None):
... |
409024 | import torch
import torchvision
from torch import nn as nn
from utils import util
class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same size as the input.
"""
def __init__(self, gan_mode, targe... |
409080 | import collections
import os
import unicodedata
from typing import List
import numpy as np
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
with open(vocab_file, "r", encoding="utf-8") as reader:
tokens = reader.readlines()
for inde... |
409083 | import numpy as np
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super().__init__()
def initialize(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
... |
409154 | import gzip
import numpy as np
def lazy_file_reader(path):
with gzip.open(path, 'rb') as fin:
for line in fin:
yield [int(i) for i in line.decode().strip().split()]
class lazy_file_iterator():
def __init__(self, path):
self.fin = gzip.open(path, "rb")
self.buf_size = 100
... |
409175 | import FWCore.ParameterSet.Config as cms
# Hodoscope Reconstruction
from RecoTBCalo.EcalTBHodoscopeReconstructor.ecal2004TBHodoscopeReconstructor_cfi import *
# TDC Reconstruction
from RecoTBCalo.EcalTBTDCReconstructor.ecal2004TBTDCReconstructor_cfi import *
# uncalibrated rechit producer
from RecoTBCalo.EcalTBRecProd... |
409181 | import os
import click
import subprocess
import docker
import sys
from anchore.configuration import AnchoreConfiguration
from anchore.version import version as anchore_version
import analyzer
import query
import audit
import system
import logs
import toolbox
import login
import feeds
import policybundle
import anchore... |
409207 | from email.utils import formatdate
import json
from testing.http_util import ChunkedResponse, JsonResponse
from ldclient.interfaces import EventProcessor, FeatureRequester, FeatureStore, UpdateProcessor
def make_items_map(items = []):
ret = {}
for item in items:
ret[item['key']] = item
return ret... |
409229 | from argparse import ArgumentParser
import sys
from toncli.modules.tests.tests import TestsRunner
from toncli.modules.utils.system.argparse_fix import argv_fix
class RunTestsCommand():
def __init__(self, string_kwargs, parser: ArgumentParser):
_, kwargs = argv_fix(sys.argv, string_kwargs)
args = pa... |
409234 | import os
import argparse
from itertools import cycle
import torch
from sklearn.manifold import TSNE
from torch.autograd import Variable
import matplotlib.pyplot as plt
from alternate_data_loader import MNIST_Paired
from torch.utils.data import DataLoader
from utils import transform_config
from networks import Encode... |
409242 | from smol_evm.constants import MAX_UINT256
from smol_evm.context import ExecutionContext
from smol_evm.opcodes import DUP1, DUP2, POP
from smol_evm.stack import Stack, StackOverflow, StackUnderflow, InvalidStackItem
from shared import with_stack_contents
import pytest
@pytest.fixture
def stack() -> Stack:
return... |
409271 | from datetime import datetime, timedelta
from pytz import utc
from timely_beliefs import BeliefsDataFrame, BeliefSource, Sensor, TimedBelief
def sixteen_probabilistic_beliefs() -> BeliefsDataFrame:
"""Nice BeliefsDataFrame to show.
For a single sensor, it contains 4 events, for each of which 2 beliefs by 2 ... |
409295 | import copy
import cupy
import chainer
import chainer.functions as F
from chainer.backends import cuda
from chainer.training.extensions import Evaluator
from chainer.dataset import convert
from chainer import Reporter
from chainer import reporter as reporter_module
from src.functions.evaluation import dice_coefficient,... |
409298 | from unittest.mock import patch
from nose.tools import assert_equal, assert_in
from pyecharts import options as opts
from pyecharts.charts import TreeMap
example_data = [
{"value": 40, "name": "我是A"},
{
"value": 180,
"name": "我是B",
"children": [
{
"value": ... |
409333 | import sys
from .client import LNDClient
from .common import get_macaroon, get_cert
MAJOR = sys.version_info[0]
MINOR = sys.version_info[1]
# only import the async client for python 3.6+
if MAJOR == 3 and MINOR >= 6:
from lndgrpc.aio.async_client import AsyncLNDClient
|
409347 | from .metrics import get_metric_func, prc_auc, bce, rmse, bounded_mse, bounded_mae, \
bounded_rmse, accuracy, f1_metric, mcc_metric, sid_metric, wasserstein_metric
from .loss_functions import get_loss_func, bounded_mse_loss, \
mcc_class_loss, mcc_multiclass_loss, sid_loss, wasserstein_loss
from .cross_validate ... |
409376 | class ThresholdStrategy:
"""
Base class for spot finder threshold strategies.
"""
def __init__(self, **kwargs):
"""
Initialise with key word arguments.
"""
pass
def __call__(self, image):
"""
Threshold the image.
"""
raise RuntimeErro... |
409377 | import os
import load as io
class HicoConstants(io.JsonSerializableClass):
def __init__(
self,
clean_dir=os.path.join(os.getcwd(),'data_symlinks/hico_clean'),
#proc_dir=os.path.join(os.getcwd(),'data_symlinks/hico_processed')):
proc_dir=os.path.join(os.getcwd(),'hi... |
409452 | class Environment:
def __init__(self, width=1000, height=1000):
self.width = width
self.height = height
self.agent = None
self.doors = []
def add_door(self, door):
self.doors.append(door)
def get_env_size(self):
size = (self.height, self.width)
return size
|
409466 | from __future__ import print_function
import digdag
def generate():
with open("result.csv", "w") as f:
f.write("ok")
def check_generated():
with open("result.csv", "r") as f:
data = f.read()
if len(data) < 2:
raise Exception("Output data is too small")
print("ok.")
class Gene... |
409516 | import torch
import torch.nn as nn
import torch.nn.functional as F
class CTLSTMCell(nn.Module):
def __init__(self, hidden_dim, beta=1.0, device=None):
super(CTLSTMCell, self).__init__()
device = device or 'cpu'
self.device = torch.device(device)
self.hidden_dim = hidden_dim
... |
409531 | from autoload import load_config
from tests.clazz.testmodule import TestModule
@load_config()
class CustomModuleB1(TestModule):
pass
|
409556 | import ibmsecurity.utilities.tools
import logging
from ibmsecurity.utilities import tools
logger = logging.getLogger(__name__)
module_uri = "/isam/felb/configuration/services"
requires_modules = None
requires_version = None
requires_model = "Appliance"
def add(isamAppliance, service_name, address, active, port, we... |
409574 | import importlib
from io import BytesIO, StringIO
import logging
import os
from os.path import abspath, basename, dirname, join
from django.conf import settings
from django.core.files.base import File
import pyimagediet as diet
logger = logging.getLogger('image_diet')
THIS_DIR = abspath(dirname(__file__))
DEFAULT_... |
409576 | from isign_base_test import IsignBaseTest
import logging
log = logging.getLogger(__name__)
class TestSubBundles(IsignBaseTest):
def test_matching_provisioning_profiles(self):
""" TODO - Given an app with sub-bundles, test that provisioning profiles are matched to the correct bundles """
# Get an ... |
409612 | import time
from contextlib import contextmanager
from random import random
from typing import Generator, Optional
import redis
class UnableToGetLock(Exception):
pass
class Redis(object):
UnableToGetLock = UnableToGetLock
def __init__(self, app=None):
self.redis = None
if app:
... |
409664 | from cleo.helpers import option
from poetry.core.masonry.builder import Builder
from poetry.core.version.helpers import format_python_constraint
from .env_command import EnvCommand
from ...managed_project import ManagedProject
class BuildCommand(EnvCommand):
name = "build"
description = "Builds a package, as... |
409684 | from pyffs.automaton_generation.utils import generate_all_bit_vectors_under_n
def test_generate_all_bit_vectors_under_0():
generated = generate_all_bit_vectors_under_n(0)
expected = [()]
assert expected == generated
def test_generate_all_bit_vectors_under_1():
generated = generate_all_bit_vectors_un... |
409701 | import collections
import enum
import filecmp
import itertools
import shutil
import sys
import click
from .. import configs
from .common import (
check_installation, get_active_names, get_version,
set_active_versions, version_command,
)
class Overwrite(enum.Enum):
yes = 'yes'
no = 'no'
smart = ... |
409734 | import _init_paths
from vrd.test import test_net
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list
from datasets.factory import get_imdb
import caffe
import argparse
import pprint
import time, os, sys
import numpy as np
import h5py
import cv2
from fast_rcnn.config import cfg, get_output_dir
from fast_rcnn... |
409739 | import re
sampletext="""
interface fa0/1
switchport mode trunk
no shut
interface fa0/0
no shut
interface fa1/0
switchport mode trunk
no shut
interface fa2/0
shut
interface fa2/1
switchport mode trunk
no shut
interface te3/1
switchport mode trunk
shut
"""
sampletext=sampletext.split("interface")
#check for interfa... |
409765 | from .method_selector import *
from .o3d_aliases import *
from .run_icp import *
from .scan2mesh import *
from .scan2mesh_icp import *
|
409775 | import datetime
import time, json
from pathlib import Path
from bson import json_util,ObjectId
import jimi
# audit Class
class _audit(jimi.db._document):
_dbCollection = jimi.db.db["audit"]
def add(self, eventSource, eventType, data):
auditData = { "time" : time.time(), "systemID" : systemSettings["s... |
409800 | import pytest
from django.contrib.auth.models import User
from faker import Faker
from news.models import News
@pytest.fixture
def user_factory():
fake = Faker(locale=['en'])
name = fake.unique.name()
user = User.objects.create_user(username=name,
email=f'{name.replace(... |
409870 | from plaza_routing.integration.routing_engine_service import RoutingEngine
from plaza_routing.integration.routing_strategy.graphhopper_strategy import GraphHopperRoutingStrategy
def get_walking_route(start: tuple, destination: tuple) -> dict:
""" returns the walking route for a start and destination based on a ro... |
409906 | import os
import sys
sys.path.append('../../common')
from env_indigo import *
import collections
indigo = Indigo()
indigo.setOption("ignore-noncritical-query-features", "true")
print("***** Aromaticity models *****")
def executeOperation (m, func, msg):
try:
func(m)
print(msg + m.smiles())
... |
409912 | import contextlib
@contextlib.contextmanager
def temp_setattr(ob, attr, new_value):
"""Temporarily set an attribute on an object for the duration of the
context manager."""
replaced = False
old_value = None
if hasattr(ob, attr):
try:
if attr in ob.__dict__:
repla... |
409938 | import io
from pyasn1.codec.ber import decoder
from pyasn1.type import univ, namedtype
class HashedType(univ.Sequence):
componentType = namedtype.NamedTypes(namedtype.NamedType('oid', univ.ObjectIdentifier()),
namedtype.NamedType('null', univ.Null())
... |
410006 | from .service import TenantService
from .midleware import tenant_middleware_factory, tenant_handler
__all__ = (
'TenantService',
'tenant_middleware_factory',
'tenant_handler',
)
|
410034 | import pytest
from wootrade import Client
from wootrade import ThreadedWebsocketManager
import os
API = os.getenv("API")
SECRET = os.getenv("SECRET")
APPLICATION_ID = os.getenv("APPLICATION_ID")
def test_create_TWM():
wsm = ThreadedWebsocketManager(API, SECRET, APPLICATION_ID, False)
|
410084 | import os
import mock
import pytest
import bridgy.inventory
from bridgy.inventory import InventorySet, Instance
from bridgy.inventory.aws import AwsInventory
from bridgy.config import Config
def get_aws_inventory(name):
test_dir = os.path.dirname(os.path.abspath(__file__))
cache_dir = os.path.join(test_dir, '... |
410100 | import functools
import operator
import os
import os.path
import sys
import numpy as np
import scipy.special
import pytest
# Bamboo utilities
current_file = os.path.realpath(__file__)
current_dir = os.path.dirname(current_file)
sys.path.insert(0, os.path.join(os.path.dirname(current_dir), 'common_python'))
import tool... |
410156 | AppLayout(header=header_button,
left_sidebar=None,
center=center_button,
right_sidebar=None,
footer=footer_button)
|
410159 | from functools import partial
from unittest import TestCase
import os
import os.path as osp
import numpy as np
from datumaro.components.annotation import (
AnnotationType, Bbox, Caption, Cuboid3d, Label, LabelCategories, Mask,
MaskCategories, Points, PointsCategories, Polygon, PolyLine,
)
from datumaro.compon... |
410165 | import numpy as np
from EOSMixture import EOSMixture
from MixtureRules.ClassicMixtureRule import ClassicMixtureRule, ClassicBMixture
from MixtureRules.MixtureRulesInterface import (
BiBehavior,
ThetaiBehavior,
DeltaMixtureRuleBehavior,
EpsilonMixtureRuleBehavior,
MixtureRuleBehavior,
)
from constan... |
410170 | from django.views.generic import TemplateView, RedirectView
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.http import Http404
from django.shortcuts import render
admin.autodiscover()
def justatemplate(path):
def view(request):
context = {
"sh... |
410183 | import errno
import os
from alembic.command import downgrade
from alembic.command import upgrade
from alembic.config import Config
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session
from sqla... |
410190 | import factory
from ipaddr import IPv4Network
from pycroft.model.net import VLAN, Subnet
from tests.factories.base import BaseFactory
class VLANFactory(BaseFactory):
class Meta:
model = VLAN
name = factory.Sequence(lambda n: f"vlan{n+1}")
vid = factory.Sequence(lambda n: n+1)
class Params:
... |
410213 | import sys
import os
import argparse
#Set up parser and top level args
parser = argparse.ArgumentParser(description='ASCENT: Automated Simulations to Characterize Electrical Nerve Thresholds')
# parser.add_argument('-s','--silent',action='store_true', help = 'silence printing')
parser.add_argument('-v','--verbose',act... |
410215 | class Result:
def __init__(self, result: bool, error = None, item = None, list = [], comment = None):
self.result = result
self.error = error
self.item = item
self.list = list
self.comment = comment
|
410219 | from django.views.generic.edit import FormMixin
from braces.views import AjaxResponseMixin, JSONResponseMixin
from django.db.models.query_utils import Q
from django.views.generic import ListView, DetailView, View
from realestate.listing.forms import ListingContactForm
from realestate.listing.models import Listing, Agen... |
410224 | import torch
import torch.nn as nn
def get_normalization(m_config, conditional=True):
norm = m_config.normalization
if conditional:
if norm == 'NoneNorm':
return ConditionalNoneNorm2d
elif norm == 'InstanceNorm++':
return ConditionalInstanceNorm2dPlus
elif norm ... |
410246 | import sublime
import os
class DlvConst(object):
def __init__(self, window):
self.__window = window
self.__settings_file_name = "GoDebug.sublime-settings"
self.__bkpt_settings_file_name = "GoDebug.breakpoint-settings"
self.__watch_settings_file_name = "GoDebug.watch-settings"
... |
410252 | from unittest import TestCase
import phi
class TestCIInstallation(TestCase):
def test_detect_tf_torch_jax(self):
backends = phi.detect_backends()
names = [b.name for b in backends]
self.assertIn('PyTorch', names)
self.assertIn('Jax', names)
self.assertIn('TensorFlow', nam... |
410270 | import json
from .wkutils import WebkitObject, Command
def evaluate(expression, objectGroup=None, returnByValue=None):
params = {}
params['expression'] = expression
if(objectGroup):
params['objectGroup'] = objectGroup
if(returnByValue):
params['returnByValue'] = returnByValue
c... |
410302 | from pathlib import Path
import aiosqlite
import pytest
from proj.server import try_make_db
@pytest.fixture
def db_path(tmp_path: Path) -> Path:
path = tmp_path / "test_sqlite.db"
try_make_db(path)
return path
@pytest.fixture
async def db(db_path: Path) -> aiosqlite.Connection:
conn = await aiosql... |
410348 | from __future__ import absolute_import, print_function, division
import unittest
import numpy
import theano
from theano.tests import unittest_tools as utt
# Skip tests if cuda_ndarray is not available.
from nose.plugins.skip import SkipTest
import theano.sandbox.cuda as cuda_ndarray
from theano.misc.pycuda_init impor... |
410351 | import sys
import os
import time
import threading
import torch
from torch.autograd import Variable
import torch.utils.data
from lr_scheduler import *
import cv2
import numpy
from AverageMeter import *
from loss_function import *
import datasets
import balancedsampler
import networks
from my_args import args
import ... |
410352 | import bisect as bs
#import time #test
# list need to be sorted first!
if __name__ == '__main__':
s = raw_input("What do yo wan to search? ")
#s = "hey"
#st = time.time()
l = []
with open('words.txt', 'r') as fin:
for line in fin:
word = line.strip()
l.append(word)
print bs.bisect(l, s) #count start from... |
410389 | import json
import uuid
import dataclasses
import urllib.request
from typing import Union
from .base import DependencyDB
from ..base import Dependency, DependencyExtra, URL, License
@dataclasses.dataclass
class PyPiDependency(DependencyExtra):
name: str
url: URL
license: License
class PyPiDB(Dependency... |
410394 | import FWCore.ParameterSet.Config as cms
CSCFakeGainsConditions = cms.ESSource("CSCFakeGainsConditions")
CSCFakePedestalsConditions = cms.ESSource("CSCFakePedestalsConditions")
CSCFakeNoiseMatrixConditions = cms.ESSource("CSCFakeNoiseMatrixConditions")
CSCFakeCrosstalkConditions = cms.ESSource("CSCFakeCrosstalkCond... |
410428 | import logging
class ActivityLog:
__instance = None
def __init__(
self,
log_name="activitiy",
log_path="activitiy.log",
log_format="%(asctime)s [%(levelname)s]: %(message)s",
log_level=logging.INFO,
):
if ActivityLog.__instance != None:
raise Ex... |
410472 | import unittest
from flask import Flask, request, Response
from werkzeug.exceptions import NotFound
from flask_jsontools import jsonapi, FlaskJsonClient, JsonResponse, make_json_response
class TestJsonApi(unittest.TestCase):
def setUp(self):
# Database
users = [
{'id': 1, 'name': 'a'}... |
410500 | import unittest, time, sys, random, math, getpass
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i, h2o_util, h2o_print as h2p
def write_syn_dataset(csvPathname, rowCount, colCount, SEED, choices):
r1 = random.Random(SEED)
dsf = open(csvPathname, "w+")
naCnt = [0 for j in ra... |
410507 | from netforce import migration
from netforce.model import get_model
from netforce.database import get_connection
class Migration(migration.Migration):
_name="account.multico"
_version="1.111.0"
def migrate(self):
db=get_connection()
print("accounts...")
db.execute("update account_a... |
410535 | def lonely_integer(m):
answer = 0
for x in m:
answer = answer ^ x
return answer
a = int(input())
b = map(int, input().strip().split(" "))
print(lonely_integer(b))
|
410567 | from __future__ import print_function
from memory_profiler import profile
import sys
from beem.steem import Steem
from beem.account import Account
from beem.blockchain import Blockchain
from beem.instance import set_shared_steem_instance, clear_cache
from beem.storage import configStorage as config
from beemapi.graphen... |
410584 | class LogHolder():
def __init__(self, dirpath, name):
self.dirpath = dirpath
self.name = name
self.reset(suffix='train')
def write_to_file(self):
with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file:
for i in self.metric_holder:
file.write(str(i) + ' ')
with open(self.di... |
410634 | from .usage import *
ConsumerControl = Usage("consumer.ConsumerControl", 0xc0001, CA)
NumericKeyPad = Usage("consumer.NumericKeyPad", 0xc0002, NAry)
ProgrammableButtons = Usage("consumer.ProgrammableButtons", 0xc0003, NAry)
Microphone = Usage("consumer.Microphone", 0xc0004, CA)
Headphone = Usage("consumer.Headphone", ... |
410636 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import tensorflow as tf
import keras
from keras.models import Model
from keras.layers import Dense, Input, Dropout
from keras.callbacks import ModelCheckpoint
from keras import backend... |
410645 | import os, sys, subprocess
#apt-get install gnuplot transfig
passed = {}
has_osv = os.path.isdir(os.path.expanduser('~/osv'))
def runbench_cython(path, name):
data = open(os.path.join(path, name), 'rb').read()
open('/tmp/cython_module.pyx', 'wb').write(data)
subprocess.check_call([
'cython',
'/tmp/cython_mo... |
410660 | from flexx.util.testing import run_tests_if_main, raises, skip
import re
from flexx.util.logging import logger, capture_log, set_log_level
def test_debug():
logger.debug('test')
def test_info():
logger.info('test')
def test_warning():
logger.warning('test')
def test_set_log_level():
with ra... |
410675 | from .resource_enum import ResourceEnum
class ConditionEnum(ResourceEnum):
E = "Excellent"
G = "Good"
F = "Fair"
P = "Poor"
|
410731 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.sea_slugs import sea_slugs
def test_sea_slugs():
"""Test module sea_slugs.py by downloading
sea_slugs.csv and testing shape of
extracted d... |
410739 | from typing import List
import json
import re
from instagram_api import response
from instagram_api.exceptions import InternalException, SettingsException
from .base import CollectionBase
__all__ = ['Account']
class Account(CollectionBase):
def get_current_user(self) -> response.UserInfoResponse:
ret... |
410771 | import numpy as np
import scipy.linalg
import theano
from theano.tensor import as_tensor_variable
import theano.tests.unittest_tools
from theano.gof import Op, Apply
class MatrixSquareRoot(Op):
def make_node(self, x):
x = as_tensor_variable(x)
assert x.ndim == 2
return Apply(self, [x], [x.... |
410779 | import math
import random
import time
#from multiprocessing.dummy import Pool
from multiprocessing import Pool
def y_is_in_circle(x, y):
"""Test if x,y coordinate lives within the radius of the unit circle"""
return x * x + y * y <= 1.0
def estimate_nbr_points_in_circle(nbr_samples):
nbr_in_circle = 0
... |
410809 | import torch
import torch.nn.functional
from torch.nn.utils.rnn import PackedSequence
import padertorch as pt
__all__ = [
'softmax_cross_entropy',
]
IGNORE_INDEX = -1
def softmax_cross_entropy(x, t):
"""Allow inputs to be of type `PackedSequence`.
In my understanding, all dimensions but the last shou... |
410815 | import asyncio
from typing import Generic, Iterable, Tuple, TypeVar
from agraffe.types import ASGIApp, Message, Scope
Req = TypeVar('Req')
Res = TypeVar('Res')
class HttpCycleBase(Generic[Req, Res]):
def __init__(self, request: Req):
self.request = request
self.status_code = 200
self.hea... |
410817 | import base64
import re
import urllib
import zlib
from urllib.request import Request
import defusedxml.ElementTree as ET
from retrying import retry
from src.util.logging import log
'''
Original from: https://github.com/aggixx/PoBPreviewBot/blob/master/util.py
&& https://github.com/aggixx/PoBPreviewBot/b... |
410821 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import pandas as pd
import torch
import kvt
def compute_metrics(predicts, labels):
N, H, W = predicts.shape
predicts = predicts.reshape((-1, H*W))
labels = labels.... |
410835 | class InvalidRating(ValueError): pass
class AuthRequired(TypeError): pass
class CannotChangeVote(Exception): pass
class CannotDeleteVote(Exception): pass
class IPLimitReached(Exception): pass |
410898 | class TransmissionData(object,IDisposable):
"""
A class representing information on all external file references
in a document.
TransmissionData(other: TransmissionData)
"""
def Dispose(self):
""" Dispose(self: TransmissionData) """
pass
@staticmethod
def DocumentIsNotTransmitted(fileP... |
410914 | import sys
from oic.oauth2 import PBase
from oic.utils.webfinger import OIC_ISSUER
from oic.utils.webfinger import WebFinger
__author__ = 'roland'
wf = WebFinger(OIC_ISSUER)
wf.httpd = PBase()
print (wf.discovery_query(sys.argv[1]))
|
410974 | from flask import Blueprint
from .load import load
blueprint = Blueprint('students', __name__, cli_group=None) # type:ignore
blueprint.cli.command('load')(load) # type: ignore
|
411006 | import numpy as np
from smartsim import Client
def create_data(seed, size):
np.random.seed(seed)
x = np.random.uniform(-15.0, 15.0, size=size)
return x
if __name__ == "__main__":
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument("--cluster", default=False, acti... |
411049 | from threadedsubscriber import ThreadedSubscriber
import redis
import socket
class Reporter:
def __init__(self, host, port):
self.host = host
self.port = port
self.name = socket.getfqdn()
self.client = redis.StrictRedis(host=self.host, port=self.port, db=0)
self.channels = ["sen... |
411052 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
l1demonstage1 = DQMEDAnalyzer('L1TDEMON',
HistFolder = cms.untracked.string('L1TEMU'),
HistFile = cms.untracked.string('l1demon.root'),
disableROOToutput = cms.untracked.bool(True),
DataEmulCompareSource =... |
411087 | import os.path as op
from skbold.core import MvpBetween
from skbold import testdata_path, roidata_path
import os
import pytest
import numpy as np
cmd = 'cp -r %s/run1.feat %s/mock_subjects/sub00%i'
_ = [os.system(cmd % (testdata_path, testdata_path, i+1)) for i in range(9)
if not op.isdir(op.join(testdata_path, ... |
411096 | import open3d as o3d
import torch
import h5py
import numpy as np
import torch.utils.data as data
import torchvision.transforms as transforms
import os
import random
#from utils import *
def read_points(filename, dataset):
if dataset == 'suncg' or dataset == 'fusion':
pcd = o3d.read_point_cloud(filename)
... |
411184 | from utils import tprint, plt
import numpy as np
from scipy.stats import rankdata
import sys
from gaussian_process import SparseGPRegressor
from hybrid import HybridMLPEnsembleGP
from process_davis2011kinase import process, visualize_heatmap
from train_davis2011kinase import train
def acquisition_rank(y_pred, var_pr... |
411187 | from pybricks.media.ev3dev import Font, Image, ImageFile
from pybricks.parameters import Color
from typing import Union
class Screen:
"""
A stub class to represent the screen member of the EV3Brick class.
Attributes:
height (int): The height of the screen in pixels.
width (int): The width... |
411203 | from orion.evaluation.common import _accuracy, _f1_score, _precision, _recall, _weighted_segment
def _point_partition(expected, observed, start=None, end=None):
expected = set(expected)
observed = set(observed)
edge_start = min(expected.union(observed))
if start is not None:
edge_start = star... |
411204 | from django.test import TestCase
from robber import expect
from data.factories import AllegationFactory, OfficerFactory, OfficerAllegationFactory
from social_graph.queries.geographic_data_query import GeographyCrsDataQuery, GeographyTrrsDataQuery
from trr.factories import TRRFactory
class GeographyCrsDataQueryTestC... |
411216 | import archon.feeds.cryptocompare as cryptocompare
e = "Kucoin"
h = cryptocompare.get_hist("LTC","BTC",e)
|
411242 | from unittest import TestCase
from unittest.mock import patch, ANY
import responses
import azkaban_cli.azkaban
from azkaban_cli.exceptions import FetchScheduleError, SessionError
class AzkabanFetchScheduleTest(TestCase):
def setUp(self):
"""
Creates an Azkaban instance and set a logged session f... |
411268 | class Page(object):
def __init__(self, url: str, path: str, links: list, pars: list, title: str, typo: str):
self.url = url
self.path = path
self.links = links
self.pars = pars
self.title = title
self.typo= typo
def set_url(self,url):
self.url = url
d... |
411322 | from tensorflow import keras as tf
import cv2
import numpy as np
from collections import Counter
from sklearn.preprocessing import LabelEncoder
import os
class Dataset:
def __init__(self, arch, path_of_dataset=None):
self.n_classes = 0
self.bad_data = []
self.X = []
self.Y = []
... |
411331 | import re
import json
import time
# This code was inspired by Jay2K1's Hangouts parser. You can see the
# blogpost for the original at:
# http://blog.jay2k1.com/2014/11/10/how-to-export-and-backup-your-google-hangouts-chat-history/
# He also runs a webservice for parsing Google Hangouts JSON files at:
# http://hango... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.