id
stringlengths
3
8
content
stringlengths
100
981k
494120
import pytest async def test_handler(app, client): from muffin.handler import Handler, route_method assert Handler @app.route('/handler', '/handler/{res}') class Index(Handler): async def get(self, request): return request.path_params or 'ok' async def post(self, reques...
494171
import os from PyQt5.QtWidgets import QDialog from cvstudio.util import GUIUtilities, FileUtilities from cvstudio.vo import DatasetVO from .base_dataset_form import Ui_Base_DatasetDialog class DatasetForm(QDialog, Ui_Base_DatasetDialog): def __init__(self, vo: DatasetVO = None, parent=None): super(Datas...
494185
from .common import pred, iroot_ceil, floor_lg from .generalized_accumulator import ( GeneralizedAccumulatorFactory, GeneralizedAccumulator, GeneralizedProver, GeneralizedVerifier, ) # Implementation of the generalized accumulator with p "evenly spaced" back-pointers. # Cost of update: O(p) # Proof si...
494193
import argparse, sys from pipelines_utils import parameter_utils, utils from pipelines_utils_rdkit import rdkit_utils, mol_utils from rdkit import Chem from . import calc_interactions def execute(suppl, writer, report, group_by_field, score_field, score_descending, stats_fields): count = 0 total = 0 err...
494203
lines = open('data.csv').read().split('\n') data = [(int(x[:x.find(',')]), float(x[x.find(',')+1:])) for x in lines if x] REPORT_THRESHOLD = 0.23 def get_error(scale, elasticity, growth): err = 0 bs_fac, fee_fac = 1 / (1 + elasticity), elasticity / (1 + elasticity) for i, (block_size, avg_fee) in enum...
494216
import bpy material = (bpy.context.material.active_node_material if bpy.context.material.active_node_material else bpy.context.material) material.subsurface_scattering.radius = 10.899, 6.575, 2.508 material.subsurface_scattering.color = 0.947, 0.931, 0.852
494265
import numpy as np a_1d = np.arange(4) print(a_1d) # [0 1 2 3] print(a_1d[[0, 2]]) # [0 2] print(a_1d[[0, 3, 2, 1, 2, -1, -2]]) # [0 3 2 1 2 3 2] print(a_1d[np.array([0, 3, 2, 1, 2, -1, -2])]) # [0 3 2 1 2 3 2] a_2d = np.arange(12).reshape(3, 4) print(a_2d) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] prin...
494267
import sys from pypy.interpreter.baseobjspace import W_Root, ObjSpace, Wrappable, \ Arguments from pypy.interpreter.error import OperationError, wrap_oserror from pypy.interpreter.gateway import interp2app from pypy.interpreter.typedef import TypeDef, GetSetProperty from pypy.rlib.libffi import * from pypy.rpytho...
494330
from typing import Final, List, Optional, Union from web3 import Web3 from web3.eth import TxReceipt from eth_account.account import LocalAccount from thirdweb.abi.multiwrap import ITokenBundleToken from thirdweb.common.marketplace import is_token_approved_for_transfer from thirdweb.common.nft import upload_or_extract...
494412
import django from gensim.models import KeyedVectors import gensim import sys import os # 获取当前文件的目录 from FunPySearch.celery import app pwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # 获取项目名的目录(因为我的当前文件是在项目名下的文件夹下的文件.所以是../) sys.path.append(pwd) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Fun...
494425
import numpy as np import sys sys.path.append(".") from ai.action.movement.movements.basic import * from ai.action.movement.movements.sit import * import ai.actionplanner def kneading(mars, times=6): sit(mars) _speed = 0.7 l = 0 for i in range(times): l += 1 leg_num = (l % 2 + 1) ...
494446
from verifai.features import * from verifai.samplers import * from collections import defaultdict def test_grid(): space = FeatureSpace({ 'weather': Feature(DiscreteBox([0,12])), 'car_positions': Feature(Box([-10,10], [0,1])) }) sampler = FeatureSampler.gridSamplerFor(space) i = 0 ...
494452
import torch import numpy as np from transformers import BertModel from sentence_transformers import SentenceTransformer, util from relevance_model import text_preprocessing, preprocessing_for_bert, bert_predict, BertClassifier from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSample...
494506
import datetime import time import os from celery import Celery celery_app = Celery('hello', broker=os.environ['REDIS_URL']) @celery_app.task def hello(): time.sleep(10) with open ('hellos.txt', 'a') as hellofile: hellofile.write('Hello {}\n'.format(datetime.datetime.now()))
494511
Import("env") with open("version.txt") as fp: version = fp.readline() env.Replace(PROGNAME="firmware_%s" % version.replace(".", "_"))
494545
from rest_framework.generics import ListCreateAPIView from rest_framework.generics import RetrieveUpdateDestroyAPIView from .models import Micropost, Usr from .serializers import MicropostSerializer class MicropostsListView(ListCreateAPIView): serializer_class = MicropostSerializer def get_queryset(self): ...
494547
class InvalidFileName(ValueError): def __init__(self, filename): self.message = 'Invalid file name: {}'.format(filename) super(ValueError, self).__init__(self.message)
494562
import os import sys import math import pickle import argparse import time from torch import optim from torch.utils.tensorboard import SummaryWriter import torch.nn.functional as F sys.path.append(os.getcwd()) from utils import * from experiments.utils.config import Config from experiments.utils.batch_gen_amass import ...
494642
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def is_leaf_node(self, root: TreeNode) -> bool: return root.left is None and root....
494667
import theano import theano.tensor as T import numpy as np from utility.utility import * from lstm_layer import * def uni_lstm_init(prefix, params, layer_setting): return lstm_init(prefix+'_forward', params, layer_setting) def uni_lstm_calc(prefix, params, layer_setting,state_below, h_init = None, c_init = None,...
494704
from commitizen import factory, out from commitizen.config import BaseConfig class Example: """Show an example so people understands the rules.""" def __init__(self, config: BaseConfig, *args): self.config: BaseConfig = config self.cz = factory.commiter_factory(self.config) def __call__(...
494717
import sys import os import matplotlib import fnmatch matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import KernelDensity from sklearn.model_selection import GridSearchCV from sklearn.model_selection import LeaveOneOut from scipy.ndimage.filters import maximum_filter fro...
494770
import uuid from django.db import models from validator.models.validation_run import ValidationRun class CeleryTask(models.Model): validation = models.ForeignKey(to=ValidationRun, on_delete=models.PROTECT, related_name='celery_tasks', null=False) celery_task_id = models.UUIDField(primary_key=True, default=u...
494773
import functools import numpy as np from ... import problems class RamseyCassKoopmansModel(problems.TwoPointBVP): """ Class representing a generic Solow growth model. Attributes ---------- equilibrium_capital : function Equilibrium value for capital (per unit effective labor). equil...
494787
import json import os import numpy as np from argparse import ArgumentParser from CLIP import clip import clipgrams def main(): # Args parser = ArgumentParser() parser.add_argument('--image_dir', type=str) parser.add_argument('--index_dir', type=str) parser.add_argument('--knn', type=int, defaul...
494798
import torch import torch.nn as nn import torch.nn.functional as F from pcdet.models.backbones_3d.sa_block import SA_block class PointContext3D(nn.Module): def __init__(self, model_cfg, IN_DIM, dropout=0.1): super().__init__() self.model_cfg = model_cfg self.pc_range = self.model_cfg.PC_R...
494945
from ._base import validate_input from ._optimizers import constrained_binary_solve from ._optimizers import constrained_multiclass_solve __all__ = [ "constrained_binary_solve", "constrained_multiclass_solve", "validate_input", ]
494991
import numpy as np __all__ = () class H5LogTable: def __init__(self, group): self._group = group def __getitem__(self, label): return self._group[label] if label in self._group else [] def resize(self, size): for ds in self._group.values(): ds.resize(size, axis=0) ...
494992
from abc import ABC, abstractmethod from msdm.core.problemclasses.mdp.mdp import MarkovDecisionProcess, State, Action from msdm.core.distributions import Distribution from msdm.core.algorithmclasses import Result import random class Policy(ABC): @abstractmethod def action_dist(self, s: State) -> Distribution[A...
494996
import unittest import os from sdc11073.wsdiscovery import WSDiscoverySingleAdapter from sdc11073 import pmtypes from sdc11073.location import SdcLocation from sdc11073.sdcclient import SdcClient from tests.mockstuff import SomeDevice loopback_adapter = 'Loopback Pseudo-Interface 1' if os.name == 'nt' else 'lo...
495003
import logging from typing import List, Optional, Sequence from langid.langid import LanguageIdentifier import numpy as np from sacred import Experiment from tqdm import tqdm from torch.utils.data import DataLoader from experiments.Experiment_utils import create_logger from experiments.data_loading import data_loadin...
495022
from flask import request, url_for from json import dumps as json_encode, loads as json_decode from app.helpers.oauth.config import oauth_config from base64 import b64encode, b64decode from slugify import slugify as slugify_str from re import sub from urllib.parse import quote, urlencode import config def json_to_b64...
495036
import tensorflow as tf from tensorflow.keras.regularizers import l2 class ArcNet(tf.keras.layers.Layer): def __init__(self, num_classes, regularizer=l2(5e-4), **kwargs): super(ArcNet, self).__init__(**kwargs) self.regularizer = regularizer self.num_classes = num_classes def build(sel...
495049
from kivy.animation import Animation from functools import partial from .base import Animator __all__ = ( "RotateOutAnimator", "RotateOutDownLeftAnimator", "RotateOutDownRightAnimator", "RotateOutUpLeftAnimator", "RotateOutUpRightAnimator", ) # rotate out class RotateOutAnimator(Animator): de...
495075
import pysftp from paramiko import sftp import mlflow as mlf import pandas as pd import json ''' model = 0 (Default), 1 (LightGBM), 2 (Multiclass), 3 (TF-Ranking) features passed saved as dictionary F1 result of model CVS of trained model ''' def mlflow_log(model, metrics, parameters, rest_params, features): c...
495077
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/api') def my_microservice(): print(request) print(request.environ) response = jsonify({'Hello': 'World!'}) print(response) print(response.data) return response if __name__ == '__main__': print(app.url_map) app.run()
495121
import pytest from nbformat import notebooknode from nb2hugo.preprocessors import ImagesPreprocessor @pytest.fixture def preprocessor(): return ImagesPreprocessor() @pytest.fixture def resources(tmpdir): nb_dir = tmpdir.mkdir('nb_dir') img_dir = nb_dir.mkdir('img_dir') img_dir.join('fake.png').write(...
495140
from django import forms from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponseNotFound from django.urls import reverse from django.utils import timezone from django.contrib.auth.decorators import login_required from django.db.models impo...
495169
from django import template register = template.Library() cache = {} @register.inclusion_tag('more_menu_links.html') def more_menu_links(): from ...utils import get_menu_links if 'links' not in cache: cache['links'] = get_menu_links() return {'links': cache['links']}
495212
import os import pytest try: from pyscf import gto, ao2mo, scf from pauxy.utils.from_pyscf import ( integrals_from_scf, integrals_from_chkfile, get_pyscf_wfn, dump_pauxy ) no_pyscf = False except (ImportError, OSError): no_pyscf = True from pau...
495232
import unittest from tests.test_utils import get_sample_pdf_with_labels, get_sample_pdf, get_sample_sdf, get_sample_pdf_with_extra_cols, get_sample_pdf_with_no_text_col ,get_sample_spark_dataframe from nlu import * class TestNameSpace(unittest.TestCase): def test_tokenize(self): df = nlu.load('en.tokeniz...
495257
import uvicorn from nebulo.gql.sqla_to_gql import sqla_models_to_graphql_schema from nebulo.server.exception import http_exception from nebulo.server.routes import get_graphiql_route, get_graphql_route from sqlalchemy import Column, DateTime, ForeignKey, Integer, Text, create_engine from sqlalchemy import text as sql_t...
495268
import numpy as np import cv2 import glob import matplotlib.pyplot as plt def inrange(v, shape): return 0 <= v[0] < shape[0] and 0 <= v[1] < shape[1] def to_int(x): return tuple(map(int, x)) def save_heatmap(prefix, image, lines): im_rescale = (512, 512) heatmap_scale = (128, 128) # fy, fx = ...
495315
import xlwt book = xlwt.Workbook() for magn in (0, 60, 100, 75, 150): for preview in (False, True): sheet = book.add_sheet('magn%d%s' % (magn, "np"[preview])) if preview: sheet.preview_magn = magn else: sheet.normal_magn = magn sheet.page_preview = preview ...
495320
import argparse from utils import get_logger logger = get_logger() arg_lists = [] parser = argparse.ArgumentParser() def str2bool(v): return v.lower() in ('true') def add_argument_group(name): arg = parser.add_argument_group(name) arg_lists.append(arg) return arg # Network net_arg = add_argument_g...
495334
import os from FinRL.finrl import config from FinRL.finrl import config_tickers if not os.path.exists("./" + config.DATA_SAVE_DIR): os.makedirs("./" + config.DATA_SAVE_DIR) if not os.path.exists("./" + config.TRAINED_MODEL_DIR): os.makedirs("./" + config.TRAINED_MODEL_DIR) if not os.path.exists("./" + config.T...
495380
import json import os from os import listdir import os.path as osp import pickle import time from collections import OrderedDict, Counter import argparse import numpy as np import pathlib import joblib from gym.wrappers.monitoring.video_recorder import VideoRecorder from TeachMyAgent.run_utils.environment_args_handle...
495390
from django.contrib import admin from .models import ExtendedBacker admin.site.register(ExtendedBacker)
495409
import sys if sys.version[0] == 3: TimeoutError = TimeoutError else: TimeoutError = OSError class Timeout(TimeoutError): """Raised when the lock could not be acquired in *timeout* seconds.""" def __init__(self, lock_file): #: The path of the file lock. self.lock_file = lock_file ...
495414
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import os import os.path as osp import numpy as np import json import provider from sklearn.model_selection import train_test_split BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TRAIN_FILES_MODELNET = provider.getDataFiles( \ ...
495423
from drawille import Canvas from timeit import timeit c = Canvas() frames = 1000 * 10 sizes = ((0, 0), (10, 10), (20, 20), (20, 40), (40, 20), (40, 40), (100, 100)) for x, y in sizes: c.set(0, 0) for i in range(y): c.set(x, i) r = timeit(c....
495452
from unittest import ( TestCase, main ) from source import ( CSTR, CINT, CConst ) from common import ( def_tokens, pypath, ee ) with pypath("..ply"): from ply.lex import lex # Defining a lexer affects `ply.yacc.LRParser.parse` invocations without # explicit `lexer` argument value b...
495508
import logging # from homeassistant.const import 'serial_port', 'config_file', 'code' # found advice in the homeassistant creating components manual # https://home-assistant.io/developers/creating_components/ # Import the device class from the component that you want to support from homeassistant.components.cover impo...
495531
import pytest @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass # https://blog.jerrycodes.com/no-http-requests/ @pytest.fixture(autouse=True) def no_http_requests(monkeypatch): def urlopen_mock(self, method, url, *args, **kwargs): raise RuntimeError( f"The test was...
495597
import uuid from typing import Optional, Union import pyrsistent from aioredis.client import Redis from pyrsistent.typing import PVector from .data import Todo class Storage: def __init__(self, *, redis: Redis, data_key: str) -> None: self.redis = redis self.data_key = data_key def build_it...
495614
import numpy as np from gym.spaces import Box from collections import deque # Implementation of SAGG-RIAC class SAGG_RIAC(): def __init__(self, min, max, continuous_competence=False): assert len(min) == len(max) self.maxlen = 200 self.regions = [[deque(maxlen=self.maxlen + 1), deque(maxl...
495706
import os import sys DATA_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.dirname(DATA_DIR))) from selenium import webdriver from Screenshot import Screenshot_Clipping from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager def test_full_sc...
495728
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: def convert(ss): d = {} return [d.setdefault(c, len(d)) for c in ss] return convert(s) == convert(t)
495740
from django.urls import path from .views import ResultListView, create_result, edit_results urlpatterns = [ path("create/", create_result, name="create-result"), path("edit-results/", edit_results, name="edit-results"), path("view/all", ResultListView.as_view(), name="view-results"), ]
495783
EVENT_MEET_GUIDE = 64 EVENT_DESOLATED_CABIN = 65 EVENT_TRAINER_K1_PRE_1 = 66 EVENT_ITEMBALL_K1_PRE_1 = 67 EVENT_TRAINER_K1_PRE_2 = 68 EVENT_TRAINER_K1_PRE_3 = 69 EVENT_TRAINER_K1_PRE_4 = 70 EVENT_TUTORIAL_WILLOW = 71 EVENT_K1_PRE_COMPLETE = 72 EVENT_ITEMBALL_K1_POST_1 = 73 EVENT_SHOWED_METAPOD = 74 EVENT_TRAINER_K1_POS...
495785
import logging import threading from datetime import datetime, timedelta from threading import Thread from apiclient import discovery logger = logging.getLogger(__name__) DELAY_SECS = 60 * 5 MAX_FOLDER_AGE_MINS = 60 # An hour class DriveCleanup: SCOPES = 'https://www.googleapis.com/auth/drive' drive = None...
495791
import os, sys import os.path as osp import argparse import warnings import time import numpy as np from utils import paired_transforms_tv04 as p_tr from PIL import Image from skimage.io import imsave from skimage.util import img_as_ubyte from skimage.transform import resize import torch from models.get_model import g...
495793
import os from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from bop_toolkit_lib import pycoco_utils import argparse from bop_toolkit_lib import config from bop_toolkit_lib import dataset_params from bop_toolkit_lib import inout from bop_toolkit_lib import misc # PARAMETERS (some can be ove...
495866
import copy import datetime import contextlib import six import traitlets import ipywidgets from .. import types # Copy the old implementation of `link` from traitlets 4.3.3. # traitlets >= 5.0.0 introduce a `!=` comparison when updating, # which fails on types that overload equality checking (like NumPy arrays, I...
495870
import logging INSTALLED_APPS = [ 'huey.contrib.djhuey', 'djangoex.test_app', ] HUEY = { 'name': 'test-django', 'consumer': { 'blocking': True, # Use blocking list pop instead of polling Redis. 'loglevel': logging.DEBUG, 'workers': 4, 'scheduler_interval': 1, '...
495880
import unittest from lib.EnumStatus import Status class Test_Enum_Status(unittest.TestCase): def test_successor(self): self.assertEqual(1, Status.CREATED.value) self.assertEqual(Status.WORK, Status.CREATED.succ()) self.assertEqual(Status.DONE, Status.CREATED.succ().succ()) with sel...
495900
import openslide import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--source_image_path", type=str, default='/data/camelyon16_original/training/normal/normal_05...
495912
from typing import Optional from primehub import Helpful, cmd, Module class Secrets(Helpful, Module): """ Query secrets for Image Pull Secrets """ @cmd(name='list', description='List secrets') def list(self) -> list: """ List secrets :rtype: list :returns: secret...
495926
from .comparesettable import CompareSetTable import pandas as pd class TableSetComparer: def __init__(self): return def run(self, compTables: list) -> CompareSetTable: # create data lists nameList = [] nucF1List = [] nucKappaList = [] relF1List = [] re...
495938
import os import resource import nltk import torch from graph4nlp.pytorch.data.dataset import Text2TextDataItem from graph4nlp.pytorch.inference_wrapper.generator_inference_wrapper import ( GeneratorInferenceWrapper, ) from graph4nlp.pytorch.models.graph2seq import Graph2Seq from args import get_args from dataset...
495946
import copy from functools import reduce import operator def dict_diff(d1, d2): diff = {} for k1, v1 in d1.items(): kdiff = {} if isinstance(v1, list): v2 = d2.get(k1, []) added = [v2i for v2i in v2 if v2i not in v1] if added: kdiff["added"] ...
495955
f = plt.figure(figsize=(10,4)) ax = plt.gca() ax.set_aspect('equal') is_weird = lmos.p_sim <= (.05/len(pres)) pres.plot(color='lightgrey', ax=ax) pres.assign(quads=lmos.q)[is_weird].plot('quads', legend=True, k=4, categorical=True, ...
496013
import os import pytest import torch import pytorch_lightning as pl from pytorch_lightning import Callback, Trainer import ray from ray_lightning import RayShardedPlugin from ray_lightning.tests.utils import BoringModel @pytest.fixture def ray_start_2_cpus(): address_info = ray.init(num_cpus=2) yield addr...
496023
from pyradioconfig.parts.lynx.calculators.calc_modulator import CALC_Modulator_Lynx class CALC_Modulator_Leopard(CALC_Modulator_Lynx): #Inherit all from Lynx pass
496036
from pipeline.runner import in_progress def import_in_progress(request): return {"import_in_progess": in_progress()}
496048
import abc from rdr_service.genomic_enums import GenomicWorkflowState class GenomicStateBase: """Abstract base class for genomic states""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def transition_function(self, signal): return class IgnoreState(GenomicStateBase): """ Ignore S...
496102
import math def mod(x, y): return x - y * math.trunc(x / y) def palindrome2(pow2, n): t = [None] * 20 for i in range(0, 20): t[i] = mod(math.trunc(n / pow2[i]), 2) == 1 nnum = 0 for j in range(1, 20): if t[j]: nnum = j for k in range(0, math.trunc(nnum / 2) + 1): ...
496123
from will.utils import warn from will.backends.storage.file_backend import FileStorage warn( """Deprecation - will.storage.file_storage has been moved to will.backends.storage.file_backend, and will be removed in version 2.2. Please update your paths accordingly!""" )
496136
from train import * from DCRN import DCRN if __name__ == '__main__': # setup setup() # data pre-precessing: X, y, A, A_norm, Ad X, y, A = load_graph_data(opt.args.name, show_details=False) A_norm = normalize_adj(A, self_loop=True, symmetry=False) Ad = diffusion_adj(A, mode="ppr", transport_ra...
496161
import heapq class mcf_graph(): n=1 pos=[] g=[[]] def __init__(self,N): self.n=N self.pos=[] self.g=[[] for i in range(N)] def add_edge(self,From,To,cap,cost): assert 0<=From and From<self.n assert 0<=To and To<self.n m=len(self.pos) self.pos.a...
496165
from typing import List, cast, Dict import numpy as np from py_headless_daw.dto.waveform import Waveform from py_headless_daw.project.content.audio_clip import AudioClip from py_headless_daw.schema.clip_track_processing_strategy import ClipTrackProcessingStrategy from py_headless_daw.schema.dto.time_interval import T...
496171
import torch import numpy as np import functools def torchify(func): """Extends to NumPy arrays a function written for PyTorch tensors. Converts input arrays to tensors and output tensors back to arrays. Supports hybrid inputs where some are arrays and others are tensors: - in this case all tensors s...
496192
from unittest import TestCase import requests_mock from parameterized import parameterized from hvac import exceptions from hvac.adapters import JSONAdapter from hvac.api.auth_methods import AppRole from hvac.constants.approle import DEFAULT_MOUNT_POINT class TestAppRole(TestCase): @parameterized.expand( ...
496202
import unittest from talent_curator.apps.google import drive class GoogleDriveAPITest(unittest.TestCase): def setUp(self): self.google_api = drive.GoogleDriveAPI() def test_build_headers(self): headers = self.google_api.build_headers(access_token="<PASSWORD>") assert headers['Authori...
496223
from typing import Optional from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint from citrine.informatics.descriptors import FormulationDescriptor __all__ = ['IngredientCountConstraint'] class Ing...
496257
import pytest from flask import Flask @pytest.fixture(scope="session") def app(): app = Flask(__name__) return app @pytest.yield_fixture(scope="session") def client(app): return app.test_client()
496266
from rasa_nlu_examples.meta.printer import print_message from rasa.shared.nlu.training_data.message import Message def test_can_print_empty_message(): print_message(Message())
496294
import zlib import uuid import time def busy_loop(): start = time.time() for i in range(0, 50): text = ''.join([str(uuid.uuid4()) for _ in range(0, 10000)]) text_encoded = text.encode('utf8') text_compressed = zlib.compress(text_encoded) zlib.decompress(text_compressed) end...
496308
import numpy as np from scipy import special as sp def jacobi_recurrence(N, alpha=0., beta=0., probability=True): r""" Compute the recursion coefficients of Jacobi polynomials which are orthonormal with respect to the Beta random variables Parameters ---------- alpha : float The first...
496328
import ray import numpy as np ray.init(num_cpus=8, object_store_memory=4e9) @ray.remote def consume(name, split): i = 0 for row in split.iter_rows(): i += 1 def gen(i): return { "a": 4.0, "b": "hello" * 1000, "c": np.zeros(25000), } ds = ray.data.range(10000).map(g...
496407
from typing import Union, List, Dict, Any, Sequence, Iterable, Optional import re reCommaWhitespacePotentiallyBreaks = re.compile(r",\s+") def dictString(d: Dict, brackets: Optional[str] = None): s = ', '.join([f'{k}={toString(v)}' for k, v in d.items()]) if brackets is not None: return brackets[:1]...
496420
from utils.header import MagicField, Field from load_command import LoadCommandHeader, LoadCommandCommand class SubClientCommand(LoadCommandHeader): ENDIAN = None FIELDS = ( MagicField('cmd', 'I', {LoadCommandCommand.COMMANDS['LC_SUB_CLIENT']: 'LC_SUB_CLIENT'}), Field('cmdsize', 'I'), ...
496443
import flask_login import logging from flask import jsonify, request from server import app, user_db from server.auth import user_mediacloud_client, user_name, user_admin_mediacloud_client,\ user_is_admin from server.util.request import form_fields_required, arguments_required, api_error_handler logger = logging....
496456
import vstruct from vstruct.primitives import * class BITMAPINFOHEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.biSize = v_uint32() self.biWidth = v_int32() self.biHeight = v_int32() self.biPlanes = ...
496459
from typing import Union, Tuple, Any import numpy as np # NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and # `np.bytes_` are already subclasses of their builtin counterpart _CharLike_co = Union[str, bytes] # The 6 `<X>Like_co` type-aliases below represent all scalars that can be # coerced int...
496462
import ssz from eth2.beacon.types.voluntary_exits import SignedVoluntaryExit, VoluntaryExit def test_defaults(sample_voluntary_exit_params, sample_signature): exit = VoluntaryExit.create(**sample_voluntary_exit_params) signed_exit = SignedVoluntaryExit.create(message=exit, signature=sample_signature) as...
496491
from setuptools import setup from os import path HERE = path.abspath(path.dirname(__file__)) def readme(): with open(path.join(HERE, 'README.rst')) as f: return f.read() setup( name='choix', version='0.3.3', author='<NAME>', author_email='<EMAIL>', description="Inference algorithms...
496500
from rest_framework.pagination import LimitOffsetPagination class LimitOffsetPaginationWithMaxLimit(LimitOffsetPagination): max_limit = 10
496578
def initialize_project(): print("Importing necessary methods...") from utils.create_proto import create_proto_files from utils.import_fixer import convert_to_relative_imports print("Creating proto files...") create_proto_files() convert_to_relative_imports() if __name__ == "__main__": pri...
496584
from server.user.interface import User from server.context import Context from django.conf import settings from .models import Page def frontend(request): return { 'page': Page.get(), 'user_': ( User.get(Context.from_request(request), request.user.pk) if request.user.is_a...