id
stringlengths
3
8
content
stringlengths
100
981k
9861458
import pickle from revscoring.datasources.datasource import Datasource from revscoring.datasources.meta import gramming from revscoring.dependencies import solve my_tokens = Datasource("my_tokens") my_grams = gramming.gram(my_tokens, grams=[(0,), (0, 2)]) def test_gramming(): assert (solve(my_grams, cache={my_t...
9861485
import tkinter as tk from PIL import Image, ImageTk class LikeButton(tk.Button): def __init__(self, master, *args, **kwargs): self.title = kwargs.pop('title') self.album = kwargs.pop('album') self.url = kwargs.pop('url') self.artist = kwargs.pop('artist') tk.Button.__init__...
9861545
import numpy as np import gurobipy as grb from gurobipy import GRB import tqdm import time from typing import List from ..utils.storage import AnnParameters from .modeling_interface import ModelingInterface class GurobiModelingInterface(ModelingInterface): """Interface for creating a Gurobi optimization model fr...
9861562
import glob import os import re import psycopg2 from pg_view.loggers import logger from pg_view.models.parsers import ProcNetParser from pg_view.utils import STAT_FIELD, dbversion_as_float def read_postmaster_pid(work_directory, dbname): """ Parses the postgres directory tree and extracts the pid of the postmas...
9861576
import numpy as np import pygeos import pytest from .common import point from .common import line_string from .common import linear_ring from .common import polygon from .common import polygon_with_hole from .common import multi_point from .common import multi_line_string from .common import multi_polygon from .common...
9861602
import numpy as np import tensorflow as tf import unittest import tcellmatch.api as tm class _TestFfnBinary_Base(unittest.TestCase): def _test_ffn( self, model: str, cost: str = "bce", label_smoothing: float = 0.1, aa_embedding_dim=None, tr...
9861627
import os from asyncio import sleep from jupyter_server.base.handlers import JupyterHandler import tornado class XarrayLeafletHandler(JupyterHandler): def set_default_headers(self): self.set_header('Content-Type', 'image/png') self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, ...
9861641
import numpy as np import os from urllib.request import urlretrieve from tensorflow import keras MNIST_PATH = "./mnist.npz" def load_mnist(path="./mnist.npz", norm=True): if not os.path.isfile(path): print("not mnist data is found, try downloading...") urlretrieve("https://s3.amazonaws.com/img-da...
9861645
from ..norm_exceptions import BASE_NORMS from ...attrs import NORM, LIKE_NUM # fmt: off _stem_suffixes = [ ["ो", "े", "ू", "ु", "ी", "ि", "ा"], ["कर", "ाओ", "िए", "ाई", "ाए", "ने", "नी", "ना", "ते", "ीं", "ती", "ता", "ाँ", "ां", "ों", "ें"], ["ाकर", "ाइए", "ाईं", "ाया", "ेगी", "ेगा", "ोगी", "ोगे", "ाने", ...
9861648
class Solution: def diffWaysToCompute(self, input: str) -> List[int]: f = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y } @lru_cache(None) def dfs(l: int, r: int): if l >= r: return [] result ...
9861735
from shutil import copyfile path = ["Build/", "../../../out/build/x64-Release/bin/"] files = [ "mimalloc-override.dll", "mimalloc-redirect.dll", "LC_DXBackend.dll", ] def CopyFiles(): for i in files: fromPath = path[0] + i toPath = path[1] + i copyfile(fromPath, toPath) p...
9861738
import FWCore.ParameterSet.Config as cms trackingMaterialAnalyser = cms.EDAnalyzer("TrackingMaterialAnalyser", MaterialAccounting = cms.InputTag("trackingMaterialProducer"), SplitMode = cms.string("NearestLayer"), SkipBeforeFirstDetector = cms.bool(False), SkipAfterLastDetector = c...
9861783
from django.contrib.gis.geos import Point from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "SOL" addresses_name = "2021-04-07T11:17:55.688819/Democracy_Club__06May2021.CSV" stations_name = "2021-04-07T11:17:55...
9861798
from blocks.bricks import Rectifier from blocks.initialization import IsotropicGaussian, Constant import itertools, numpy from math import sin, cos MEANS = [numpy.array([cos(id * numpy.pi * 2 / 8), sin(id * numpy.pi * 2 / 8)]) for id in range(8)] VARIANCES = [0.01 ** 2 * numpy.eye(len(mean)) for mean in MEANS] config...
9861799
import time def make_cache_value(result, ttl): return result, time.time() + ttl def is_cache_value_valid(value): return time.time() < value[1] def retrieve_result_from_cache_value(value): return value[0]
9861807
import pytest import numpy as np import tensorflow as tf from mock import Mock, mock from tfsnippet.bayes import BayesianNet from tfsnippet.distributions import Normal from tfsnippet.stochastic import StochasticTensor class BayesianNetTestCase(tf.test.TestCase): def test_observed_dict(self): # test no o...
9861819
TEMPLATE = """ import numpy as np from sapsan.core.abstrctions.dataset import Dataset class {name}Dataset(Dataset): def load(self): return np.random.random((4, 4)) """ def get_template(name: str): return TEMPLATE.format(name=name.capitalize())
9861843
import requests BASE_URL = "http://127.0.0.1:5000" def test_index_request(session): res = requests.get(f"{BASE_URL}") assert(res.status_code == 200) def test_jsonify(session): r = requests.get(f"{BASE_URL}/jsonify") assert r.json()=={"hello":"world"} assert r.status_code==200 def test_html(sessi...
9861850
import sys, logging, time, resource, gc, os import multiprocessing from multiprocessing import Pool from util import print_datetime import numpy as np import gurobipy as grb import torch def estimateWeightsWithoutNeighbor(YT, M, XT, prior_x, sigma_yx_inv, X_constraint, dropout_mode, irepli): logging.info(f'{print_d...
9861860
def contains(self, value): cur = head for i in range(0, itemCount): cur = cur.nextNode if cur.value == value: return True return False
9861896
import os from tkinter import * from casymda.visualization.canvas.tk_canvas import ScaledCanvasTk from casymda.visualization.process_visualizer import ProcessVisualizer from examples.wait_for_interrupt.model import Model from simpy import Environment FLOW_SPEED = 2 ** 20 def test_visualized_run(): if os.name !=...
9861913
from OpenNero import * def createInputMapping(): ioMap = PyIOMap() ioMap.ClearMappings() # bind our keys from common.module import openWiki ioMap.BindKey("KEY_F1", "onPress", openWiki('RunningOpenNero')) ioMap.BindKey("KEY_ESCAPE", "onHold", lambda: getSimContext().killGame()) return ioMap
9861921
import bottle from bottle import route, run app = bottle.default_app() @route('/') def hello_world(): return "Hello, world! (From Full Stack Python)" if __name__ == '__main__': run(host="0.0.0.0", port=8080, debug=True, reloader=True)
9862003
from datetime import datetime from timeit import default_timer as timer import numpy as np import pandas as pd from great_expectations.dataset.pandas_dataset import PandasDataset np.random.seed(42) N_ROWS = 1_000_000 COL_NAME = "x" N = 10 INT_MIN = 0.0 INT_MAX = 10_000 FLOAT_MIN = 0.0 FLOAT_MAX = 10_000.0 DT_MIN...
9862046
import torch import numpy as np def get_gradient(A, y, x): (n ,d) = A.size() tmp = y - torch.mm(A, x.view(d, -1)) return - torch.mm(A.t(), tmp.view(n, -1)) / np.float(n) def get_loss(A, y, x): (n ,d) = A.size() return torch.sum(torch.pow(y.view(n, -1) - torch.mm(A, x.view(d, -1)), 2)) def nnls(A,...
9862052
import unittest import requests import time from test_tasks_base import TestTasksBase #from multiprocessing.dummy import Pool as ThreadPool import threading class TestTasksConcurrent(TestTasksBase): def single_task_create(self): task = self.create_task(0, 1) self.assertEqual(task['state'], 'CREA...
9862070
from ..factory import Type class passportElements(Type): elements = None # type: "vector<PassportElement>"
9862216
import nlu from nlu.discovery import Discoverer from nlu.pipe.utils.storage_ref_utils import StorageRefUtils from typing import List, Tuple, Optional, Dict, Union import streamlit as st from nlu.utils.modelhub.modelhub_utils import ModelHubUtils import numpy as np import pandas as pd from nlu.pipe.viz.streamlit_viz.str...
9862258
from glrm.loss import QuadraticLoss from glrm.reg import NonnegativeReg, QuadraticReg from glrm import GLRM from glrm.util import pplot from numpy.random import randn, choice, seed from numpy.random import choice from itertools import product from numpy import sign # Generate problem data m, n, k = 20, 20, 5 eta = 0.1...
9862413
from __future__ import print_function import argparse from pyne.utils import QA_warn QA_warn(__name__) def main(): parser = argparse.ArgumentParser("Generates PyNE API") parser.add_argument('--debug', action='store_true', default=False) parser.add_argument('--enrich', action='store_true', default=False) ...
9862422
from collections import OrderedDict import hashlib from django.db import models from django.conf import settings from django.urls import reverse from django.utils.safestring import mark_safe import jsonfield from model_utils.models import TimeStampedModel from tworaven_apps.utils.basic_response import (ok_resp, err_...
9862449
import torch import math import numpy as np import pandas as pd import torch.nn.functional as F import os import json import matplotlib.pyplot as plt from models.dynamic_net import Vcnet, Drnet, TR from models.itermidate_models import VcnetAtt, VcnetAttv2 from models.DisCri import DisCri from datas.data import get_it...
9862464
import numpy as np from advent.dataset.base_dataset import BaseDataset class GTA5DataSet(BaseDataset): def __init__(self, root, list_path, set='all', max_iters=None, crop_size=(321, 321), mean=(128, 128, 128), num_classes=19): super().__init__(root, list_path, set, max_i...
9862470
import argparse import importlib import pkgutil import sys from typing import List import monitoring from monitoring.prober import infrastructure # Import all tests def import_submodules(package, recursive=True): """ Import all submodules of a module, recursively, including subpackages :param package: package (...
9862521
import os from enum import Enum from os.path import join, exists import argparse import pathlib import click import numpy as np import pandas as pd import download_data import dataframe import plotter class ModelTypes(Enum): STANDARD = ('Standard resnet50', 'tab:blue', 80) DATA_AUG = ('Trained with heavy da...
9862569
import sentry_sdk from flask import Flask, g, render_template from flask_env import MetaFlaskEnv from sentry_sdk.integrations.flask import FlaskIntegration from telegram import Bot from .models import get_user_by_confirmation_link class Configuration(metaclass=MetaFlaskEnv): DEBUG = False PORT = 5000 BOT...
9862601
import sphinx_rtd_theme extensions = [ "jupyter_sphinx", ] templates_path = ["_templates"] def setup(app): app.add_css_file("main_stylesheet.css") master_doc = "index" source_suffix = ".rst" # General information about the project. project = "HERE Map Widget for Jupyter" copyright = "Copyright (C) 2019-2...
9862613
from pwnypack.shellcode.linux import Linux from pwnypack.shellcode.arm import ARM from pwnypack.shellcode.arm.thumb import ARMThumb from pwnypack.shellcode.arm.thumb_mixed import ARMThumbMixed from pwnypack.shellcode.mutable_data import gnu_as_mutable_data_finalizer from pwnypack.shellcode.stack_data import stack_data_...
9862656
import matplotlib matplotlib.use('Agg') import pylab as plt import numpy as np from collections import Counter from astrometry.util.fits import * from astrometry.util.multiproc import * from astrometry.util.util import * from astrometry.util.plotutils import * from astrometry.util.stages import * from tractor import...
9862661
import re def extractor(inpList, kind): parsed = set() inp = ''.join(inpList) domain = r'[\w\.\-]+' ip = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b' if kind == 'domain': pattern = domain else: pattern = ip matches = re.findall(pattern, inp) for match in matches: i...
9862663
import os import sys import pickle import argparse import numpy as np from matplotlib import rc import matplotlib.pyplot as plt sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))) from deep_sprl.experiments import BallCatchingExperiment, CurriculumType rc('font', **{'family': 'sans-serif...
9862689
print('Load tensorflow models') # main imports import numpy as np from sklearn.metrics import roc_auc_score import tensorflow as tf class uni_AutoEncoder(object): # def __init__(self,optimizer='adam',loss='mean_squared_error',metrics=None,epochs=50,batch_size=512,shuffle=True, shuffle_buffer...
9862691
from twisted.spread import pb from twisted.internet import reactor import sys PORT = 8992 DELAY = 1 DOG_DELAY = 2 RESTART_DELAY = 5 class Pinger: def __init__( self, host ): self.ping = None self.host = host self.ball = 0 self._start() def _start...
9862700
from typing import List, Tuple import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.utils import create_tensor from relogic.logickit.tokenizer import CustomizedBertTokenizer, RobertaXLMTokenizer class MixSentExample(Example): """MixSent Example contains th...
9862721
import warnings warnings.filterwarnings("ignore") from nose.tools import assert_equal, assert_true from nerds.models import TransformerNER from nerds.utils import load_data_and_labels import numpy as np import shutil def test_bert_ner(): X, y = load_data_and_labels("nerds/test/data/example.iob") model = Tr...
9862776
import os import sys HERE = os.path.dirname(__file__) if __name__ == "__main__": import pytest errcode = pytest.main([HERE] + sys.argv[1:]) sys.exit(errcode)
9862811
from collections import deque from infoblox_client.connector import Connector class E2EConnectorFacade(Connector): """ Connector class facade for end-to-end tests. This facade will remember all created objects, and then sweep those objects after the test is done. """ def __init__(self, opti...
9862813
from typing import Any, Tuple, Callable, Optional from abc import ABC, abstractmethod from cellrank.ul._docs import d from cellrank.ul._parallelize import parallelize import numpy as np from scipy.sparse import csr_matrix class ThresholdSchemeABC(ABC): """Base class for all connectivity biasing schemes.""" ...
9862840
import os import atexit import subprocess process = subprocess.Popen( args=('node', os.path.join(os.path.dirname(__file__), 'test_server.js'),), stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) # Ensure the process is killed on exit atexit.register(lambda _process: _process.kill(), process) def read_li...
9862845
import os class Config(object): DEBUG = False TESTING = False SECRET_KEY = 'notejam-flask-secret-key' CSRF_ENABLED = True CSRF_SESSION_KEY = 'notejam-flask-secret-key' class ProductionConfig(Config): DEBUG = False SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI') clas...
9862873
import random def apply_tournament_selection(individuals, tot_rounds: int): """Tournament selection based on dominance (D) between two individuals, if the two individuals do not interdominate the selection is made based on crowding distance (CD). The *individuals* sequence length has to be a mu...
9862882
import argparse import sys sys.path.append('../') from BearSki.Manager import create_project from BearSki.gui.ApiTestGui import gui_start from BearSki.utils.hartool import HarTool import BearSki def main(): parser = argparse.ArgumentParser(description=BearSki.__description__+" version :"+BearSki.__version__) # pa...
9862919
from numpy import tanh def tanh_based_scaleup(shape, inflection_time, lower_asymptote, upper_asymptote=1.0): """ return the function t: (1 - sigma) / 2 * tanh(b * (a - c)) + (1 + sigma) / 2 :param shape: shape parameter :param inflection_time: inflection point :param lower_asymptote: lowest asympt...
9862921
from providers.provider import BaseProvider # Subclasses implement a way to get a list of popular movies in # the form of a list of search strings # # To implement a OutputProvider: # - Create a new file in popularity/ and call it provider_[your name].py # - Add the path to your file in settings.py, under OUTPUT_P...
9862950
IDS_ERROR = set() # NO FILE /6/norine_braun-now_and_zen-08-gently-117-146.mp3 # CORRUPTED /8/jacob_heringman-josquin_des_prez_lute_settings-19-gintzler__pater_noster-204-233.mp3 # CORRUPTED /9/american_baroque-dances_and_suites_of_rameau_and_couperin-25-le_petit_rien_xiveme_ordre_couperin-88-117.mp3 IDS_ERROR.add('35...
9862964
from django.dispatch import Signal # If any attached handler returns Truthy, CORS will be allowed for the request. # This can be used to build custom logic into the request handling when the # configuration doesn't work. check_request_enabled = Signal()
9862969
import json import uuid import time from functools import partial from threading import Thread, RLock import pika from lib.ipc.util import poll_for_connection from lib.config import logger connkeeper = {} def get_rpc_client(id: int): """manager function to keep track of connections between processes in wsgi ...
9862995
from test.dungeons.TestDungeon import TestDungeon class TestEasternPalace(TestDungeon): def testEastern(self): self.starting_regions = ["Eastern Palace"] self.run_tests([ ["Eastern Palace - Compass Chest", True, []], ["Eastern Palace - Cannonball Chest", True, []]...
9863003
from pathlib import Path from typing import TYPE_CHECKING from typing import Optional from typing import Union from poetry.core.packages.project_package import ProjectPackage as _ProjectPackage from poetry.core.utils import toml if TYPE_CHECKING: from poetry.core.semver.version import Version # noqa class Proj...
9863016
from ..resizing import Crop from ..exceptions import CropDusterException class DummyImage(object): def __init__(self, image): self.size = [image.width, image.height] def set_as_auto_crop(thumb, reference_thumb, force=False): """ Sometimes you need to move crop sizes into different crop groups. T...
9863026
import numpy as np from .features import frame_secs, maybe_parallel_map from . import quality_of_fit def score_function(labels, probs): "Score for binary labels vs probabilistic predictions" # Computes "expected accuracy" of labels vs predicted, where the # components of predicted are independent and Bern...
9863045
import sys import os.path from zipfile import ZipFile from distutils import log from distutils.command.install_data import install_data import setuptools import six # if six.PY3: # from past import autotranslate # autotranslate(['maven', 'maven.requestor', 'maven.downloader']) module_name = __name__.split('....
9863054
import argparse import json import boto3 def main(): # Parse command line arguments parser, args = parse_args() client = boto3.client('iot-data') count = 0 with open(args.datafile) as f: messages = json.load(f) for message in messages: response = client.publish( ...
9863083
import dis import inspect import unittest import os from pathlib import Path from checkov.dockerfile.runner import Runner from checkov.runner_filter import RunnerFilter class TestRunnerValid(unittest.TestCase): def test_runner_empty_dockerfile(self): current_dir = os.path.dirname(os.path.realpath(__fil...
9863089
from django.utils.translation import ugettext_lazy as _ from tally_ho.libs.utils.enum import Enum class DisableReason(Enum): NOT_OPENED = 0 HNEC_DECISION = 1 COMPLAINT_COURT = 2 COMPLAINT_HNEC = 3 DISQUALIFIED_HNEC = 4 DISQUALIFIED_COURT = 5 MATERIALS_DESTROYED = 6 OTHER = 7 CHOI...
9863121
import unittest from katas.beta.string_evaluation import string_evaluation class StringEvaluationTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_evaluation( 'aab#HcCcc##l#', ['a<b', '#==4', 'c>=C', 'H!=a'] ), [False, True, True, True]) def test_equal_...
9863128
math_commands = [ ("\\alpha",), ("\\beta",), ("\\gamma",), ("\\delta",), ("\\epsilon",), ("\\varepsilon",), ("\\zeta",), ("\\eta",), ("\\theta",), ("\\vartheta",), ("\\iota",), ("\\kappa",), ("\\varkappa",), ("\\lambda",), ("\\mu",), ("\\nu",), ("\\xi"...
9863149
import collections import logging import sys from . import argument_parser from . import formatter from . import loader from . import logic def main(): parser = argument_parser.get_parser() args = parser.parse_args() logging.basicConfig( format='%(asctime)s: %(levelname)s: %(message)s', level=logg...
9863150
import pkg_resources import pytest import stan import stan.plugins program_code = "parameters {real y;} model {y ~ normal(0,1);}" class DummyPlugin(stan.plugins.PluginBase): def on_post_sample(self, fit, **kwargs): """Do nothing other than print a string.""" print("In DummyPlugin `on_post_sample...
9863154
import os import re import sys import platform import subprocess import socket import time import shutil import argparse from setuptools import setup, Extension from setuptools.command.build_ext import build_ext parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument...
9863155
import torch from torch import nn from torch.nn import functional as F, Parameter import numpy as np def array1d_repr(t, format='{:.3f}'): res = '' for i in range(len(t)): res += format.format(float(t[i])) if i < len(t) - 1: res += ', ' return '[' + res + ']' class SteFloo...
9863202
import komand from komand_cef.util import utils from .schema import ParseSingleInput, ParseSingleOutput, Input, Output, Component class ParseSingle(komand.Action): def __init__(self): super(self.__class__, self).__init__( name="parse_single", description=Component.DESCRIPTION, ...
9863226
from django.utils.importlib import import_module from ..conf import conf def get_check(func_path): mod_name, func_name = func_path.rsplit(".", 1) module = import_module(mod_name) return getattr(module, func_name) def run_checks(): warnings = set() for func_path in conf.SECURE_CHECKS: ...
9863238
import multiprocessing import pyQBWC import qwcSimulator import time # this is the script to start everything up. It starts two servers # in two separate processes. # by uncommenting the last three lines it can also start a third client process that simulates the Quickbooks web connector for testing. def QuickBooksF...
9863249
import io import numpy as np from PIL import Image from PyQt5 import QtGui, QtWidgets, QtCore, uic class Painter(QtWidgets.QWidget): def __init__(self, color_picker): super().__init__() self.color_picker = color_picker self.chosen_point = [] self._hint = QtGui.QPixmap(500, 500) ...
9863287
import xml.etree.ElementTree as ET class DataReaderMOEX(): ''' DataReaderMOEX class used for MOEX xml parsing ''' def __init__(self, path_to_xml): self.file_path = path_to_xml def get_total_rows(self): ''' Gets TOTAL attribute value from the row element ''' ...
9863332
from peewee import * from app import Account, PageView DEFAULT_ACCOUNT_ID = 1 class Report(object): def __init__(self, account_id=DEFAULT_ACCOUNT_ID): self.account = Account.get(Account.id == account_id) self.date_range = None def get_query(self): query = PageView.select().where(Pag...
9863370
from typing import List, Tuple, Callable, Optional, NamedTuple import unicodedata from allennlp_models.rc.dataset_readers.utils import STRIPPED_CHARACTERS from src.data.types import Span def get_sequence_boundaries(special_tokens_mask: List[int]): """ Returns the token index boundaries of a sequence that wa...
9863404
import copy import importlib from datetime import datetime import pytest from django.conf import settings as dj_settings from django.core.exceptions import ImproperlyConfigured import grandchallenge.core.storage def test_invalid_private_kwarg(settings): """Check that invalid kwargs raise a validation error.""" ...
9863411
import traceback import json import aiohttp from aiohttp import web import asyncio from appdaemon import utils as utils class WSHandler: def __init__(self, ADStream, app, path, ad): self.AD = ad self.ADStream = ADStream self.app = app self.logger = ad.logging.get_child("_stream...
9863460
import pandas as pd import numpy as np from datetime import datetime from multiprocessing import Pool from functools import partial from pathos import pools as pp import pickle as pkl from UserCentricMeasurements import * from ContentCentricMeasurements import * from CommunityCentricMea...
9863468
from collections import defaultdict ######################### # Diagnose entity - ICD # ######################### def parser(ICDfile): """ Parses and extracts relevant data from ICD-10 files (Classification of Diseases). :param ICDfile: list of files downloaded from the ontology database and used to gene...
9863482
from __future__ import print_function """ various test cases for YAML files """ import sys import pytest # NOQA import platform from .roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA class TestYAML: def test_backslash(self): round_trip( """ handlers: ...
9863504
from pathlib import Path import h5py import numpy as np import torch from torch.utils.data import Dataset from torchvision.datasets.utils import download_and_extract_archive class Traffic4Cast20(Dataset): """ Data for the 2020 traffic4cast challenge. """ URLS = { "https://zurich-ml-datasets.s3.amazo...
9863528
from serpent.frame_transformer import FrameTransformer class FrameTransformationPipelineError(BaseException): pass class FrameTransformationPipeline: def __init__(self, pipeline_string=None): if pipeline_string is None or not isinstance(pipeline_string, str): raise FrameTransformationPi...
9863581
if __name__ == "__main__": print("Creating sdf command file...") tiles = ["Tile_PE", "Tile_MemCore"] # We can create one file to contain all annotation commands with open("sub_cmd.cmd", "w+") as fi: for tile in tiles: # Read through each tile instance and annotate with op...
9863585
expected_output = { "60m": { 1: {"average": 10, "maximum": 51}, 2: {"average": 20, "maximum": 69}, 3: {"average": 10, "maximum": 56}, 4: {"average": 10, "maximum": 15}, 5: {"average": 20, "maximum": 75}, 6: {"average": 10, "maximum": 21}, 7: {"average": 30, "m...
9863700
from .testutils import FullStackTests import os import time from webrecorder.models.usermanager import CLIUserManager # ============================================================================ class TestRateLimits(FullStackTests): BASE_LIMIT = 1200 RESTRICT_LIMIT = 500 @classmethod def setup_cla...
9863729
from collections import namedtuple import json from pprint import pprint import pytest import ujson from polyswarmd.websockets import messages @pytest.fixture(autouse=True) def mock_md_fetch(monkeypatch): """Mock out the metadata-fetching implementation Override _substitute_metadata so we can test `fetch_m...
9863777
import pytest @pytest.fixture(scope="module") def ansible_vars(host): return host.ansible.get_variables() def test_plugins_role_was_executed(host, ansible_vars): assert host.file(ansible_vars['plugins_test_file_path']).exists def test_correct_plugins_are_installed(host, ansible_vars): for pack in ansi...
9863792
import time from airflow.utils.decorators import apply_defaults from scheduler.dags.operators import QosOperator class AfterSubdagOperator(QosOperator): @apply_defaults def __init__(self, params, *args, **kwargs): super(AfterSubdagOperator, self).__init__(params, *args, **kwargs) def execute(se...
9863845
import cartography.intel.jamf.computers import tests.data.jamf.computers TEST_UPDATE_TAG = 123456789 def test_load_jamf_computer_group_data(neo4j_session): _ensure_local_neo4j_has_test_computergroup_data(neo4j_session) # Test that the Redshift cluster node was created expected_nodes = { 123, ...
9863896
import tensorflow as tf from tensorflow.keras.datasets import fashion_mnist def make_model(n_classes): return tf.keras.Sequential( [ tf.keras.layers.Conv2D( 32, (5, 5), activation=tf.nn.relu, input_shape=(28, 28, 1) ), tf.keras.layers.MaxPool2D((2, 2), (...
9863902
from act import Act from learning.statistics import Statistics from utils.inout import * class GetStatistics(Act): def start(self): if self.arguments.stat_type == 'VI': datasets_dir = join_path(self.arguments.data_dir, self.arguments.datasets_dir) cluster_files = get_files_in_dir(...
9863931
import numpy as np from midas.weights import ExpAlmonWeights, BetaWeights def test_beta_es(): w = BetaWeights(1., 5.).weights(3) assert np.allclose(w, [0.941176, 0.0588238, 9.4118e-25]) def test_beta_es_nz(): w = BetaWeights(1, 5, 0.1).weights(3) assert np.allclose(w, [0.800905, 0.122172, 0.07692...
9863942
import collections import typing import numpy as np from numpy import testing import pytest from hamilton import base def test_numpymatrixresult_int(): """Tests the happy path of build_result of numpymatrixresult""" outputs = collections.OrderedDict( a=np.array([1, 7, 3, 7, 3, 6, 4, 9, 5, 0]), ...
9863943
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ Base class for renderers """ __author__ = "<NAME> (<EMAIL>)" __copyright__ = "Copyright 2014, <NAME>" __license__ = "MIT (http://opensource.org/licenses/MIT)" import logging log = logging.getLogger...
9863994
import pytest from konfik import ( Colorize, DotMap, Konfik, MissingConfigError, MissingVariableError, __version__, cli_entrypoint, ) def test_colorize(config_dict, capsys): colorize = Colorize() colorize.colorize_entity(config_dict) out, err = capsys.readouterr() assert ...
9864017
import multiprocessing as mp import numpy as np import radontea def test_simple(): """Simple test for backproject""" count = mp.Value("i") max_count = mp.Value("i") sino = np.random.random((10, 30)) radontea.backproject(sinogram=sino, angles=np.arange(len(sino)), ...
9864065
from django.db import models class TestClient(models.Model): STATUS_CHOICES = ((0, 'Ready'), (1, 'Not Ready'), (2, 'Undetermined')) name = models.CharField(max_length=100) ip = models.CharField(max_length=50) platform = models.CharField(max_length=100) owner = models.CharField(max_length=50) ...