id
stringlengths
3
8
content
stringlengths
100
981k
1695944
from freezegun import freeze_time from openinghours.tests.tests import OpeningHoursTestCase class FormsTestCase(OpeningHoursTestCase): def setUp(self): super(FormsTestCase, self).setUp() def tearDown(self): super(FormsTestCase, self).tearDown() def test_hours_are_published(self): ...
1695967
import logging import requests from io import BytesIO from PIL import Image, ImageDraw, ImageFont, ImageOps import app.data.firestore as data logger = logging.getLogger('food-flex') INTERNAL_RES = (1024, 1024) OUTPUT_RES = (1024, 1024) FONT_PATH = 'static/DejaVuSans-Bold.ttf' FONT_BASE_SIZE = int(0.2 * INTERNAL_RES[1...
1695975
from flask import jsonify, request from flask_security.recoverable import send_reset_password_instructions from flask_security.views import _security from http import HTTPStatus from werkzeug.datastructures import MultiDict from .blueprint import frontend, security from ..decorators import anonymous_user_required @f...
1696005
import random from os import urandom from typing import Callable, Tuple from dataclasses import dataclass from ecc.curve import Curve, Point @dataclass class ElGamal: curve: Curve def encrypt(self, plaintext: bytes, public_key: Point, randfunc: Callable = None) -> Tuple[Point, Point]: ...
1696047
import os import sys import re import types import itertools import matplotlib.pyplot as plt import numpy import scipy.stats import numpy.ma import Stats import Histogram from CGATReport.Tracker import * from cpgReport import * ########################################################################## class replica...
1696085
from sources.base.interface import DownloadableSource from utils import file from downloaders import BaseDownloader from sources.base import BaseSource class TextSource(BaseSource,DownloadableSource): __source_name__ = "text" def __init__(self, url, headers, filename,filecontent): self.url = url ...
1696091
import torch from torch import nn import numpy as np import cv2 ### FB Global Reasoning Block ### # From: https://github.com/facebookresearch/GloRe class GCN(nn.Module): """ Graph convolution unit (single layer) """ def __init__(self, num_state, num_node, bias=False): super(GCN, self).__init__() ...
1696101
from xml.dom import minidom from .svg_to_axes import FigureLayout, repar, tounit, XMLNS, get_elements_by_attr import copy import matplotlib.pyplot as plt import numpy as np import pkg_resources def get_empty_svg_document(tmp_filename=".fifi_tmp.svg"): """ Creates basic svg template file and saves it to disk...
1696133
FILE = 'tests/__init__.py' MESSAGE = 'This is a test.' RESPONSE_DATA = {'status': 1, 'message': 'fail'} SERVERS_AND_FILES = ( ('https://vim.cx', FILE), # PrivateBin 1.3 ('https://privatebin.gittermann1.de/', FILE), # PrivateBin 1.2 ('https://paste.carrade.eu/', FILE), # PrivateBin 1.1 # ('https://pas...
1696139
from adafruit_circuitplayground.express import cpx import time while True: print(cpx.button_a) time.sleep(0.05)
1696176
import pytest import os, re, io import helper import peeringdb from peeringdb import cli as _cli CMD = "peeringdb_test" client = helper.client_fixture("full") # Run with config dir class RunCli: def __init__(self, c): self.config_dir = str(c) def __call__(self, *args): fullargs = [CMD] ...
1696198
import random class Teacher: """ A class to implement a teacher that knows the optimal playing strategy. Teacher returns the best move at any time given the current state of the game. Note: things are a bit more hard-coded here, as this was not the main focus of the exercise so I did not spend as ...
1696208
from pathlib import Path from numpy import array from manim import * class VectorAddition(Scene): def construct(self): VECT1 = np.array([3, 2, 0]) VECT2 = np.array([2, -1, 0]) VECT1_COLOR = "#b9b28b" VECT2_COLOR = "#b98b99" VECT3_COLOR = "#8ba7b9" vect1 = Line(st...
1696264
import argparse import format_helper import madlibber import path_helper import word_helper def parse_args(): """Returns parsed arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '-input_words', type=str, required=True, help='The input words to substitute into templat...
1696275
from django import forms from ftp.models import Account from web.models import VHost class AccountCreateForm(forms.ModelForm): password = forms.CharField(widget=forms.widgets.PasswordInput) vhost = forms.ModelChoiceField(queryset=VHost.objects.all(), empty_label="/", required=False) class Meta: model = Account...
1696288
import math from pyjamas.chart import GChartUtil from pyjamas.chart.GChart import GChart from pyjamas.chart import AnnotationLocation from pyjamas.chart import SymbolType from pyjamas.ui.Button import Button from pyjamas.ui.FocusPanel import FocusPanel from pyjamas.ui.Grid import Grid from pyjamas.ui import KeyboardL...
1696293
from typing import Dict, Union import os import torch import tqdm import onnx from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder, ImageNet from furiosa_sdk_quantizer.evaluator.model_caller import ModelCaller from furiosa_sdk_quantizer.evaluator.data_loader import random_subset from f...
1696303
import unittest import sys from PyQt5.QtWidgets import QApplication, QDialog from ui import FetchProgressDialog app = QApplication(sys.argv) fetch_progress_dialog = QDialog() fetch_progress_dialog_ui = FetchProgressDialog.Ui_FetchProgressDialog() fetch_progress_dialog_ui.setupUi(fetch_progress_dialog) class FetchPr...
1696306
import os import time import numpy as np import argparse import torch import torch.nn as nn import torch.nn.functional as F import ray from ray.util.sgd import TorchTrainer from ray.util.sgd.utils import AverageMeterCollection from ray.util.sgd.torch import TrainingOperator import dgl from dgl.data import RedditData...
1696473
from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.models import Attachment from django_summernote.settings import summernote_config __widget__ = SummernoteWidget if summernote_config['iframe'] \ else ...
1696487
from rated_statistic_storage import * from constraint_item import * class Constraint(object): """Contains the whole constraint with corresponding reactions. """ def __init__( self, name, constraint_root, planned_reaction, min_reaction_interval, reaction_timeout): super(Co...
1696523
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from post.models import Channel, Question from post.forms import post_form class TestPostViews(TestCase): @classmethod def setUpTestData(cls): user = User.objects.create_user(username="usern...
1696630
from ...scheme import Scheme from ..schemeinfo import SchemeInfoDialog from ...gui import test class TestSchemeInfo(test.QAppTestCase): def test_scheme_info(self): scheme = Scheme(title="A Scheme", description="A String\n") dialog = SchemeInfoDialog() dialog.setScheme(scheme) stat...
1696649
from ..filters import run_filters, cheap_filters, all_filters from ..utils.misc import invert, values_map_to_same_key, one_hot from ..utils.graph_ops import get_node_cover from .alldiffs import count_alldiffs import numpy as np from functools import reduce # TODO: count how many isomorphisms each background node parti...
1696664
import datetime import json from nose.tools import eq_, ok_ import mock from django.conf import settings from django.contrib.auth.models import Group from django.utils import timezone from django.core.urlresolvers import reverse from airmozilla.main.models import ( Event, EventTweet, Location, Approv...
1696679
from torch import optim from contextlib import contextmanager class Trainer: r"""Abstract base class for training models. The Trainer class makes it incredibly simple and convinient to train, monitor, debug and checkpoint entire Deep Learning projects. Simply define your training loop by implemen...
1696733
import csv from Bio.Blast import NCBIWWW from Bio.Blast import NCBIXML from Bio import SeqIO import shutil import re import os from collections import defaultdict from time import sleep class CalculateReferenceProteomeSimilarity: def __init__(self, input_file, input_fasta, output_file, match_length=8, species='hum...
1696745
import math import torch import torch.nn as nn class PositionEncoding(nn.Module): """ Add positional information to input tensor. :Examples: >>> model = PositionEncoding(d_model=6, max_len=10, dropout=0) >>> test_input1 = torch.zeros(3, 10, 6) >>> output1 = model(test_input1) ...
1696843
from utils import youtube_authenticate, get_video_id_by_url, get_channel_id_by_url def get_comments(youtube, **kwargs): return youtube.commentThreads().list( part="snippet", **kwargs ).execute() if __name__ == "__main__": # authenticate to YouTube API youtube = youtube_authe...
1696851
from enum import auto from functools import lru_cache from typing import Any, Dict, Optional import sqlalchemy as sa from pydantic import validator from fastapi_auth.fastapi_util.settings.base_api_settings import BaseAPISettings from fastapi_auth.fastapi_util.util.enums import StrEnum class DatabaseBackend(StrEnum)...
1696869
logs = { "img": [ "[INFO] Loading input image: {}", "[ERROR] On '{}': you need to pass the image path!", "\te.g. --img='Pictures/notNord.jpg'" ], "out": [ "[INFO] Set output image name: {}", "[ERROR] On '{}': no output filename specify!", "\te.g. --out='Pict...
1696891
import abc import typing as t from .protocols import UserLike class UserProvider(abc.ABC): # pragma: no cover """User provides perform user look ups over data storages. These classes are consumed by Authenticator instances and are not designed to be a part of login or logout process.""" async def f...
1696896
from collections import OrderedDict import pytest from deepspeech.data.alphabet import Alphabet SYMBOLS = OrderedDict([(symbol, index) for index, symbol in enumerate('abcd')]) @pytest.fixture def alphabet(): return Alphabet(SYMBOLS.keys()) def test_duplicate_symbol_raise_valuerror(): with pytest.raises(...
1696920
import numpy as np import tools import warnings class Alpha(): """ Docstring for ALPHA. Alpha is the an influence coefficient matrix Influence coefficient matrix is a representation of the change of vibration vector in a measuring point when putting a unit weight on a balancing plane. """ ...
1696923
class Player: def __init__( self, username: str, player_class, ): self.username = username self.invetory = Inventory() self.player_class = player_class self.skills = None self.gender = None self._count = 0 self.direction...
1696976
from __future__ import absolute_import from __future__ import print_function import glob import gc import numpy as np from lmatools.stream.subset import coroutine from lmatools.density_tools import unique_vectors import logging log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # ---------------...
1696981
import tensorflow as tf import model as M bn_training = True def conv_layers(inp,reuse=False): global bn_training with tf.variable_scope('enc',reuse=reuse): mod = M.Model(inp) mod.set_bn_training(bn_training) mod.convLayer(7,16,stride=2,activation=M.PARAM_LRELU,batch_norm=True) #128 mod.convLayer(5,32,str...
1697069
import tensorflow as tf class NodeSequenceTest(tf.test.TestCase): def test_node_sequence(self): neighborhood = tf.constant([ [1, 0, 3, -1], [2, 1, 0, -1], ]) nodes = tf.constant([ [0.5, 0.5, 0.5], [1.5, 1.5, 1.5], [2.5, 2.5, 2.5...
1697101
import matplotlib.pyplot as plt import seaborn as sns import numpy as np from matplotlib import gridspec sns.set_style("whitegrid") def plot_residuals(predicted_series, actual_series, time_vector, num_training_points, num_validation_points, ...
1697124
import pandas as pd import numpy as np from typing import List, Optional import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") class Indices: """ Price Technical Indicators """ def __init__( self, df: pd.DataFrame, date_col: str = "date", price_col: str = "price" ...
1697170
import torch import torch.nn.functional as F def to_tensor(x): if type(x).__name__ == 'ndarray': return torch.Tensor(x) else: return x def clipwise_binary_crossentropy(output_dict, target_dict): '''Weakly labelled loss. The output and target have shape of: (batch_size, classes_num) ...
1697175
from collections import defaultdict from ..config_new import ID_RESOLVING_APIS from ..utils.common import getPrefixFromCurie, getValFromCurie class CurieGroup: def __init__(self, semanticType, curies): self.semanticType = semanticType self.curies = curies @staticmethod def _findAPI(seman...
1697177
from torch.nn import Sequential, Conv2d, BatchNorm2d, ReLU from ..utils import RichRepr class Bottleneck(RichRepr, Sequential): r""" A 1x1 convolutional layer, followed by Batch Normalization and ReLU """ def __init__(self, in_channels: int, out_channels: int): super(Bottleneck, self).__init...
1697211
import pytest from brownie import network, AdvancedCollectible def test_can_create_advanced_collectible( get_account, get_vrf_coordinator, get_keyhash, get_link_token, chainlink_fee, get_seed, ): # Arrange if network.show_active() not in ["development"] or "fork" in network.show_active...
1697233
import pickle from blinker._utilities import symbol def test_symbols(): foo = symbol('foo') assert foo.name == 'foo' assert foo is symbol('foo') bar = symbol('bar') assert foo is not bar assert foo != bar assert not foo == bar assert repr(foo) == 'foo' def test_pickled_symbols(): ...
1697279
import math class Queue(object): def __init__(self): self.__values = [] def enqueue(self, v): self.__values.insert(0, v) def dequeue(self): if len(self.__values) == 0: return None else: return self.__values.pop() def len(self): return l...
1697282
from ._operation import RingQK, RingAV from .layers import TransformerSelfAttentionRing __all__ = ['TransformerSelfAttentionRing', 'RingAV', 'RingQK']
1697339
import abc import enum from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd Record = Dict[str, Any] Records = List[Record] InputRecords = Union[Records, pd.DataFrame] DataRecord = Tuple[Dict[str, Union[np.ndarray, float]], ...] BatchDataRecords = Tuple[Dict[str, np.ndarray], ...] ...
1697395
SECRET_KEY = 'tests' INSTALLED_APPS = [ "drynk", "drynk.tests", ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'drynk.sqlite3', } }
1697402
import json import functools IOS_OSS_APPS_DATASET = "../oss_ios_apps/contents_july_2018.json" @functools.lru_cache() def get_project(gh_user, gh_project): """Ola.""" project_name = f"{gh_user}/{gh_project}" datastore = _read_app_dataset() projects = datastore['projects'] return next( (proj...
1697470
import struct from typing import Optional from bxgateway import ont_constants from bxgateway.messages.ont.ont_message import OntMessage from bxgateway.messages.ont.ont_message_type import OntMessageType class VerAckOntMessage(OntMessage): MESSAGE_TYPE = OntMessageType.VERACK def __init__(self, magic: Option...
1697486
import pytest import shutil from pathlib import Path from click.testing import CliRunner from bnmutils import ConfigParser from bnmutils.novelty import cd from logme.exceptions import LogmeError from logme.utils import get_logger_config from logme import __version__ from logme import cli class TestCli: @clas...
1697488
from .base import * import dj_database_url ALLOWED_HOSTS = ['.herokuapp.com'] DEBUG = False STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # overide database settings db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)
1697563
import ipaddress import sys from contextlib import contextmanager from types import SimpleNamespace from typing import ( Any, Awaitable, Callable, Dict, Generator, Iterable, Optional, Set, cast, ) import aiohttp from aiohttp import ( TraceRequestEndParams, TraceRequestExcept...
1697576
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * CLI_ADD = "add backup local" BASH_ADD = '/etc/cli.sh -c "' + CLI_ADD + '"' def main(): res = [] tbl = [] devices = demisto.get(demisto.args(), 'devices') devicesBackupStarted = [] devicesBackupErr...
1697601
from sqlalchemy.orm.exc import NoResultFound from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship from flask_rest_jsonapi.exceptions import ObjectNotFound from commandment.apps.schema import ApplicationManifestSchema, ApplicationSchema, ManagedApplicationSchema from commandment.apps.models ...
1697605
from collections import defaultdict def count_extra_contrib(sufficient_count, n): extra = 0 for i in range(sufficient_count): extra += (n-(i+1)) return extra for _ in range(int(input())): n = int(input()) count_of_pattern = defaultdict(int) non_sufficient_patterns = [] extra = 0 cnt = 0 sufficient_count =...
1697656
import random from adsimulator.utils.principals import get_cn, get_sid_from_rid, get_dn from adsimulator.utils.users import get_user_timestamp, generate_sid_history from adsimulator.utils.boolean import generate_boolean_value from adsimulator.utils.parameters import get_perc_param_value, print_user_generation_parameter...
1697688
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(os.path.join(ROOT_DIR, 'utils')) from .losses import smoothl1_loss, l1_loss, SigmoidFocalClassificationLo...
1697696
def get_job_definition(account, region, container_name, job_def_name, job_param_s3uri_destination, memoryInMB, ncpus, role_name): """ This is the job definition for this sample job. :param account: :param region: :param container_name: :param job_def_name: :param memoryInM...
1697711
from UE4Parse.BinaryReader import BinaryStream from UE4Parse.Assets.Objects.FText import FText class FNavAgentSelectorCustomization: SupportedDesc: FText def __init__(self, reader: BinaryStream): self.SupportedDesc = FText(reader)
1697728
import pandas as pd from shapely.geometry import LineString, Point from syspy.spatial import spatial, zoning from syspy.transitfeed import feed_links # seconds def to_seconds(time_string): return pd.to_timedelta(time_string).total_seconds() def point_geometry(row): return Point(row['stop_lon'], row['stop_la...
1697738
import pytest from unittest import mock from nesta.packages.novelty.lolvelty import lolvelty def test_lolvelty(): es = mock.MagicMock() es.count.return_value = {'count': 100} # Very novel es.search.return_value = {'hits': {'hits':[{'_score':100}, {'_score'...
1697752
from pathlib import Path from manim import * class Determinant(Scene): def construct(self): text_color = "#333" vect1_color = "#b98b99" vect2_color = "#b9b28b" numberplane = NumberPlane( background_line_style={ "stroke_opacity": 0.4 } ...
1697762
from ctypes import byref, sizeof, c_uint32 from typing import Optional, List, Callable import gc from .vimba_object import VimbaObject from .vimba_exception import VimbaException from .frame import Frame from . import vimba_c SINGLE_FRAME = 'SingleFrame' CONTINUOUS = 'Continuous' def _camera_infos() -> List[vimba_...
1697801
import FWCore.ParameterSet.Config as cms process = cms.Process('RERECO') # this is to avoid the postpathendrun probem with same process name (only with http reader) process.options = cms.untracked.PSet( IgnoreCompletely = cms.untracked.vstring('Configuration') # SkipEvent = cms.untracked.vstring('Configuration...
1697809
from typing import Dict, List, Tuple, Union, Any, TypeVar from scipy.sparse.csr import csr_matrix from numpy import memmap from sqlitedict import SqliteDict from tempfile import mkdtemp from DocumentFeatureSelection.init_logger import logger from numpy import ndarray, int32, int64 import pickle import json import csv i...
1697811
personas = int(input("¿Cuantas personas hay en su grupo de cena?")) if personas > 8: print("Tendran que esperar una mesa") else: print("Su mesa esta lista")
1697821
from django.conf.urls.defaults import * urlpatterns = patterns('saved_searches.views', url(r'^most_recent/$', 'most_recent', name='saved_searches_most_recent'), url(r'^most_recent/username/(?P<username>[\w\d._-]+)/$', 'most_recent', name='saved_searches_most_recent_by_user'), url(r'^most_recent/area/(?P<s...
1697848
from typing import Any, Dict from sovereign.sources.lib import Source from sovereign.config_loader import Loadable class File(Source): def __init__(self, config: Dict[str, Any], scope: str = "default"): super(File, self).__init__(config, scope) try: self.path = Loadable.from_legacy_fmt...
1697856
import json import os import typing from pathlib import Path import reseval ############################################################################### # Get subjective evaluation results ############################################################################### def results( name: str, directory: ...
1697892
import tkinter as tk count=0 def reset(): global count count=0 def EXIT(): window.destroy() def counter(): global count if(count>=10 and count<20): label2.config(text=str(count),fg='green') elif(count>=20): label2.config(text=str(count),fg='red2') ...
1697921
class BaseClass: """Simple BaseClass with a name.""" def __init__(self, name: str): self.name = name def say_hi(self): print(f"I'm {self.name} of type {type(self)}") def short_desc(self) -> str: return f"BaseClass({self.name})" class ChildClass(BaseClass): """Simple chil...
1697975
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import dill from collections import defaultdict import numpy as np import pandas as pd import torch from torch.ut...
1697984
from bs4 import BeautifulSoup from datetime import datetime from threading import Lock mutex = Lock() class AdapterXinhua: def __init__(self): self.clear() def clear(self): self.name = 'xinhua' self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Appl...
1697986
import os import dill import numpy as np def get_function_path(base_path=None, experiment_name=None, make=True): """ This function gets the path to where the function is expected to be stored. Parameters ---------- base_path : str Path to the directory where the experiments are to be sto...
1698092
from PyHook import wait_for_process, on_credential_submit, log import frida import sys hook_process_name = "explorer" def logger(message): log(hook_process_name, message) def wait_for(): hook() def hook(): try: logger("Trying To Hook Into Explorer") session = frida.attach("explorer.ex...
1698109
import numpy as np from scipy.sparse import linalg def weighted_mean(x, w): # numpy.average can do the same computation assert(x.shape == w.shape) s = w.sum() if s == 0: raise ValueError("Sum of weights is zero") return (x * w).sum() / s def get_solver_(method, **kwargs): def lstsq...
1698138
import numpy as np import pandas as pd import quantipy as qp import copy import re import warnings from quantipy.core.tools.dp.query import uniquify_list from quantipy.core.helpers.functions import ( emulate_meta, cpickle_copy, get_rules_slicer, get_rules, paint_dataframe ) from quantipy.core.tool...
1698204
import sys import urllib3 import certifi import re import os import random import time from json import loads import socket from urllib3.contrib.socks import SOCKSProxyManager from bs4 import BeautifulSoup from tqdm import tqdm import asyncio import aiohttp import sqlite3 # setup colored output from colorama import i...
1698250
import geopandas as gpd import networkx as nx import pandas as pd import shapely from shapely.ops import cascaded_union from syspy.spatial import polygons, spatial from syspy.syspy_utils import neighbors, pandas_utils, syscolors from tqdm import tqdm def compute_coverage_layer(layer, buffer, extensive_cols=[]): "...
1698261
from messagebird.base import Base from messagebird.call_data import CallData CALL_STATUS_STARTING = "starting" CALL_STATUS_ONGOING = "ongoing" CALL_STATUS_ENDED = "ended" class Call(Base): def __init__(self): self.id = None self._data = None @property def data(self): return self...
1698269
from PIL import Image, ImageStat import numpy as np def is_color_image(file, thumb_size=50, MSE_cutoff=140, adjust_color_bias=True): try: pil_img = Image.open(file) except: print 'Couldn\'t open file %s'%file return False np_img = np.array(pil_img) if len(np_img.shape) > 2 and ...
1698278
from __future__ import absolute_import import inspect import logging import warnings import threading import lore.env import lore.estimators from lore.util import timed, before_after_callbacks lore.env.require( lore.dependencies.XGBOOST + lore.dependencies.SKLEARN ) import xgboost logger = logging.getLogge...
1698282
import time, os, json, sys start_time = time.time() from modules.main import ArgParse from modules.logging import Logger from modules import process as k8s from modules.get_svc_acc import K8sSvcAcc class ServiceAccount: def __init__(self, namespace, logger): self.namespace = namespace self.logger =...
1698294
import torch # torch.manual_seed(0) import torch.nn as nn from modelZoo.resNet import ResNet, Bottleneck, BasicBlock from modelZoo.DyanOF import creatRealDictionary from utils import generateGridPoles, gridRing,fista import numpy as np def load_preTrained_model(pretrained, newModel): 'load pretrained resnet-X to s...
1698306
import matplotlib import matplotlib.pyplot as plt import numpy as np import pytest from SphereVoxelization_fft import compute_2d, compute_3d import freud matplotlib.use("agg") class TestSphereVoxelization: def test_random_points_2d(self): width = 100 r_max = 10.0 num_points = 10 ...
1698312
from __future__ import absolute_import, division, print_function # LIBTBX_SET_DISPATCHER_NAME iotbx.pdb.split_models from libtbx.utils import Sorry, Usage, null_out import os import sys master_phil = """ split_models .short_caption = Split multi-model PDB file .caption = This utility will separate a multi-model P...
1698336
import asyncio import json import logging import random from contextlib import suppress import pmdefaults as PM try: import aiohttp from aiohttp import web except ImportError as e: web = None logging.warning("aiohttp in required to start the REST interface, but it is not installed") try: resthelp...
1698339
from pyhafas import HafasClient from pyhafas.profile import VSNProfile def test_vsn_locations_request(): client = HafasClient(VSNProfile()) locations = client.locations(term="Göttingen Bahnhof/ZOB") assert len(locations) >= 1
1698344
from typing import Callable import pytest from tests.taxonomy.conftest import TestDirectory, validate_taxonomy @pytest.mark.parametrize( "defect", [(1, 79), (2, 120), (3, 122), (4, 86), (5, 40)], ) def test_xbps(defect, defect_path: Callable[[int, int], TestDirectory], gitenv): index, case = defect ...
1698357
import requests, os import json is_prod = True webhook_url = os.environ.get('SLACKBOT_WEBHOOK_URL', '') def post_health(message): if not is_prod: return r = requests.post(webhook_url, data=json.dumps({"text": message}), headers={'content-type':'application/json'}) return r
1698376
from time import time import numpy as np from cd4ml.get_encoder import get_trained_encoder from cd4ml.logger.fluentd_logging import FluentdLogger from cd4ml.model_tracking import tracking from cd4ml.model_tracking.validation_metrics import get_validation_metrics from cd4ml.utils.problem_utils import Specification from ...
1698384
import numpy as np import scipy.interpolate as si def euclidean_distance(a, b): diff = a - b return np.sqrt(np.dot(diff, diff)) # source: https://stackoverflow.com/questions/34803197/fast-b-spline-algorithm-with-numpy-scipy def bspline(cv, n=100, degree=3, periodic=False): """Calculate n samples on a bs...
1698393
from __future__ import with_statement import datetime import sys import os try: from urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl import requests import requests_mock from requests.exceptions import ConnectTimeout from akismet import Akismet, SpamStatus, AKISMET_CHECK_URL...
1698403
from protocols import participant_1_0_0 from protocols import participant_1_0_3 from protocols.migration import BaseMigration class MigrationParticipants103To100(BaseMigration): old_model = participant_1_0_3 new_model = participant_1_0_0 def migrate_cancer_participant(self, cancer_participant): m...
1698415
from aiogram.dispatcher.filters.state import State, StatesGroup class ConfigFlow(StatesGroup): waiting_for_api_key = State() class SettingsFlow(StatesGroup): waiting_for_setting_select = State() waiting_for_new_key = State()
1698468
from typing import AnyStr, List from pyre_extensions import safe_json from backend.common.datafeed_parsers.exceptions import ParserInputException from backend.common.models.alliance import EventAlliance from backend.common.models.keys import TeamKey from backend.common.models.team import Team class JSONAllianceSele...
1698507
MOCK_USERS = [{"email": "<EMAIL>", "salt": "8Fb23mMNHD5Zb8pr2qWA3PE9bH0=", "hashed": "1736f83698df3f8153c1fbd6ce2840f8aace4f200771a46672635374073cc876cf0aa6a31f780e576578f791b5555b50df46303f0c3a7f2d21f91aa1429ac22e"}] class MockDBHelper: def get_user(self, email): user = [x for x in MOCK_U...
1698585
from carriage import Row, X def test_basic(): assert X.y(Row(x=2, y=3)) == 3 assert X['x'](dict(x=4, y=5)) == 4 assert (X + 3)(5) == 8 assert (X - 2)(6) == 4 assert (X * 3)(4) == 12 assert (X / 2)(9) == 4.5 assert (X // 2)(9) == 4 assert (X % 3)(5) == 2 assert (divmod(X, 3))(5) == ...