id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9939132 | import sys
sys.path.insert(1,"../../../")
import h2o
import math
from tests import pyunit_utils
from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm
# Given arrays of lambda and alpha, the glm should return the best submodel in its training metrics calculation.
#
# When an array of alpha and/or lambdas ... |
9939174 | import unittest
from flask import Flask
from flask_login import UserMixin
__author__ = 'gbalaraman'
class FlaskBloggingTestCase(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.app.config['SECRET_KEY'] = "test-secret"
self.app.config["WTF_CSRF_ENABLED"] = False # to ... |
9939179 | import numpy as np
from collections import namedtuple
from sklearn.utils.extmath import cartesian
from scipy.stats import mode
from scipy.stats import itemfreq
from attrdict import AttrDict
import pdb
def max_product_update_var(state, messages, sender_id, recipient_id):
variable_index = sender_id[1:]
factor_i... |
9939183 | from os import *
# modify os to my liking
from subprocess import Popen, PIPE, STDOUT
from time import sleep
def system(cmd: str):
process = Popen(cmd, shell=True,
stdout=PIPE, stderr=STDOUT,
universal_newlines=True)
while True:
output = process.stdout.readlin... |
9939217 | import subprocess
from tenacity import wait_exponential, retry, stop_after_attempt
@retry(wait=wait_exponential(min=2, max=60), stop=stop_after_attempt(5))
def install_sqlserver():
"""
Install with TCP/IP enabled, see: https://chocolatey.org/packages/sql-server-2017
"""
print("Install sql-server-2017... |
9939222 | import json
import sys
from django.core.management import BaseCommand
from dimagi.utils.modules import to_function
from corehq.apps.domain.models import (
Domain,
DynamicReportConfig,
DynamicReportSet,
)
class Command(BaseCommand):
help = "Set up a dynamic report for a domain"
def add_argument... |
9939234 | from AWSLibrary.base import LibraryComponent
from AWSLibrary.base.robotlibcore import keyword
from AWSLibrary.base.exceptions import KeywordError
import os
class ResourceKeywords(LibraryComponent):
@keyword("Local File Should Exist")
def local_file_should_exist(self, path):
""" Verifies Local File at... |
9939271 | import unittest
import win32gui
import win32gui_struct
import win32con
import array
import pythoncom
class TestBase(unittest.TestCase):
def assertDictEquals(self, d, **kw):
checked = dict()
for n, v in kw.items():
self.assertEqual(v, d[n], "'%s' doesn't match: %r != %r" % (n, v, d[n]))... |
9939289 | import logging
import time
import memcache
from botocore.exceptions import ClientError
memcache.SERVER_MAX_VALUE_LENGTH = 128*1024*2014
def get_client(ip, port=11211):
try:
endpoint = ip + ":" + str(port)
client = memcache.Client([endpoint])
except ClientError as e:
# AllAccessDisable... |
9939302 | import subprocess
import os
import sys
# name of the main latex .tex file without extension
mainfilename = 'oral_presentation'
open_pdf = True
# binary to a pdf reader
pdfreader = 'C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe'
# argument parsing
if 'quick' in sys.argv:
quick = True
else:
quick = Fal... |
9939310 | from echomesh.build.BuildConfig import CONFIG
from echomesh.build.Clean import Clean
from echomesh.build.CleanOlder import clean_older
from echomesh.build.Install import Install
from echomesh.build.Library import Library
|
9939317 | from flask import Flask
from flask.wrappers import Response
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from app.scripts import posters4k, posters3d, hide4k, disney, pixar, migrate, restore_posters, fresh_hdr_posters
import os
from flask_apscheduler import APScheduler
import sql... |
9939322 | from flask import Blueprint
# __name__ variable is used to determine root path of the application
api = Blueprint('api', __name__)
# routes separated by resource type, each in own module
from . import views # noqa
|
9939335 | import os
import sys
sys.path.append(os.path.abspath(__file__).replace('kame/code/kame.py', '') + 'pybotics/')
import time
import numpy as np
import math
import smbus
from driver.pca9685.pca9685 import ServoController
import control.octosnake.octosnake as octosnake
# Servos:
# _________ ________ _________
# |... |
9939343 | import pytest
from demo.models import ReversionConcurrentModel
from reversion import add_to_revision, revisions, set_comment
from reversion.models import Version
try:
from django.core.urlresolvers import reverse
except ImportError:
from django.urls import reverse
@pytest.mark.django_db
@pytest.mark.functiona... |
9939349 | import pep8
import ast
from mccabe import _read, PathGraphingAstVisitor
from .file_helpers import count_py_files
def count_pep8_violations(repository_info, max_line_length=79, path_whitelist=None):
path_whitelist = path_whitelist or []
pep8style = pep8.StyleGuide(
paths=['--max-line-length', str(max_... |
9939359 | from abc import ABCMeta
from binascii import hexlify
from logging import getLogger
from re import compile
from re import sub
from struct import error
from struct import unpack
from warnings import warn
from sqlite_dissect.constants import DATABASE_TEXT_ENCODINGS
from sqlite_dissect.constants import INTERIOR_PAGE_HEADER... |
9939389 | import config
from utils import Utils
import json
import time
import logging
logger = logging.getLogger(__name__)
class Mails:
"""Get and read mails."""
ut = Utils()
def __init__(self, player):
"""Mails class init.
Args:
player: contains player with username, password and uha... |
9939400 | from .augmentations import get_spacenet7_augmentation
from .preprocesses import get_spacenet7_preprocess
def get_preprocess(config, is_test):
"""[summary]
Args:
config ([type]): [description]
is_test (bool): [description]
Returns:
[type]: [description]
"""
return get_spac... |
9939405 | from operator import mul
from functools import reduce
import sympy as sym
def prod(seq):
return reduce(mul, seq) if seq else 1
def mk_exprs_symbs(rxns, names):
# create symbols for reactants
symbs = sym.symbols(names, real=True, nonnegative=True)
# map between reactant symbols and keys in r_stoich, ... |
9939413 | import asyncio
import json
import unittest
from typing import Dict, Awaitable, Any, List
from aioresponses import aioresponses
from hummingbot.connector.exchange.liquid.liquid_api_order_book_data_source import LiquidAPIOrderBookDataSource
from hummingbot.connector.exchange.liquid.constants import Constants
class Li... |
9939461 | import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
def FCN8_atonce(images, num_classes=3):
paddings = tf.constant([[0, 0], [96, 96], [96, 96], [0, 0]])
pad_images = tf.pad(images, paddings, 'CONSTANT')
model = nets.vgg
with slim.arg_scope(model.v... |
9939477 | import torch
import torch.nn.functional as F
# Calculates mean and std channel-wise
def calc_mean_std(input, eps=1e-5):
batch_size, channels = input.shape[:2]
reshaped = input.view(batch_size, channels, -1) # Reshape channel wise
mean = torch.mean(reshaped, dim = 2).view(batch_size, channels, 1, 1) # Ca... |
9939478 | from tool.runners.python import SubmissionPy
class ThoreSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
return sum(
len(set.intersection(*(set(a) for a in answers.split("\n"))))
for answers... |
9939495 | from django.apps import AppConfig
class MetaConfig(AppConfig):
name='voxel_globe.meta'
def ready(self):
import signals |
9939510 | from typing import Dict, Hashable, Optional, Union
import numpy as np
import torch
from swyft.types import Array, Device
def dict_to_device(d, device, non_blocking=False):
return {k: v.to(device, non_blocking=non_blocking) for k, v in d.items()}
def dict_array_to_tensor(
d, device="cpu", non_blocking=Fals... |
9939559 | from django.core.management.base import BaseCommand
from common.models import Officer
class Command(BaseCommand):
help = 'Clean Officer Names'
def handle(self, *args, **options):
for officer in Officer.objects.filter():
if officer.officer_first:
officer.officer_first = of... |
9939582 | import pygsti.algorithms.fiducialpairreduction as fpr
import pygsti.circuits as pc
from pygsti.circuits import Circuit
from . import fixtures
from ..util import BaseCase
_SEED = 1234
class FiducialPairReductionStdData(object):
def setUp(self):
super(FiducialPairReductionStdData, self).setUp()
sel... |
9939593 | import os
import requests
import pytest
from pathod import test
from pathod.pathod import SSLOptions, CA_CERT_NAME
class TestDaemonManual:
def test_simple(self):
with test.Daemon() as d:
rsp = requests.get("http://localhost:%s/p/202:da" % d.port)
assert rsp.ok
assert ... |
9939617 | import base64
import pytest
import struct
from winrm.encryption import Encryption
from winrm.exceptions import WinRMError
def test_init_with_invalid_protocol():
with pytest.raises(WinRMError) as excinfo:
Encryption(None, 'invalid_protocol')
assert "Encryption for protocol 'invalid_protocol' not supp... |
9939671 | import FWCore.ParameterSet.Config as cms
consumer = cms.OutputModule("PoolOutputModule",
outputCommands = cms.untracked.vstring('keep *'),
fileName = cms.untracked.string('digis.root')
)
|
9939726 | import pdb
import unittest
class Fitted(object):
def __init__(self, training_data, neighborhood, model):
assert training_data in Fitted.training_data_choices()
assert neighborhood == 'global' or neighborhood in Fitted.selected_cities_choices()
assert model in Fitted.model_choices()
... |
9939748 | import pytest
from covidmx import CovidMX
def test_makes_plot():
try:
dge_plot = CovidMX().get_plot()
for st in dge_plot.available_status:
file_name = '{}.png'.format(st)
mx_map = dge_plot.plot_map(status=st, save_file_name=file_name)
mx_map_with_muns = dge_plot... |
9939798 | import pandas as pd
import pickle
data = pd.read_pickle("/Users/bguillouet/These/trajectory_review/data/extracted/starting_from/Caltrain_city_center_v3.pkl")
traj_list = [group[["lons","lats"]].values for _,group in data.groupby("id_traj")]
pickle.dump(traj_list, open("/Users/bguillouet/These/trajectory_distance/da... |
9939799 | from matrixprofile.distanceProfile import *
import numpy as np
import pytest
class TestClass(object):
def test_naiveDistanceProfile_self(self):
outcome = (np.array([0.0,2.828,np.inf,np.inf,np.inf,np.inf,np.inf,2.828,0.0]),np.array([4.,4.,4.,4.,4.,4.,4.,4.,4.]))
b = np.array([0.0,1.0,1.0,0.0,0.0,1... |
9939836 | from abstract_subsystem_1 import AbstractSubsystem1
class ConcreteSubsystem1(AbstractSubsystem1):
"""Concrete implementation of AbstractSubsystem1"""
_name = None
_year_of_birth = None
def __init__(self, name, year_of_birth):
self._name = name
self._year_of_birth = year_o... |
9939848 | from utils import CanadianJurisdiction
# The municipal association lists only top-level officials.
# @see http://www.municipalnl.ca/?Content=Contact/Municipal_Directory
class NewfoundlandAndLabradorMunicipalities(CanadianJurisdiction):
classification = 'legislature'
division_id = 'ocd-division/country:ca/prov... |
9939890 | from baseline_configs.walkthrough.walkthrough_rgb_ppo import (
WalkthroughPPOExperimentConfig,
)
class WalkthroughRGBResNetPPOExperimentConfig(WalkthroughPPOExperimentConfig):
USE_RESNET_CNN = True
@classmethod
def tag(cls) -> str:
return "WalkthroughRGBResNetPPO"
|
9939891 | try:
from OpenGL import NullFunctionError
except ImportError:
from OpenGL.error import NullFunctionError
from OpenGL.GL import *
from OpenGL.GL import shaders
import re
## For centralizing and managing vertex/fragment shader programs.
def initShaders():
global Shaders
Shaders = [
ShaderProgram... |
9939960 | TOOL_NAME = "backd"
LOG_FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s"
NULL_ADDRESS = "0x0000000000000000000000000000000000000000"
ETH_ADDRESS = "0x0000000000000000000000000000000000000000"
DSR_DECIMALS = 27
DEFAULT_DECIMALS = 10 ** 18
RAY = 10 ** 27
DAY = 3600 * 24
|
9939978 | from __future__ import absolute_import, unicode_literals
from fontTools.misc.py23 import *
from fontTools.misc.loggingTools import CapturingLogHandler
from fontTools.misc.testTools import parseXML, getXML
from fontTools.misc.textTools import deHexStr
from fontTools.ttLib import TTFont, newTable
from fontTools.misc.fixe... |
9939982 | import argparse
import numpy as np
import gym
import torch
from agent import VanillaPG
from agent import OffPolicyPG
def off_policy_run(env, args):
agent = OffPolicyPG(env, args)
global_steps = 0
for ep in range(args.num_ep):
rollouts, ep_steps, ep_rewards = run_episode(env, agent)
globa... |
9939985 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df_prisoners = pd.read_csv("prisoners.csv")
# 1.Data Loading:
# a.Load the dataset “prisoners.csv” using pandas and display the first and last five rows in the dataset.
print(df_prisoners.head())
print(df_prisoners.tail())
# b.Use des... |
9940016 | import logging
import threading
from typing import Any, Iterator, Optional, cast
import boto3
import botocore.client
import botocore.config
import botocore.exceptions
from tilecloud import Tile, TileLayout, TileStore
logger = logging.getLogger(__name__)
lock = threading.Lock()
CLIENT_TIMEOUT = 60
class S3TileStore... |
9940034 | from __future__ import annotations
from typing import Awaitable, Callable, Dict, List, Optional, Tuple, Union
from aioquic.h3.connection import H3Connection
from aioquic.h3.events import DataReceived, HeadersReceived
from aioquic.h3.exceptions import NoAvailablePushIDError
from aioquic.quic.connection import QuicConn... |
9940064 | CLASSES_NAMES = [
"background", # class 0
"aeroplane", # class 1
"bicycle", # class 2
"bird", # class 3
"boat", # class 4
"bottle", # class 5
"bus", # class 6
"car", # class 7
"cat", # class 8
"chair", # class 9
"cow", # class 10
"table", # class 11
"dog",... |
9940065 | import redis
import datetime
from abc import ABC, abstractmethod
from typing import Tuple, Optional
from gtmcore.logging import LMLogger
from gtmcore.inventory.inventory import InventoryManager
logger = LMLogger.get_logger()
class RepoCacheEntry(ABC):
""" Represents a specific entry in the cache for a specific ... |
9940080 | import random
numbers_retrieved = 0
# Randomly retrieve numbers until you get them in order of 1-100
while True:
curr_int = random.randint(1, 100)
if curr_int != numbers_retrieved + 1:
continue
else:
print("Fizz"*(curr_int%3==0)+"Buzz"*(curr_int%5==0) or curr_int)
numbers_retrieved... |
9940097 | from typing import Any
from pydantic import BaseConfig, BaseModel
class APIModel(BaseModel):
"""
Intended for use as a base class for externally-facing models.
"""
@classmethod
def schema(cls, by_alias: bool = True) -> Any: # type: ignore # noqa: WPS210
model_schema = super().schema()
... |
9940100 | from gpiozero import PWMLED, MCP3008
from signal import pause
led = PWMLED(17)
pot = MCP3008()
led.source = pot
pause()
|
9940149 | from tastypie.paginator import Paginator
class NoCountingPaginator(Paginator):
"""
The default paginator contains the total_count value, which shows how
many objects are in the underlying object list. Obtaining this data from
the database is inefficient, especially with large datasets, and unfiltered ... |
9940197 | import torch
def sinkhorn(feature1, feature2, pcloud1, pcloud2, epsilon, gamma, max_iter):
"""
Sinkhorn algorithm
Parameters
----------
feature1 : torch.Tensor
Feature for points cloud 1. Used to computed transport cost.
Size B x N x C.
feature2 : torch.Tensor
... |
9940206 | load("//scala_proto/default:repositories.bzl", "scala_proto_default_repositories")
load(
"//scala_proto/private:scala_proto.bzl",
_make_scala_proto_library = "make_scala_proto_library",
_scala_proto_library = "scala_proto_library",
)
load(
"//scala_proto/private:scala_proto_aspect.bzl",
_make_scala_... |
9940207 | import json
from ..models import Quota
from .literals import (
TEST_QUOTA_DATA, TEST_QUOTA_DOTTED_PATH, TEST_QUOTA_WITH_MIXINS_DOTTED_PATH,
TEST_QUOTA_TEST_LIMIT_EDITED
)
class QuotaTestMixin:
def _create_test_quota(self):
self.test_quota = Quota.objects.create(
backend_data=json.dum... |
9940214 | import copy
import inspect
import itertools
import new
import os
import re
import sys
import unittest2 as unittest
from datetime import datetime
from collections import defaultdict
import tinctest
from qautils.gppylib import gpversion
from tinctest.runner import TINCTextTestResult
def dataProvider(name):
"""
... |
9940217 | import os, sys
import imp
import random
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import *
constants = imp.load_source('modulename', 'constants.py')
from decimal import *
def get_merchant_details():
merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = c... |
9940300 | import numpy as np
import pandas as pd
import logging
import sys
sys.path.insert(0, '../../smap-nepse')
from prediction import prepareInput as pi
from preprocessing import moreIndicators as indi
from logger import log as log
from sklearn import preprocessing
from sklearn.tree import DecisionTreeClassifier
from sklearn.... |
9940383 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.n_f_l2007_standings import n_f_l2007_standings
def test_n_f_l2007_standings():
"""Test module n_f_l2007_standings.py by downloading
n_f_l2007... |
9940386 | from bitmovin_api_sdk.encoding.encodings.muxings.packed_audio.information.information_api import InformationApi
|
9940399 | from State2NN import AI_Board
import numpy as np
from nn import neural_net
NUM_INPUT = 11
def play(model):
game_state = AI_Board()
game_state.reset()
# Do nothing to get initial.
state,_ = game_state.next(0.5)
# Move.
while True:
# Choose action.
action = (np.argmax... |
9940459 | from unittest import TestCase
import gym
from torch import Tensor
from pl_bolts.models.rl.common.gym_wrappers import ToTensor
class TestToTensor(TestCase):
def setUp(self) -> None:
self.env = ToTensor(gym.make("CartPole-v0"))
def test_wrapper(self):
state = self.env.reset()
self.ass... |
9940464 | import gevent
import os
import subprocess
from ajenti.api import *
from ajenti.api.helpers import subprocess_call_background
from ajenti.ui.binder import Binder
from ajenti.util import platform_select
from ajenti.plugins.services.api import ServiceMultiplexor
from ajenti.plugins.supervisor.client import SupervisorSer... |
9940532 | import os,sys,time
import tensorflow as tf
from common import data_root, model_root, batch_size, epochs, training_examples , testing_examples
import data
import model
def gen_pred_txt(tag):
with open(os.path.join(data_root, 'list', 'pred.txt'),'w') as file:
"""
You can modify codes below to predict... |
9940575 | class UploadNotAllowed(Exception):
"""This exception is raised if the upload was not allowed.
You should catch it in your view code and
display an appropriate message to the user.
"""
|
9940606 | import numpy as np
true_b = 1
true_w = 2
N = 100
# Data Generation
np.random.seed(42)
x = np.random.rand(N, 1)
y = true_b + true_w * x + (.1 * np.random.randn(N, 1))
# Shuffles the indices
idx = np.arange(N)
np.random.shuffle(idx)
# Uses first 80 random indices for train
train_idx = idx[:int(N*.8)]
# Uses the remai... |
9940612 | from externaldep import externaldep_function
def somedep_function(x):
return externaldep_function(x * 2)
|
9940645 | import unittest
import Attack.BaseAttack as BAtk
from Attack.Parameter import MACAddress, IPAddress
# TODO: improve coverage
class TestBaseAttack(unittest.TestCase):
def test_is_valid_ipaddress_valid(self):
self.assertTrue(BAtk.BaseAttack.is_valid_ip_address("192.168.178.42"))
def test_is_valid_i... |
9940662 | def lowerToUpper():
wordList = []
with open('test.txt') as file:
content = file.read()
new_str = ''
for ch in content:
if ch.isalpha() and ch.islower():
new_str += ch.upper()
else:
new_str += ch
with open('test.txt', 'w') as file:
file.write(new_str)
lowerToUpper()
|
9940675 | import random as rand
from Card import Card
numSuits = 4
minRank = 2
maxRank = 15
class Deck:
def __init__(self):
self.deck = []
for suit in range(0,numSuits):
for rank in range(minRank,maxRank):
self.deck.append(Card(rank, suit))
def __str__(self):
deckStr = ''
for card in self.deck:
deckStr +=... |
9940696 | import argparse
import numpy
import theano
import theano.tensor as T
from databases.lm_reconstruction_database import LmReconstructionDatabase
from vae import Sampler, Dropword, LMReconstructionModel
from nn.layers1d import LayoutCNNToRNN, LayoutRNNToCNN, Convolution1d, Deconvolution1D
from nn.layers import Linear, E... |
9940772 | import ipfsapi
c = ipfsapi.connect()
result = c.cat('QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ/cat.jpg')
with open('cat.jpg', 'wb') as f:
f.write(result)
|
9940776 | import mlrose
import logging
logger = logging.getLogger('logger')
__all__ = ['sort_per_shortest_path_mlrose']
def sort_per_shortest_path_mlrose(slicer,
population_size=200,
mutation_probability=0.1,
max_attempts=10... |
9940802 | from django.http import Http404, HttpResponse
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.utils.html import escape
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.generic.base import TemplateView
from patt... |
9940818 | from ts2vg._version import __version__
from ts2vg.graph.natural import NaturalVG
from ts2vg.graph.horizontal import HorizontalVG
__all__ = [
'NaturalVG',
'HorizontalVG',
]
|
9940833 | from allocloud.openapt.errors import CircularDependencyException
class Graph():
def __init__(self):
self.edges = EdgeCollection()
def add_dependency(self, source, dependency):
self.edges.append(source, dependency)
def resolve(self, entities, limits=None):
# Resolving the dependenc... |
9940862 | class StreamerAdapterStub:
def open(self):
pass
def get_current_block_number(self):
return 0
def export_all(self, start_block, end_block):
pass
def close(self):
pass
|
9940887 | import requests
from flask import request
from appkernel import Model, AppKernelException
from appkernel.core import MessageType
from appkernel.model import _get_custom_class
class RequestHandlingException(AppKernelException):
def __init__(self, status_code, message):
super().__init__(message)
se... |
9940920 | import villares_arcs_and_bars_pyp5js as source_sketch
from pyp5js import *
event_functions = {
"deviceMoved": source_sketch.deviceMoved,
"deviceTurned": source_sketch.deviceTurned,
"deviceShaken": source_sketch.deviceShaken,
"keyPressed": source_sketch.keyPressed,
"keyReleased": source_sketch.keyRe... |
9940931 | import testutils
import json
import psycopg2
def _map_labels(results):
return list(map(lambda row: row[0]['label'], results))
def _map_ids(results):
return list(map(lambda row: row[0]['label'], results))
class TestAdvancedQueries(testutils.BedquiltTestCase):
def test_eq(self):
rows = [
... |
9941071 | import argparse, itertools, jxmlease, more_itertools, numpy as np, pathlib
from ..utilities import units
from ..utilities.dataclasses import MetaDataAnnotation, MyDataClass
from ..utilities.misc import dummylogger, printlogger
from ..utilities.tableio import readtable, writetable
from .csvclasses import Annotation, Reg... |
9941076 | import math
import operator
from typing import Optional, Union, Callable, Any
from .base import Loader, ILoaderClass
from .utils import keep, check_only
NUMBER_TYPES = (int, float)
NUMBER_TYPING = Union[int, float]
def numeric(int_ok: bool = True, float_ok: bool = True, inf_ok: bool = True) -> ILoaderClass:
if ... |
9941079 | from uuid import uuid4
import datetime
import requests
from requests import Session
from requests.exceptions import RequestException
from .exceptions import SpendeeError
class Spendee(Session):
def __init__(self, email: str, password: str, base_url: str = 'https://api.spendee.com/', google_client_id: str = 'AIz... |
9941086 | from captcha.fields import ReCaptchaField
from django import forms
class SupportForm(forms.Form):
email = forms.EmailField(
max_length=256,
required=True
)
subject = forms.CharField(
max_length=256
)
message = forms.CharField(
max_length=65536
)
captcha = Re... |
9941119 | import logging
from itertools import combinations
from typing import Any, Callable, List, Optional, Set
from payton.math.geometry import distance
from payton.scene.geometry.base import Object
from payton.scene.geometry.mesh import Mesh
from payton.scene.geometry.sphere import Sphere
class Collision:
"""Collision... |
9941170 | from typing import List, Optional
from tokenizers import Encoding
from transformers import PreTrainedTokenizerBase # noqa
from transformers import RobertaTokenizerFast as _RobertaTokenizerFast
from transformers import PreTrainedTokenizerFast as _PreTrainedTokenizerFast
from .base import InputTexts, TokenizedOutput, S... |
9941192 | from datetime import timedelta
from django.utils.timezone import now
from bluebottle.test.utils import BluebottleTestCase
from bluebottle.time_based.tests.factories import (
DateActivityFactory, DateActivitySlotFactory, PeriodActivityFactory
)
class PeriodActivityModelTestCase(BluebottleTestCase):
def test_... |
9941195 | import argparse
import copy
import os
import sys
import PyFBA
from PyFBA import log_and_message
"""
This code is designed to exemplify some of the gap-filling approaches. If you start with an ungapfilled set of
reactions, we iteratively try to build on the model until it is complete, and then we use the bisection cod... |
9941215 | import time
import logging
delay = 0.05
months_border = 2 # if the conversation is shorter than this values than xticks will be weeks, not months.
def avg(l):
if not l:
return 0
return sum(l) / len(l)
def log_line(*args):
logging.getLogger("message_analyser").log(logging.INFO, ' '.join([str(arg... |
9941227 | import datetime
from django import template
register = template.Library()
@register.filter
def timedelta_from_now(delta):
"""
Add a timedelta to now, plus a fudge factor of a few seconds.
Most useful for chaining with Django's builtin filter "timeuntil",
for producing a humanized timedelta.
"""
... |
9941239 | import sys, pysam, time, os, copy, argparse, random
from collections import Counter
import numpy as np
import multiprocessing as mp
from pysam import VariantFile
from intervaltree import Interval, IntervalTree
def get_cnd_pos(v_pos,cnd_pos, seq='ont'):
if seq=='ont':
ls=cnd_pos[abs(cnd_pos-v_pos)<50000]
... |
9941242 | import math
import re
import numpy as np
from scipy.spatial import distance
from strsimpy.metric_lcs import MetricLCS
class PostProcess:
""" A simple abstraction layer for using the Post-Processing module of the CSO classifier """
def __init__(self, model = None, cso = None, **parameters):
"""Function... |
9941245 | def insertion_sort[L]:
for i in range(0,len(L)):
temp=L[i]
ptr=i-1
while (ptr>=0) and L[ptr]>temp:
L[ptr+1]=L[ptr]
ptr=ptr-1
L[ptr]=temp
print L,
|
9941255 | from keras import layers
from keras import optimizers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout
from keras.models import Model
from keras.initializers import glorot_uniform
from keras.utils import to_categorical
from keras... |
9941298 | from fastapi import APIRouter, Depends
from streams_explorer.api.dependencies.streams_explorer import (
get_streams_explorer_from_request,
)
from streams_explorer.models.pipelines import Pipelines
from streams_explorer.streams_explorer import StreamsExplorer
router = APIRouter()
@router.get("", response_model=P... |
9941307 | from jedi.inference.compiled import CompiledValue
import pytest
@pytest.mark.parametrize('source', [
pytest.param('1 == 1'),
pytest.param('1.0 == 1'),
# Unfortunately for now not possible, because it's a typeshed object.
pytest.param('... == ...', marks=pytest.mark.xfail),
])
def test_equals(Script, ... |
9941310 | import argparse
import time
import os
import json
import numpy as np
import matplotlib.pyplot as plt
import sys
import joblib
import tensorflow as tf
from PIL import Image
import moviepy.editor as mpy
from meta_policy_search.utils import logger
from meta_policy_search.envs.normalized_env import normalize
from meta_po... |
9941311 | from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_duration
from payments.models import Payment
class Command(BaseCommand):
help = "Manually confirm a Payment"
def add_arguments(self, parser):
parser.add_argument('id', actio... |
9941323 | import time
import logging
from odm360.serial_device import SerialDevice
logger = logging.getLogger(__name__)
class Camera360Serial(SerialDevice):
"""
Class creates a serial connection to a raspi with a raspi camera. Functionalities act similar to gphoto2
functionalities so that an end user has the feeli... |
9941330 | from __future__ import division
from .exceptions import OutOfBoundsError
from .core import get_period, _Schedule
from numpy import searchsorted
class Workshift(object):
"""A period of time during which a business agent is either on or off duty.
A workshift consists of at least one base unit and may span... |
9941336 | import FWCore.ParameterSet.Config as cms
process = cms.Process("HcalGeometryTest")
process.load("Geometry.HcalCommonData.testGeometry17bXML_cfi")
#process.load("Geometry.HcalCommonData.testPhase2GeometryFineXML_cfi")
process.load("Geometry.HcalCommonData.hcalDDConstants_cff")
process.load("Geometry.HcalEventSetup.hca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.