id
stringlengths
3
8
content
stringlengths
100
981k
3325319
import spacy nlp = spacy.load("de_core_news_sm") text = "Apple wurde 1976 von <NAME>, <NAME> und <NAME> gegründet." # Verarbeite den Text doc = ____ # Iteriere über die vorhergesagten Entitäten for ent in ____.____: # Drucke den Text und das Label der Entität print(ent.____, ____.____)
3325334
def sprint(*arg,end="\n",sep = " "): if(len(arg)==0): print(end=end,sep=sep) return for ele in arg[:len(arg)-1]: res = str(ele) if(len(res)>3000): print(res[:1000]+"\n"+"......\n"+"...... (%d characters)\n" %(len(res)-2000)+"......\n"+res[len(res)-1000:],end=se...
3325348
from polyphony import testbench class C: def __init__(self, x, y): self.x = x self.y = y def field02(x, y): c = C(x, y) a = c.x + c.y c.x = 10 return a + c.x @testbench def test(): assert 13 == field02(1, 2) assert 15 == field02(2, 3) assert 17 == field02(3, 4) test()...
3325412
import pytest from openeo.internal.graph_building import PGNode from openeo.rest.connection import Connection import openeo def test_raster_to_vector(con100): img = con100.load_collection("S2") vector_cube = img.raster_to_vector() vector_cube_tranformed = vector_cube.process_with_node(openeo.UDF("python s...
3325424
import unittest import sys from PyQt5.QtWidgets import QApplication, QDialog from ui import RemoveVendorDialog app = QApplication(sys.argv) remove_vendor_dialog = QDialog() remove_vendor_dialog_ui = RemoveVendorDialog.Ui_dialog_remove() remove_vendor_dialog_ui.setupUi(remove_vendor_dialog) class RemoveVendorDialogTe...
3325433
from jarray import array from java.lang import String from java.lang import Class from org.myrobotlab.service import Clock from org.myrobotlab.service import Log from org.myrobotlab.service import Runtime from org.myrobotlab.framework import Message # inputTest.py # example script for MRL showing Python Service # inpu...
3325466
import numpy as np from threading import Thread import rospy from geometry_msgs.msg import Pose from geometry_msgs.msg import Twist from ControlLaw import ControlLawDiff class RobotControl(Thread): def __init__(self, loop_rate=10): Thread.__init__(self) self.period = 1.0/loop_rate self....
3325494
from pytorch_complex_tensor.complex_scalar import ComplexScalar from pytorch_complex_tensor.complex_grad import ComplexGrad from pytorch_complex_tensor.complex_tensor import ComplexTensor
3325550
from rest_framework.pagination import PageNumberPagination class CustomPageNumberPagination(PageNumberPagination): page_size = 1 max_page_size = 1
3325575
from azaka.commands import VNCondition as VNC from azaka.commands.proxy import _BoolOProxy def test_cdns() -> None: expr = '(((id >= 0) and (search ~ "*")) or (id = [1, 2, 3]))' proxy = ((VNC.ID >= 0) & (VNC.SEARCH % "*")) | (VNC.ID_ARRAY == [1, 2, 3]) assert isinstance(proxy, _BoolOProxy) assert prox...
3325588
from cliport.models.resnet import ResNet43_8s from cliport.models.clip_wo_skip import CLIPWithoutSkipConnections from cliport.models.rn50_bert_unet import RN50BertUNet from cliport.models.rn50_bert_lingunet import RN50BertLingUNet from cliport.models.rn50_bert_lingunet_lat import RN50BertLingUNetLat from cliport.model...
3325589
import torch import util_funcs as uf def torch_f1_score(pred, target, n_class): ''' Returns macro-f1 and micro-f1 score Args: pred: target: n_class: Returns: ma_f1,mi_f1: numpy values of macro-f1 and micro-f1 scores. ''' def true_positive(pred, target, n_class...
3325606
import argparse import inspect import numpy as np import theano from matplotlib import pyplot as plt from scipy.signal import convolve2d from scipy.stats import multivariate_normal from time import time from theano import d3viz from kusanagi.ghost import regression from kusanagi import utils np.set_printoptions(linew...
3325648
import sys import numpy as np from . import discriminative_sequence_classifier as dsc import pdb class CRFOnline(dsc.DiscriminativeSequenceClassifier): """ Implements a first order CRF""" def __init__(self, observation_labels, state_labels, feature_mapper, regularizer=0.00001, ...
3325651
from __future__ import print_function import inspect import pkgutil import six from rdopkg import exception from rdopkg.utils import log if six.PY2: inspect_getargspec = inspect.getargspec else: inspect_getargspec = inspect.getfullargspec class Arg(object): def __init__(self, name, **kwargs): se...
3325662
import logging import graphene from atlas.models import Profile class EmployeeTypeEnum(graphene.Enum): NONE = "" FULL_TIME = "Full-time" CONTRACT = "Contract" INTERN = "Intern" class EmployeeTypeNode(graphene.ObjectType): id = graphene.String() name = graphene.String() num_people = gra...
3325664
import numpy as np from numpy import zeros, abs, min, sign, ceil, ones, pi, cos, sin from pymoo.core.problem import Problem class SYMPARTRotated(Problem): """ The SYM-PART test problem proposed in [1]. Parameters: ----------- length: the length of each line (i.e., each Pareto subsets), default i...
3325670
import tensorflow as tf from tensorflow.contrib import slim from tensorflow.contrib.slim.python.slim.nets.vgg import vgg_16 as slim_vgg_16 from tensorflow.contrib.slim.python.slim.nets.vgg import vgg_arg_scope from nninst import Graph from nninst.backend.tensorflow.graph import build_graph from nninst.utils.fs import ...
3325695
from .TestCase import TestCase from .MockInput import MockInput from .HttpTestResponse import HttpTestResponse from .DatabaseTransactions import DatabaseTransactions
3325716
from collections import namedtuple from typing import NamedTuple from ztom import core from ztom import errors from ztom import TradeOrder import copy import uuid import time class ActionOrderSnapshot(NamedTuple): symbol: str = "" amount: float = 0.0 price: float = 0.0 side: str = "" status: str =...
3325725
import time import numpy as np def OnlyEven(*numbers): """Solo retorna los pares""" EVENS=[n for n in numbers if n%2==0] return EVENS def long_line(x): h = x**3 * np.cos(x/42) res = x*5*h+3*np.cos(4 + x**2*np.sin(x)) - np.tan(x)*(np.pi/180*x+x/np.exp(x)) return class Animal: def _...
3325732
from youtube_livechat_messages.utils import isostr_to_datetime class EventType: # Todo: Support more events textMessageEvent = "textMessageEvent" superChatEvent = "superChatEvent" fanFundingEvent = "fanFundingEvent" class Author: def __init__(self, author_json): self.raw_json = author_j...
3325756
import re # Taken from http://build.fhir.org/references.html (2.3.0.1). # Note 1: Additional set of parenthesis placed after the closing slash on _history and end # Note 2: '$' added to the end of of the string # Note 3: Additional set of parenthesis placed on the resource identifier portion # TODO: Find a mech...
3325760
import setuptools def readme(): with open('README.md') as f: README = f.read() return README setuptools.setup( name='hungarian_algorithm', version='0.1.11', author='<NAME>', author_email='<EMAIL>', description='Python 3 implementation of the Hungarian Algorithm for the assignment problem.', long_description...
3325779
import torch import torch.nn as nn class LinMod(nn.Linear): '''Linear modules with or without batchnorm, all in one module ''' def __init__(self, n_inputs, n_outputs, bias=False, batchnorm=False): super(LinMod, self).__init__(n_inputs, n_outputs, bias=bias) if batchnorm: self.b...
3325784
import torch import numpy as np from collections import OrderedDict class Seq(torch.nn.Sequential): ''' Seq uses sequential module to implement tree in the forward. ''' def give(self, xg, num_layers_boosted, ep=0.001): ''' Saves various information into the object for further usage in ...
3325790
import numpy as np from numpy.random import rand import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') from matplotlib import pyplot as plt from solutions import sqrt64 def invsqrt64(A, reps): Ac = A.copy() if 0 < reps: Ac2 = A.copy() Ac2 /= - 2 ...
3325853
from pysolr import * import socket import logging log = logging.getLogger('solr') from contextlib import contextmanager class SolrResultsPaginator(object): """Offers an iterator on Solr results. You simply provide a configured pysolr `Solr` instance, a query, and the default parameters. This class takes c...
3325861
import FWCore.ParameterSet.Config as cms from L1TriggerConfig.L1ScalesProducers.L1MuTriggerScalesConfig_cff import * from L1TriggerConfig.L1ScalesProducers.L1MuTriggerPtScaleConfig_cff import * from L1TriggerConfig.L1ScalesProducers.L1MuGMTScalesConfig_cff import * from L1TriggerConfig.GMTConfigProducers.L1MuGMTParame...
3325892
import torch from openchem.modules.embeddings.openchem_embedding import OpenChemEmbedding class OneHotEmbedding(OpenChemEmbedding): def __init__(self, params): super(OneHotEmbedding, self).__init__(params) if self.padding_idx is not None: weight = torch.eye(self.num_embeddings - 1) ...
3325926
from typing import List import torch from ..utils.box import jaccard_vectorized def generate_prediction_table( preds: List[torch.Tensor], targets: List[torch.Tensor] ) -> List[torch.Tensor]: """Generates prediction table Args: preds (List[torch.Tensor]): list of predictions as [torch.Tensor(N,5...
3325929
from functools import reduce from os import listdir from os.path import join, splitext from re import M from re import search as re_search from typing import Any, Union from docopt import docopt from snakypy.helpers.ansi import FG, NONE from snakypy.helpers.logging import Log from snakypy.zshpower import __info__ fro...
3325935
import numpy as np import torch def get_batches(model, sentences, max_batch, tagset, training=True): """ Partitions a list of sentences (each a list containing [word, label]) into a set of batches Returns: -- batched_sents: original tokens in sentences -- batched_orig_token_lens: length of original tokens in...
3325972
from __future__ import annotations import enum from typing import cast, List, Sequence, Tuple, Union, TYPE_CHECKING, Any if TYPE_CHECKING: from arkouda.categorical import Categorical import numpy as np # type: ignore from typeguard import typechecked, check_type from arkouda.client import generic_msg from arkouda.p...
3325975
def main(request, response): headers = [(b"Content-Type", b"text/javascript"), (b"Cache-Control", b"private, no-store")] id = request.GET.first(b"id") with request.server.stash.lock: status = request.server.stash.take(id) if status is None: status = 200 ...
3326014
from OSIsoftPy.client import client import datetime import random from time import sleep # arguments piWebApi = 'https://applepie.dstcontrols.local' verifySSL = False server = client(piWebApi, authenticationType='kerberos', verifySSL=verifySSL).PIServers()[0] testTag = "AlansPythonTestTag" testTag2 = "AlansPythonTes...
3326034
from bs4 import BeautifulSoup import requests import json import re from .base import ScribdBase from .. import internals from .. import const from .. import exceptions class Track: """ A class for an audio chapter in a Scribd audiobook playlist. Parameters ---------- track: `dict` A dic...
3326050
from django.core.management.base import BaseCommand from fluff.pillow import FluffPillowProcessor from pillowtop.utils import get_pillow_by_name class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'pillow_name', ) parser.add_argument( ...
3326056
from src.subscriber.aggregation.user.contributions import get_contributions from src.subscriber.aggregation.user.follows import get_user_follows from src.subscriber.aggregation.user.package import get_full_user_data, get_user_data from src.subscriber.aggregation.wrapped.package import main as get_wrapped_data __all__ ...
3326065
import pytest import yaml from argo_workflow_tools import dsl, Workflow @dsl.Task(image="python:3.10") def say_hello(name: str): message = f"hello {name}" return message @dsl.DAG() def command_hello(name): message = say_hello(name) return message def test_diamond_params_run_independently(): w...
3326102
from .detector3d_template import Detector3DTemplate from ...utils import loss_utils, common_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import os from torch.nn.modules.batchnorm import _BatchNorm class PointRCNNMe...
3326106
from pathlib import Path from morelia.config import TOMLConfig from morelia.formatters import ( Buffered, FileOutput, RemoteOutput, TerminalOutput, TextFormat, ) fixtures_dir = Path(__file__).parent / "fixtures" def test_creates_writers(): config = TOMLConfig("terminals", filename=fixtures_d...
3326109
import pickle import socket import time from netqasm.logging.glob import get_netqasm_logger from netqasm.sdk.classical_communication.socket import Socket as _Socket from simulaqron.general.host_config import SocketsConfig from simulaqron.settings import simulaqron_settings class Socket(_Socket): RETRY_TIME = 0....
3326120
import mafs import json fs = mafs.MagicFS() fs.add_argument('file', help='json file to read from') # read json file with open(fs.args.file) as f: items = json.load(f) def dig(d, parts): if parts: try: res = d.get(parts[0]) if res: return dig(res, parts[1:]) ...
3326156
import torch # import numpy as np from options.train_options import TrainOptions import util.util as util import os from PIL import Image import glob mask_folder = 'masks/testing_masks' test_folder = './datasets/Paris/test' util.mkdir(mask_folder) opt = TrainOptions().parse() f = glob.glob(test_folder+'/*.png') prin...
3326172
import logging import os.path import random import socket import string import time import uuid import docker import pytest from bitshares import BitShares from bitshares.account import Account from bitshares.asset import Asset from bitshares.exceptions import AccountDoesNotExistsException, AssetDoesNotExistsException...
3326190
from Zhihu.NN.one.Network import * from Zhihu.NN.Layers import * from Util.Util import DataUtil np.random.seed(142857) # for reproducibility def main(): nn = NNDist() epoch = 1000 x, y = DataUtil.gen_xor(100) nn.add(ReLU((x.shape[1], 24))) nn.add(CrossEntropy((y.shape[1],))) nn.fit(x, y...
3326235
from drl_grasping.utils import conversions from geometry_msgs.msg import Transform from rclpy.executors import MultiThreadedExecutor from rclpy.node import Node from rclpy.parameter import Parameter from sensor_msgs.msg import PointCloud2 from threading import Thread from typing import List, Tuple import numpy as np im...
3326252
from django import forms import json from workflows.models import AbstractWidget class ImportForm(forms.Form): data = forms.CharField(widget=forms.Textarea(attrs={'class':'formfieldclass'})) def clean_data(self): def get_all_abstract_widgets(jsondata,awset): widgets = jsondata.g...
3326308
functions = { 'Abort': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' } ], 'returns': 'ViStatus' }, 'CheckAcquisitionStatus': { 'parameters': [ { 'dir...
3326315
import os,sys, getopt,re badlyNamedProperties = ["kOfxImageEffectFrameVarying", "kOfxImageEffectPluginRenderThreadSafety"] def getPropertiesFromDir(sourcePath, recursive, props): if os.path.isdir(sourcePath): files=sorted(os.listdir(sourcePath)) for f in files: absF = sourcePath + '/'...
3326339
from pyspark.sql import DataFrame from datafaucet.data import _Data from datafaucet.spark import dataframe class Data(_Data): def collect(self, n=1000, axis=0): res = self.df.select(self.columns).limit(n).toPandas() return res.T if axis else res def scd_analyze(self, merge_on=None, **kwargs)...
3326359
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from siamban.core.config import cfg from siamban.tracker.siamban_tracker import SiamBANTracker TRACKS = { 'SiamBANTracker': SiamBANTracker } def bui...
3326397
from enumfields.drf.fields import EnumField as EnumSerializerField from enumfields.fields import EnumFieldMixin from rest_framework.fields import CharField, ChoiceField, IntegerField class EnumSupportSerializerMixin: enumfield_options = {} enumfield_classes_to_replace = (ChoiceField, CharField, IntegerField) ...
3326399
class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return max(nums[-1]*nums[-2]*nums[-3], nums[-1]*nums[0]*nums[1])
3326432
class Option: """ Represents an option to add to a Command object """ def __init__(self, name: str, description: str, type: int, required: bool): self.name = name self.description = description self.type = type self.required = required self.choices = [] ...
3326467
import xlrd # from paddlenlp.embeddings import TokenEmbedding import paddlehub as hub import numpy as np concernKey1 = ['n', 'nr', 'nz', 'PER', 'ns', 'LOC', 's', 'nt', 'ORG', 'nw'] concernKey2 = ['v'] lac = hub.Module(name="lac") # test_text = "还记得你之前跟我说,我能及格猪都能上树。可教练我拿到驾照了,猪不仅能上树还能上高速,我再给你来个倒车入库,压线了难受不?以前...
3326473
import fbuild.config.c as c # ------------------------------------------------------------------------------ class readline_h(c.Test): header = c.header_test('readline/readline.h')
3326486
from registrasion.models import commerce from registrasion.models import inventory from django.db.models import Case from django.db.models import F, Q from django.db.models import Sum from django.db.models import When from django.db.models import Value from .batch import BatchController from operator import attrgett...
3326516
from contextlib import contextmanager from multiprocessing.dummy import threading, Pool as ThreadPool # ThreadLocal _local = threading.local() @contextmanager def acquire(*args): # 以id将锁进行排序 args = sorted(args, key=lambda x: id(x)) # 确保不违反以前获取的锁顺序 acquired = getattr(_local, 'acquired', []) if ac...
3326538
from distutils.core import setup setup(name='onnx2keras', version='0.1', py_modules=['onnx2keras'], )
3326554
import torch from torch import nn from torch.nn import functional as F from lib.layers.wrappers import make_act, make_conv, make_norm class PPM(nn.Module): def __init__(self, dim_in, ppm_dim=512, pool_scales=(1, 2, 3, 6), **kwargs): """ :param dim_in: (int) input tensor channel :param p...
3326565
import unittest from tests.core import TestCore from pyrep.sensors.gyroscope import Gyroscope class TestGyroscope(TestCore): def setUp(self): super().setUp() self.sensor = Gyroscope('gyroscope') def test_read(self): angular_velocities = self.sensor.read() self.assertEqual(len...
3326576
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from models.tools import load_data # path path_to_data = "data/" path_to_submissions = "submissions/" path_to_stacking = "stacking/" path_to_plots = "plots/" # tuned hyper-parameters parameters = { "criterion": ...
3326581
from fabric.api import * @task @roles('app_all') def remove_original_settings_files(repo, site): with settings(warn_only=True): run("rm -R /var/www/%s/www/sites/%s/*.settings.php" % (repo, site)) print "===> Removed *.settings.php from initial autoscale app folders"
3326597
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 from langdetect import detect_langs def detect_language(text): res = detect_langs(text) md = "### Detected languages (probability):\n" langs = [] for line in res: lang = str(line).split(':')[0] ...
3326643
import os from config import cfg root = '/home/opt603a/gjy_netdisk/seg/cityscape dataset' raw_img_path = os.path.join(root, 'leftImg8bit_trainvaltest/leftImg8bit') raw_mask_path = os.path.join(root, 'gtFine_trainvaltest/gtFine') processed_path = os.path.join(cfg.DATA.ROOT, 'City') processed_train_path = os.path.join(p...
3326648
import numpy as np import torch from torch import nn import sys import util class DataLoader(nn.Module): """Data loader module for training MCFlow Args: mode (int): Determines if we are loading training or testing data seed (int): Used to determine the fold for cross validation experiments or r...
3326653
from bokeh.models import PolyDrawTool, PolyEditTool from bokeh.plotting import figure, output_file, show output_file("tools_poly_edit.html") p = figure(x_range=(0, 10), y_range=(0, 10), width=400, height=400, title='Poly Edit Tool') p1 = p.patches([], [], fill_alpha=0.4) p2 = p.patches([[1, 2, 3]], [[3, 5...
3326678
import pyorient.ogm.property from .element import GraphElement import pyorient.ogm.what from .operators import LogicalConnective, ArithmeticOperation class ArgConverter(object): """Convert query function argument to expected string format""" Label = String = Format = 0 Expression = 1 Field = 2 Ve...
3326685
import tensorflow as tf def cin_layer(x0, xk, hk_1, index): """ xdeepfm模型的Compressed Interaction Network部分 Args: x0 (tensor): 原始输入tensor, shape=(batch, m, D) xk (tensor): 上一CIN层输出tensor, shape=(batch, hk, D) hk_1 (int): 本层输出维度, 也是feature map个数 index (int): 序号 Retur...
3326709
from .vit_tiny_patch16_224 import model model.patch_size = 32 model.embed_dim = 768 model.num_heads = 12
3326771
mc_version = "1.15.2" mc_file_md5 = "1d87e7d75a99172f0cffc4f96cdc44da" of_file_name = "1.15.2_HD_U_G1_pre15" of_file_md5 = "0127f841a34f112b20889ccf81063adf" of_build_md5 = "788146cce32fe9b23b4d3d9e12953388" minecrift_version_num = "1.15.2" minecrift_build = "jrbudda-3-b13" of_file_extension = ".jar" mcp_version = "mcp...
3326787
from modules.base import BaseModule, registerModule from sources import * from sources.base import SourceSelector, BaseSource from utils.command import OptionParser @registerModule class RealUrl(BaseModule): name = "RealUrl" selector = SourceSelector(Wenku8TXT, KakadmSource, ...
3326801
from typing import List import pytest from sqlalchemy.orm import Session from app.enums.userenums import UserStatus from app.models import usermodels from app.service import userservice from app.service.passwordservice import verify_password from tests import common, factories def test_create(db_session: Session): ...
3326824
import argparse import json import os import random import scipy.io import codecs import numpy as np import cPickle as pickle from collections import defaultdict from nltk.tokenize import word_tokenize import re def gatherCandidates(params,nSamples=-1,skipSet = set()): eval_names = {} n_evals = params['n_evals'] ...
3326835
import os.path as osp from tqdm import tqdm from copy import deepcopy import torch import dgl from torch.utils.data import DataLoader, Dataset from dgl import DGLGraph, NID from dgl.dataloading.negative_sampler import Uniform from dgl import add_self_loop from utils import drnl_node_labeling class GraphDataSet(Datase...
3326843
from sharpy.combat import MicroStep, Action from sc2 import AbilityId from sc2.unit import Unit from sc2.units import Units class MicroOverseers(MicroStep): def group_solve_combat(self, units: Units, current_command: Action) -> Action: return current_command def unit_solve_combat(self, unit: Unit, cu...
3326852
import random import time import string from client_app.pages.dataset_listing.dataset_listing_page import DatasetListingPage from client_app.pages.project_listing.project_listing_page import ProjectListingPage from selenium import webdriver from tests.constants_enums.constants_enums import ProjectConstants from client...
3326879
from typing import Optional from keycloak_admin_aio._lib.utils import remove_none from keycloak_admin_aio.types import GroupRepresentation from .... import ( AttachedResources, KeycloakResource, KeycloakResourceWithIdentifierGetter, ) from .by_id import UsersByIdGroupsById class UsersByIdGroups(Keycloak...
3326882
from binascii import hexlify from logging import getLogger from struct import unpack from sqlite_dissect.constants import FILE_TYPE from sqlite_dissect.constants import LOGGER_NAME from sqlite_dissect.constants import PAGE_TYPE from sqlite_dissect.carving.carver import SignatureCarver from sqlite_dissect.version_histor...
3326920
import pytest from cloudvolume.lru import LRU import time import random def test_lru(): lru = LRU(5) assert len(lru) == 0 for i in range(5): lru[i] = i assert len(lru) == 5 for i in range(5): lru[i] = i for i in range(100): lru[i] = i assert len(lru) == 5 lru.resize(10) for i in ra...
3326927
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if t < 0 or k == 0: return False cache = {} for i in xrange(len(nums)): k...
3326980
from enum import Enum import json from typing import Dict from api.db.models.base import BaseSchema class IssueCredentialProtocolType(str, Enum): v10 = "v1.0" v20 = "v2.0" class CredentialType(str, Enum): anoncreds = "anoncreds" json_ld = "json_ld" class CredentialRoleType(str, Enum): issuer ...
3327018
import bson import requests import struct import wav2letter class w2l_engine: def __init__(self, path=None): if path is None: path = os.path.join(os.path.dirname(__file__), 'w2l') w2l_loader = wav2letter.W2lLoader(path) self.model = w2l_loader.load() def decode(self, sample...
3327044
import graphene from django.core.exceptions import ValidationError from ....core.permissions import OrderPermissions from ....order import OrderStatus, models from ....order.error_codes import OrderErrorCode from ...core.types import OrderError from ..types import Order from .draft_order_create import DraftOrderCreate...
3327065
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.morley import morley def test_morley(): """Test module morley.py by downloading morley.csv and testing shape of extracted data has 100 row...
3327082
from pychecker2.Check import Check from pychecker2.util import BaseVisitor from pychecker2.Warning import Warning from compiler import ast, walk from types import * import re class UnknownError(Exception): pass def _compute_node(node, recurse): if isinstance(node, ast.Add): return recurse(node.left) + rec...
3327087
from simglucose.simulation.user_interface import simulate from simglucose.controller.base import Controller, Action class MyController(Controller): def __init__(self, init_state): self.init_state = init_state self.state = init_state def policy(self, observation, reward, done, **info): ...
3327098
from gitlabform.gitlab.projects import GitLabProjects class GitLabProjectBadges(GitLabProjects): def get_project_badges(self, project_and_group_name): badges = self._make_requests_to_api( "projects/%s/badges", project_and_group_name, expected_codes=200, ) ...
3327118
from IPython.display import display, HTML from IPython.display import Markdown as md import qgrid DEFAULT_GRID_OPTIONS = dict(enableColumnReorder=True) def dataframe(df, grid_options=None): if grid_options is None: grid_options = DEFAULT_GRID_OPTIONS if len(df) == 0: html = HTML( ...
3327140
import pandas as pd import matplotlib.pyplot as plt import numpy as np import argparse import os import sys from typing import List, Dict, Any """ Count connections between data types """ def count_contents(data_summary_folder, all_versions, all_years): if all_versions and all_years: FILE_PATH = 'all_cves...
3327164
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import time from utils import * SESS_CONF = tf.ConfigProto(allow_soft_placement=True) SESS_CONF.gpu...
3327179
from collections import defaultdict, OrderedDict class LFUCache: def __init__(self, capacity: int): self.rank = defaultdict(OrderedDict) self.key_to_rank = dict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.key_to_rank: return -1 return...
3327210
def run(verbose=False): from os import path import pytest args = [path.dirname(__file__)] if verbose: args.append('--verbose') return pytest.main(args)
3327250
import torch from transformers import RobertaTokenizer, RobertaModel, RobertaConfig from transformers.modeling_roberta import RobertaForSequenceClassification, RobertaClassificationHead from experiment.bert_utils import BertWrapperModel from experiment.qa.model import BaseModel from torch import nn class RobertaSigmo...
3327265
import torch from .Lanczos import symeigLanczos class DominantSymeig(torch.autograd.Function): """ Function primitive of dominant real symmetric eigensolver, where the matrix is represented in normal form as a torch.Tensor. input: A -- the real symmetric matrix A. k -- number of Lan...
3327273
from json import loads, dumps, JSONEncodeException, JSONDecodeException from proxy import ServiceProxy, JSONRPCException
3327299
import pytest try: import submission except ImportError: pass def test_passes(): """This test should pass""" assert submission.return_true() def test_fails(): """This test should fail""" assert submission.return_false() @pytest.mark.timeout(5) def test_loops(): """This test should time...
3327337
from os.path import dirname, join _root = dirname(__file__) _models_path = join(_root, "asdf") ID2VEC = join(_models_path, "id2vec_1000.asdf") DOCFREQ = join(_models_path, "docfreq_1000.asdf") QUANTLEVELS = join(_models_path, "quant.asdf") BOW = join(_models_path, "bow.asdf") COOCC = join(_models_path, "coocc.asdf") ...