id
stringlengths
3
8
content
stringlengths
100
981k
11544115
from error import Error class Token(): def __init__(self, type, value): self.type = type self.value = value class Lexer(): def __init__(self, code): """Initializes an instance of Lexer Arguments: code {str} -- The raw text written by the user """ se...
11544116
import pykd def get_address(localAddr): res = pykd.dbgCommand("x " + localAddr) result_count = res.count("\n") if result_count == 0: print localAddr + " not found." return None if result_count > 1: print "[-] Warning, more than one result for", localAddr return res.split()[0] class handle_allocate_heap(p...
11544147
from pydantic.types import ConstrainedInt, ConstrainedFloat class PositiveInt(ConstrainedInt): # These ensure mypy knows what is going on with constrained types # Directly using confloat, conint works, but mypy gets unhappy. # https://github.com/samuelcolvin/pydantic/issues/239 ge = 0 class UnitFloa...
11544203
from setuptools import setup with open('README.rst') as f: long_description = f.read() setup( name='pytest-faulthandler', version="2.0.1", url='https://github.com/pytest-dev/pytest-faulthandler', license='MIT', install_requires=['pytest>=5.0'], author='<NAME>', author_email='<EMAIL>',...
11544216
import datetime from sdcclient._common import _SdcCommon class ActivityAuditDataSource: CMD = "command" NET = "connection" KUBE_EXEC = "kubernetes" FILE = "fileaccess" _seconds_to_nanoseconds = 10 ** 9 class ActivityAuditClientV1(_SdcCommon): def __init__(self, token="", sdc_url='https://secu...
11544231
from django.db import models, IntegrityError from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature from modeltests.delete.models import (R, RChild, S, T, U, A, M, MR, MRNull, create_a, get_default_r, User, Avatar, HiddenUser, HiddenUserProfile) class OnDeleteTests(TestCase): def setUp(self):...
11544234
from enum import Enum, auto from typing import Tuple class EndpointType(Enum): # endpoint / collection types GCP = auto() GCSV5_ENDPOINT = auto() GUEST_COLLECTION = auto() MAPPED_COLLECTION = auto() SHARE = auto() NON_GCSV5_ENDPOINT = auto() # most likely GCSv4, but not necessarily @...
11544240
from ztag.annotation import * class DLinkVoIPRouter(Annotation): protocol = protocols.HTTP subprotocol = protocols.HTTP.GET port = None def process(self, obj, meta): if obj["title"].strip() == "D-Link VoIP Router": meta.global_metadata.manufacturer = Manufacturer.DLINK ...
11544248
from fastapi import APIRouter from fastdash.api.routes import fastdash router = APIRouter() router.include_router(fastdash.router, tags=["fastdash"], prefix="/fastdash")
11544255
from xml.dom.minidom import Document import cv2 import os import glob import shutil import numpy as np from tools.convert_utils import build_voc_dirs def generate_xml(img_name, lines, img_size, class_sets): doc = Document() def append_xml_node_attr(child, parent=None, text=None): ele = doc.createEle...
11544264
class stacki: size=0 capacity=1000 li=[0]*capacity def __init__(self): pass def empty(self): return self.size==0 def full(self): return self.size==self.capacity def push(self,a): if self.size==self.capacity: print("Stack ful...
11544405
from django.db import models from django.utils import timezone class DoorStatus(models.Model): datetime = models.DateTimeField() status = models.BooleanField(default=False) name = models.CharField(max_length=20) def __str__(self): return self.name @staticmethod def get_door_by_name(n...
11544422
from services.VideoRehabService.ConfigManager import ConfigManager config_man = ConfigManager() redis_client = None api_user_token_key = None api_device_token_key = None api_device_static_token_key = None api_participant_token_key = None api_participant_static_token_key = None
11544425
import astropy.units as astropy_units import numpy as np from past.utils import old_div import astromodels.functions.numba_functions as nb_func from astromodels.core.units import get_units from astromodels.functions.function import (Function1D, FunctionMeta, ModelAssertionVi...
11544455
import pandas as pd import numpy as np from surprise import Reader, Dataset from surprise.model_selection import cross_validate import surprise as sp train_data = pd.read_csv('train.csv', parse_dates=["date"]) test_data = pd.read_csv('test.csv', parse_dates=["date"]) # Prepare data reader = Reader() data = Dataset.l...
11544462
import logging from dataclasses import dataclass, field from datetime import datetime, timezone, timedelta from typing import Optional import coloredlogs import requests from dataclasses_json import dataclass_json from dateutil.parser import parse, parserinfo from pyquery import PyQuery as pq logger = logging.getLogg...
11544534
from django.urls import path from . import views urlpatterns = [ path('site_topology/', views.SiteTopologyView.as_view(), name='site_topology'), path('topology/', views.TopologyView.as_view(), name='topology'), ]
11544565
from .base import BaseConfiguration class Local(BaseConfiguration): # Apps INSTALLED_APPS = BaseConfiguration.INSTALLED_APPS INSTALLED_APPS += ["debug_toolbar"] # Debug DEBUG = True # https://docs.djangoproject.com/en/dev/ref/settings/#internal-ips INTERNAL_IPS = ["127.0.0.1"] # Ch...
11544588
from pytest import raises from sqlalchemy_continuum import ( ClassNotVersioned, transaction_class, versioning_manager ) from tests import TestCase class TestTransactionClass(TestCase): def test_with_versioned_class(self): assert ( transaction_class(self.Article) == ver...
11544641
import numpy as np from geopandas import GeoDataFrame from shapely.geometry import Polygon from region.tests.util import region_list_from_array, convert_from_geodataframe from region.util import dataframe_to_dict # The following data describe the max-p-regions problem depicted in figure 2 on # p. 402 in [DAR2012]_. ...
11544660
import sys import os from github import Github from dotenv import load_dotenv load_dotenv() path = os.getenv("FILEPATH") username = os.getenv("USERNAME") password = os.getenv("PASSWORD") def create(): folderName = str(sys.argv[1]) folderpath = os.path.join(path,folderName) if os.path.exists(folderpath): ...
11544662
from selenium import webdriver from selenium.webdriver.common.by import By import time class SwitchToWindow(): def test(self): baseUrl = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.maximize_window() driver.get(baseUrl) # Find paren...
11544686
import sys from ralph.settings import * # noqa # for dhcp agent test sys.path.append(os.path.join(BASE_DIR, '..', '..', 'contrib', 'dhcp_agent')) DEBUG = False TEST_DB_ENGINE = os.environ.get('TEST_DB_ENGINE', 'mysql') if TEST_DB_ENGINE == 'psql': DATABASES['default'].update({ 'ENGINE': 'transaction_ho...
11544688
from .general_r2 import GeneralOnR2 from .rot2d_on_r2 import Rot2dOnR2 from .fliprot2d_on_r2 import FlipRot2dOnR2 from .flip2d_on_r2 import Flip2dOnR2 from .trivial_on_r2 import TrivialOnR2 __all__ = [ "GeneralOnR2", "Rot2dOnR2", "FlipRot2dOnR2", "Flip2dOnR2", "TrivialOnR2", ]
11544714
from mod_pywebsocket import common from mod_pywebsocket import stream def web_socket_do_extra_handshake(request): pass def web_socket_transfer_data(request): payload1 = b'Invalid continuation frame to be ignored.' payload2 = b'Valid frame after closing should be disposed.' request.connection.write( ...
11544722
from wandb.plot.bar import bar from wandb.plot.confusion_matrix import confusion_matrix from wandb.plot.histogram import histogram from wandb.plot.line import line from wandb.plot.line_series import line_series from wandb.plot.pr_curve import pr_curve from wandb.plot.roc_curve import roc_curve from wandb.plot.scatter i...
11544731
from .single_level import SingleRoIExtractor from .single_level_straight3d import SingleRoIStraight3DExtractor __all__ = [ 'SingleRoIExtractor', 'SingleRoIStraight3DExtractor' ]
11544743
from orchestra.contrib.settings import Setting ORDERS_BILLING_BACKEND = Setting('ORDERS_BILLING_BACKEND', 'orchestra.contrib.orders.billing.BillsBackend', validators=[Setting.validate_import_class], help_text="Pluggable backend for bill generation.", ) ORDERS_SERVICE_MODEL = Setting('ORDERS_SERVICE_MODE...
11544745
from libsaas import http, parsers from libsaas.services import base from . import resource class Replies(resource.PaginatedDeskResource): path = 'replies' class Reply(resource.DeskResource): path = 'replies' class CasesBase(resource.DeskResource): path = 'cases' class Cases(CasesBase): def ...
11544781
import array from PIL import Image SLICES = 361 size = (100, 100, 100) imout = Image.new("L", (size[0], size[1]*size[2])) for i in range(size[2]): z = i * SLICES/size[2] filename = "bunny/"+str(z+1)+".png" im = Image.open(filename) im = im.resize((110, 110)) region = im.crop((3, 7, 103, ...
11544813
from setuptools import setup, find_packages def get_readme_rst(): import subprocess try: proc = subprocess.Popen( ['pandoc', 'README.md', '--to', 'rst'], stdout=subprocess.PIPE ) description = proc.communicate()[0].decode() except OSError: with open(...
11544831
def error (x,y) : if y != '(' and y != ')' and y != '0' and y != '1' and y != '*': print ("Недопустимый символ", y) elif x == 0 and y == '(': print ("Ожидался символ (") elif x == 1 and y == ')' : print ("Количество единиц не удовлетворяет условию. Ожидался символ 1") elif x == 1...
11544832
from typing import Type from .charybdis import CharybdisController class SolanumController(CharybdisController): software_name = "Solanum" binary_name = "solanum" def get_irctest_controller_class() -> Type[SolanumController]: return SolanumController
11544853
import timeit from random import randint def stooge_sort(collection, left, right, counter): if left >= right: return if collection[right] < collection[left]: collection[left], collection[right] = collection[right], collection[left] counter += 1 print("Step %i -->" % counter, ...
11544904
class Solution: def numSubseq(self, nums: List[int], target: int) -> int: nums.sort() if nums[0] * 2 > target: return 0 MOD = 10 ** 9 + 7 left = 0 right = len(nums) - 1 ret = 0 while left <= right: if nums[left] + nums[right] <= target:...
11544908
from django.urls import path import qatrack.reports.views as views urlpatterns = [ path('', views.select_report, name="reports"), path('filter/', views.get_filter, name="reports-filter"), path('preview/', views.report_preview, name="reports-preview"), path('save/', views.save_report, name="reports-sav...
11544923
def count_provider(count: int): sum = 0 for i in range(count): sum = sum+i return sum
11544944
import os import sys from io import open import torch from torch import nn import numpy as np from GPG.models.model_utils import init_wt_normal class BertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config, position_embeddings_fla...
11544961
import PikaStdDevice // kernel // TODO // hal class GPIO(PikaStdDevice.GPIO): def platformHigh(): pass def platformLow(): pass def platformEnable(): pass def platformDisable(): pass def platformSetMode(): pass def platformRead(): pass
11544983
import pkg_resources # These test files need to be available to the rest of the test suite # They are included in MANIFEST.in example_data_dir = pkg_resources.resource_filename(__name__, 'data')
11545024
from django.core.management.base import BaseCommand from onadata.apps.logger.models import XForm, Instance from onadata.apps.fsforms.models import XformHistory, FInstance from onadata.settings.local_settings import XML_VERSION_MAX_ITER import os import re class Command(BaseCommand): help = 'Check if XForm and Xfo...
11545053
import json import logging from pocket import Pocket, PocketException from .logger import Log logger = Log.get_logger(__name__) class PocketAPIClient: pocket_client = None def __init__(self, consumer_key, access_token): self.pocket_client = Pocket(consumer_key, access_token) def get_articles_da...
11545057
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404 from django.utils.timezone import now from django.views.decorators.http import require_safe from django.http import HttpResponseForbidden from core.csv_export import CSV_EXPORT_FORMATS, csv_response from core.mod...
11545065
import click from prog.cli import delete from prog.cli import set from prog.cli import show from prog import client from prog import output from prog import utils import time def _list_profile_display_format(rule): rule["type"] = client.CfgTypeDisplay[rule["cfg_type"]] rule["modified"] = time.strftime("%Y-%m...
11545103
import json import sys def load(path): with open(path, "r") as f: return f.read().strip() args = sys.argv[1:] assert len(args) % 3 == 0, "must be a multiple of three arguments for (name, hash, version) triplets, not: %d" % len(sys.argv[1:]) version_cache = {} for name_file, hash_file, version_file in ...
11545113
from .app import SparkCeleryApp from .task import SparkCeleryTask from .cache import cache from .main import main
11545118
from unittest import TestCase from office365.sharepoint.client_context import ClientContext from office365.sharepoint.directory.SPHelper import SPHelper from office365.sharepoint.directory.directory_session import DirectorySession from tests import test_user_credentials, test_site_url class TestDirectorySession(Test...
11545144
from abc import ABC, abstractmethod class Factory(ABC): @abstractmethod def instance(self): pass
11545152
from followthemoney.dedupe.judgement import Judgement import structlog from itertools import combinations from opensanctions.core.dataset import Dataset from opensanctions.core.context import Context from opensanctions.core.loader import Database from opensanctions.core.entity import Entity from opensanctions.core.htt...
11545157
SECURITY_BYPASS_HEADERS = { 'Connection': 'keep-alive', 'Tele2-User-Agent': '"mytele2-app/3.17.0"; "unknown"; "Android/9"; "Build/12998710"', 'X-API-Version': '1', 'User-Agent': 'okhttp/4.2.0' } MAIN_API = 'https://my.tele2.ru/api/subscribers/' SMS_VALIDATION_API = 'https://my.tele2.ru/api/validation/n...
11545160
class DestList: def __init__(self): self.destList = [] def getDestList(self): return self.destList def setDestList(self, destList): self.destList = destList
11545187
from pytest import mark, skip from sys import version_info from argparse import OPTIONAL, ZERO_OR_MORE, ONE_OR_MORE, REMAINDER @mark.parametrize('action', ['store', 'append', 'extend']) def test_actions_with_argument(empty_parser, autocomplete_and_compare, action): if action == 'extend' and version_info.minor < 8...
11545200
from distutils.core import setup setup( name='typy', version='0.2.0', author='<NAME>', author_email='<EMAIL>', packages=('typy',), py_modules=('typy',), url='http://www.github.com/cyrus-/typy', license='MIT', description='A programmable static type system, embedded into Python.', long_description='', instal...
11545204
COMPANIES_HOUSE_COMPANY = 'companies-house-company' NON_COMPANIES_HOUSE_COMPANY = 'non-companies-house-company' NOT_COMPANY = 'not-company' OVERSEAS_COMPANY = 'overseas-company' # companies that have companies house numbers prefixed with below do not have address in companies house COMPANY_NUMBER_PREFIXES_INCOMPLETE_I...
11545207
import json import os import shlex import subprocess from jinja2 import Environment, BaseLoader import pytest ## Uncomment following lines for running in shell # os.environ['TEST_PROFILE_DIR'] = 'profiles/webapp' # os.environ['PIPDEPTREE_EXE'] = 'profiles/webapp/.env_python3.6_pip-latest/bin/pipdeptree' test_profi...
11545236
from . import color_space, generators, pc_io, quality_eval, parallel_process, grid __all__ = ['color_space', 'generators', 'pc_io', 'quality_eval', 'parallel_process', 'grid']
11545243
class Solution: def preorder(self, root: 'Node') -> List[int]: # base_case: traverse_stack = [root] path = [] # general case: while traverse_stack: current = traverse_stack.pop() if current: ...
11545244
from abc import ABC, abstractmethod from typing import Union from discord import User from redbot.core import Config from redbot.core.bot import Red from redbot.core.commands import Cog from .classes import Letter class MixinMeta(ABC): def __init__(self, *_args): self.bot: Red self.config: Confi...
11545263
import pickle import sys from typing import Dict import elasticsearch import time import tqdm sys.setrecursionlimit(10000) from preprocessing.pipeline_job import PipelineJob def some_query_terms_entity_pair( triple, hits, es, INDEX_NAME, filter_stopwords, entity_mentions_map_filtered_low_count_implicits_dict )...
11545269
from wordcloud import WordCloud, STOPWORDS def cwordcloud(words, filename='output.png', height=2000, width=4000): words = words.replace(';', ' ') word_cloud = WordCloud(stopwords=STOPWORDS, background_color='white', height=height, width=width).generate(words) word_cloud.to_file(filename) return 1
11545284
from __future__ import print_function import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import time # Training settings parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_ar...
11545311
import re import typing from typing import ( AbstractSet, AsyncContextManager, AsyncGenerator, AsyncIterator, Callable, ChainMap, Collection, Container, Counter, Deque, Dict, FrozenSet, ItemsView, Iterable, Iterator, KeysView, List, Mapping, Ma...
11545344
import os import unittest from collections import namedtuple from celescope.tools.step import Step class Tests(unittest.TestCase): def setUp(self): pass @unittest.skip("tested") def test_stat_to_metric(self): os.chdir('/SGRNJ01/RD_dir/pipeline_test/zhouyiqi/multi_tests/rna') arg...
11545350
import numpy as np from random import randint def flip(image, option_value): """ Args: image : numpy array of image option_value = random integer between 0 to 3 Return : image : numpy array of flipped image """ if option_value == 0: # vertical image = np.fli...
11545358
import sqlite3 from .db import DB class DailySummary(DB): def __init__(self): super().__init__() self.table_name = 'KL_daily_summary' self.table_desc = 'Summary of new COVID-19 cases (last 24 hours)' self.cols = self.getcolumns() def getcolumns(self): cols = { ...
11545369
import logging from typing import Callable from ..helpers import Helpers class StreamHandler(object): def __init__(self, event: str, invocation_id: str): self.event = event self.invocation_id = invocation_id self.logger = Helpers.get_logger() self.next_callback =\ lambda...
11545372
from collections import namedtuple Performance = namedtuple( 'Performance', ['name', 'get', 'get_buy_and_hold', 'hline']) sharpe_ratio_performance = Performance( name='Sharpe ratio', get=lambda environment: environment.get_sharpe_ratio(), get_buy_and_hold=lambda environment: environment.get_sharpe_rat...
11545390
import json import pytest import requests_mock from pubg_python.base import PUBG, Shard, APIClient from pubg_python.domain.base import Match, Roster, Participant, Asset from pubg_python.domain.telemetry.resources import GAME_MODE, SEASON_STATE api = PUBG('apikey', Shard.STEAM) BASE_URL = APIClient.BASE_URL @pytest.f...
11545401
from typing import List, Optional, Tuple import cv2 import numpy as np from l5kit.data.zarr_dataset import AGENT_DTYPE from l5kit.data.filter import filter_agents_by_labels, filter_agents_by_track_id from l5kit.geometry import rotation33_as_yaw # , transform_points from l5kit.rasterization.rasterizer import EGO_EXTE...
11545420
import math import sys def cont(): print("Do you want to continue ") print("Press Y/N to continue and exit respectively") inputchar = input() if inputchar == "Y" or inputchar == "y": switch() elif inputchar == "N" or inputchar == "n": sys.exit() def switch(): print("-" * 40) ...
11545450
import json import requests from utils.logger import log from utils.cmd_args import args class ArgsCheckException(Exception): def __init__(self, _message): self.message = _message def __str__(self): return self.message user_name = list("aaaaaaaaaaaa") def unifie_to_string(_arg): ...
11545514
import numpy as np from scipy.stats.mstats import winsorize from sklearn.linear_model import LinearRegression from sklearn import linear_model from sklearn.mixture import GaussianMixture import scipy from scipy.signal import find_peaks DESCRIPTION = { 'S1': "High shaggy aEEG baseline (constantly at 4-200 mV).", ...
11545570
from setuptools import setup, find_packages long_description = '''\ image-diet is a Django application for removing unnecessary bytes from image files. It optimizes images without changing their look or visual quality ("losslessly"). It works on images in JPEG, GIF and PNG formats and will leave others unchanged. Pr...
11545603
import subprocess from django.conf import settings def create_dict(local=None, field=None, **kwargs): """ 以字典的形式从局部变量locals()中获取指定的变量 :param local: dict :param field: str[] 指定需要从local中读取的变量名称 :param kwargs: 需要将变量指定额外名称时使用 :return: dict """ if field is None or local is None: r...
11545636
from brownie import * from brownie.network.contract import InterfaceContainer from brownie.network.state import _add_contract, _remove_contract import shared from munch import Munch #todo only deploy one token, read the other def deployTokens(acct): print("Deploying test tokens.") tokens = Munch() tokens.su...
11545657
import git import json import psutil def commit_info(path_to_repo): repo = git.Repo.init(path_to_repo) return repo.commit().committed_datetime.isoformat(), str(repo.commit()) def store_additional_data(rev, cdate, resources, filename): data = { 'revision': rev, 'softmasking': True, ...
11545750
in_global_scope = 'in_global_scope_value' class SomeClass(object): def method(self): print('breakpoint here') if __name__ == '__main__': SomeClass().method() print('TEST SUCEEDED')
11545764
from settree.set_data import * from settree.set_tree import * from settree.gbest import * from settree.set_rf import * from settree.operations import * from settree.explainability import *
11545771
import time import subprocess as sp import json import six from dwencode.ffpath import get_ffprobe_path def probe(vid_file_path, ffprobe_path=None): """ From https://stackoverflow.com/a/36743499/1442895 Give a json from ffprobe command line @vid_file_path : The absolute (full) path of the video file, ...
11545782
from pudzu.charts import * df = pd.read_csv("datasets/flagsnewold.csv") groups = list(remove_duplicates(df.group)) array = [[dict(r) for _,r in df.iterrows() if r.group == g] for g in groups] COLS = 3 arrays = list(generate_batches(array, ceil(len(array) / COLS))) datas = [pd.DataFrame(array) for array in arrays] FO...
11545794
from collections import OrderedDict from indy_common.constants import ROLE, CLAIM_DEF_SIGNATURE_TYPE, CLAIM_DEF_SCHEMA_REF from plenum.common.constants import TXN_TYPE, TARGET_NYM, \ DATA, ENC, RAW, HASH, ALIAS, TXN_TIME, VERKEY from plenum.common.types import f def getTxnOrderedFields(): return OrderedDict(...
11545798
import FWCore.ParameterSet.Config as cms source = cms.Source("EmptySource") generator = cms.EDProducer("FlatRandomEGunProducer", PGunParameters = cms.PSet( PartID = cms.vint32(11), MinEta = cms.double(0.0), MaxEta = cms.double(0.0), MinPhi = cms.double(1.57079632679), MaxPh...
11545811
import pytest from padl.dumptools import packagefinder @pytest.fixture def ignore_padl_requirement(monkeypatch): monkeypatch.setattr(packagefinder, '_ignore_requirements', packagefinder._ignore_requirements + ['padl'])
11545835
from typing import Optional from collections import namedtuple import numpy as np __all__ = ["calibration_bins", "multiclass_calibration_bins", "binary_calibration_bins", "average_confidence", "Bins"] Bins = namedtuple("Bins", "accs confs counts edges") def multiclass_calibration_bins(truth: np.ndarray, probs: np....
11545840
from imutils import face_utils import datetime import imutils import time import dlib import cv2, math import numpy as np from imutils import face_utils, rotate_bound # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor print("[INFO] loading facial landmark predictor...") mode...
11545869
from __future__ import annotations import logging import typing from typing import Any, Dict, List from silex_client.action.command_base import CommandBase from silex_client.utils.thread import execute_in_thread if typing.TYPE_CHECKING: from silex_client.action.action_query import ActionQuery import os import p...
11545945
from django.core.urlresolvers import reverse from django.template.context import Context from django.template.loader import get_template from core.prismriver.dashboard.plugins import pluginbase from core.prismriver.settings import CUSTOM_MENU from core.prismriver.dashboard.settings import APP_MENU from core.prismriver....
11545955
import py, sys, subprocess currpath = py.path.local(__file__).dirpath() def setup_make(targetname): if sys.platform == 'win32': py.test.skip("win32 not supported so far") import pypy.module._cppyy.capi.loadable_capi as lcapi popen = subprocess.Popen(["make", targetname], cwd=str(currpath), ...
11545992
from datetime import timedelta from celery.task.schedules import crontab from django.utils import timezone from orchestra.contrib.tasks import periodic_task from . import settings from .models import BackendLog @periodic_task(run_every=crontab(hour=7, minute=0)) def backend_logs_cleanup(): days = settings.ORCH...
11546014
import pandas as pd import numpy as np import streamlit as st import plotly.express as px import plotly.graph_objects as go import matplotlib import matplotlib.pyplot as plt import pages.home import csv import scipy.stats as scs def write(): with st.spinner("Loading Modelling ..."): st.title('A/B Testing'...
11546038
def v_star(y, α, β, μ): """ True value function """ c1 = np.log(1 - α * β) / (1 - β) c2 = (μ + α * np.log(α * β)) / (1 - α) c3 = 1 / (1 - β) c4 = 1 / (1 - α * β) return c1 + c2 * (c3 - c4) + c4 * np.log(y) def σ_star(y, α, β): """ True optimal policy """ return (1 - α * ...
11546065
from IPayment import IPayment from CPU import CPU from VGA import VGA class CreditCard(IPayment): def visit(self, component): if type(component) is CPU: print("Purchase CPU with Credit Card") elif type(component) is VGA: print("Purchase VGA with Credit Card")
11546067
import threading import time class ThreadManager: # Define thread types for starting threads SINGLE = 0 # One thread at once, block if already running MULTIPLE = 1 # Multiple threads, name with counter, and run KILLABLE = 2 # Thread can be killed with a flag REPLACEABLE = 3 # Like SI...
11546083
from models import Base, User from flask import Flask, jsonify, request, url_for, abort from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy import create_engine from flask import Flask engine = create_engine('sqlite:///users.db') Base.metadata...
11546104
import tensorflow as tf def clip_boxes_to_img_boundaries(decode_boxes, img_shape): xmin = decode_boxes[:, 0] ymin = decode_boxes[:, 1] xmax = decode_boxes[:, 2] ymax = decode_boxes[:, 3] img_h, img_w = img_shape[1], img_shape[2] img_h, img_w = tf.cast(img_h, tf.float32), tf.cast(img_w...
11546116
from typing import Any, Dict from pytest_assert_utils import assert_dict_is_subset, assert_model_attrs from pytest_common_subject import precondition_fixture from pytest_lambda import lambda_fixture, static_fixture from pytest_drf import ( APIViewTest, Returns200, Returns201, Returns204, UsesDelet...
11546160
import sys, re from optparse import OptionParser usage = "usage: %prog [options] infile outfile" parser = OptionParser(usage=usage) parser.add_option("-f", "--from", dest="from_string", type="string", help="The value to that will be replaced.") parser.add_option("-t", "--to", dest="to_string", type="...
11546165
from typing import List from boa3.builtin import public from boa3.builtin.interop.runtime import Notification from boa3.builtin.type import UInt160 from boa3_test.test_sc.interop_test.runtime.GetNotifications import with_param @public def main(args: list, key: UInt160) -> List[Notification]: return with_param(ar...
11546173
import nox @nox.session(python=["3.7", "3.8", "3.9", "3.10"]) def tests(session): session.install(".[all]") session.install(".[tests]") session.run("pytest", "--disable-warnings", "--asyncio-mode=auto")
11546184
import unittest import json import os from jinja2 import TemplateNotFound from PyStacks.PyStacks.template import getResources from PyStacks.PyStacks.template import template from PyStacks.PyStacks.template import writecompiled from PyStacks.PyStacks.template import templateCF from PyStacks.PyStacks.template import vo...