id
stringlengths
3
8
content
stringlengths
100
981k
11452935
from c2nl.inputters.vocabulary import EOS_WORD, BOS_WORD class Summary(object): """ Summary containing annotated text, original text, a list of candidate documents, answers and well formed answers. """ def __init__(self, _id=None): self._id = _id self._text = None self._to...
11452967
import typing from urllib.parse import urlencode class VkException(Exception): pass class VkAuthError(VkException): def __init__( self, error, description, url: str = "", params: typing.Any = "" ): self.error = error self.description = description self.url = "{}?{}".forma...
11453051
from __future__ import absolute_import, division, print_function from joblib import delayed, Parallel import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor import multiprocessing import threading import warnings...
11453064
def sequentialSearch(alist, item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos+1 return found testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequentialSearch(testlist, 3)) print(s...
11453068
import cPickle model=cPickle.load(open('lstm_tanh_relu_[1468202263.38]_2_0.610.p')) cPickle.dump(model,open('model.bin.nlg','wb'))
11453071
import time import os.path as osp import numpy as np import torch import torch.nn.functional as F from model.trainer.base import Trainer from model.trainer.helpers import ( get_dataloader, prepare_model, prepare_optimizer, ) from model.utils import ( pprint, ensure_path, Averager, Timer, count_acc, com...
11453108
from twisted.internet.task import react from twisted.internet.defer import inlineCallbacks as coroutine from autobahn.twisted.wamp import Connection session = ApplicationSession() @session.on_join def on_join(session): print("Session {} has joined".format(session.id)) @session.on_leave def on_leave(session, deta...
11453119
import torch import torch.nn as nn class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, device): """ :param input_size: 5 which is OHLC + trend """ super(EncoderRNN, self).__init__() self.device = device self.hidden_size = hidden_size sel...
11453193
import pandas as pd import numpy as np from scipy.io.wavfile import read as read_wav import librosa import os from sklearn.preprocessing import MinMaxScaler def preprocessing_audio(data_info_path, audio_path): sampleRate = 16000 # Ziel Samplefrequence in Hz cutAudio = 0.3 # je am ...
11453195
from unittest import mock from django.test import TestCase from django.test.utils import override_settings from django.core import mail from django.core.mail.backends.base import BaseEmailBackend from django.utils import translation from geotrek.feedback.parsers import SuricateParser from geotrek.feedback.factories i...
11453212
import numpy as np import dlib import glob import cv2 import os os.chdir('/media/imi-yujun/579e63e9-5852-43a7-9323-8e51241f5d3a/yujun/Course_porject_fac e') def LoadBase(): predictor_path = 'Network/shape_predictor_68_face_landmarks.dat' detector = dlib.get_frontal_face_detector() predictor = dlib.shape_p...
11453254
import unittest, time, sys, random sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_import as h2i, h2o_jobs, h2o_rf class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init(3) @classmethod def te...
11453266
import FWCore.ParameterSet.Config as cms def customizeHLTforMC(process): """adapt the HLT to run on MC, instead of data see Configuration/StandardSequences/Reconstruction_Data_cff.py which does the opposite, for RECO""" # PFRecHitProducerHCAL if 'hltParticleFlowRecHitHCAL' in process.__dict__: process.h...
11453268
import torch import torch.nn as nn import torchvision.transforms as transforms import numpy as np import cv2 from functools import partial def get_image(path, torch_img=True): """ if torch_img == True: return image that can be directly used by our CNN model else: return numpy resize image ...
11453284
from __future__ import absolute_import, unicode_literals import logging import imagehash import numpy as np import pytest from PIL.Image import Image from psd_tools.api.psd_image import PSDImage from ..utils import full_name logger = logging.getLogger(__name__) QUALITY_TEST_FILES = [ # ('mask-index.psd',), # ...
11453291
import re from six import string_types # for 2-3 compatibility import types from numbers import Number core_types = [ ] class SchemaError(Exception): pass class SchemaMismatch(Exception): pass class SchemaTypeMismatch(SchemaMismatch): def __init__(self, name, desired_type): SchemaMismatch.__init__(self, ...
11453337
from .arrayfuncs import ( reshape_1d_to_2d, convert_sparse_matrix, ) from .exceptions import ( DimensionalityError, UnknownCategoryError, NotInstalledError, NotBucketedError, NotPreBucketedError, NotBucketObjectError, BucketingPipelineError, BucketerTypeError, ) from .dataframe i...
11453344
from django.db import models from django.template.defaultfilters import slugify from datetime import datetime # Create your views here. class Doctorant(models.Model): nationaliter = models.CharField(max_length=50,null=False) nom = models.CharField(max_length=50,null=False) prenom = models.CharField(max_len...
11453383
import os import pdb from buche import BucheDb global_interactor = None if os.environ.get("BUCHE"): class BuDb(BucheDb): def __init__(self, **kw): super().__init__(None) self.interactor = global_interactor def set_trace(self, frame=None): self.interactor.sho...
11453412
import sys from collections import * files=[("base","results/marvin_results_base.txt"),("large","results/marvin_results_large.txt")] by_model={} conditions=set() for title,fname in files: lines = open(fname) results=defaultdict(Counter) by_model[title]=results skipped = set() for line in lines: ...
11453439
import time import numpy as np import pinocchio as pin from numpy.linalg import det, eig, inv, norm, pinv, svd import vizutils # COST 3D ##################################################################### class Cost3d: def __init__(self, rmodel, rdata, frameIndex=None, ptarget=None, viz=None): self.rm...
11453449
import ast from pyflakes.checker import Checker as PyFlakesChecker from wemake_python_styleguide.checker import Checker code_that_breaks = ''' def current_session( telegram_id: int, for_update: bool = True, ) -> TelegramSession: """ Was triggering `AttributeError`. See: https://github.com/wemake...
11453479
import base64 import hashlib import importlib import json import logging from urllib.parse import parse_qs from urllib.parse import urlparse from urllib.parse import urlsplit from urllib.parse import urlunsplit import uuid from cryptography.fernet import Fernet from cryptojwt import as_unicode from cryptojwt.utils imp...
11453495
import sys if sys.platform == 'darwin': from ..lib.platform.darwin.link_opener import * elif sys.platform == 'win32': from ..lib.platform.win32.link_opener import * elif sys.platform in ('linux', 'linux2'): from ..lib.platform.linux.link_opener import * else: from ..lib.platform.unsupported.link_opener...
11453523
import os import scipy.sparse as sp DIR_NAME = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'data', 'noisy_diff') NOISY_DIFF_PATH = { 'citeseer': { '2500': os.path.join( DIR_NAME, 'citeseer-diff-2500.npz'), '5000': os.path.join( DIR_NAME, 'citesee...
11453554
import abc from typing import get_type_hints from flash.core.serve._compat import cached_property class BaseType(metaclass=abc.ABCMeta): """Base class for Types. Any Grid Types must be inherited from this class and must implement abstract methods. The constructor (or the initializer for pythonistas) can...
11453558
class AbstractEventHandler: """ Abstract class for basic functionality required of an event handler. Inherit from this when creating your custom event handlers! """ def __init__(self): self.instance = None self.debug = False def setup(self, instance, debug: bool): self...
11453577
from . import ( db, definitions, hyper_params, logger, music, slider, timing, utils )
11453579
import pika import multiprocessing import threading import os import signal import sys import json import socket from init_client import handle_config,rabbitmq_detail key = '<KEY>' handle_config(key) from time import sleep from connection import manage_connection from database_management import manage_...
11453585
from ariadne import InterfaceType from graphql import GraphQLObjectType from .base import RelayConnectionType class RelayInterfaceType(RelayConnectionType, InterfaceType): def bind_resolvers_to_graphql_type( self, graphql_type: GraphQLObjectType, replace_existing: bool = True ) -> None: super...
11453620
import stgfunc as stg import kagefunc as kgf import vapoursynth as vs from typing import Tuple core = vs.core def get_detail_mask(clip_y: vs.VideoNode) -> vs.VideoNode: return core.std.Expr([ stg.mask.generate_detail_mask(clip_y, 0.013), kgf.kirsch(clip_y) ], "x y -") def get_linemasks(clip_y: vs.V...
11453633
from rest_framework import serializers from downloads.models import OS, Release, ReleaseFile class OSSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = OS fields = ('name', 'slug', 'resource_uri') class ReleaseSerializer(serializers.HyperlinkedModelSerializer): class ...
11453642
from orm_choices import choices @choices class ArticleStatus: class Meta: UNPUBLISHED = [1, "Not published yet"] PUBLISHED = [2, "Published"] REVIEW_REQUIRED = [3, "To be reviewed"] DELETED = [4, "Deleted"]
11453659
import pandas as pd import yaml class Dict2Class(object): def __init__(self, dvar, def_topvar): if not isinstance(dvar, dict) or not dvar: setattr(self, def_topvar, None) return for key in dvar: if isinstance(dvar[key], list): nested_dclass = []...
11453680
def test_shocksine(): """ tests against expected sharpclaw results """ import shocksine from clawpack.pyclaw.util import test_app, check_diff def verify_shocksine(controller): """ given an expected value, returns a verification function """ import numpy as np import os ...
11453686
import unittest from deployer.query import Q, Query, QueryResult from deployer.node import Node, Env from deployer.exceptions import QueryException, ActionException from .our_hosts import LocalHost def get_query_result(query, instance): return query._execute_query(instance).result class ExpressionTest(unittes...
11453696
import os import unittest import docker # The DOCKER_IMAGE envvar is needed to specify what # image to test # The `docker` library gives all output from containers as raw bytes, so # we need to use byte string literals for comparison/membership tests SOCKET_PATH = b"/tmp/statsd.socket" COMMON_ENVIRONMENT = [ "D...
11453703
s = input() upper = [] lower = [] odd_digit = [] even_digit = [] for i in s: if i.isupper(): upper.append(i) elif i.islower(): lower.append(i) elif i.isdigit(): if int(i) % 2 == 0: even_digit.append(i) else: odd_digit.append(i) l = [upper, lower, odd_...
11453722
import os import re from copy import deepcopy import numpy as np from snapgene_reader import snapgene_file_to_seqrecord from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord try: # Biopython <1.78 from Bio.Alphabet import DNAAlphabet has_dna_alphabet = True except ImportError: # Biopython >=1....
11453741
import pytest from tests.communication.test_CommBase import TestComm as base_class class TestForkComm(base_class): r"""Tests for ForkComm communication class.""" test_error_send = None test_error_recv = None test_work_comm = None test_send_recv_raw = None @pytest.fixture(scope="class", autou...
11453758
from flask import Flask # Ozellikle POST metodunda gonderilen body icerigini almak icin isimize yarayacak from flask import request import jsonschema from jsonschema import validate # JSON schema kontrolu icin kullanabiliriz from flask import jsonify # JSONlastirma destegi icin app = Flask(__name__) # baslangic icin...
11453763
from PIL import Image, ImageDraw import numpy as np from glob import glob from os import path import csv def tile_intersect_patch(x0, y0, sx0, sy0, x1, y1, sx1, sy1): if x0 > x1 + sx1 or x1 > x0 + sx0: return False if y0 > y1 + sy1 or y1 > y0 + sy0: return False return True def info2patch_...
11453825
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import i2c, sensor from esphome.const import ( CONF_BUS_VOLTAGE, CONF_CURRENT, CONF_ID, CONF_POWER, CONF_SHUNT_RESISTANCE, CONF_SHUNT_VOLTAGE, DEVICE_CLASS_VOLTAGE, DEVICE_CLASS_CURRENT, DEVIC...
11453835
import sys sys.path.append('..') import os import scipy.io as scio import numpy as np import theano import theano.tensor as T import lasagne import h5py import shutil import json from time import time from PIL import Image from lib.data_utils import processing_img, convert_img_back, convert_img, Batch, shuffle, iter...
11453890
from nltk import word_tokenize from marmot.features.feature_extractor import FeatureExtractor from marmot.exceptions.no_data_error import NoDataError class PseudoReferenceFeatureExtractor(FeatureExtractor): ''' A feature that extracts the pseudo-reference feature for pseudo-references provided in a file...
11453921
from docs_snippets_crag.concepts.assets.materialization_jobs import my_user_model_job def test_pipelines_compile_and_execute(): jobs = [my_user_model_job] for job in jobs: result = job.execute_in_process() assert result.success
11453937
from pathlib import Path from hyperstyle.src.python.review.inspectors.inspector_type import InspectorType from hyperstyle.src.python.review.inspectors.issue import CodeIssue, IssueDifficulty, IssueType from hyperstyle.src.python.review.reviewers.utils.issues_filter import filter_duplicate_issues def test_filter_dupl...
11454033
import time import logging from botocore.exceptions import ClientError import boto3 LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) def codepipeline_success(job_id): """ Puts CodePipeline Success Result """ try: codepipeline = boto3.client('codepipeline') codepipeline.put_jo...
11454048
import numpy as np from pytheas import Scatt3D # import numpy.testing as npt from testutils import * def model(verbose=False): fem = Scatt3D() fem.rm_tmp_dir() fem.eps_des = 2 - 0 * 1j fem.hx_des = 3 fem.hy_des = 3 fem.hz_des = 0.5 fem.hx_box = fem.hx_des * 1.1 fem.hy_box = fem.hy_des...
11454052
import pytest from unittest.mock import Mock from collections import OrderedDict from nbformat.v4 import new_code_cell from .. import translators from ..exceptions import PapermillException from ..models import Parameter @pytest.mark.parametrize( "test_input,expected", [ ("foo", '"foo"'), (...
11454076
import torch from mmseg.models.utils import DropPath def test_drop_path(): # zero drop layer = DropPath() # input NLC format feature x = torch.randn((1, 16, 32)) layer(x) # input NLHW format feature x = torch.randn((1, 32, 4, 4)) layer(x) # non-zero drop layer = DropPath(0...
11454125
import cv2 import numpy as np import matplotlib.pyplot as plt # Canny def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian f...
11454137
class Dog: def __init__(self, name): self.name = name def speak(self): print("Woof! My name is", self.name) dog_one = Dog('Rover') dog_two = Dog('Rex') dog_one.speak() dog_two.speak()
11454145
import abc import tempfile from .. import Subject, ScalarImage from ..utils import get_torchio_cache_dir from ..download import download_and_extract_archive class VisibleHuman(abc.ABC, Subject): URL = 'https://mri.radiology.uiowa.edu/website_documents/visible_human_tar_files/{}{}.tar.gz' # noqa: E501, FS003 ...
11454205
from typing import Optional, Set, Dict, Type, Union from .base import Base from .list import List from .map import Map, MapWrapper from .reference import Reference, ReferenceXOR from .string import String from .version import Version class Entity(MapWrapper): # This must be overridden in derived classes ATTR...
11454228
from integration.helpers.base_test import BaseTest class TestFunctionWithHttpApi(BaseTest): def test_function_with_http_api(self): self.create_and_verify_stack("combination/function_with_http_api") stack_outputs = self.get_stack_outputs() base_url = stack_outputs["ApiUrl"] self.ve...
11454240
import numpy as np from flare.kernels.kernels import ( force_helper, force_energy_helper, grad_helper, three_body_fe_perm, three_body_ee_perm, three_body_se_perm, three_body_ff_perm, three_body_sf_perm, three_body_ss_perm, three_body_grad_perm, grad_constants, ) from numba im...
11454242
import sys import re import pysam import shutil import os import gzip from multiprocessing import Pool from optparse import OptionParser from collections import Counter from contextlib import contextmanager opts = OptionParser() usage = "usage: %prog [options] [inputs] Script to process aligned .bam files to 1) spli...
11454294
from hathor.graphviz import GraphvizVisualizer from tests import unittest from tests.simulation.base import SimulatorTestCase from tests.utils import add_custom_tx, gen_new_tx class BaseConsensusSimulatorTestCase(SimulatorTestCase): def checkConflict(self, tx1, tx2): meta1 = tx1.get_metadata() met...
11454313
IS_QT_5 = False if IS_QT_5: from PySide2 import QtGui, QtCore, QtWidgets IS_QT_5 = True else: from PySide import QtGui, QtCore import PySide.QtGui as QtWidgets import time # common used classes QComboBox = QtWidgets.QComboBox QTableWidgetItem = QtWidgets.QTableWidgetItem QDoubleSpinBox = QtWidgets.QD...
11454349
import discord from discord.ext import commands import os from .utils.dataIO import dataIO from cogs.utils import checks from __main__ import send_cmd_help import asyncio import time import re from .utils.chat_formatting import pagify, box try: from tabulate import tabulate except Exception as e: raise RuntimeE...
11454422
import re import warnings from typing import Any, Dict, Optional, Tuple, Type, TypeVar, Union from neo4j import Driver, GraphDatabase from pandas import Series from pandas.core.frame import DataFrame from .call_builder import CallBuilder from .direct_endpoints import DirectEndpoints from .error.unable_to_connect impo...
11454424
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from .utils import lang_names def get_page_desc(_id): """Builds the first big text card that introduces users to the page""" return [ dbc.Row( children=[ dbc.Col([ ...
11454437
from ..remote import RemoteModel class ChangeSummaryNetworkAnalysisGridRemote(RemoteModel): """ This table provides a summary of the changes identified by NetMRI. | ``id:`` The internal NetMRI identifier of the grid entry. | ``attribute type:`` number | ``ChangeTime:`` The EARLIEST date/time...
11454510
from amaranth.asserts import * import warnings warnings.warn("instead of nmigen.asserts, use amaranth.asserts", DeprecationWarning, stacklevel=2)
11454534
import os import sys from datetime import datetime import csv import json # Layer code, like parsing_lib, is added to the path by AWS. # To test locally (e.g. via pytest), we have to modify sys.path. # pylint: disable=import-error try: import parsing_lib except ImportError: sys.path.append( os.path.joi...
11454582
from config import OptimizerConfig from lib import tf_util, util from player.aiplayer import AIPlayer from time import time, sleep try: import _pickle as pickle except: import pickle import glob def start(): config = OptimizerConfig() tf_util.update_memory(config.gpu_mem_fraction) util.set_high_proce...
11454644
import os import random import torch import torch.utils.data as data import torchvision.transforms as T from PIL import Image class LowLightFDataset(data.Dataset): def __init__(self, root, image_split='images_aug', targets_split='targets', training=True): self.root = root self.num_instances = 8 ...
11454750
import six from django.db.models import Case, When, Q, F, Sum, CharField, Value from django.db.models.functions import Coalesce from django.shortcuts import _get_queryset from django_pivot.utils import get_column_values, get_field_choices, default_fill def pivot(queryset, rows, column, data, aggregation=Sum, choices...
11454764
import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F Vis_REGISTER = {} class SimpleConvNetwork(nn.Module): def __init__(self, visual_dim): super().__init__() self.net = nn.Sequential( nn.Conv2d(visual_dim[-1], 16, kernel_size=8, stride=4), ...
11454774
class Constants: DATABASE_PATH = "deepluna_db.json" ALLSCR_MRG = "allscr.mrg" SCRIPT_TEXT_MRG = "script_text.mrg" EXPORT_DIRECTORY = "export/" IMPORT_DIRECTORY = "import/" LEGACY_IMPORT_DIRECTORY = "update/" CHARS_PER_LINE = 55
11454817
from django.http import Http404 from django.views.generic import ListView, DetailView, FormView from django.utils.translation import ugettext_lazy as _ from rest_framework import generics from .serializers import SongSerializer from .models import Song from .forms import SongFilterForm class SongList(ListView, Form...
11454833
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import tensorflow_hub as hub import h5py import json import sys def build_elmo(): token_ph = tf.placeholder(tf.string, [None, None]) len_ph = tf.placeholder(tf.in...
11454867
import requests import pandas as pd import glob import json import time import os def pull_ridership_by_stop(line_number): """ Pull the ridership data from the local files - only get the fields we care about, sorted, and return the Dataframe. """ # allFiles = glob.glob('.' + "/gps_*.csv") fram...
11454875
import collections import sys from pathlib import Path from tqdm import tqdm import torch from torch import nn from torch import optim from torch.utils.data import DataLoader from modelzoo import get_model from experiments.utils.training import evaluate, update from experiments.utils.logging import Logger from experi...
11454902
from .em_rvm import EMRVR, EMRVC from ._version import __version__ __all__ = ['EMRVR', 'EMRVC', '__version__']
11454963
import csv import os from rdr_service.config import LOCALHOST_DEFAULT_BUCKET_NAME from rdr_service.api_util import open_cloud_file, list_blobs from rdr_service.dao.participant_dao import ParticipantDao from rdr_service.offline.table_exporter import TableExporter from rdr_service.participant_enums import make_primary_p...
11454964
import ctypes import pandas lib = ctypes.CDLL('./numpypandas.dll') increase = lib.increase increase.argtypes = [ ctypes.POINTER(ctypes.c_longlong), ctypes.c_longlong, ctypes.c_longlong, ] people = pandas.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'age': [20, 30, 40], }) # First we check t...
11454969
import datetime import unittest from localstack.utils.aws import aws_stack DEFAULT_TASK_LIST = {"name": "default"} class TestSwf(unittest.TestCase): def setUp(self): self.swf_client = aws_stack.create_external_boto_client("swf") self.swf_unique_id = datetime.datetime.now().isoformat() s...
11454987
import click import yaml from . import driver from ckan_cloud_operator import logs @click.group() def jenkins(): """Interact with a Jenkins server""" pass @jenkins.command() @click.argument('JENKINS_USER') @click.argument('JENKINS_TOKEN') @click.argument('JENKINS_URL') @click.argument('POST_JSON_DATA', req...
11454998
import torch from .utils import * # === Import model-related objects === from comvex.perceiver import Perceiver # === Instantiate your Model === # - For single model model = Perceiver( data_shape=[3, 224, 224], cross_heads=1, num_latent_tokens=32, dim=128, heads=4, layers_indice=[0] + [1]*7,...
11455020
import FWCore.ParameterSet.Config as cms process = cms.Process("CSC HLT DQM") #------------------------------------------------- # DQM Module Configuration #------------------------------------------------- process.load("DQM.CSCMonitorModule.csc_hlt_dqm_sourceclient_cfi") #---------------------------- # Event Sourc...
11455037
from poop.hfdp.decorator.pizza.pizza import Pizza class ThincrustPizza(Pizza): def __init__(self) -> None: self.description = "Thin crust pizza, with tomato sauce" def cost(self) -> float: return 7.99
11455067
from setuptools import setup, find_packages import sys if sys.version_info < (3,): sys.exit("Sorry, Python3 is required.") with open("README.md", encoding="utf8") as f: readme = f.read() with open('requirements.txt') as f: install_reqs = f.read().splitlines() setup( name="nlpaug", version="1.1.1...
11455071
import argparse import os import numpy as np import scipy.misc as ssc import kitti_util import imageio def project_disp_to_depth(calib, disp, max_high, baseline=0.54): disp[disp < 0] = 0 mask = disp > 0 depth = calib.f_u * baseline / (disp + 1. - mask) rows, cols = depth.shape c, r = np.meshgrid(...
11455085
import os import tempfile from unittest import mock, TestCase import gdal2tiles class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self class OptionParserInputOutputTest(TestCase): def test_vanilla_input_output(self): ...
11455156
import re import sys import traceback from typing import NoReturn import pytest from .._util import ( bytesify, LocalProtocolError, ProtocolError, RemoteProtocolError, Sentinel, validate, ) def test_ProtocolError() -> None: with pytest.raises(TypeError): ProtocolError("abstract b...
11455179
import time import yaml from pathlib import Path import matplotlib import numpy as np import yaml matplotlib.use('Agg') import matplotlib.pyplot as plt import torch import torch.utils.data from torch.utils import tensorboard from liegroups.torch import SO3 from deeplio import datasets as ds from deeplio.common im...
11455198
import sys import argparse import json def main(args): json.dump([line.strip('\n') for line in args.ifile], args.ofile) if __name__=='__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--ifile', type = argparse.FileType('r'), ...
11455290
from math import sqrt from numba import njit import numpy as np import flare.kernels.cutoffs as cf from flare.kernels.kernels import coordination_number, q_value_mc @njit def get_2_body_arrays( positions, atom: int, cell, r_cut, cutoff_2, species, sweep, nspecie, species_mask, ...
11455311
def count_Binary_One(arr,low,high): if high>=low: mid = low + (high-low)//2 if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)): return mid+1 if arr[mid]==1: return count_Binary_One(arr, (mid+1), high) return count_Binary_One(arr, low, mid-1) return 0 arr=list(map(int, input("Enter NUMS with ...
11455317
from __future__ import absolute_import import logging import contextlib import itertools from collections import namedtuple from huskar_api.models.auth import Application from huskar_api.models.const import SELF_APPLICATION_NAME from .const import (TYPE_SITE, TYPE_TEAM, TYPE_APPLICATION, TYPE_CONF...
11455344
import pytest from openbb_terminal.settings_controller import SettingsController # pylint: disable=W0621 @pytest.fixture() def controller(mocker): mocker.patch( "openbb_terminal.settings_controller.obbff.USE_PROMPT_TOOLKIT", True, ) mocker.patch("openbb_terminal.settings_controller.sessi...
11455345
import pytest from brownie import chain, history from brownie.test import given, strategy from hypothesis import settings WEEK = 86400 * 7 YEAR = 86400 * 365 @pytest.fixture(scope="module", autouse=True) def setup(gauge_controller, accounts, three_gauges, token, voting_escrow): # We handle setup logic in a fixtu...
11455388
from __future__ import print_function import six from tempfile import mkdtemp from shutil import rmtree from os.path import join from subprocess import CalledProcessError from dark.diamond.conversion import FIELDS, DiamondTabularFormat from dark.process import Executor from dark.utils import cd def diamondInstalle...
11455406
from verta import Client client = Client('https://dev.verta.ai') client.set_project('Demo - Jenkins+Prometheus') client.set_experiment('Demo') run = client.set_experiment_run() class Predictor(object): def __init__(self): pass def predict(self, X): return X run.log_model(Predictor())
11455407
import random import typing from typing import List, Callable from hearthstone.simulator.agent.actions import StandardAction, generate_standard_actions, BuyAction, EndPhaseAction, \ SummonAction, DiscoverChoiceAction, RearrangeCardsAction, FreezeDecision, RerollAction, \ SellAction, TavernUpgradeAction, HeroPo...
11455497
from .client import DockerClient from .container import DockerContainer from .image import DockerImage __all__ = [ "DockerClient", "DockerContainer", "DockerImage", ]
11455508
import os import sys import tensorflow as tf sys.path.append('./TFext/models/slim') from datasets import dataset_utils from nets import inception from preprocessing import inception_preprocessing from coco_loss import coco_loss_layer slim = tf.contrib.slim url = 'http://download.tensorflow.org/models/inception_v3_2016...
11455521
import pytest import numpy as np import os.path import sofa import scipy.io.wavfile as wavfile from pyfar.samplings import SphericalVoronoi from pyfar import Orientations from pyfar import Coordinates from pyfar import FrequencyData, TimeData import pyfar.classes.filter as fo import pyfar.signals from pyfar.testing i...