id
stringlengths
3
8
content
stringlengths
100
981k
92650
from armulator.armv6.opcodes.abstract_opcodes.bkpt import Bkpt from armulator.armv6.opcodes.opcode import Opcode from bitstring import BitArray class BkptA1(Bkpt, Opcode): def __init__(self, instruction): Opcode.__init__(self, instruction) Bkpt.__init__(self) def is_pc_changing_opcode(self): ...
92663
from RecoTauTag.RecoTau.pfRecoTauProducerDef_cfi import pfRecoTauProducerDef pfRecoTauProducer = pfRecoTauProducerDef.clone()
92679
from django.dispatch import Signal task_cleanup_signal = Signal(providing_args=['apiview', 'result', 'task_id', 'status', 'obj'])
92690
from datetime import date from decimal import Decimal from openroboadvisor.ledger import Ledger from openroboadvisor.ledger.account import AccountType from openroboadvisor.ledger.asset import Currency, Security from openroboadvisor.ledger.entry import OpenAccount from openroboadvisor.portfolio.account import Account, E...
92763
from detectron2.structures import BoxMode from pathlib import Path import json import cv2 SAL_THR = 0.5 def get_assr_dicts(root, mode): root = Path(root) json_file = root / f"obj_seg_data_{mode}.json" list_file = root / f"{mode}_images.txt" with open(json_file) as f: imgs_anns = json.load(f) ...
92800
from django import forms from .utils import get_coins_list class ChooseCoinToPayForm(forms.Form): currency = forms.ChoiceField(choices=get_coins_list(), widget=forms.RadioSelect(), label='', required=True)
92836
from typing import Any, Dict, Set, cast from functools import cached_property from opensanctions.core.dataset import Dataset from opensanctions.core.source import Source class Collection(Dataset): """A grouping of individual data sources. Data sources are bundled in order to be more useful for list use.""" ...
92846
from .. import config config.setup_examples() import infermedica_api if __name__ == "__main__": api: infermedica_api.APIv3Connector = infermedica_api.get_api() # Prepare the diagnosis request object request = config.get_example_request_data() # call triage method response = api.suggest(**request...
92898
import copy import errno import os import logging import math import torch from torch import nn import torch.nn.functional as F from torch.nn.parallel import DistributedDataParallel from .helper import TensorBoardWriter from .linear_eval import iter_eval_epoch, linear_eval_online, linear_eval_offline from data import...
92963
from typing import Optional, List from seedwork.domain.entities import Aggregate from seedwork.domain.value_objects import UUID from modules.iam.domain.value_objects import Session ANONYMOUS_ID = UUID("00000000-0000-0000-0000-000000000000") class User(Aggregate): id: UUID username: str email: str = "" ...
92981
from django.dispatch import Signal handler_add = Signal(providing_args=["user"]) view_init = Signal(providing_args=["user"])
92983
from torchtext.data.datasets_utils import ( _RawTextIterableDataset, _wrap_split_argument, _add_docstring_header, _download_extract_validate, _create_dataset_directory, _create_data_from_iob, ) import os import logging URL = { 'train': "https://www.clips.uantwerpen.be/conll2000/chunking/tra...
92990
class Solution: def minSteps(self, n: int) -> int: res, m = 0, 2 while n > 1: while n % m == 0: res += m n //= m m += 1 return res
93050
import pytest from django.contrib.auth.models import User from django.urls import reverse from rest_framework.test import APIClient from tests.test_data import DEFAULT_PASSWORD def test_valid_rest_login(client: APIClient, user: User): res = client.post( reverse("rest_login"), {"email": user.email, "passw...
93072
from django.forms import widgets from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from orchestra.api.serializers import SetPasswordHyperlinkedSerializer from orchestra.contrib.accounts.serializers import AccountSerializerMi...
93079
import numpy as np import cv2 from matplotlib import pyplot as plt import glob # for iterating through directories import sys import os path_training_items = '/home/amilan/ownCloud/ARChallenge2017/acrv_apc_2017_data/data/items/Training_items/' #path_training_items = '/home/amilan/ownCloud/ARChallenge2017/acrv_a...
93100
import ctypes import json import html2text import logging import pprint import random import requests import sys import time import traceback from DDPClient import DDPClient from multiprocessing import Manager from multiprocessing.dummy import Process from six.moves.urllib import parse from will import settings from ...
93147
import base64 from typing import Optional from cryptography.hazmat.primitives.ciphers.aead import AESGCM from fidesops.core.config import config from fidesops.util.cryptographic_util import bytes_to_b64_str def encrypt_to_bytes_verify_secrets_length( plain_value: Optional[str], key: bytes, nonce: bytes ) -> byt...
93166
import torch import unittest from qtorch.quant import * from qtorch import FixedPoint, BlockFloatingPoint, FloatingPoint DEBUG = False log = lambda m: print(m) if DEBUG else False class TestStochastic(unittest.TestCase): """ invariant: quantized numbers cannot be greater than the maximum representable number...
93173
import random from dateutil import parser from django.utils import timezone from django.core import signing from .primes import PRIMES SURVEY_TOKEN_SALT = 'salary:survey' SURVEY_TOKEN_MAX_AGE = 60 * 60 * 24 * 7 # 7 days def get_survey_unique_primes(*emails): if len(emails) > len(PRIMES): raise ValueE...
93196
import pandas as pd from enum import Enum class EQUI(Enum): EQUIVALENT = 1 DIF_CARDINALITY = 2 DIF_SCHEMA = 3 DIF_VALUES = 4 """ UTILS """ def most_likely_key(df): res = uniqueness(df) res = sorted(res.items(), key=lambda x: x[1], reverse=True) return res[0] def uniqueness(df): r...
93217
async def say_hello(): print("hey, hello world!") async def hello_world(): print("Resume coroutine.") for i in range(3): await say_hello() print("Finished coroutine.") class MyLoop: def run_until_complete(self, task): try: while 1: task.send(None) ...
93232
import sys import numpy as np import argparse from mung.data import DataSet, Partition PART_NAMES = ["train", "dev", "test"] parser = argparse.ArgumentParser() parser.add_argument('data_dir', action="store") parser.add_argument('split_output_file', action="store") parser.add_argument('train_size', action="s...
93235
import argparse import numpy as np import h5py from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt ''' Usage python plot_trajectory --filename <path to file> If data collector is modified, use extra arguments to modify pose_name: topic name of pose in h5f data action_name: topic of action name...
93242
from abc import ABC, abstractmethod from copy import copy from typing import Any, Optional import numpy as np from gym.spaces import Space from gym.utils import seeding class Operator(ABC): # Set these in ALL subclasses suboperators: tuple = tuple() grid_dependant: Optional[bool] = None action_depe...
93246
from collections import defaultdict def load_words(filename = "words.txt"): with open(filename) as f: for word in f: yield word.rstrip() # return a generator def all_anagram(s): ''' s: string ''' d = defaultdict(list) for i in s: signature = ''.join(sorted(i)) # siganature is a after-sort string of ch...
93288
import datetime import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import Pegasus.db.schema as schema from Pegasus.db.ensembles import EMError, Triggers, TriggerType @pytest.fixture(scope="function") def session(): """ Create in-memory sqlite database with tables setu...
93308
import gym from gym import spaces import cv2 import pygame import copy import numpy as np from overcooked_ai_py.mdp.overcooked_env import OvercookedEnv as OriginalEnv from overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld from overcooked_ai_py.visualization.state_visualizer import StateVisualizer from ov...
93314
from fbrp import life_cycle from fbrp import registrar import argparse @registrar.register_command("down") class down_cmd: @classmethod def define_argparse(cls, parser: argparse.ArgumentParser): parser.add_argument("proc", action="append", nargs="*") @staticmethod def exec(args: argparse.Name...
93338
from diesel.web import DieselFlask, request app = DieselFlask(__name__) @app.route("/") def hello(): name = request.args.get('name', 'world') return "hello, %s!" % name @app.route("/err") def err(): a = b return "never happens.." if __name__ == '__main__': import diesel def t(): whil...
93340
import pytest from pg13 import pgmock_dbapi2, sqparse2 def test_connection(): with pgmock_dbapi2.connect() as a, a.cursor() as acur: acur.execute('create table t1 (a int)') acur.execute('insert into t1 values (1)') acur.execute('insert into t1 values (3)') # test second connction into same DB with p...
93365
from math import sin, pi import random import numpy as np from scipy.stats import norm def black_box_projectile(theta, v0=10, g=9.81): assert theta >= 0 assert theta <= 90 return (v0 ** 2) * sin(2 * pi * theta / 180) / g def random_shooting(n=1, min_a=0, max_a=90): assert min_a <= max_a return [r...
93395
import sys import re import os import fnmatch from os import walk as py_walk def walk(top, callback, args): for root, dirs, files in py_walk(top): callback(args, root, files) def find_data_files(srcdir, destdir, *wildcards, **kw): """ get a list of all files under the srcdir matching wildcards, ...
93456
from os import makedirs from os.path import exists, join from fedot.core.composer.gp_composer.gp_composer import GPComposerBuilder, GPComposerRequirements from fedot.core.data.data import InputData from fedot.core.data.data_split import train_test_data_setup from fedot.core.optimisers.gp_comp.gp_optimiser import GPGra...
93481
from django.apps import AppConfig class PIDConfig(AppConfig): name = 'waldur_pid' verbose_name = 'PID' service_name = 'PID' def ready(self): pass
93490
from starkware.cairo.lang.compiler.ast.cairo_types import ( CairoType, TypePointer, TypeFelt, ) from starkware.cairo.lang.compiler.identifier_definition import StructDefinition from starkware.crypto.signature.signature import FIELD_PRIME def is_felt_pointer(cairo_type: CairoType) -> bool: return isins...
93502
from radixlib.actions import TransferTokens from typing import Dict, Any import unittest class TestTransferTokensAction(unittest.TestCase): """ Unit tests for the TransferTokens action of mutable tokens """ ActionDict: Dict[str, Any] = { "from_account": { "address": "tdx1qspqqecwh3tgsgz92l...
93530
from typing import TypeVar class Config(): SimplexMax: int = 8 Epsilon: float = 1e-5 Max: float = 1e37 PositiveMin: float = 1e-37 NegativeMin: float = -Max Pi: float = 3.14159265 HalfPi: float = Pi / 2.0 DoublePi: float = Pi * 2.0 ReciprocalOfPi: float = 0.3183098861 GeometryEp...
93533
import unittest import datetime as dt from AShareData.config import get_db_interface, set_global_config from AShareData.date_utils import date_type2datetime class MyTestCase(unittest.TestCase): def setUp(self) -> None: set_global_config('config.json') self.db_interface = get_db_interface() d...
93535
import os from os.path import join from collections import OrderedDict templateFile = open('../MaterialDesignIcons/template.xml', 'w') file1 = open('part1.txt', 'r') for line in file1: templateFile.write(line), file1.close() icons_path = "../MaterialDesignIcons/root/material-design-icons" walk = os.listdir(icons...
93541
from datetime import timedelta from jcasts.episodes.emails import send_new_episodes_email from jcasts.episodes.factories import EpisodeFactory from jcasts.podcasts.factories import SubscriptionFactory class TestSendNewEpisodesEmail: def test_send_if_no_episodes(self, user, mailoutbox): """If no recommend...
93548
import django_filters from django.contrib.auth.models import User, Group from rest_framework import viewsets, mixins from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework import filters from api.pagination import LargeResultsSetPagination from api...
93634
from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import TTLocalizer from toontown.battle import DistributedBattleBldg class DistributedCogdoBattleBldg(DistributedBattleBldg.DistributedBattleBldg): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedCogdoBattleBldg') def _...
93640
from datetime import date, timedelta, datetime, time from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.db import models from django.db import connections from django.utils import timezone from .models import Period, StatisticByDate, StatisticByDateAndObject clas...
93643
import discord from discord.ext import commands,tasks import time import json with open('./setting.json', mode='r',encoding='utf8') as jfile: jdata = json.load(jfile) intents = discord.Intents.all() bot=commands.Bot(command_prefix=".",intents=intents) @bot.event async def on_ready(): print('We have logged in...
93649
import os import pytest from ruamel.yaml import YAML _TEST_DIR = os.path.dirname(__file__) # Fixtures in pytest work with reused outer names, so shut up pylint here. # pylint:disable=redefined-outer-name @pytest.fixture def test_file_path(): def loader(*path): return os.path.join(_TEST_DIR, "data", *pa...
93655
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ai_pics', '0002_aiattachment_file_no'), ] operations = [ migrations.AddField( model_name='aipics', name='is_valid', field=models.NullBooleanField(), ...
93701
import os serenityff_C6 = os.path.dirname(__file__) + "/C6/" serenityff_C12 = os.path.dirname(__file__) + "/C12/"
93706
import uuid from django.core.exceptions import ValidationError from django.test import TestCase from app.models import Uuid class UuidTests(TestCase): @classmethod def setUpTestData(cls): cls.uuid_value = uuid.uuid4() Uuid.objects.create(uuid=cls.uuid_value) def test_uuid(self): ...
93726
import sys import logging import argparse import json from blocksec2go import CardError def main(argv=None): if argv == None: argv = sys.argv prog = sys.argv[0] args = sys.argv[1:] parser = argparse.ArgumentParser( prog=prog, description='Command line interface for Infineon\'s...
93738
from video import * import sys header_color='#ffaa00' slide("title.png",48,[(50,"A Novel Mass Spring",header_color), (50,"Model for Simulating",header_color), (50,"Full Hair Geometry",header_color), " ", (36,"paperid 0384"), ...
93748
from common import * def test_virtual_columns_spherical(): df = vaex.from_scalars(alpha=0, delta=0, distance=1) df.add_virtual_columns_spherical_to_cartesian("alpha", "delta", "distance", "x", "y", "z", radians=False) x, y, z = df['x'].values[0], df['y'].values[0], df['z'].values[0] np.testing.asser...
93785
r""" Check for SageMath Python modules """ from . import PythonModule from .join_feature import JoinFeature class sage__combinat(JoinFeature): def __init__(self): # sage.combinat will be a namespace package. # Testing whether sage.combinat itself can be imported is meaningless. # Hence, w...
93798
from django.http import JsonResponse, Http404 from django.shortcuts import redirect def parse_ip_address(request): ipaddress = request.META.get("HTTP_X_REAL_IP") \ or request.META.get("HTTP_X_FORWARDED_FOR") \ or request.environ.get("REMOTE_ADDR") or "" if "," in ipaddress: # multiple ips in...
93804
import csv import shutil from mock import patch from django.core.management import call_command from django.test import TestCase from dmd.models import AMP, AMPP, VMP, VMPP from dmd.management.commands.import_dmd import get_common_name from frontend.models import ImportLog, Presentation, NCSOConcession from openpres...
93813
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from baselines.chac.utils import Base, hidden_init class Critic(Base): def __init__(self, env, level, n_levels, time_scale, device, lr=0.001, gamma=0.98, hidden_size=64): super(Critic, self).__init_...
93853
from tornado.httputil import HTTPServerRequest def query_argument_contains_string(request: HTTPServerRequest, query_argument_name: str, containing_value: str) -> bool: return containing_value in str(request.query_arguments[query_argument_name][0])
93860
import base64 import json import logging import os import pathlib import re import subprocess import tempfile import warnings from collections import defaultdict from typing import Dict, List, Optional, Set, Tuple import backoff import google.auth import google.auth.exceptions import google.auth.transport.requests imp...
93862
from __future__ import print_function def josephus(list_of_players, step): #skipdeadguy step -= 1 index = step while len(list_of_players) > 1: print("Player Died : " , list_of_players.pop(index)) index = (index + step) % len(list_of_players) print('Player Survived : ', list_of_players[0]) def main(): print(...
93888
from __future__ import absolute_import, division, print_function from mmtbx.geometry import topology import unittest class TestAtom(unittest.TestCase): def test_1(self): foo = object() bar = object() a = topology.Atom( foo = foo, bar = bar ) self.assertEqual( a.foo, foo ) self.assertEqual( a...
93913
import sys import os import subprocess import json from utils import get_training_world, unarchive_data from datetime import datetime if __name__ == "__main__": start_time = datetime.now() print('Starting training...') # print("Training started at {}".format(start_time)) world = get_training_world() ...
93915
from .cifar import CIFAR10Instance, PseudoCIFAR10 from .folder import ImageFolderInstance, PseudoDatasetFolder __all__ = ('CIFAR10Instance', 'PseudoDatasetFolder')
93950
import time, random, requests from concurrent.futures import ThreadPoolExecutor class Downloader(object): def __init__( self, workers = 8, tries = 3, sleep = 2, multiplier = 1.5, ): """ Launch a thread pool of workers to ...
93954
import logging import sys from deeplens.struct import VideoStream from deeplens.dataflow.map import Sample from deeplens.ocr.pytesseract import PyTesseractOCR from timeit import default_timer as timer if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) start = timer() if len(sys.argv) < ...
93956
import asyncio import math from concurrent.futures.process import ProcessPoolExecutor from datetime import date from datetime import datetime import pytest from yui.apps.compute.calc import BadSyntax from yui.apps.compute.calc import Decimal as D from yui.apps.compute.calc import Evaluator from yui.apps.compute.calc ...
93958
from whos_there import __version__ def test_version(): # real version initialized in package from poetry and resolved from resources assert __version__ == "0.0.0"
93978
try: # Python 3 from http.client import HTTPResponse, IncompleteRead except (ImportError): # Python 2 from httplib import HTTPResponse, IncompleteRead from ..console_write import console_write class DebuggableHTTPResponse(HTTPResponse): """ A custom HTTPResponse that formats debugging info fo...
93980
import info class subinfo(info.infoclass): def setTargets( self ): self.description = 'Real-time Noise Suppression Plugin' #self.svnTargets["master"] = "https://github.com/werman/noise-suppression-for-voice" ver = "0.91" self.targets[ver] = f"https://github.com/werman/noise-suppress...
93985
import os import re import json import time import numpy as np import pandas as pd from plotnine import * # Config PATH = os.getcwd() path_n = re.split(pattern=r"/|\\", string=PATH)[1:] if os.name == "posix": path_n = "/" + os.path.join(*path_n) else: drive = PATH[0:3] path_n = drive + os.path.join(*path_n...
93987
import pytest from numerous.engine.model import Model from numerous.engine.simulation import Simulation from numerous.utils.logger_levels import LoggerLevel from numerous.multiphysics.equation_base import EquationBase from numerous.multiphysics.equation_decorators import Equation from numerous.engine.system.item import...
94035
from typing import List, Optional import pickle import pandas as pd import numpy as np from pathlib import Path from sklearn.pipeline import Pipeline def fit( X: pd.DataFrame, y: pd.Series, output_dir: str, class_order: Optional[List[str]] = None, row_weights: Optional[np.ndarray] = None, **kw...
94061
from torch import Tensor from torch_geometric.data import Data import torch import torch_geometric.utils as tu from torch_scatter import scatter_add def degree(edge_index: Tensor, direction='out', num_nodes=None, edge_weight=None): """calulcates the degree of each node in the graph Args: edge_index ...
94064
import re from wagtail import __version__ as WAGTAIL_VERSION def is_wagtail_version_more_than_equal_to_2_5(): expression = '^((2.([5-9]{1,}|([1-9]{1,}[0-9]{1,}))(.\d+)*)|(([3-9]{1,})(.\d+)*))$' return re.search(expression, WAGTAIL_VERSION) def is_wagtail_version_more_than_equal_to_2_0(): expression = '^((2.([0-...
94065
import re import string from collections import Counter from pathlib import Path from gutenberg_cleaner import simple_cleaner from more_itertools import windowed import nltk from gender_analysis.text import common class Document: """ The Document class loads and holds the full text and metadata (author,...
94077
import arcpy import pandas as pd import os fc = r"C:\\temp\\GasPipelineEnterpriseDataManagement\\Databases\\UPDM_UtilityNetwork.gdb\\UtilityNetwork\\PipelineLine" field_group_name = 'Limit Material By Asset Type' def view_cav(table, subtype_field): index = ['fieldGroupName', 'subtype', 'isRetired', 'id'] dat...
94079
import itertools class Solution: def combinationSum(self, k, n): ls = [] for c in itertools.combinations(range(1, 10), k): s = sum(c) if s > c: break elif s == c: ls.append(list(c)) return ls
94095
from reprojection import runSuperGlueSinglePair,image_pair_candidates, runSIFTSinglePair from ray_dist_loss import preprocess_match, proj_ray_dist_loss_single import torch import numpy as np import os from random import random import numpy as np import torch import torchvision.transforms as TF import matplotlib.pypl...
94102
from .utils import ( find_offending_time_points, temporal_variance_mask, generate_summarize_tissue_mask, NuisanceRegressor ) from .nuisance import ( create_regressor_workflow, create_nuisance_regression_workflow, filtering_bold_and_regressors ) from .bandpass import ( bandpass_voxels )...
94103
import librosa import numpy as np import matplotlib.pyplot as plt from sys import argv script, content_audio_name, style_audio_name, output_audio_name = argv N_FFT=2048 def read_audio_spectum(filename): x, fs = librosa.load(filename, duration=58.04) # Duration=58.05 so as to make sizes convenient S = librosa.stft(x...
94113
import six class InvalidPaddingError(Exception): pass class Padding(object): """Base class for padding and unpadding.""" def __init__(self, block_size): self.block_size = block_size def pad(self, value): raise NotImplementedError('Subclasses must implement this!') def unpad(se...
94148
from . import api from flask import render_template @api.route('/', methods=['GET']) def index(): # example of a route with HTML templating message = "Hello, World" entries = [] entries.append({"title":"entry 1", "text":"text 1 ?</>"}) entries.append({"title":"entry 2", "text":"text 2 ?</>"}) r...
94172
from datetime import datetime from utils import build_accuracy import tempfile import tensorflow as tf import tensorflow.contrib.slim as slim flags = tf.app.flags FLAGS = flags.FLAGS class OneStreamTrainer(object): def __init__(self, model, logger=None, display_freq=1, learning_rate=0.0001, nu...
94175
from django.contrib import admin from .models import * admin.site.register(Location) admin.site.register(Conference) admin.site.register(Section) admin.site.register(Speaker) admin.site.register(Lecture) admin.site.register(Speech) admin.site.register(Comment) # Register your models here.
94212
from dpipe.predict.functional import * def test_chain_decorators(): def append(num): def decorator(func): def wrapper(): return func() + [num] return wrapper return decorator @append(1) @append(2) @append(3) def f(): return [] ...
94235
import os import gettext from . import db LOCALEDIR = os.path.join(os.path.dirname(__file__), 'locales') langcodes = [ f for f in os.listdir(LOCALEDIR) if os.path.isdir(os.path.join(LOCALEDIR, f)) ] translates = { lang: gettext.translation('main', LOCALEDIR, [lang]) for lang in langcodes } languages = ...
94242
from graphviz import Digraph dot = Digraph( comment='First flowchart', name='<NAME>', filename='hello_world.dot', ) dot.node('1', 'Inicio') dot.node('2', '"<NAME>"', shape='invhouse') #dot.node('2', '"<NAME>"', shapefile='assets/print.svg') dot.node('3', 'Fin') dot.node('4', 'Fin 2') dot.edge('1', '2') #...
94307
from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import names from nltk.stem import WordNetLemmatizer import glob import os import numpy as np file_path = 'enron1/ham/0007.1999-12-14.farmer.ham.txt' with open(file_path, 'r') as infile: ham_sample = infile.read() print(ham_sample) fil...
94332
from bitmovin_api_sdk.encoding.encodings.live.insertable_content.schedule.schedule_api import ScheduleApi
94355
import contextlib import os import re import shlex import subprocess from behave import * ANSI_ESCAPE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") def strip_ansi_codes(inp): return ANSI_ESCAPE.sub("", inp) @contextlib.contextmanager def pushd(new_dir): old_dir = os.getcwd() os.chdir(new_dir) yield ...
94396
import numpy as np from .qnumber import is_qsparse __all__ = ['retained_bond_indices', 'split_matrix_svd', 'qr'] def retained_bond_indices(s, tol): """ Indices of retained singular values based on given tolerance. """ w = np.linalg.norm(s) if w == 0: return np.array([], dtype=int) # ...
94397
import copy import inspect import itertools import types import warnings from typing import Any, Dict import numpy as np from axelrod import _module_random from axelrod.action import Action from axelrod.game import DefaultGame from axelrod.history import History from axelrod.random_ import RandomGenerator C, D = Acti...
94398
from django.test import TestCase from newsletter.models import Subscriber class NewsletterModelTest(TestCase): """ Test suite for customer model """ def setUp(self): """ Set up test database """ Subscriber.objects.create(email='<EMAIL>', confirmed=True) Subscriber.objects.cr...
94403
from typing import List import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from chemcharts.core.container.chemdata import ChemData from chemcharts.core.plots.base_plot import BasePlot, _check_value_input from chemcharts.core.utils.value_functions import generate_value from c...
94436
from django.conf.urls.defaults import * from satchmo_store.urls import urlpatterns urlpatterns += patterns('', (r'test/', include('simple.localsite.urls')) )
94438
from scipy.stats import multivariate_normal as normal import numpy as np from time import time from experiments.lnpdfs.create_target_lnpfs import build_target_likelihood_planar_n_link from sampler.SliceSampling.slice_sampler import slice_sample num_dimensions = 10 conf_likelihood_var = 4e-2 * np.ones(num_dimensions) c...
94449
import logging from openeye import oechem, oeszybki, oeomega from torsion.utils.process_sd_data import get_sd_data, has_sd_data from torsion.dihedral import get_dihedral TORSION_LIBRARY = [ '[C,N,c:1][NX3:2][C:3](=[O])[C,N,c,O:4] 0 180', # amides are flipped cis and trans '[#1:1][NX3H:2][C:3...
94454
import asyncio import hashlib import json import re import ssl import websocket import websockets class OKCoinWSPublic: Ticker = None def __init__(self, pair, verbose): self.pair = pair self.verbose = verbose @asyncio.coroutine def initialize(self): TickerFirstRun = True while True: i...
94477
from ethereum.utils import sha3, encode_hex class EphemDB(): def __init__(self, kv=None): self.reads = 0 self.writes = 0 self.kv = kv or {} def get(self, k): self.reads += 1 return self.kv.get(k, None) def put(self, k, v): self.writes += 1 self.kv[k...
94503
import torch class DistributionLayer(torch.nn.Module): """A distribution layer for action selection (e.g. for actor-critic)""" def __init__(self, action_space, input_size): """Initializes the distribution layer for the given action space and input_size (i.e. the output size of the model) ...
94507
import unittest from canvas_sdk.exceptions import CanvasAPIError class TestExceptions(unittest.TestCase): longMessage = True def setUp(self): self.default_api_error = CanvasAPIError() def test_default_status_for_canvas_api_error(self): """ Test expected default status for instance of C...