id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11438273 | from __future__ import print_function
import os
from floor.data import SequentialReadingsData
from test_tube import HyperOptArgumentParser, Experiment
from sklearn import linear_model
import numpy as np
from sklearn.externals import joblib
def main_trainer(hparams):
print_params(hparams)
exp = Experiment(nam... |
11438307 | class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
countArray = [0] * (n + 1)
for citation in citations:
countArray[min(citation, n)] += 1
k = n
s = countArray[k]
while k > s:
k -= 1
s += countArray[k]... |
11438382 | import sys
from easyprocess import EasyProcess
help = """
usage: cli.py [-h] [-b BACKEND] [-a] [--debug] filename directory
positional arguments:
filename path to archive file
directory directory to extract to
optional arguments:
-h, --help show this help message and exit
... |
11438443 | from ..helpers import PluginImporter
importer = PluginImporter(virtual='interest.plugins.', actual='interest_')
importer.register()
del PluginImporter
del importer
|
11438454 | import os
from contextlib import contextmanager
class CloudPickleWrapper(object):
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
"""
def __init__(self, x):
self.x = x
def __getstate__(self):
import cloudpickle
return cloudpickl... |
11438547 | import pytest
from peloton_client.pbgen.peloton.api.v0.task import task_pb2 as task
from peloton_client.pbgen.peloton.private.hostmgr.hostsvc import (
hostsvc_pb2 as hostmgr)
from tests.integration.job import Job, kill_jobs, with_instance_count
from tests.integration.common import IntegrationTestConfig
import tes... |
11438553 | import functools
import keras
import tensorflow as tf
from keras.utils import conv_utils
import keras.layers
class Conv2DDenseSame(keras.layers.Conv2D):
def __init__(
self, *args, dilation_rate_test=None, strides_test=None, bottomright_stride=False,
bottomright_stride_test=False, **kwargs... |
11438568 | import os
import time
import numpy as np
from simtk.openmm import app
from simtk.openmm.app import PDBFile
from rdkit import Chem
from fe.utils import to_md_units
from fe import free_energy
from ff.handlers.deserialize import deserialize_handlers
from ff import Forcefield
from timemachine.lib import LangevinIntegra... |
11438581 | from selenium import webdriver
import threading
from queue import Queue
import warnings
import time
warnings.filterwarnings("ignore")
span = '/html/body/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[2]/div[1]/div[2]/div/span[1]'
base_url = 'https://translate.google.com/#'
class Translate:
def __init__(self, from... |
11438615 | from typing import Dict, List, Set
import torch
class Dataset:
def __init__(self,
ids: Set[str],
id_to_document: Dict[str, List[torch.LongTensor]],
id_mapping: Dict[str, Dict[str, Set[str]]],
negative_ids: Set[id] = None):
"""
Ho... |
11438669 | import torch as th
from models import REGISTRY as mo_REGISTRY
from components.scheme import Scheme
from components.transforms import _generate_input_shapes, _generate_scheme_shapes
class BasicAgentController():
def __init__(self,
n_agents,
n_actions,
args,
... |
11438691 | import time
import numpy as np
from scipy.io import savemat, loadmat
import torch
from matplotlib import pyplot as plt
from sinkhorn_barycenters import barycenter
from sharp_barycenter import sharp_barycenter_img
from free_barycenter import barycenter_free, create_distribution_2d
from make_ellipse import make_nest... |
11438702 | import doctest
import os
import textwrap
import pytest
from pytest_sphinx import docstring2examples
from pytest_sphinx import get_sections
@pytest.mark.parametrize("in_between_content", ["", "\nsome text\nmore text"])
def test_simple(in_between_content):
doc = """
.. testcode::
import pprint
pprint.ppr... |
11438708 | from src.algorithms.algorithm_utils import Algorithm
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
class PcaRecons(Algorithm):
def __init__(self, name: str='PcaRecons', explained_var=0.9, seed: int=None, details=True, out_dir=None,
... |
11438717 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import L... |
11438742 | from __future__ import print_function
from config import cfg, cfg_from_file
from datasets import TextDataset
from datasets import prepare_data
from model import CNN_ENCODER
import os
import sys
import time
import random
import argparse
import numpy as np
import pprint
import torch
from torch.auto... |
11438755 | from setuptools import setup, find_packages
setup(name='kernel_exp_family',
version='0.1',
description='Various estimators for the infinite dimensional exponential family model',
url='https://github.com/karlnapf/kernel_exp_family',
author='<NAME>',
author_email='<EMAIL>',
license='... |
11438790 | import os.path
import time
from moler.config import load_config
from moler.device.device import DeviceFactory
def test_network_outage():
load_config(config=os.path.abspath('config/my_devices.yml'))
unix1 = DeviceFactory.get_device(name='MyMachine1')
unix2 = DeviceFactory.get_device(name='MyMachine2')
... |
11438803 | import sys
sys.path.append("../bin/")
import pyHiChi as hichi
import random
def new_random_array(size) :
p_array = hichi.ParticleArray() #type = ELECTRON
for i in range(size) :
pos = hichi.Vector3d(1.2*i, 3.4*i, 5.6*i)
mo = hichi.Vector3d(9.8*i, 7.6*i, 54.3*i)
new_p = hichi.Particle(po... |
11438808 | import tensorflow as tf
def rnnt_loss(logits, labels, label_length, logit_length, blank=0):
try:
from warprnnt_tensorflow import rnnt_loss as warp_rnnt_loss
except BaseException:
raise ModuleNotFoundError(
'warprnnt_tensorflow not installed. Please install it by compile from https:... |
11438813 | import re
import contextlib
from collections import namedtuple
from ._lazyimport import m
from .raw import setup_extra_parser # noqa
_loader = None
Guessed = namedtuple("Guessed", "spreadsheet_id, range, sheet_id")
def guess(
pattern: str, *, sheet_rx=re.compile("/spreadsheets/d/([a-zA-Z0-9-_]+)")
) -> Guessed:... |
11438908 | from collections import namedtuple
from abc import ABC, abstractmethod
import numpy as np
from scipy.signal import find_peaks
from scipy.ndimage import maximum_filter
# Helper functions for validating inputs.
def ensure_covariance_size(R, array):
"""Ensures the size of R matches the given array design."""
m = ... |
11438912 | from web3 import Web3
def mine_blocks(web3: Web3, num_blocks: int) -> None:
web3.testing.mine(num_blocks) # type: ignore
|
11438921 | import globals
from globals import get_soup, job_insert
from job import Job
# Coalition for Responsible Community Development
organization = 'Coalition for Responsible Community Development'
url = 'http://www.coalitionrcd.org/get-involved/work-at-crcd/'
organization_id = 13
def run(url):
soup = get_soup(url)
... |
11438932 | from globals import *
import life as lfe
import libtcodpy as tcod
import language
import alife
import menus
import logging
def create_encounter(life, target, context=None):
_encounter = {}
if life['encounters']:
return None
if not life['id'] in target['know']:
logging.warning('Encounter: %s does not know... |
11438954 | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from botocore.waiter import Waiter
class Client(BaseClient):
def can_paginate(self, operation_name: str = None):
pass
def create_group(self, Grou... |
11438962 | import toolshed as ts
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import OLSInfluence
import scipy.stats as ss
from statsmodels.formula.api import ols
import pandas as pd
from... |
11439060 | import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Java/Jboss Deserialization [RCE]''',
"description": '''In Jboss Application Server as shipped with Red Hat Enterprise Application Platform 5.2, it was found that the doFilter method in the ReadOnlyAcce... |
11439077 | from setuptools import setup
setup(
name='girder-plugin-geometa-obj',
author='Kitware, Inc.',
entry_points={
'geometa.types': [
'vector=building_obj.schema:handler'
]
},
packages=[
'building_obj'
],
install_requires=[
# Eventually will require geo... |
11439112 | import trimesh
import numpy as np
#make sure the order of identity points and gt points are same
#for original_model, please keep the identity and pose points in different order
ours_mesh = trimesh.load('ours.obj')
ours_vertices=ours_mesh.vertices
ours_bbox= np.array([[np.max(ours_vertices[:,0]), np.max(ours... |
11439182 | import torch
from torch.utils.data import DataLoader
from dataloaders.dataloader_msrvtt_retrieval import MSRVTT_DataLoader
from dataloaders.dataloader_msrvtt_retrieval import MSRVTT_TrainDataLoader
from dataloaders.dataloader_msvd_retrieval import MSVD_DataLoader
from dataloaders.dataloader_lsmdc_retrieval import LSMDC... |
11439232 | import unittest
from contracts import (check, ContractNotRespected, Contract, parse,
check_multiple, ContractSyntaxError, fail)
class TestIdioms(unittest.TestCase):
def test_check_1(self):
res = check('tuple(int,int)', (2, 2))
assert isinstance(res, dict)
def test_ch... |
11439247 | import unittest
class TestAnagrams(unittest.TestCase):
def test_group_anagrams(self):
anagram = Anagram()
self.assertRaises(TypeError, anagram.group_anagrams, None)
data = ['ram', 'act', 'arm', 'bat', 'cat', 'tab']
expected = ['ram', 'arm', 'act', 'cat', 'bat', 'tab']
self... |
11439253 | import os
import requests
class MicroServiceProxy:
def __init__(self, env_name, **kwargs):
self.session = requests.Session()
self.cws_id = os.getenv(f'{env_name}_CWS_ID')
self.cws_token = os.getenv(f'{env_name}_CWS_TOKEN')
self.cws_stage = os.getenv(f'{env_name}_CWS_STAGE')
... |
11439258 | import pymongo
client = pymongo.MongoClient("mongodb+srv://Hao:<EMAIL>/test?retryWrites=true")
db = client.get_database('Python')
collection = db.get_collection('Test')
def test01():
"""
Scrapy框架主要的组件有:
scheduler调度器:封装url列表,压入队列
scrapy engine引擎:连接各个组件的中转中心
downloader下载器:类似于get_data方法... |
11439283 | from aorist import *
from aorist_recipes import programs
from scienz import (
probprog, subreddit_schema,
fasttext_datum, spacy_ner_datum,
probprog,
)
universe = Universe(
name="my_cluster",
datasets=[probprog],
endpoints=EndpointConfig(),
compliance=None,
)
result = dag(universe, ["Upl... |
11439284 | from datetime import datetime
import archon.broker as broker
import archon.exchange.exchanges as exc
import archon.exchange.bitmex.bitmex as mex
import archon.facade as facade
import archon.model.models as models
from archon.brokersrv.brokerservice import BrokerService
from archon.util.custom_logger import setup_logg... |
11439292 | import numpy as np
import astropy.constants as const
import astropy.units as u
import scipy.integrate as integrate
import h5py
from fruitbat import utils
__all__ = ["ioka2003", "inoue2004", "zhang2018", "batten2021"
"builtin_method_functions", "add_method",
"available_methods", "reset_methods",... |
11439294 | import logging
import numpy as np
from mcerp import *
from scipy.optimize import minimize
from sympy import *
from sympy.utilities.lambdify import lambdify, lambdastr
from uncertainties import ufloat
from uncertainties import umath as a_umath
from Charm.utils.gaussian_decomposition import gaussian_decomposition
from ... |
11439327 | from ..schemas.datasets import DatasetMetaData, FileMetaData
DatasetsOut = DatasetMetaData
FileMetaDataOut = FileMetaData
|
11439391 | import os
import tensorflow as tf
import diffvg
import pydiffvg_tensorflow as pydiffvg
import time
from enum import IntEnum
import warnings
print_timing = False
__EMPTY_TENSOR = tf.constant([])
def is_empty_tensor(tensor):
return tf.equal(tf.size(tensor), 0)
def set_print_timing(val):
global print_timing
... |
11439398 | class DiamondHunt:
def countDiamonds(self, mine):
c, l, f = 0, len(mine), True
while f:
f = False
for i in xrange(l - 1):
if mine[i : i + 2] == "<>":
mine, l = mine[:i] + mine[i + 2 :], l - 2
c += 1
f... |
11439432 | from matplotlib.lines import Line2D
from matplotlib.text import Text
from matplotlib.patches import Rectangle
import pylab
from xml.etree.ElementTree import ElementTree
width = 300
class ItemArtist:
def __init__(self, position, state):
self.position = position
indx = state.positions.index(position)
... |
11439449 | import io
import email
import unittest
from email.message import Message
from test.test_email import TestEmailBase
class TestCustomMessage(TestEmailBase):
class MyMessage(Message):
def __init__(self, policy):
self.check_policy = policy
super().__init__()
MyPolicy = TestEmailB... |
11439464 | from __future__ import absolute_import, print_function
import itertools
from climin import Smd
from .losses import Quadratic, LogisticRegression, Rosenbrock
def test_smd_quadratic():
obj = Quadratic()
# TODO: I don't know why these parameters work, but they do.
opt = Smd(obj.pars, obj.f, obj.fprime, ob... |
11439493 | import unittest
import os
import sys
sys.path.insert(1, 'src')
from systemdu import SystemdUser
from systemdu import USER_PATH
TEST_TIMER_FILE = 'test.timer'
TEST_SERVICE_FILE = 'test.service'
class TestSystemdUser(unittest.TestCase):
def setUp(self):
if os.path.exists(TEST_TIMER_FILE):
os.r... |
11439499 | del_items(0x80124F0C)
SetType(0x80124F0C, "void PreGameOnlyTestRoutine__Fv()")
del_items(0x80126FD0)
SetType(0x80126FD0, "void DRLG_PlaceDoor__Fii(int x, int y)")
del_items(0x801274A4)
SetType(0x801274A4, "void DRLG_L1Shadows__Fv()")
del_items(0x801278BC)
SetType(0x801278BC, "int DRLG_PlaceMiniSet__FPCUciiiiiii(unsigne... |
11439540 | from django.core.management.base import BaseCommand, CommandError
from build.management.commands.build_human_residues import Command as BuildHumanResidues
from protein.models import ProteinConformation
class Command(BuildHumanResidues):
help = 'Creates residue records for non-human receptors'
pconfs = Prote... |
11439574 | import cv2
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import warnings
from einops import rearrange
class LayerNorm2D(nn.Module):
def __init__(self, dim):
super(LayerNorm2D, self).__init__()
self.norm = nn.LayerNorm(dim)
def forward(self, ... |
11439630 | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import time
from six.moves import queue
from echomesh.base import Settings
from echomesh.command import Command
from echomesh.expression import Expression
from echomesh.util import Log
from echomesh.util.thread.MasterRunnab... |
11439651 | from crispy_forms.helper import FormHelper
from django.forms import ModelForm
from leave.models import LeaveRecord
class LeaveRecordForm(ModelForm):
class Meta:
model = LeaveRecord
exclude = ("employee", "leave_year")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwa... |
11439715 | import json
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from fnmatch import fnmatch
from threading import Lock
from typing import Union, List, Tuple, Dict, Generator, Optional, Set, Type, Callable, Iterable
import pandas as pd
from redo import retrier
from .expressions import BaseColum... |
11439724 | from benderopt.stats import sample_generators
from benderopt.stats import probability_density_function
import numpy as np
np.random.seed(0)
def test_uniform_generator():
low = 0
high = 1
step = None
size = 10000
epsilon = 1e-2
samples = sample_generators["uniform"](size=size, low=low, high=... |
11439728 | import curses
import fcntl
import os
import struct
import termios
import threading
import time
__version_info__ = (1, 0, 4)
__version__ = '.'.join(map(str, __version_info__))
def tail_files(filenames):
"""
`filenames` is a list of files to tail simultaneously.
"""
columns, rows = _terminal_size()
... |
11439734 | import re
from django import template
from django.utils.html import format_html
from admin_volt.utils import get_menu_items
from django.utils.safestring import mark_safe
from django.contrib.admin.views.main import (PAGE_VAR)
register = template.Library()
assignment_tag = register.assignment_tag if hasattr(register, 'a... |
11439753 | import argparse
import os
import os.path as osp
import sys
import numpy as np
from sklearn.metrics import f1_score
from detectron2.data import DatasetCatalog, MetadataCatalog
import mmcv
from tqdm import tqdm
cur_dir = osp.dirname(osp.abspath(__file__))
sys.path.insert(0, osp.join(cur_dir, "../../../"))
import ref
fro... |
11439756 | from LPBv2.client import Lockfile
import pytest
@pytest.fixture
def lockfile():
return Lockfile()
def test_lockfile_init(lockfile):
assert isinstance(lockfile.lcu_pid, int)
assert isinstance(lockfile.pid, int)
assert isinstance(lockfile.port, int)
assert isinstance(lockfile.auth_key, str)
as... |
11439779 | from sanic.blueprints import Blueprint
from sanic.response import json
from sanic.views import HTTPMethodView
from data import test_station
from models import Station
from sanic_openapi import openapi
blueprint = Blueprint('Repair', '/repair')
class RepairStation(HTTPMethodView):
@openapi.summary("Fetches all r... |
11439813 | import sys
import os
import argparse
from holstep_parser import FormulaToGraph
from holstep_parser import parse_formula
from formula import NodeType
def check_incoming_outgoing(graph):
'''This function checks if incoming is consistent with outgoing'''
incoming_dict = {}
outgoing_dict = {}
for node in... |
11439839 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
# Create your models here.
class Session(models.Model):
"""docstring ... |
11439846 | import unittest
import os
import sys
if os.environ.get('USELIB') != '1':
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pyleri import (
KeywordError,
create_grammar,
Regex,
) # nopep8
class TestRegex(unittest.TestCase):
def test_regex(self):
regex = Regex('^(?:\'... |
11439854 | import argparse
import os
import numpy as np
import keras.backend as K
from keras.optimizers import Adam
from keras.utils import generic_utils
from keras.callbacks import ModelCheckpoint
import nets
def load_img_and_dct_data(dataset_path):
files = os.listdir(dataset_path)
X = np.zeros((len(files), 224, 224... |
11439864 | import os
import re
import json
import numpy as np
import pandas as pd
from tqdm import tqdm
from konlpy.tag import Okt
FILTERS = "([~.,!?\"':;)(])"
PAD = "<PAD>"
STD = "<SOS>"
END = "<END>"
UNK = "<UNK>"
PAD_INDEX = 0
STD_INDEX = 1
END_INDEX = 2
UNK_INDEX = 3
MARKER = [PAD, STD, END, UNK]
CHANGE_FILTER = re.comp... |
11439867 | import parser
def str2bool(v):
return v.lower() in ('true')
def str_list(value):
if not value:
return value
else:
return [num for num in value.split(',')]
def int_list(value):
return [int(num) for num in value.split(',')]
def add_argument_group(parser, name):
arg = parser.add_arg... |
11439906 | import pytest
from click.testing import CliRunner
from yogit.yogit import cli
from yogit.yogit.errors import ExitCode
from yogit.tests.mocks.mock_settings import temporary_settings
@pytest.fixture
def runner():
return CliRunner()
def test_cli_without_commands(runner):
result = runner.invoke(cli.main)
a... |
11439914 | import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
df.to_csv('ch02/ans11.txt', sep=' ', index=False, header=None)
|
11439924 | import numpy as np
import json
from matplotlib import pyplot as plt
if __name__ == '__main__':
with open('submit.json', 'r') as f:
data = json.load(f)
print(len(data))
prods = []
for i, k in enumerate(data):
print(i, k, data[k]['prob'])
prods.append(data[k]['prob'])
plt.his... |
11439936 | import FIAT
import finat
import numpy as np
from gem.interpreter import evaluate
from fiat_mapping import MyMapping
def test_awnc():
ref_cell = FIAT.ufc_simplex(2)
ref_el_finat = finat.ArnoldWintherNC(ref_cell, 2)
ref_element = ref_el_finat._element
ref_pts = ref_cell.make_points(2, 0, 3)
ref_vals... |
11439970 | from yarll.actionselection.action_selection import ActionSelection
import numpy as np
class ContinuousActionSelection(ActionSelection):
"""Selection of an action in a continuous action space"""
# def select_action(self, mu, sigma):
# return np.random.normal(mu, sigma)
# Without sigma
def sele... |
11439997 | from spektral.utils import misc
def test_misc():
l = [1, [2, 3], [4]]
flattened = misc.flatten_list(l)
assert flattened == [1, 2, 3, 4]
|
11439998 | import argparse
import csv
import sys
from shutil import rmtree
from PIL import Image
from glob import glob
from os import makedirs, rename
from os.path import join, splitext, basename, exists
from lib.preprocess import resize_and_center_fundus
parser = argparse.ArgumentParser(description='Preprocess EyePACS data set.... |
11440042 | import sqlite3
from textwrap import dedent
from typing import Any
from snakypy.helpers import FG, NONE
from snakypy.zshpower import HOME
from snakypy.zshpower.config.base import Base
from snakypy.zshpower.database.sql import sql
class DAO(Base):
def __init__(self):
try:
Base.__init__(self, H... |
11440044 | from django.conf import settings
from django.conf.urls import url
from oldp.apps.courts.views import CourtAutocomplete, StateAutocomplete
from oldp.utils.cache_per_user import cache_per_user
from . import views
app_name = 'courts'
urlpatterns = [
url(r'^$', cache_per_user(settings.CACHE_TTL)(views.CourtListView.a... |
11440089 | import cv2
import numpy as np
import tensorflow as tf
from tensorflow import keras
from settings import *
import os
pwdpath=os.getcwd()
#modified from- https://medium.com/towards-data-science/robust-facial-landmarks-for-occluded-angled-faces-925e465cbf2e
def findc(img):
# ret, img = cap.read()
# img =... |
11440130 | import os
import glob
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def get_latest_checkpoint(logs_path):
def get_chec... |
11440140 | from django.conf.urls import url, patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from wazimap.urls import urlpatterns
from janaganana.sitemap import JanagananaSitemap
sitemaps = {
"static": JanagananaSitemap,
}
site_url = url(
r"^sitemap\.xml$",
sitemap,
{... |
11440176 | import wx
import sys
class RefreshTimer(wx.Timer):
"""
This calls refresh on all registered objects every second
"""
def __init__(self):
wx.Timer.__init__(self)
self.registered = set()
self.inited = True
def Register(self,item):
"""
Ad... |
11440241 | import sys
import frappe
class StudentProgress:
"""Progress of a student.
"""
def __init__(self, course, email):
self.email = email
if isinstance(course, str):
course = frappe.get_cached_doc("LMS Course", course)
self.course = course
def get_progress(self):
... |
11440245 | import unittest
from wiki_dump_reader import Cleaner
class TestRemoveComments(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.cleaner = Cleaner()
def test_remove_comments_normal(self):
text = "[[面包]]是德国饮食的重要组成部分。德国出产近600种面包和1,200种糕点和[[圆面包]]。德国[[奶酪]]的生产数量占到全欧" \
... |
11440351 | from .credit_card_charge_address import CreditCardChargeAddress
from xendit.models._base_model import BaseModel
from xendit.models._base_query import BaseQuery
class CreditCardChargeBillingDetails(BaseModel):
"""BillingDetails class of Charge (API Reference: Credit Card)"""
class Query(BaseQuery):
"... |
11440357 | from . import testing
class Test(testing.DataBaseTesting):
def test1(self):
self.create_table("weapons", name=str, type=str, dmg=int)
...
|
11440360 | import sys
import os
def replace_digits(word):
for i in xrange(10):
word = word.replace(str(i), "#")
return word
def prep_targ(direc, fi):
"""
replaces digits, and gets rid of 'ROOT' and '@ROOT'
"""
newfi = "targ-" + fi
with open(os.path.join(direc, newfi), "w+") as g:
with... |
11440369 | from Optimizacion.Instrucciones.instruccion import *
from Optimizacion.Asignaciones.asignacion import *
class Ins_if(Instruccion):
def __init__(self, ins, params, goto):
Instruccion.__init__(self, ins, params)
self.goto = goto
def execute(self):
return {'ins': self.ins, 'params': self.p... |
11440414 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
import yfinance as yf
yf.pdr_override()
import datetime as dt
# input
symbol = 'SPY'
start = dt.date.today() - dt.timedelta(days = 365*7)
end = dt.date.today()
# Read data
df = yf.download(symbol,... |
11440448 | def pytest_addoption(parser):
# The Docker tests are ridiculously slow (~1 hour), take a bunch of disk
# space, and are flaky by nature. So let's not run them by default (we have
# mocks as well as the Docker integration tests).
parser.addoption(
'--docker',
action='store_true',
... |
11440450 | from armulator.armv6.all_registers.abstract_register import AbstractRegister
class TTBCR(AbstractRegister):
"""
Translation Table Base Control Register
"""
def __init__(self):
super(TTBCR, self).__init__()
def set_eae(self, flag):
self.value[0] = flag
def get_eae(self):
... |
11440469 | import os
import logging
import core.configurations
import sqlite3
class OutputHandler(object):
"""
Handle all the output handlers, write to files, db, print to screen...
"""
def __init__(self):
pass
def get_output(self, output):
"""
Pass the result object to all the outpu... |
11440475 | import simdgen
import numpy
a = numpy.array([1,2,3,4,5,6,7], dtype='float32')
b = numpy.arange(len(a), dtype='float32')
sg = simdgen.SgCode("x+0.5")
print(a)
sg.calc(b, a)
print(b)
sg.destroy()
sg = simdgen.SgCode("red_sum(x)")
print("sum=", sg.calc(b))
|
11440505 | PULL_POLICY = [("Always", "Always"), ("IfNotPresent", "IfNotPresent"), ("Never", "Never")]
RESTART_POLICY = [("Always", "Always"), ("OnFailure", "OnFailure"), ("Never", "Never")]
byte_units = {
"E": 1000 ** 6,
"P": 1000 ** 5,
"T": 1000 ** 4,
"G": 1000 ** 3,
"M": 1000 ** 2,
"K": 1000,
"Ei":... |
11440519 | from typing import Union, Optional, Sequence
from typing_extensions import Literal
from anndata import AnnData
from cellrank._key import Key
from scanpy._utils import deprecated_arg_names
from cellrank.ul._docs import d, _initial, _terminal, inject_docs
from cellrank.tl.estimators import GPCCA, CFLARE
_find_docs = ""... |
11440568 | import pytest
from tests.support.asserts import assert_error, assert_success
from tests.support.helpers import center_point
def element_click(session, element):
return session.transport.send(
"POST", "session/{session_id}/element/{element_id}/click".format(
session_id=session.session_id,
... |
11440586 | import os
import pytest
from click.testing import CliRunner
from igit.core.commands import Igit
from igit.core.shell_ops import Shell
from igit.cli import add, unstage, undo, commit
@pytest.fixture()
def source_dir():
return os.environ['source_dir']
@pytest.fixture()
def test_dir():
return os.environ['tes... |
11440603 | from django.shortcuts import render
from departments import models
from django.urls import reverse_lazy
from accounts.models import Employee
from django.views.generic import (DetailView,
ListView,
CreateView,
UpdateView,
... |
11440665 | from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 1. Prepare the Data
from keras.utils import to_categorical
train_images = train_images.reshape((60000, 28 * 28)).astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28)).astype('float32') ... |
11440730 | import sys
import os
from curtsies.fmtfuncs import blue, red, bold, on_red
from curtsies.window import FullscreenWindow
import time
if __name__ == '__main__':
print(blue('hey') + ' ' + red('there') + ' ' + red(bold('you')))
n = int(sys.argv[1]) if len(sys.argv) > 1 else 100
with FullscreenWindow() as ... |
11440734 | import time
import random
import json
import os
import torch
import tqdm
import multiprocessing as mp
from program_synthesis.common.tools import saver
from program_synthesis.naps.uast import lisp_to_uast, uast_pprint
from program_synthesis.naps.pipes.basic_pipes import JsonLoader, Batch
from program_synthesis.naps.pi... |
11440746 | from sanic.blueprints import Blueprint
from sanic.response import json
from data import test_manufacturer, test_success
from models import Driver, Status
from sanic_openapi import openapi
blueprint = Blueprint('Manufacturer', '/manufacturer')
@blueprint.get("/", strict_slashes=True)
@openapi.summary("Fetches all ma... |
11440747 | import requests
import re
import json
from bs4 import BeautifulSoup as bs
from getconf import *
def getIds():
global product_id
global size_id
for script in scripts:
if 'spConfig =' in script.getText():
regex = re.compile(r'var spConfig = new Product.Config\((.*?)\);')
match... |
11440752 | class GroupId(object):
"""The unsubscribe group ID to associate with this email."""
def __init__(self, group_id=None):
"""Create a GroupId object
:param group_id: The unsubscribe group to associate with this email.
:type group_id: integer, optional
"""
self._group_id = ... |
11440791 | from pathlib import Path
import brender.material
from terial import models, config
def material_to_brender(material: models.Material, **kwargs):
if material.type == models.MaterialType.AITTALA_BECKMANN:
base_dir = Path(config.MATERIAL_DIR_AITTALA, material.substance,
material.name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.