id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
122410 | import os
# from sklearn.metrics import log_loss, roc_auc_score
import time
from librerank.utils import *
from librerank.reranker import *
from librerank.rl_reranker import *
def eval(model, data, l2_reg, batch_size, isrank, metric_scope, _print=False):
preds = []
# labels = []
losses = []
data_size... |
122424 | import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*testing.product_dict(
[
{'shape': (), 'pad_width': 1, 'mode': 'constant'},
{'shape': (2, 3), 'pad_width': 0, 'mode': 'constant'},
{'shape': (2, 3), 'pad_width': 1, 'mode': 'constant'},
{'... |
122437 | import pytest
import pandas as pd
from iguanas.rule_selection._base_filter import _BaseFilter
from iguanas.rules import Rules
@pytest.fixture
def _create_data():
X_rules = pd.DataFrame({
'A': [1, 0, 1],
'B': [1, 1, 1]
})
return X_rules
def test_transform(_create_data):
X_rules = _cre... |
122446 | import param
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# from gym_film.utils.convert_reward import to_single_reward
# from matplotlib.patches import Patch
# Uses the following methods/attributes from env:
# - O, R (observation and reward)
# - jets_power
# - system_state
# - reward, ... |
122478 | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base
from config import create_new_sqla
from helpers import (get_video_douban_ids,
get_celebrity_douban_ids,
get_animation_bilibili_ids)
test_database_url = 'sqlite://... |
122485 | import logging
import random
from flask import request
from flask_restplus import Resource, Namespace, fields
from ..managers import copy_job_manager
from .. import tasks
from ..exceptions import HTTP_EXCEPTION
api = Namespace('copy-jobs', description='CopyJob related operations')
dto = api.model('copy-job', {
... |
122487 | import sys
src = sys.argv[1]
trg = sys.argv[2]
with open(src, "rb") as f:
contents = f.read()
with open(trg, "wb") as f:
f.write(contents)
|
122604 | from django.db import models
from datetime import datetime
class TestModel(models.Model):
date = models.DateField(default=datetime.today())
|
122611 | import numpy as np
import pandas as pd
import streamlit as st
import altair as alt
from matplotlib import pyplot as plt
import config, dataset, main, utils
# Matplotlib params
plt.style.use("seaborn")
plt.rcParams["figure.dpi"] = 300
def get_altair_hist_plot(series, name, bin_min, bin_max, bin_step):
"""
P... |
122641 | from __future__ import print_function
import networkx as nx
from semnav.lib.categories import room2category, behavior_id2category
from semnav.lib.sem_graph import Node, Edge
class SubGraph(object):
"""Sub-graph of SemGraph used for graph networks.
"""
def __init__(self, sem_graph, cur_position, n_neigh... |
122741 | import os
import re
import bpy
import logging
import json
from . import bpy_helper
from . import ifc_helper
from . import io
from . import exporter
def create(project, ifc_type=None, group_name='', prefix='', **kwargs):
i = 0
if ifc_type:
for elem in ifc_helper.elements_by_type(project, ifc_type):
... |
122761 | import re
from datetime import datetime
from pathlib import Path
from subprocess import Popen, check_output
from tempfile import TemporaryDirectory
from django.core.files.base import ContentFile
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django_rq import job
from tqd... |
122771 | import tensorflow as tf
tf.enable_eager_execution()
import numpy as np
import pandas as pd
import os
# import argparse
def read_tf(tfrecord_path):
"""
read in the tensors
:param tfrecord_path: the path to the tensor
:return: the image and the label
"""
raw_image_dataset = tf.data.TFRecordDatas... |
122784 | import threading
from functools import wraps
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
_kwd_mark = object()
_data_lock = threading.Lock()
def cache(f):
"""
Decorator that caches the function's return value, so cached RDDs,
DataFrames, and other objects can be shared... |
122786 | import datetime
print(1,datetime.datetime.now())
import apscheduler
print(2,datetime.datetime.now())
import gevent
print(3,datetime.datetime.now())
import eventlet
print(4,datetime.datetime.now())
import asyncio
print(5,datetime.datetime.now())
import threading
print(6,datetime.datetime.now())
import pymongo
pri... |
122794 | import numpy as np
from pyriemann.estimation import Covariances
from pyriemann.spatialfilters import CSP
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from moabb.pipelines.ut... |
122825 | import torch
from torch import nn
from torch.nn import functional as F
from typing import Dict, Optional
from utils.misc_utils import combine_first_ax
from slowfast.models.video_model_builder import SlowFast, ResNet
from fairseq.models.transformer import (
TransformerEncoder,
TransformerDecoder,
# EncoderO... |
122847 | from bltk.langtools.taggertools import adjective_suffix, noun_suffix, verb_suffix, pronouns
from bltk.langtools.pos_tagger import PosTagger
class UgraStemmer:
def __init__(self):
self.pos_tagger = PosTagger()
self.pronoun_values = list(pronouns.values())
self.pronoun_keys = list(pronouns.k... |
122851 | import FWCore.ParameterSet.Config as cms
# Trigger Primitive Producer
from SimCalorimetry.EcalTrigPrimProducers.ecalTriggerPrimitiveDigis_readDBOffline_cfi import *
|
122873 | from games.abstract_game import AbstractGame
import subprocess
from constants import *
import json
import platform
class Mario(AbstractGame):
"""
Represents a single Mario game.
"""
def __init__(self, model, game_batch_size, seed, level=None, vis_on=False, use_visualization_tool=False, test=False):
... |
122885 | from moto.core.exceptions import RESTError
class InvalidParameterValueError(RESTError):
def __init__(self, message):
super(InvalidParameterValueError, self).__init__(
"InvalidParameterValue", message
)
class ResourceNotFoundException(RESTError):
def __init__(self, message):
... |
122933 | def dfs(at, graph, visited):
if visited[at]:
return
visited[at] = True
print(at, end=" -> ")
neighbours = graph[at]
for next in neighbours:
dfs(next, graph, visited)
if __name__ == "__main__":
n = int(input("No. of Nodes : "))
graph = []
for i in range(n):
graph... |
122947 | from ltypes import i32
def test_list_i32():
a: list[i32] = [1]
a.append(2)
a.append(3)
a.append(4)
a.append(5)
print(a[1])
assert a[1] == 2 or a[1] == 3
test_list_i32()
|
122961 | import os
from pathlib import Path
import time
class Source_file_generator:
"""
Library to easily generate proximal functions
"""
number_of_spaces_in_tab=4
def __init__(self,location,function_type):
"""
Parameters
---------
location : target location
functio... |
122965 | from conftest import rvo_output, rvo_err
from click.testing import CliRunner
from rvo import cli
def test_delete_yes():
options = ['delete', '569e5eed6815b47ce7bdb583', '--yes']
output = ["Removed"]
rvo_output(options,output)
def test_delete_input_yes():
runner = CliRunner()
result = runner.invoke... |
122982 | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
# For reproducibility
np.random.seed(1000)
if __name__ == '__main__':
# Load MNIST digits
digits = load_digits()
# Show some random dig... |
123088 | from hivemind.client.expert import RemoteExpert
from hivemind.client.moe import RemoteMixtureOfExperts
from hivemind.client.switch_moe import RemoteSwitchMixtureOfExperts
from hivemind.client.averaging import DecentralizedAverager
from hivemind.client.averaging.training import TrainingAverager
|
123131 | import c4d
from c4d import documents
from . import Utilities as util
from .CustomIterators import ObjectIterator
from .Utilities import dazToC4Dutils
from .IkMax import applyDazIK, ikmaxUtils
from .AllSceneToZero import AllSceneToZero
dazName = "Object_"
class DazToC4D:
def figureFixBrute(self):
"""Har... |
123132 | import json
from enum import Enum
from test.util import TestCase
from OpenCast.app.command.video import CreateVideo
from OpenCast.app.tool.json_encoder import (
EnhancedJSONEncoder,
EventEncoder,
ModelEncoder,
)
from OpenCast.domain.event.video import VideoCreated
from OpenCast.domain.model.player import P... |
123134 | import subprocess, re, sys,os, os.path, shutil, time, glob
ROOT="/home/blackie/dump/KDABViewer"
BUILDROOT=ROOT+"/build"
ITERATIONS=5
FOREAL=1
CCACHE="/usr/lib/ccache"
def runCommand(cmd):
print(" ".join(cmd))
if FOREAL:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
... |
123147 | import os, math
import errno
import stat
from py.builtin import sorted
from pypy.tool import udir
from pypy.rpython.test.test_rbuiltin import BaseTestRbuiltin
from pypy.rpython.module.test.test_ll_time import BaseTestTime as llBaseTestTime
class BaseTestBuiltin(BaseTestRbuiltin):
def test_os_flags(self):
... |
123205 | import numpy
import json
import os
import sys
import time
import sh_common
if len(sys.argv) != 2:
print("import_vgg7.py JSONPATH")
print(" i.e. import_vgg7.py /home/you/Documents/External/waifu2x/models/vgg_7/art/scale2.0x_model.json")
sys.exit(1)
try:
os.mkdir("model-kipper")
except:
pass
data_l... |
123241 | import time
from oeqa.oetest import oeRuntimeTest
from oeqa.utils.helper import shell_cmd_timeout
class RebootTest(oeRuntimeTest):
'''Reboot target device
@class RebootTest
'''
def setUp(self):
'''pre condition check
@fn setUp
@param self
@return
'''
self... |
123263 | import pytest
from django.contrib.auth import get_user_model
from django.core.management import call_command
from parkings.models import ParkingArea, PaymentZone, PermitArea
from ..management.commands import (
import_parking_areas, import_payment_zones, import_permit_areas)
from .request_mocking import mocked_req... |
123267 | import json
import pytest
import requests
from mjolnir.kafka.msearch_daemon import Daemon, FlexibleInterval, MetricMonitor, StreamingEMA
def test_consume_nothing(mocker):
mocker.patch('kafka.KafkaProducer')
# Test it doesn't blow up
Daemon(None).consume([])
def test_consume_end_sigil(mocker, monkeypat... |
123303 | import carla
import os
import sys
import cv2
import json
import numpy as np
CARLA_ROOT = os.getenv("CARLA_ROOT")
if CARLA_ROOT is None:
raise ValueError("CARLA_ROOT must be defined.")
scriptdir = CARLA_ROOT + "PythonAPI/"
sys.path.append(scriptdir)
from examples.synchronous_mode import CarlaSyncMode
scriptdir = ... |
123331 | from decimal import Decimal
from unittest import TestCase
import copy
import unittest
import os
import sys
from importlib import reload
from mock import Mock, call
from mockextras import stub
sys.path = [os.path.abspath(os.path.join('..', os.pardir))] + sys.path
from digesters.charges.charge_card_digester import Char... |
123357 | from bokeh.models import ActionTool
class ParallelResetTool(ActionTool):
""" Tool to reset only plot axes and not selections
"""
__implementation__ = 'parallel_reset.ts'
|
123372 | from django.db.models.signals import post_save
from .models import Demand, DemandHub
from profiles.models import ProfileHub
from hubs.models import HubGeolocation
from utils.utils import coordinates_calculation, distance_calculation
def demand_created_or_updated(sender, update_fields, **kwargs):
instance = kwarg... |
123494 | from litex.soc.integration.soc_core import mem_decoder
from litex.soc.integration.soc_sdram import *
from liteeth.common import convert_ip
from liteeth.core import LiteEthUDPIPCore
from liteeth.frontend.etherbone import LiteEthEtherbone
from liteeth.mac import LiteEthMAC
from liteeth.phy import LiteEthPHY
from target... |
123499 | from html.parser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start :", tag)
for li in attrs:
print('->', li[0], '>', li[1])
def handle_endtag(self, tag):
... |
123522 | import json
import os
import sys
from glob import glob
from tasks.utils import *
TASK = sys.argv[1]
MODEL = sys.argv[2]
METHOD = sys.argv[3]
SPECIAL_METRICS = {
'cb' : 'f1',
'mrpc' : 'f1',
'cola' : 'matthews_correlation',
'stsb' : 'combined_score'
}
METRIC = "accuracy"
if TASK in SPECIAL_METRICS:
... |
123556 | from ..errors.validation import Validation
from . import element as element_module, section_element
from .element_base import ElementBase
from .missing import missing_empty
from .missing import missing_field
from .missing import missing_fieldset
from .missing import missing_list
from .missing import missing_section
fro... |
123590 | from .session import ClientSession
from .endpoints import (
LiveEndpointsMixin,
VREndpointsMixin,
RoomEndpointsMixin,
UserEndpointsMixin,
OtherEndpointsMixin
)
from json import JSONDecodeError
import time
from showroom.api.utils import get_csrf_token
from requests.exceptions import HTTPError
import ... |
123610 | from os import path
from django.core.management.base import BaseCommand
from uwsgiconf.sysinit import get_config, TYPE_SYSTEMD
from uwsgiconf.utils import Finder
from ...toolbox import SectionMutator
class Command(BaseCommand):
help = 'Generates configuration files for Systemd, Upstart, etc.'
def add_argu... |
123634 | import numpy as np
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import ops
from gpflow import settings
float_type = settings.float_type
jitter_level = settings.jitter
cla... |
123637 | import numpy as np
class ReplayMemory(object):
def __init__(self, max_size, obs_dim, act_dim):
self.max_size = int(max_size)
self.obs = np.zeros((max_size, ) + obs_dim, dtype='float32')
self.action = np.zeros((max_size, act_dim), dtype='float32')
self.reward = np.zeros((max_size,)... |
123643 | import json
import os
from pathlib import Path
import logging
def read_json(loc : str):
'''
:param loc: path to file
:return: yaml converted to a dictionary
'''
with open(loc) as f:
data = json.load(f)
return data
def write_json(data, loc):
with open(loc, 'w') as json_file:
... |
123676 | import re
inName = "./char_order.txt"
inLines = file(inName, 'r').readlines()
charDict = dict()
puncDict = dict()
for line in inLines:
seq = line.split()
if re.match('[a-zA-Z\.\,\'\"\-]', seq[1]):
count = int(seq[2][1:])
if charDict.has_key(seq[1]):
charDict[seq[1]] += count
... |
123722 | from EasyLogin import EasyLogin
a=EasyLogin()
def get_question(qid):
global a
html=a.get("http://gre.kmf.com/question/{qid}.html".format(qid=qid), cache=True)
soup = a.b
question_type = soup.find("input",{"id":"GlobeQUESTIONNAME"})["value"]
question_from = soup.find("span",{"class":"gray"})... |
123745 | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kompassi.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
123763 | import os
# hydra
import hydra
from omegaconf import DictConfig, OmegaConf
# pytorch-lightning related imports
from pytorch_lightning import Trainer
import pytorch_lightning.loggers as pl_loggers
from pytorch_lightning.callbacks import LearningRateMonitor
# own modules
from dataloader import PL_DataModule
from metho... |
123883 | import _optimize
def _optimize_fold_load_constants(nn_layers):
"""
Fold load constants that interact through 'add', 'multiply', 'activation',
'slice', 'reduce' or 'unary' layers.
In other words, evaluate any sub-graph that involves only 'load_constant',
'multiply', 'add', 'activation', 'slice', 'reduce'
or... |
123891 | from nesi.devices.softbox.api import db
class ServicePort(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(64))
box_id = db.Column(db.Integer, db.ForeignKey('box.id'))
admin_state = db.Column(db.Enum('0', '1', '2'), default='0') # Alcatel: 0 => down, 1 => up, 2 => ... |
123962 | import json
from pathlib import Path
import aiohttp
import pytest
from gentools import sendreturn
import ns
import snug
live = pytest.config.getoption('--live')
CRED_PATH = Path('~/.snug/ns.json').expanduser()
auth = json.loads(CRED_PATH.read_bytes())
@pytest.fixture(scope='module')
async def exec():
async wit... |
123988 | import base64
import binascii
import decimal
import json
import os
import platform
import sys
import urllib.parse as urlparse
from http.client import HTTP_PORT, HTTPConnection
DEFAULT_USER_AGENT = "AuthServiceProxy/0.1"
DEFAULT_HTTP_TIMEOUT = 30
# (un)hexlify to/from unicode, needed for Python3
unhexlify = binascii.... |
124015 | from bson import json_util
slide_list_file = '/data08/shared/lehhou/necrosis_segmentation_workingdir/slide_list.txt';
# read from file
with open(slide_list_file) as f:
content = f.readlines();
#lines = content.split('\n');
print content[-1][-2];
#print (content[-1][-3]);
|
124022 | class Base(object):
def __secret(self):
print("don't tell")
def public(self):
self.__secret()
class Derived(Base):
def __secret(self):
print("never ever")
if __name__ == "__main__":
print("Base class members:", dir(Base))
print("Derived class members:", dir(Derived))
... |
124025 | from kubernetes_manager.models import (
KubernetesBase,
KubernetesConfigMap,
KubernetesContainer,
KubernetesDeployment,
KubernetesIngress,
KubernetesJob,
KubernetesMetadataObjBase,
KubernetesNamespace,
KubernetesNetworkingBase,
KubernetesPodTemplate,
KubernetesService,
Ku... |
124041 | import click
from pprint import pprint
from .decorators import onlineChain, unlockWallet
from .main import main
@main.command()
@click.pass_context
@onlineChain
@click.argument("members", nargs=-1)
@click.option("--account", help="Account that takes this action", type=str)
@unlockWallet
def approvecommittee(ctx, memb... |
124042 | from itertools import islice
from re import compile
from snowddl.blueprint import TableBlueprint, TableColumn, DataType, BaseDataType
from snowddl.resolver.abc_schema_object_resolver import AbstractSchemaObjectResolver, ResolveResult, ObjectType
cluster_by_syntax_re = compile(r'^(\w+)?\((.*)\)$')
class TableResolve... |
124043 | from aqt import gui_hooks
from aqt.utils import showWarning
opened = False
def startup():
global opened
if opened:
warning_text = "\n".join((
"Pokemanki does not support opening a second profile in one session.",
"Please close Anki and reopen it again to the desired profile."... |
124046 | import grpc
import pytest
from uuid import uuid4
from multiprocessing import Event
from google.protobuf import json_format
from google.protobuf.empty_pb2 import Empty
from common.cryptographer import Cryptographer
from teos.watcher import Watcher
from teos.responder import Responder
from teos.gatekeeper import UserI... |
124064 | import cv2
from skimage.feature import hog
from sklearn.decomposition import PCA
class FeatureSelection:
def __init__(self):
print("\n----------------------------------------------------------")
print("--------------P-R-O-C-E-S-S-I-N-G---D-A-T-A---------------")
print("-------------------... |
124101 | from tulip import hybrid
import polytope
import scipy.io
"""
Contains functions that will read a .mat file exported by the MATLAB function
mpt2python and import it to either a PwaSysDyn or a LtiSysDyn.
<NAME>, June 2014
"""
def load(filename):
data = scipy.io.loadmat(filename)
islti = bool(data['islti'][0][... |
124107 | from ._base import DanubeCloudCommand, CommandError
class Command(DanubeCloudCommand):
help = 'Initialize the virtual environments.'
def handle(self, *args, **options):
raise CommandError('Use ctl.sh directly')
|
124148 | import FWCore.ParameterSet.Config as cms
import EventFilter.RPCRawToDigi.rpcUnpackingModule_cfi
rpcunpacker = EventFilter.RPCRawToDigi.rpcUnpackingModule_cfi.rpcUnpackingModule.clone()
rpcunpacker.InputLabel = cms.InputTag("rawDataCollector")
rpcunpacker.doSynchro = cms.bool(True)
|
124151 | from luigi.contrib.s3 import S3Target
from ob_pipelines.batch import BatchTask, LoggingTaskWrapper
from ob_pipelines.config import cfg
from ob_pipelines.entities.sample import Sample
from ob_pipelines.pipelines.xenograft.tasks.star_by_species import StarBySpecies
class DisambiguateHumanMouse(BatchTask, LoggingTaskWr... |
124152 | def test_metadata(system_config) -> None:
assert system_config.provider_code == "system"
assert system_config._prefix == "TEST"
def test_prefixize(system_config) -> None:
assert system_config.prefixize("key1") == "TEST_KEY1"
assert system_config.unprefixize("TEST_KEY1") == "key1"
def test_get_variab... |
124181 | from functools import partial
from textwrap import dedent
from io import StringIO
import pytest
import pandas.testing as pdtest
import numpy
import pandas
from wqio.utils import misc
from wqio.tests import helpers
@pytest.fixture
def basic_data():
testcsv = """\
Date,A,B,C,D
X,1,2,3,4
Y,5,6,7,8
... |
124236 | class NoDataError(Exception):
def __init__(self, field, obj, module):
message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module
super(NoDataError, self).__init__(message)
|
124240 | from absl import logging
import os
from lib import dataset
from libs import settings
import tensorflow as tf
def generate_tf_record(
data_dir,
raw_data=False,
tfrecord_path="serialized_dataset",
num_shards=8):
teacher_sett = settings.Settings(use_student_settings=False)
student_se... |
124252 | from lrabbit_scrapy.spider import LrabbitSpider
from lrabbit_scrapy.common_utils.network_helper import RequestSession
from lrabbit_scrapy.common_utils.print_log_helper import LogUtils
from lrabbit_scrapy.common_utils.all_in_one import FileStore
import os
from lrabbit_scrapy.common_utils.mysql_helper import MysqlClient
... |
124275 | from keyboard_alike import reader
class BarCodeReader(reader.Reader):
"""
This class supports Lindy USB bar code scanner configured to work as a keyboard
http://www.lindy.co.uk/accessories-c9/input-devices-c357/barcode-scanners-c360/barcode-scanner-ccd-usb-p1352
"""
pass
if __name__ == "__main__... |
124312 | import requests
import json
import base64
import redis
import os
def handle(st):
# parse Github event
req = json.loads(st)
minutes = 1
minutes_val = os.getenv("cache-minutes")
if minutes_val != None:
minutes = int(minutes_val)
loginName = req["sender"]["login"]
try:
redis... |
124317 | from py2neo import authenticate, Graph
import os.path
import bleach
import sys
from flask import Flask
app = Flask(__name__)
def FindSimilarRepositories(InputrepoK):
#Sanitize input
print("got ......",InputrepoK)
sys.stdout.flush()
Inputrepo = bleach.clean(InputrepoK).strip()
host = os.environ['LOCALNEO4JIPPORT'... |
124322 | from graphwar.attack.flip_attacker import FlipAttacker
class UntargetedAttacker(FlipAttacker):
r"""Base class for adversarial non-targeted attack.
Parameters
----------
data : Data
PyG-like data denoting the input graph
device : str, optional
the device of the attack ru... |
124328 | import torch
import warnings
from torch.optim.optimizer import Optimizer, required
import math
import itertools as it
import torch.optim as optim
warnings.filterwarnings("once")
def get_optimizer(optimizer: str = 'Adam',
lookahead: bool = False,
model=None,
separa... |
124377 | import fnmatch
import json
import logging
import os
import re
from collections import Counter
from operator import itemgetter
import en_core_web_sm
from spacy.matcher import Matcher
from gamechangerml.configs.config import DefaultConfig as Config
import gamechangerml.src.modelzoo.semantic.term_extract.version_ as v
... |
124392 | from a_resnet_training_common_cli import Hyperparameters
from stanford_cars_augmentation_cli import AugmentHyperparameters, AugmentCLI
def generate_cli_hpo(parser):
"""Adding Hyperparameters to CLI arguments"""
parser.add_argument("--" + Hyperparameters.SCEDULER_RATE.value, dest=Hyperparameters.SCEDULER_RATE.... |
124417 | class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
length = len(num)
# use dict: value: index + 1
# since there is only one solution, the right value must not be duplicated
dic = {}
for i in xrange(0, length):
val = num[i]
... |
124482 | from .lop_setup import *
def test_matrix_1():
A = jnp.ones([4, 4])
op = lop.matrix(A)
x = jnp.ones(4)
assert_allclose(op.times(x), A @ x)
assert_allclose(op.trans(x), A.T @ x)
def test_matrix_2():
A = jnp.reshape(jnp.arange(20), (4,5))
op = lop.matrix(A)
x = jnp.ones(4)
y = jnp.o... |
124497 | import os.path
import os
import sys
import math
import argparse
import time
import random
from collections import OrderedDict
import torch
import options.options as option
from utils import util
from data import create_dataloader, create_dataset
from models import create_model
from utils.logger import Logger, PrintLo... |
124499 | from PIL import Image, ImageDraw
img = Image.new("RGB", (100, 100), (88, 88, 88))
draw = ImageDraw.Draw(img)
if 0:
draw.line((0, 0) + img.size, fill="red")
draw.line((0, img.size[1], img.size[0], 0), fill="blue")
if 0:
draw.point((75, 50), fill="red")
draw.rectangle([20, 50, 30, 65], fill="green", outli... |
124505 | import numpy as np
a1 = np.ones((2, 3), int)
print(a1)
# [[1 1 1]
# [1 1 1]]
a2 = np.full((2, 3), 2)
print(a2)
# [[2 2 2]
# [2 2 2]]
print(np.block([a1, a2]))
# [[1 1 1 2 2 2]
# [1 1 1 2 2 2]]
print(np.block([[a1], [a2]]))
# [[1 1 1]
# [1 1 1]
# [2 2 2]
# [2 2 2]]
print(np.block([[a1, a2], [a2, a1]]))
# [[1 ... |
124547 | from tkinter import *
import vote_bot
from functools import partial
import threading
from utils import loadCredentials
def start(mail,password,option,delay,url):
#print(mail.get(),password.get(),url.get())
process = threading.Thread(target=vote_bot.start_bot,args=(int(option.get()),mail.get(),password.get(),ur... |
124571 | import pandas as pd
import numpy as np
import py_entitymatching as em
from .magellan_modified_feature_generation import get_features
#Given a CANDIDATE SET and the list of ACTUAL duplicates (duplicates_df),
#this function adds the 1/0 labels (column name = GOLD) to the candset dataframe
def add_labels_to_candset(dupl... |
124585 | from contrib.views import char_count
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
urlpatterns = [
path("admin/", admin.site.urls),
path("char_count", char_count, name="char_count"),
re_path(".*", TemplateView.as_view(template_name="ind... |
124599 | import os
from scipy.io import loadmat
import h5py
import numpy as np
from tools.getDistSqrtVar import getDistSqrtVar
from tools.getCNNFeature import getCNNFeature
from tools.get_ilsvrimdb import readAnnotation as ilsvr_readAnnotation
from tools.get_cubimdb import readAnnotation as cub_readAnnotation
from tools... |
124633 | import tempfile
import unittest
from pyspark import Row
from sourced.ml.models import DocumentFrequencies
from sourced.ml.tests import create_spark_for_test
from sourced.ml.transformers import Indexer
class IndexerTests(unittest.TestCase):
def setUp(self):
data = [Row(to_index="to_index%d" % i, value=i)... |
124635 | class RenderedView(object):
def __init__(self, view_file: str, data):
self.view_file = view_file
self.data = data
|
124655 | description = 'Email and SMS notifiers'
group = 'lowlevel'
devices = dict(
email = device('nicos.devices.notifiers.Mailer',
mailserver = 'mailhost.frm2.tum.de',
sender = '<EMAIL>',
copies = [
('<EMAIL>', 'all'),
('<EMAIL>', 'all'),
('<EMAIL>', 'all'),
... |
124664 | from . import numpy_ndarray_as
def random(size, nulls=False):
"""Return random xnd.xnd instance of 64 bit floats.
"""
import xnd
import numpy as np
r = numpy_ndarray_as.random(size, nulls=nulls)
if nulls:
xr = xnd.xnd(r.tolist(), dtype='?float64')
for i in np.where(np.isnan(r))... |
124667 | import unittest
from test import support
import socket
import test_data
import time
from lxml import etree
import uuid
import asyncio
from common_testing_tools import TCPClient
class TCPServiceTests(unittest.TestCase):
def setUp(self):
""" setup method to establish two sockets.
this method is run ... |
124669 | from doctest import testmod
import unittest
from julius import resample, fftconv, lowpass, bands, utils
class DocStringTest(unittest.TestCase):
def test_resample(self):
self.assertEqual(testmod(resample).failed, 0)
def test_fftconv(self):
self.assertEqual(testmod(fftconv).failed, 0)
def... |
124701 | from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import time
start_time = time.time()
options = Options()
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--disable-extens... |
124713 | from tg_bot import bot
from app.constants import (
emoji, all_stations, personalization_answer, select_home_station,
select_univer_station
)
from app import new_functions as nf, db
from flask import g
import telebot_login
from tg_bot.keyboards import stations_keyboard, personalization_keyboard
# Personalizati... |
124719 | import math
try:
from ulab import scipy, numpy as np
except ImportError:
import scipy
import numpy as np
A = np.array([[3, 0, 2, 6], [2, 1, 0, 1], [1, 0, 1, 4], [1, 2, 1, 8]])
b = np.array([4, 2, 4, 2])
# forward substitution
result = scipy.linalg.solve_triangular(A, b, lower=True)
ref_result = np.array(... |
124721 | from .client import MarathonClient
from .models import MarathonResource, MarathonApp, MarathonTask, MarathonConstraint
from .exceptions import MarathonError, MarathonHttpError, NotFoundError, InvalidChoiceError
from .util import get_log
log = get_log()
|
124724 | class Dictionary(object):
def __init__(self):
self.my_dict = {}
def look(self, key):
return self.my_dict.get(key, "Can't find entry for {}".format(key))
def newentry(self, key, value):
""" new_entry == PEP8 (forced by Codewars) """
self.my_dict[key] = value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.