id
stringlengths
3
8
content
stringlengths
100
981k
9935081
import pytest class MyFile(pytest.File): def collect(self): return [MyItem.from_parent(name="hello", parent=self)] def pytest_collect_file(file_path, parent): return MyFile.from_parent(path=file_path, parent=parent) class MyItem(pytest.Item): pass
9935083
import pytest from openpyxl import Workbook import datetime from pyDEA.core.models.categorical_dmus import ModelWithCategoricalDMUs from pyDEA.core.models.categorical_dmus import get_dmus_with_fixed_hierarchical_category from pyDEA.core.models.multiplier_model_base import MultiplierModelBase from pyDEA.core.models.mul...
9935112
import csv import json def csv_to_json(file_basename): csv_filename = '%s.csv' % file_basename data = {} with open(csv_filename, 'r', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile) for row in csv_reader: # data check if len(row) != 2: ...
9935175
try: from . import caesar except: import caesar def rot5(content: bytes): p = list(content) for i in range(len(p)): if ord('0') <= p[i] <= ord('9'): p[i] = ord('0') + (p[i] - ord('0') + 5) % 10 return bytes(p) def rot13(content: bytes): return caesar.encode(content, 13) ...
9935198
from glob import glob import os import shutil def separate_folder(target_dir, new_target_dir, folder_name, remove_remained=False): """ 同一フォルダ内にファイルがすべてあって`target_dir/*.png`、データセットをファイル名で分けているときに、 データセットごとにフォルダを作成して、画像を'new_target_dir/datasest/images/*.png`に移動させる。 画像ファイル名は、(動画の属性)_(フレーム番号).pngになっている必要が...
9935249
from django.contrib.auth.models import AnonymousUser from django.db.models import Q import django_filters from core.models import Size, Provider, ProviderMachine from core.query import only_current from api.v2.serializers.details import SizeSerializer from api.v2.views.base import AuthReadOnlyViewSet from api.v2.view...
9935258
import sys import os PYTHON3 = sys.version_info[0] > 2 def decode(str_, codec='utf8'): """decode a string. if str is a python 3 string, do nothing.""" if PYTHON3: return str_ else: return str_.decode(codec) def encode(str_, codec='utf8'): """encode a string. if str is a python 3 str...
9935268
import argparse import tensorflow as tf import librosa from joblib import dump import utils from model_helper import las_model_fn from preprocess_all import calculate_acoustic_features SAMPLE_RATE = 16000 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--waveform', type=str, requir...
9935306
import os import imp # from S3 import CallingFormat # from boto.s3.connection import OrdinaryCallingFormat BASE = os.path.abspath(os.path.dirname(__file__)) DEBUG = True ADMINS = () # SERVER_EMAIL = "<EMAIL>" MANAGERS = ADMINS TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' SITE_ID = 1 WSGI_APPLICATION = "wsgi.applicati...
9935360
import os import pytest import yaml from grader.models.gradesheet import GradeSheetError from grader.models.config import ConfigValidationError def test_new_without_repo(parse_and_run): """Test vanilla assignment initialization """ path = parse_and_run(["init", "cpl"]) parse_and_run(["new", "assignme...
9935373
from django.contrib import admin from app.models import ( Document, ) @admin.register(Document) class DocumentAdmin(admin.ModelAdmin): model = Document list_display = ('id', 'title', 'published_at', 'modified_at') search_fields = ('title',)
9935387
from xmlrpc.server import SimpleXMLRPCServer def sum(a, b): """return a+b""" return a + b # PS:50051是gRPC默认端口 server = SimpleXMLRPCServer(('', 50051)) # 把函数注册到RPC服务器中 server.register_function(sum) print("Server启动ing,Port:50051") server.serve_forever()
9935393
def extractHeroicNovels(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [ ('id', 'ID – The Greatest Fusion Fantasy', 'translated'), ('Magician City',...
9935398
import gzip import logging import os from multiprocessing import Process, Queue from datetime import datetime import osmutils from utils import format_date from RdfHandler import RdfHandler log = logging.getLogger('osm2rdf') def writer_thread(worker_id, queue, options): while True: ts, file_id, data, l...
9935420
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from mmcv.cnn.weight_init import caffe2_xavier_init from ..utils import ConvModule from ..registry import NECKS @NECKS.register_module class MatrixFPN(nn.Module): """Matrix Nets https://arxiv.or...
9935440
from django.db import models # Create your models here. class Global(models.Model): cupos_totales= models.IntegerField(default=0) cupos_desayuno = models.IntegerField(default=0) cupos_almuerzo = models.IntegerField(default=0) cupos_cena = models.IntegerField(default=0) cupos_disponibles = models....
9935441
from sciencebeam_parser.models.training_data import ( is_same_or_parent_path_of ) class TestIsSameOrParentPathOf: def test_should_return_true_for_same_path(self): assert is_same_or_parent_path_of(['parent', 'child1'], ['parent', 'child1']) is True def test_should_return_true_for_parent_path_of_ch...
9935446
try: import cupy except: # print("No cupy detected") pass from torch.utils.dlpack import to_dlpack, from_dlpack def to_cupy(m_tensor): return cupy.fromDlpack(to_dlpack(m_tensor)) def from_cupy(m_cp): return from_dlpack(m_cp.toDlpack())
9935453
import os from opensextant.utility import get_list uni_array = [] ascii_array =[] uni_mapping = dict() with open(os.path.join("solr7/gazetteer/conf/OpenSextant-Gazetteer-ASCIIFolding.txt"), "r", encoding="UTF-8") as fh: for line in fh: text = line.strip() if not text or text.startswith("#"): ...
9935455
from ReverseEncodingTree.benchmark.methods import inherent from ReverseEncodingTree.benchmark.methods.evolutor import GA, PBIL, BI, CMAES from ReverseEncodingTree.benchmark.methods.show_me_results import clime_by_generation, get_mount_everest def obtain_ga(start_position, stride): _, _, landscape = get_moun...
9935493
import time from test_framework.cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT from test_framework.mininode import CTransaction, FromHex, ToHex, CTxOut from test_framework.script import OP_RETURN, CScript import random from binascii import hexlify, unhexlify # Append junk outputs until it reaches at least min_size...
9935504
def query(question, default=None): s = question if default: s += " [%s]" % default s += ": " answer = raw_input(s) answer = answer.strip() if not answer: return default return answer
9935518
from pyplates import core, functions class BaseTemplate(core.CloudFormationTemplate): def add_server(self): self.parameters.add( core.Parameter('EC2InstanceType', 'String', { 'Default': 'm1.small', 'Description': 'Instance type to use for...
9935525
from __future__ import absolute_import __author__ = 'katharine' import calendar import collections import datetime import dateutil.parser from dateutil.tz import tzlocal import logging import requests import struct import time import traceback from uuid import UUID import urllib import pypkjs.PyV8 as v8 from libpebbl...
9935527
import unittest import math import torch from nnc.helpers.torch_utils.numerics import cos_difference,\ sin_difference,\ sin_difference_mem,\ cos_difference_mem class MyTestCase(unittes...
9935544
if __name__ == '__main__': import sys import numpy numpy.set_printoptions(precision=3) num_bins = int(sys.argv[1]) inputs = [] for line in sys.stdin: inputs.append(float(line.strip())) histo, bin_edges = numpy.histogram(inputs, bins=num_bins, density=True) q25 = numpy.percentile(inputs, 25)...
9935551
from .bump_version import BumpVersion from .dist_build import DistBuild from .publish import Publish from .test import PyTest ALL = { "test": PyTest, "bump_version": BumpVersion, "dist_build": DistBuild, "publish": Publish, }
9935565
from streamlink.plugins.ceskatelevize import Ceskatelevize from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlCeskatelevize(PluginCanHandleUrl): __plugin__ = Ceskatelevize should_match = [ "https://www.ceskatelevize.cz/zive/ct1/", "https://www.ceskatelevize.cz/zive/ct2/"...
9935570
from pyradioconfig.parts.panther.calculators.calc_frame import CALC_Frame_panther class CALC_Frame_lynx(CALC_Frame_panther): def _combine_rx_fcds(self, model): """_combine_rx_fcds Args: model (ModelRoot) : Data model to read and write variables from """ # Due to IPMCUS...
9935613
from datetime import datetime from django.test import TestCase from devilry.utils import datetimeutils class TestIsoformatNoseconds(TestCase): def test_sanity(self): self.assertEqual( '2015-12-24 17:42', datetimeutils.isoformat_noseconds(datetimeutils.default_timezone_datetime(20...
9935645
from beluga.utils import load import matplotlib.pyplot as plt sol_set = load('chain.beluga')['solutions'] for sol in sol_set[-1]: plt.plot(sol.y[:, 0], sol.y[:, 1]) plt.show()
9935649
from abc import ABCMeta, abstractmethod from pyzshcomplete.utils.zsh_constants import ZshConstants class ArgumentAdapterInterface(metaclass=ABCMeta): ''' DO NOT subclass from this class directly, as it doesn't contain the completion generation logic. See ArgumentAdapter. Defines the interface to be ...
9935668
import collections import math import islpy from soap.common.cache import cached from soap.expression import ( expression_factory, is_expression, is_variable, Variable, FixExpr, expression_variables ) class DependenceType(object): independent = 0 flow = 1 anti = 2 output = 3 def is_isl_exp...
9935672
from weakref import WeakKeyDictionary import six from ..cypher.operations import CypherExpression, CypherOperatorInterface from ..exceptions import ImmutableAttributeError try: str = unicode except NameError: pass class SetOnceDescriptor(object): def __init__(self, name, type=None): self.name =...
9935680
from cv_bridge import CvBridge, CvBridgeError from keras.models import model_from_json import cv2 import numpy as np import rospy bridge = CvBridge() def callback_img(data, target_size, crop_size, rootpath, save_img): try: image_type = data.encoding img = bridge.imgmsg_to_cv2(data, image_type) ...
9935688
from __future__ import print_function from optparse import OptionParser import numpy as np import healpy as hp import matplotlib.pyplot as plt import pymaster as nmt import os import sys DTOR=np.pi/180 def opt_callback(option, opt, value, parser): setattr(parser.values, option.dest, value.split(',')) parser = Opt...
9935739
import fileinput import argparse def replace_words(my_dict, filename): #Read input file inp_file = open(filename+".en") out_file = open(filename+".new.en", "w") count = 0 #Total number of lines modified count2 = 0 #Total number of lines #Replace words and write to file for line in inp_fi...
9935755
nfiles = 16 # number of *.ddcMD files mypath = "surface.llnl.gov:/g/g19/jpc/sl/emhm/2016_PAPER/FIRST_ROUND_EXPS_NEWEST/NSTIM_1/snapshot.000000208000_COPY/" threshmin = 100 # threshold operation minimum value pseudomin = threshmin # pseudocolor minimum color value myattr = "cellTypeNew" # the name of the attribute you...
9935769
import os import shutil import cv2 import numpy as np from tqdm import tqdm from utils.masked_face_creator import MaskedFaceCreator class ClebAMaskedFaceDatasetCreator: def __init__(self, dataset_path, dataset_assert_file, new_dataset_folder_path, mask_type="a"): self.dataset_path = dataset_path ...
9935783
from django.db import models from django.conf import settings from django.contrib.postgres.fields import ArrayField, HStoreField, JSONField from django.contrib.auth.models import Group from plyara import Plyara from .managers import YaraRuleManager, YaraRuleCommentManager class YaraRule(models.Model): ACTIVE_S...
9935788
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cPickle as pickle from zie import fit_emb from zie import evaluate_emb from random_data import rand_data def experiment(): ## Step 1: load data print('Generating a dataset...
9935802
class Kernel: def __init__(self, corpus): from gensim.models import KeyedVectors as kv try: self.model = kv.load_word2vec_format('./src/' + corpus, binary=True) except: print('[gensimError] Failed to load corpus.') exit() def get_sim(self, word, num):...
9935852
import requests import yaml import json fullname = "ironscales" locations = [ "https://appapi.ironscales.com/appapi/docs/partner-full/api-docs/appapi/get-token", "https://appapi.ironscales.com/appapi/docs/partner-full/api-docs/appapi/mitigation", "https://appapi.ironscales.com/appapi/docs/partner-full/api-...
9935902
import sys, os import tomotopy as tp curpath = os.path.dirname(os.path.realpath(__file__)) print(curpath) model_cases = [ (tp.LDAModel, curpath + '/sample.txt', 0, None, {'k':40}, None), (tp.LLDAModel, curpath + '/sample_with_md.txt', 1, lambda x:x, {'k':5}, None), (tp.PLDAModel, curpath + '/sample_with_m...
9935905
from pathlib import Path import numpy as np import pandas as pd import pytest import requests from tests.conftest import ( delete_file_if_exists, IMAGE_FILENAMES, IMAGE_URLS, keep_filename_save_png_in_tempdir, TEMP_DATA_DIR, ) from wildebeest import CustomReportingPipeline, Pipeline from wildebees...
9935930
from datetime import timedelta from django.test import tag from django.utils import timezone from aidants_connect_web.models import Mandat from aidants_connect_web.tests.factories import ( AidantFactory, MandatFactory, UsagerFactory, ) from aidants_connect_web.tests.test_functional.testcases import Funct...
9935943
from .client_proxy import ClientProxy from .space import Space """ contentful_management.spaces_proxy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module implements the SpacesProxy class. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/spaces :copyright: (c) 2018 ...
9935978
from django.contrib import admin from django.core import serializers from django.http import HttpResponse from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from reference.EmissionFactor import EmissionFactor from reference.GPCSector import GPCSector actions = ['export'] @admin.ac...
9935997
import json import datasets _CITATION = """\ @misc{dinan2019second, title={The Second Conversational Intelligence Challenge (ConvAI2)}, author={<NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> ...
9936069
from typing import Any, Dict from .Action import Action from .ActionType import ActionType from ..DurableHttpRequest import DurableHttpRequest from ..utils.json_utils import add_attrib, add_json_attrib class CallHttpAction(Action): """Defines the structure of the Call Http object. Provides the information n...
9936117
from typing import List import pandas from . import Market class MarketMACD: DATE_COLUMN: str = "Date" MACD_COLUMN: str = "MACD" SIGNAL_COLUMN: str = "Signal" HIST_COLUMN: str = "Hist" market: Market dataframe: pandas.DataFrame def __init__( self, market: Market, ...
9936123
class ConversionLevel: """Describe the various ways we can convert between two typed python Types.""" def __lt__(self, other): return self.LEVEL < other.LEVEL def __le__(self, other): return self.LEVEL <= other.LEVEL def __gt__(self, other): return self.LEVEL > other.LEVEL ...
9936144
from math import sqrt from compyle.api import declare from pysph.sph.equation import Equation class ComputeNormals(Equation): """Compute normals using a simple approach .. math:: -\frac{m_j}{\rho_j} DW_{ij} First compute the normals, then average them and finally normalize them. """ d...
9936163
from twilio.twiml.voice_response import VoiceResponse, Say response = VoiceResponse() response.say('Hello World') print(response)
9936165
try: import PyQt4 as _PyQt4 # Qt5 -> Qt4 _PyQt4.QtCore.QItemSelection = _PyQt4.QtGui.QItemSelection _PyQt4.QtCore.QItemSelectionModel = _PyQt4.QtGui.QItemSelectionModel except ImportError: _PyQt4 = None try: import PySide2 as _PySide except ImportError: try: import PySide as _PySide...
9936228
from __future__ import print_function import unittest from rdkit.Chem import AllChem from descriptastorus import append_store, make_store, DescriptaStore from descriptastorus.descriptors.rdDescriptors import RDKit2D from descriptastorus import descriptors import logging, struct import contextlib, tempfile, os, shutil, ...
9936239
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.SCALEWAY) driver = cls('SCALEWAY_ACCESS_KEY', 'SCALEWAY_SECRET_TOKEN') volumes = driver.list_volumes() for volume in volumes: print(volume) snapshots = driver.list_volume_snapshots(volume) ...
9936252
import itertools from .batch import BatchController from .conditions import ConditionController from registrasion.models import commerce from registrasion.models import conditions from django.db.models import Case from django.db.models import F, Q from django.db.models import Sum from django.db.models import Value f...
9936268
from dash.dependencies import Input, Output, State class coinCallbacksClass: def __init__(self, defichainAnalyticsModel, coinView, app): @app.callback(Output('figureCoin', 'figure'), [Input('coinsSelectionGraphic', 'value')]) def updateTVLGraphs(selectedRepresentation): ...
9936292
import pytest import keepachangelog def test_changelog_not_found(): with pytest.raises(FileNotFoundError): keepachangelog.to_dict("do not exists")
9936336
from scripts.rewards.rewards_utils import calc_next_cycle_range import time from brownie import * from config.badger_config import badger_config from rich.console import Console from scripts.systems.badger_system import BadgerSystem, connect_badger from scripts.rewards.propose_root import propose_root from assistant.r...
9936342
from plumbum.cmd import git from semantic_version import Version from changes.models.repository import GitRepository def test_repository_parses_remote_url(git_repo): repository = GitRepository() assert 'test_app' == repository.repo assert 'michaeljoseph' == repository.owner assert repository.is_githu...
9936369
import matplotlib.pyplot as plt def smooth_curve(xs, alpha=0.0): res = [] for x in xs: if len(res) == 0: res.append(x) else: res.append(res[-1] * (1 - alpha) + alpha * x) return res
9936408
import argparse import cv2 import numpy as np import glob import time import matmul_inference import inpaint_inference import os INPUT_SIZE = 512 # input image size for Generator ATTENTION_SIZE = 32 # size of contextual attention MULTIPLE = 6 NPTYPE = np.float32 def sort(str_lst): return [s for s in sorted(str...
9936411
import sys import urllib2 import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--proxy", type=str, metavar="PROXY", required=True, help="address of a proxy server") parser.add_argument("--user", type=str, metavar="USER", required=True, ...
9936421
from django.apps import AppConfig class RandomuserdataConfig(AppConfig): name = 'randomUserData'
9936425
from .layout import Layout class HSplit(Layout): """ Split the screen horizontally at `row` from top or bottom of the screen (depending on the sign of `row`). If `row` is a float, it's taken to be percentage of the screen (i.e., HSplit(.33) will split the screen 33% of the distance from top to bottom)...
9936454
import math from Instrucciones.TablaSimbolos.Instruccion import Instruccion from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato, Tipo from Instrucciones.Excepcion import Excepcion from Instrucciones.TablaSimbolos import Instruccion3D as c3d from Optimizador.C3D import Valor as ClassValor from Optimizador.C3D import ...
9936459
import math # Example points in 3-dimensional space... x = (5, 6, 7) y = (8, 9, 9) distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(x, y)])) print("Euclidean distance from x to y: ",distance)
9936468
class CreateSchema: name = 'create_schema' desc = 'creates new DB schema' args = [] def run(self, db, _): db.remove_schema() db.create_schema() db.commit()
9936478
from trader import Trader class TraderQueryTrade(Trader): def __init__(self, addr): Trader.__init__(self, addr=addr) def on_qrytrade(self, msg): if msg['error_id'] != 0: print("query error: " + msg['error_id']) return qry_result = msg['data']['data'] f...
9936501
import sys import os import sqlite3 as sql import json from datetime import datetime import tempfile import csv parent_module = sys.modules['.'.join(__name__.split('.')[:-1]) or '__main__'] if __name__ == '__main__' or parent_module.__name__ == '__main__': #sys.path.append(os.path.abspath(os.path.realpath("python_...
9936509
import struct import pyzatt.zkmodules.defs as DEFS import pyzatt.misc as misc """ This file contains provides functions to create, parse, receive and send, packets, it also suppors reading of large datasets(see ex_data protocol spec). Author: <NAME> <<EMAIL>> """ class PacketMixin: def create_packet(self, cmd_...
9936514
import subprocess as sp def run_command(command: str, timeout: int=60, **kwargs) -> sp.CompletedProcess: fixed_kwargs = { 'shell': True, 'stdout': sp.PIPE, 'stderr': sp.PIPE, 'timeout': timeout, 'check': True} kwargs.update(fixed_kwargs) try: result = sp.run(command, **kwargs) except sp.Timeou...
9936519
import discord from discord_slash import SlashContext from utils.config import config async def can_action_member(ctx: SlashContext, member: discord.Member) -> bool: # Stop mods from actioning on the bot. if member.bot: return False # Stop mods from actioning one another, people higher ranked th...
9936584
import pandas as pd from sklearn.preprocessing import LabelEncoder class MultiColumnLabelEncoder: def __init__(self, columns=None): self.columns = columns # array of column names to encode def fit(self, X, y=None): return self # not relevant here def transform(self, X): ''' ...
9936588
import sys from app.standalone_app import StandaloneApp if __name__ == "__main__": StandaloneApp().run()
9936598
def routes(): from .paths import CreateR, DeleteR, InfoR, NICsR, ListR, StartR, StopR p = paths() create_r = CreateR() delete_r = DeleteR() info_r = InfoR() nics_r = NICsR() list_r = ListR() start_r = StartR() stop_r = StopR() funcs = [create_r, delete_r, ...
9936654
import pandas as pd from pandasql import sqldf import os import re import sys import pprint prefix = '' suffix = '' def parse_filename(filename): assert filename.startswith(prefix) assert filename.endswith(suffix) d = {} filename = filename[len(prefix):] if len(suffix) != 0: filename = filename[:-len(su...
9936662
import os from os.path import join from shutil import move toc_string = """\n --- bookToc: false --- \n""" current_working_dir = os.getcwd() # print(f"current_working_dir: {current_working_dir}") dir_names = os.listdir(current_working_dir) # print(dir_names) print(len(dir_names)) for file_name in dir_names: ...
9936675
import pytest @pytest.fixture def testcases(): return { "inject": ( """ def test_injection(snapshot): assert snapshot is not None """ ), } @pytest.fixture def run_testcases(testdir, testcases): pyfile_content = "\n\n".join(testcases.val...
9936685
import weakref class GarbageCollectionMarker(object): def mark(self, obj): marker = _Marker(obj) obj.__marker__ = _MarkerAnchor(marker) return marker class _Marker(object): destroyed = False def __init__(self, obj): super(_Marker, self).__init__() self._weakref ...
9936694
from __future__ import print_function, division from fenics import * import mshr def scale_mesh(mesh, width, height): """ Scale coordinates of the mesh to be (0, 0) to (width x height). """ coords = mesh.coordinates() x = coords[:, 0] y = coords[:, 1] x[:] = (x - min(x)) / (max(x) - min(x)) * widt...
9936701
import scipy import scipy.spatial def knn_search(query_points, source_points, k): """ KNNSEARCH finds the k nearnest neighbors of query_points in source_points Inputs: query_points: N-by-D numpy array of query points source_points: M-by-D numpy array existing points k: number of ne...
9936724
import itertools import pytest import torch from allennlp.common.util import cycle_iterator_function from allennlp.data import DatasetReader, Instance, Vocabulary from allennlp.data.fields import LabelField from allennlp.data.dataset_readers import MultiTaskDatasetReader from allennlp.data.data_loaders.multitask_data...
9936736
import pytest import pymongo import pymongo.errors def pytest_addoption(parser): parser.addoption( "--server", action="store", default=None, help="enter a MongoURI or 'local' to use localhost." ) def pytest_configure(config): config.addinivalue_line("markers", "mongo: mark test as needing mongo ...
9936772
import random import unittest import numpy as np import torch from snorkel.classification import DictDataLoader, DictDataset from snorkel.classification.training.schedulers import ( SequentialScheduler, ShuffledScheduler, ) dataset1 = DictDataset( "d1", "train", X_dict={"data": [0, 1, 2, 3, 4]}, ...
9936799
import os import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from seisnn.io import read_hyp, read_event_list from seisnn.utils import get_config W, E, S, N = 121.2, 121.9, 23.5, 24.3 s...
9936801
from testlib import getSource, mySink, alias x = getSource() mySink(x) mySink(foo=x) # OK mySink(sinkName=x) # NOT OK mySink(alias()) # NOT OK mySink(alias().chain()) # NOT OK mySink(alias().chain().chain()) # NOT OK mySink(alias().chain().safeThing()) # OK from testlib import Args Args.arg0(one, two, three, four,...
9936802
import unittest import skype4pytest from Skype4Py.skype import * class SkypeTest(skype4pytest.TestCase): def setUpObject(self): self.obj = self.skype # Methods # ======= def testApiSecurityContextEnabled(self): # Returned type: bool def test(): self.obj.ApiSecuri...
9936805
import typing from torch.utils.data import Dataset import torch from pathlib import Path import json from util.globals import * REMOTE_URL = f"{REMOTE_ROOT_URL}/data/dsets/known_1000.json" class KnownsDataset(Dataset): def __init__(self, data_dir: str, *args, **kwargs): data_dir = Path(data_dir) ...
9936822
from os import path as op import tornado.web import tornadio import tornadio.router import tornadio.server ROOT = op.normpath(op.dirname(__file__)) class IndexHandler(tornado.web.RequestHandler): """Regular HTTP handler to serve the chatroom page""" def get(self): self.render("index.html") class Cha...
9936835
import os DMENU = "dmenu" ROFI = "rofi" SUPPORTED_MENUS = [DMENU, ROFI] BSPWM = 'bspwm' I3 = 'i3' OPENBOX = 'openbox' SUPPORTED_APPS = [BSPWM, I3, OPENBOX] PARSERS = { BSPWM: "BspwmConfigParser", I3: "I3ConfigParser", OPENBOX: "OpenBoxConfigParser" } DMENU_HOTKEYS_DIR = os.path.dirname(__file__) DMENU_H...
9936839
import cv2 import gym import numpy as np def init_logger(lp): """ Call before using the log function to initialize the log file. """ global log_path log_path = lp f = open(log_path, 'w+') f.close() def log(string): """ Log something to the log file created by `init_logger`...
9936894
import re MSG = re.compile(b'^MSG\s+(?P<subject>[^\s\r\n]+)\s+(?P<sid>[^\s\r\n]+)\s+(?P<reply>([^\s\r\n]+)[^\S\r\n]+)?(?P<size>\d+)\r\n') OK = re.compile(b'^\+OK\s*\r\n') ERR = re.compile(b'^-ERR\s+(\'.+\')?\r\n') PING = re.compile(b'^PING\r\n') PONG = re.compile(b'^PONG\r\n') INFO = re.compile(b'^INFO\s+([^\r\n]+)\r\...
9936914
kleros_abi = [ { "constant": True, "inputs": [], "name": "challengePeriodDuration", "outputs": [{"name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], ...
9936967
import netbox_agent.dmidecode as dmidecode from netbox_agent.config import config from netbox_agent.logging import logging # NOQA from netbox_agent.vendors.dell import DellHost from netbox_agent.vendors.generic import GenericHost from netbox_agent.vendors.hp import HPHost from netbox_agent.vendors.qct import QCTHost f...
9936988
from typing import Callable, Dict, Text, Any import pytest import responses from rasa.engine.graph import ExecutionContext from rasa.engine.storage.resource import Resource from rasa.engine.storage.storage import ModelStorage from rasa.nlu.extractors.duckling_entity_extractor import DucklingEntityExtractor from rasa....
9936992
import cudf import dask_cudf import xgboost # confirm RAPIDS and xgboost are available df = cudf.DataFrame() df['a'] = [0, 1, 2] df['b'] = [1, 2, 3] df['c'] = df.a * df.b + 100 dmat = xgboost.DMatrix(df) # confirm Dask is available ds = dask_cudf.from_cudf(df['c'], npartitions=2) ds.compute()
9937002
import six from chainer.dataset.convert import _concat_arrays from chainer.dataset.convert import to_device def concat_examples(batch, device=None): # batch: img, bboxes, whole_mask, labels, scale if len(batch) == 0: raise ValueError('batch is empty') first_elem = batch[0] result = [] f...