id
stringlengths
3
8
content
stringlengths
100
981k
11467418
import sys import re import yaml import random from glob import glob from collections import defaultdict from fractions import Fraction import argparse # Bresenham's line algorithm from Rosetta Code # https://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#Not_relying_on_floats def line(xy0, xy1)...
11467419
import numpy as np mapping = {0:0,1:1,2:2,3:3,4:4,5:5,6:10,7:11,8:12,9:13,10:14,11:15,12:8,14:9} def stabilize(crazy): numVisible = crazy.shape[0] joints = -1*np.ones((16,2)) cluttered = 13 for i in range(numVisible): ithJoint = crazy[i] id = ithJoint[0][0][0] x = ithJoint[1][0][0] y = ithJoint[2][0][0] ...
11467436
import io from http import HTTPStatus from pathlib import Path from typing import Optional, Tuple import pytest import requests from requests import Response @pytest.mark.parametrize(["extension"], [["zip"], ["jar"]]) def test_upload_get_delete( resources_folder: Path, server_url: str, extension: str ) -> None: ...
11467452
print ((1+3)/2) print ((4/2)+3) print ((1L+3L)/2L) print ((1L+3L)/3L) print ((1L/2L)+1L) print ((4L/2L)+3L) print 4L**2L-5L+3L/7L%2L print (4L**2L)-5L+((3L/7L)%2L)
11467454
import numpy as np import ipywidgets as widgets import shutil import matplotlib.pyplot as plt import struct global base global all_volts global times global stim dt = 0.1 from tkinter import * from tkinter.filedialog import askopenfilename from tkinter.filedialog import askdirectory from ipywidgets import * def test(...
11467468
import nltk from nltk.corpus import treebank_chunk print(treebank_chunk.chunked_sents()[1]) treebank_chunk.chunked_sents()[1].draw()
11467497
import pkg_resources from chef.api import ChefAPI from chef.exceptions import ChefObjectTypeError from chef.permissions import Permissions class Acl(object): """ Acl class provides access to the Acl in the Chef 12 Acl(object_type, name, api, skip_load=False) - object_type - type of the Chef ...
11467508
import datetime import json import os import random import string import time class PPasteException(Exception): '''Custom exception''' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class PasteManager: NAME_LEN = 6 ALPHABET = list(strin...
11467520
from art_web import app from flask import render_template, request, flash, redirect, url_for, session from models import db, User, Feedback, Paintings, Artist, AdminUser from forms import SignupForm, SigninForm , FeedbackForm, SubmitArt from flask_admin import Admin from flask_admin.base import MenuLink from flask_admi...
11467527
import pytest import theano import theano.tensor as T import numpy as np def test_cosine_similarity(): from ntm.similarities import cosine_similarity key_var, memory_var = T.tensor3s('key', 'memory') cosine_similarity_fn = theano.function([key_var, memory_var], \ cosine_similarity(key_var, memor...
11467585
from .base import * # noqa # We want to set the task to be run as syncronous as this make testing easier. IEVV_BATCHFRAMEWORK_ALWAYS_SYNCRONOUS = True testfilesdir = 'devilry_testfiles' if not exists(testfilesdir): os.mkdir(testfilesdir) logdir = join(testfilesdir, 'log') if not exists(logdir): os.mkdir(log...
11467600
CLASSES = 14 WIDTH = 224 HEIGHT = 224 CHANNELS = 3 LR = 0.0001 EPOCHS = 5 BATCHSIZE = 64 IMAGENET_RGB_MEAN = [0.485, 0.456, 0.406] IMAGENET_RGB_SD = [0.229, 0.224, 0.225] TOT_PATIENT_NUMBER = 30805 # From data
11467630
from glob import glob from pathlib import Path from .constants import DEFAULT_FRAMERATE, TEMP_AUDIO_FILENAME from .command import Command import ffmpeg import os import logging logger = logging.getLogger(__name__) FRAME_FILENAME_LENGTH = 4 def _getwh(path): data = probe(path) width = data["streams"][0]["widt...
11467710
import math import random import torch from torch.autograd import Variable def calculate_gain(nonlinearity, param=None): """Return the recommended gain value for the given nonlinearity function. The values are as follows: ============ ========================================== nonlinearity gain ====...
11467711
import hyperchamber as hc from hypergan.losses.base_loss import BaseLoss class SoftmaxLoss(BaseLoss): """https://arxiv.org/abs/1704.06191""" def _forward(self, d_real, d_fake): ln_zb = (((-d_real).exp().sum()+(-d_fake).exp().sum())+1e-12).log() d_target = 1.0 / d_real.shape[0] g_targ...
11467742
from models.preliminary_contest import PreliminaryProblem from flask import Blueprint from main import db, config from common.utils import unpack_argument from utils import make_response from models import PreliminaryContest, PreliminaryContest, PreliminaryProblemType from models.user import User import math ro...
11467753
def show(o): """ This tests that the proper method is called. """ o.msg() def show2(o): """ This tests oo inheritance. """ o.print_msg() class A(object): def __init__(self): self._a = 5 def msg(self): print("A.msg()") def print_msg(self): self.msg...
11467756
import einops import tensorflow as tf from einops import rearrange from einops.layers.tensorflow import Rearrange class Attention(tf.keras.layers.Layer): def __init__( self, dim, heads=8, dim_head=64, dropout=0.0, max_pos_emb=512, **kwargs ): super(Attention, self).__init__(**kwargs) i...
11467761
import docassemble.base.config import docassemble.webapp.user_database import sys if __name__ == "__main__": docassemble.base.config.load() if len(sys.argv) > 1: db_config = sys.argv[1] else: db_config = 'db' print(docassemble.webapp.user_database.alchemy_url(db_config))
11467801
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_mapr_user(host): u = host.user('mapr') assert u.exists assert u.name == "mapr" assert u.group == "mapr" for g in [...
11467819
import os import requests import zipfile ######################################## def extract(url, base, path, name): if not os.path.exists(base + "/zips/" + name + ".zip"): print(f"Downloading from {url}") r = requests.get(url) with open(base + "/zips/" + name + ".zip",'wb') as ...
11467827
import unittest import data class TestCora(unittest.TestCase): def setUp(self): self.A, self.X, self.Y = data.parse_cora() def test_A_symmetry(self): self.assertTrue( (self.A == self.A.T).all() ) def test_A_min(self): self.assertTrue( self.A.min() >= 0.0 ) def test_A_max(sel...
11467832
from MDRSREID.DataLoaders.Datasets import Dataset from MDRSREID.utils.get_files_by_pattern import get_files_by_pattern import os.path as osp class DukeMTMCreID(Dataset): def __init__(self, cfg=None, mode=None, domain=None, name=None, ...
11467860
import numpy as np import torch from torchvision.transforms import RandomVerticalFlip, RandomHorizontalFlip, RandomCrop from torchvision.transforms import ColorJitter, ToTensor class GlobalContrastNormalize(object): """ Code adapted from https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/expr/preproces...
11467875
from .fixtures import get_product, paddle_client # NOQA: F401 def test_list_products(paddle_client, get_product): # NOQA: F811 response = paddle_client.list_products() assert 'count' in response assert 'total' in response for product in response['products']: assert 'id' in product as...
11467915
from . import * from pya import * class Contra_DC_SWG_segmented(pya.PCellDeclarationHelper): """ Author: <NAME> <EMAIL> """ def __init__(self): # Important: initialize the super class super(Contra_DC_SWG_segmented, self).__init__() TECHNOLOGY = get_technology_by_name('EBeam') ...
11467922
import tensorflow as tf import numpy as np import math import time from pixel_cnn_pp.nn import * def lrelu(x, rate=0.1): # return tf.nn.relu(x) return tf.maximum(tf.minimum(x * rate, 0), x) def fc_lrelu(inputs, num_outputs): fc = tf.contrib.layers.fully_connected(inputs, num_outputs, ...
11467937
from FreeTAKServer.model.SpecificCoT.SendHealthCheck import SendHealthCheck class SendHealthCheckController: # TODO: deprecate this function def __init__(self, RawCoT): self.RawCoT = RawCoT self.HealthCheck = SendHealthCheck() self.HealthCheck.xmlString = RawCoT.xmlString self.H...
11467960
import itertools a = [1, 2, 3] b = ["One", "Two"] result1 = list(zip(a, b)) result2 = list(itertools.zip_longest(a, b)) print(result1) print(result2)
11467966
from __future__ import print_function import csv import distutils import shutil import pandas as pd import os import re from collections import defaultdict import six import sys from Bio import SeqIO from tracerlib.tracer_func import process_chunk, find_possible_alignments from tracerlib.core import Invar_cell impo...
11467973
import numpy as np import copy from scipy import sparse from argoverse.map_representation.map_api import ArgoverseMap class GraphExtractor(object): def __init__(self, config, mode='train'): self.am = ArgoverseMap() self.config = config self.mode = mode def __del__(self): del se...
11467991
from problems.tsp.problem_tsp import TSP from problems.vrp.problem_vrp import CVRP, SDVRP from problems.op.problem_op import OP from problems.pctsp.problem_pctsp import PCTSPDet, PCTSPStoch from problems.pdp.problem_pdp import PDP
11467998
from math import exp from tempfile import NamedTemporaryFile import cv2 import torch from torch.nn.functional import conv2d def gaussian(window_size, sigma): """Gaussian window. https://en.wikipedia.org/wiki/Window_function#Gaussian_window """ _exp = [exp(-(x - window_size // 2) ** 2 / float(2 * sig...
11468051
from .account import * from .instrument import * from .order import * from .position import * from .pricing import * from .trade import * from .transaction import * from .user import * __all__ = (account.__all__ + instrument.__all__ + order.__all__ + pricing.__all__ + trade....
11468054
import logging import re from django.conf import settings from oldp.apps.courts.models import Court from oldp.apps.courts.processing import CourtProcessingStep logger = logging.getLogger(__name__) class ProcessingStep(CourtProcessingStep): description = 'Assign jurisdiction' def process(self, court: Court...
11468089
import numpy as np from matplotlib import pyplot as plt import os ##### Functions that calculate things ##### def local_maxima_detector(y): ''' Finds local maxima in ordered data y. :param y: 1d numpy float array :return maxima: 1d numpy bool array *maxima* is *True* at a local maximum, *False*...
11468106
import random from exterminate.Utilities import builtins _shuffle = random.shuffle _sorted = builtins.sorted def alt_shuffle(a: list, *args, **kwargs): a.sort() # Shuffle returns None and shuffles in place def alt_sorted(a, *args, **kwargs): shuffled = list(a) _shuffle(shuffled) return shuffled ...
11468122
import time class UserInterface(object): def __init__(self): self.open_player_menu = lambda: None self.stop = lambda: None def run(self): while True: time.sleep(1) userInterface = UserInterface()
11468139
from functools import partial from ... import documentation_helpers from ...component_index import component_index from . import cfc_utils SIDE_COLOR = "color(var(--bluish) blend(var(--background) 60%))" def get_inline_documentation(cfml_view, doc_type): if not cfml_view.project_name: return None c...
11468177
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * '''IMPORTS''' import re import json from datetime import datetime, date import urllib3.util # Disable insecure warnings urllib3.disable_warnings() def parse_tag_field(tags_str): tags = [] regex = re.compile(r...
11468210
import z5py from heimdall import view # this fails with out-of-range due to # https://github.com/napari/napari/issues/699 def example(): path = '/home/pape/Work/data/cremi/example/sampleA.n5' with z5py.File(path) as f: raw = f['volumes/raw/s0'] raw.n_threads = 8 seg = f['volumes/segme...
11468226
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import Permission from tenant_users.permissions.models import UserTenantPermissions class UserBackend(ModelBackend): """ Authenticates against UserProfile Authorizes against the UserTenantPermissions. The Facade cla...
11468250
import sys import torch.nn as nn from typing import Union from torchvision import models from dffml.base import config, field from dffml.util.entrypoint import entrypoint from .utils import create_layer from .pytorch_base import PyTorchModelConfig, PyTorchModelContext, PyTorchModel class LayersNotFound(Exception): ...
11468252
import objc as _objc __bundle__ = _objc.initFrameworkWrapper( "EventKit", frameworkIdentifier="com.apple.EventKit", frameworkPath=_objc.pathForFramework( "/System/Library/Frameworks/EventKit.framework" ), globals=globals() )
11468294
from neural_layout.network_graph import Network def vgg16_network(): net = Network() net.add_layer('input', [1, 224, 224]) net.add_layer('l1', [1, 224, 224]) net.add_layer('l2', [1, 224, 224]) net.add_layer('l3', [2, 112, 112]) net.add_layer('l4', [2, 112, 112]) net.add_layer('l5', [4, 56,...
11468325
from uhd_restpy.base import Base from uhd_restpy.files import Files class GlobalPause(Base): __slots__ = () _SDM_NAME = 'globalPause' _SDM_ATT_MAP = { 'HeaderDstAddress': 'globalPause.header.header.dstAddress-1', 'HeaderSrcAddress': 'globalPause.header.header.srcAddress-2', 'Header...
11468335
class DataTree(object): def __init__(self, scr, data): self.scr = scr self.save = True self.valid = True self._data = data if isinstance(data, dict): self._data = {} for k, v in data.items(): self._data[k] = DataTree(self.scr, v) ...
11468341
import torch import pdb from utils.learning import pick_valid_points from utils.io import safe_printout def get_cam_mat(width, height, focal_length): """ Get intrinsic camera matrix (tensor) """ cam_mat = torch.eye(3) cam_mat[0, 0] = focal_length cam_mat[1, 1] = focal_length cam_mat[0, 2] ...
11468347
from binascii import hexlify, unhexlify from eth_hash.auto import keccak from os import urandom from secp256k1 import Secp256k1, SECRET_KEY_SIZE, PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE_COMPRESSED, \ EC_COMPRESSED, EC_UNCOMPRESSED from ._libsecp256k1 import ffi, lib class SecretKey: def __init__(self): # Byt...
11468368
import torch import random import torch.nn as nn from torch.nn import functional as F from torch.distributions.categorical import Categorical import torchvision from . import resnet, resnext, mobilenet, hrnet, u_net, attention_u_net, attention_u_net_deep, attention_u_net_deep_ds4x, hrnetv2_nonsyn from lib.nn import Syn...
11468389
import functools def deprecated(func): """This is a decorator which can be used to mark functions as deprecated.""" @functools.wraps(func) def new_func(*args, **kwargs): return func(*args, **kwargs) return new_func
11468395
import typing as T import numpy as np import py import pytest pd = pytest.importorskip("pandas") # noqa pytest.importorskip("xarray") # noqa import xarray as xr from cfgrib import xarray_to_grib @pytest.fixture() def canonic_da() -> xr.DataArray: coords: T.List[T.Any] = [ pd.date_range("2018-01-01T0...
11468400
import theano, theano.tensor as TT from cgt.utils import Message import time import numpy as np def normc(x): assert x.ndim == 2 return x/norms(x,0)[None,:] def randnf(*shp): return np.random.randn(*shp).astype(theano.config.floatX) def norms(x,ax): return np.sqrt(np.square(x).sum(axis=ax)) class GRUC...
11468432
import argparse import os import cv2 import numpy as np import torch from torch.utils.data import DataLoader import tqdm import models from datasets.validation_datasets import FolderDataset from config import * def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--src-dir', type=str, r...
11468438
p4 = bfrt.int.pipe.Ingress.Int_sink_config.tb_int_sink def setUp(): global p4 # To configure when Tofino switch is used as a sink node p4.add_with_configure_sink(ucast_egress_port=132, sink_reporting_port=132) p4.dump() setUp()
11468503
def func(a, b=4, c=88): print(a, b, c) func(1) # prints: 1 4 88 func(b=5, a=7, c=9) # prints: 7 5 9 func(42, c=9) # prints: 42 4 9 func(42, 43, 44) # prints: 42, 43, 44
11468517
from pathlib import Path from palm.plugins.base import BasePlugin # This plugin is intended for use in testing palm-cli. # It is not intended to be used in production. TestInternalPlugin = BasePlugin( name='test_internal', command_dir=Path(__file__).parent / 'commands', )
11468575
from keras.models import load_model import h5py import numpy as np import matplotlib.pyplot as plt model = load_model('my_model_12.h5') def read_dataset(print_shape=True): x = [] y = [] hdf5_file = h5py.File('all_data.hdf5', "r") data = hdf5_file["sim_data"][:, ...] hdf5_file.close() print(dat...
11468581
load("@com_google_protobuf//:protobuf.bzl", "cc_proto_library") def baikaldb_proto_library(name, srcs, deps=[], include=None, visibility=None, testonly=0): native.filegroup(name=name + "_proto_srcs", srcs=srcs, visibility=visibility,) cc_proto_library(name=name, ...
11468606
import uvicorn from fastapi import FastAPI from data.config import * from routers import * from model.todo import * from model.user import * Base.metadata.create_all(engine) app = FastAPI( title="Pexon-Rest-API", description="A full Rest-API for JSON response included Docker Contains.", version="1.0.0", )...
11468637
import uuid from django.contrib.postgres.fields import ArrayField from django.db import models from django.db.models.indexes import Index from django_zombodb.indexes import ZomboDBIndex from django_zombodb.querysets import SearchQuerySet class Restaurant(models.Model): id = models.UUIDField(primary_key=True, de...
11468641
import os API_VERSION = '1.19.0' # Elasticsearch settings ES_HOST = os.getenv("ES_HOST", "127.0.0.1") ES_PORT = os.getenv("ES_PORT", 9200) ES_USER = os.getenv("ES_USER") ES_PWD = os.getenv("ES_PWD") ES_INDEX = os.getenv("ES_INDEX", "platsannons-read") ES_STREAM_INDEX = os.getenv("ES_STREAM_INDEX", "platsannons-stream...
11468659
import csv import datetime from dateutil.relativedelta import relativedelta import io from itertools import chain from sqlalchemy import and_, or_, func, desc from sqlalchemy.sql import text from PIL import Image from cStringIO import StringIO from wand.image import Image as WandImage from xhtml2pdf import pisa from f...
11468702
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * def GetPlacementType(item): if hasattr(item, "FamilyPlacementType"): return item.FamilyPlacementType else: return None items = UnwrapElement(IN[0]) if isinstance(IN[0], list): OUT = [GetPlacementType(x) for x in items] else: OUT = GetPlacement...
11468715
from __future__ import absolute_import, division, print_function import boost_adaptbx.boost.python as bp ext = bp.import_ext("mmtbx_validation_ramachandran_ext") from mmtbx_validation_ramachandran_ext import rama_eval # maps programatic name to file name aminoAcids = { 'general' : 'general', 'glycine' : 'gly-...
11468743
import numpy as np from collections import OrderedDict from typing import Tuple from classifiers import TextCNNClassifier class SentimentAnalyzer(object): """ Анализатор тональности текстового контента. """ def __init__(self, cls: TextCNNClassifier): self.cls = cls def analyze(self, web...
11468818
from thenewboston.utils.fields import standard_field_names from v1.banks.models.bank import Bank from v1.self_configurations.helpers.self_configuration import get_self_configuration from v1.validators.models.validator import Validator def create_bank_from_config_data(*, config_data): """Create bank from config d...
11468819
r''' Euler angle rotations and their conversions for Tait-Bryan zyx convention See :mod:`euler` for general discussion of Euler angles and conventions. This module has specialized implementations of the extrinsic Z axis, Y axis, X axis rotation convention. The conventions in this module are therefore: * axes $i, j,...
11468838
import cv2 import numpy as np import os import sys from tqdm import tqdm import math import conf # DEPTH = 4 -> 4 * 4 * 4 = 64 colors DEPTH = conf.DEPTH # list of rotations, in degrees, to apply over the original image ROTATIONS = conf.ROTATIONS img_path = sys.argv[1] img_dir = os.path.dirname(img_path) img_name, ex...
11468842
import configparser import os import unittest from TM1py.Objects import User from TM1py.Services import TM1Service from TM1py.Utils.Utils import CaseAndSpaceInsensitiveSet config = configparser.ConfigParser() config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')) PREFIX = "TM1py_Tests_" ...
11468876
import os import pyshark import argparse INFILE_PATH = 'miner.pcapng' OUTFILE_PATH = 'datasets/mining_4t_nicehash.dat' SAMPLE_DELTA = 0.5 LOCAL_IP = '192.168.1.158' LOCAL_IPV6 = 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b' REMOTE_PORTS = [3341, 3333, 3334, 3357, 80, 443] def save_to_file(delta, last_bytes_up, last_byt...
11468892
from dataclasses import dataclass from typing import Optional from lightning_transformers.core.nlp import HFTransformerDataConfig @dataclass class HFSeq2SeqConfig: val_target_max_length: Optional[int] = 128 num_beams: Optional[int] = 1 compute_generate_metrics: bool = True @dataclass class Seq2SeqDataC...
11468900
import financedatabase as fd import FundamentalAnalysis as fa import pandas as pd import matplotlib.pyplot as plt all_technology_companies = fd.select_equities(sector='Technology') silicon_valley = fd.search_products(all_technology_companies, query='San Jose', search='city') API_KEY = "YOUR_API_KEY_HERE" data_set = {...
11468926
import io import os import pytest from django.core.management import call_command from django.core.management.base import CommandError files = ( 'conditions.xml', 'domain.xml', 'options.xml', 'questions.xml', 'tasks.xml', 'views.xml' ) @pytest.mark.parametrize('file_name', files) def test_im...
11468950
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("fluent_contents", "0001_initial")] operations = [ migrations.CreateModel( name="RawHtmlItem", fields=[ ( "contentitem_ptr", ...
11468957
from pyspark import SparkContext import json import sys if __name__ == "__main__": if len(sys.argv) != 4: print "Error usage: LoadJson [sparkmaster] [inputfile] [outputfile]" sys.exit(-1) master = sys.argv[1] inputFile = sys.argv[2] outputFile = sys.argv[3] sc = SparkContext(master,...
11468960
from threading import Thread class ant_colony: class ant(Thread): def __init__(self, init_location, possible_locations, pheromone_map, distance_callback, alpha, beta, first_pass=False): """ initialized an ant, to traverse the map init_location -> marks where in the map that the ant starts possible_locat...
11468979
from homie.device_base import Device_Base from homie.node.node_base import Node_Base class Device_Status(Device_Base): def __init__( self, device_id=None, name=None, homie_settings=None, mqtt_settings=None ): super().__init__(device_id, name, homie_settings, mqtt_settings) node = Nod...
11469000
from django.apps import AppConfig class CountConfig(AppConfig): name = 'apps.count' verbose_name = '统计'
11469002
import os import dj_email_url from django.conf import settings from django.db import migrations from django.utils.module_loading import import_string def populate_email_config_in_user_email_plugin(apps, schema): user_email_path = "saleor.plugins.user_email.plugin.UserEmailPlugin" if user_email_path not in se...
11469058
import pandas as pd, numpy as np import pickle, time from sklearn.model_selection import StratifiedKFold, KFold, train_test_split from hyperopt import fmin, tpe, Trials, STATUS_OK, STATUS_FAIL from datetime import datetime from cat_counter import CatCounter #from pandas.io.common import EmptyDataError import os class...
11469108
import unittest import numpy as np import skfda class TestsSklearn(unittest.TestCase): def setUp(self) -> None: unittest.TestCase.setUp(self) self.x = np.linspace(-1, 1, 1000)[:, np.newaxis] def _test_compare_sklearn( self, cov: skfda.misc.covariances.Covariance, ) -> ...
11469148
import random import dgl import numpy as np import torch as th from torch.utils.data import DataLoader from dgl.nn.functional import edge_softmax from openhgnn.models import build_model import torch.nn.functional as F from . import BaseFlow, register_flow from ..tasks import build_task from sklearn.metrics import f1_sc...
11469159
from collections import defaultdict from typing import TYPE_CHECKING, Dict, Iterable, List, Optional import graphene from django.core.exceptions import ValidationError from ...core.exceptions import InsufficientStock from ...order.error_codes import OrderErrorCode from ...order.utils import get_valid_shipping_methods...
11469163
class CodeCheckingParameterServiceData(object,IDisposable): """ The data needed by code checking server to perform code checking. """ def Dispose(self): """ Dispose(self: CodeCheckingParameterServiceData) """ pass def GetCurrentElements(self): """ GetCurrentElements(self: CodeCheckingParameterServiceD...
11469193
from django import forms from .models import Set, Card from random import randrange class SetForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput, label='') color = forms.CharField(widget=forms.TextInput, label='') class Meta: model = Set fields = ['name'] class CardFor...
11469214
import unittest from satella.coding import static_var class FunTestTest(unittest.TestCase): def test_fun_static_function(self): @static_var("counter", 2) def static_fun(a): static_fun.counter += 1 return a static_fun(2) static_fun(3) self.assertEqu...
11469239
import sqlite3 try: conexion = sqlite3.connect('RyMDB.db') cursor = conexion.cursor() print('Conectado a SQLite') query = 'SELECT sqlite_version();' cursor.execute(query) rows = cursor.fetchall() print('Version de SQLite: ', rows) cursor.close() except sqlite3.Error as error: print(...
11469245
from __future__ import division from __future__ import print_function from past.utils import old_div import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator # In this test, we check and make sure that the scale parameter is app...
11469302
import inspect from ..exceptions import DumpException from .Dump import Dump class Dumper: def __init__(self, application): self.app = application self.dumps = [] def clear(self): """Clear all dumped data""" self.dumps = [] return self def dd(self, *objects): ...
11469324
import sys, traceback from timeit import default_timer as timer from ytmusiclibtracker.common import log from ytmusiclibtracker.create_library_changelog import create_library_changelog from ytmusiclibtracker.export_playlists import export_to_csv def changelog(): create_library_changelog() def export(): exp...
11469333
from brownie import * import random import numpy as np from bisect import bisect_left from helpers import * #global variables day = 24 month = 24 * 30 year = 24 * 365 period = year #number of runs in simulation #n_sim = 8640 n_sim = year # number of liquidations for each call to `liquidateTroves` NUM_LIQUIDATIONS =...
11469354
import pandas as pd import numpy as np import yfinance as yf #Yahoo Finance API from datetime import datetime as dt, date import time df = pd.DataFrame() tickers = ["^KS11", "^GSPC", "^N225", "^HSI", "^N100", "^FTSE", "^DJI"] start_day = dt(2019, 12, 1) today = str(date.today()) kospi = yf.download('^KS11', start=dt(...
11469378
import hashlib import struct import hmac import base58 try: hashlib.new("ripemd160") except ValueError: # No native implementation from . import _ripemd def ripemd160(*args): return _ripemd.new(*args) else: # Use OpenSSL def ripemd160(*args): return hashlib.new("ripemd160", *ar...
11469390
import datetime as dt import json import pytest import pytz from stix2.base import STIXJSONEncoder def test_encode_json_datetime(): now = dt.datetime(2017, 3, 22, 0, 0, 0, tzinfo=pytz.UTC) test_dict = {'now': now} expected = '{"now": "2017-03-22T00:00:00Z"}' assert json.dumps(test_dict, cls=STIXJSO...
11469409
import django from .views import ( test, test_model_form, test_custom_error_message, test_per_form_format, test_non_required, test_id_prefix, test_custom_generator, ) if django.VERSION >= (3, 1, 0): from django.urls import re_path as url, include else: from django.conf.urls import u...
11469411
import http.client import mock from datetime import timedelta from rdr_service import clock from rdr_service.model.utils import to_client_participant_id from rdr_service.dao.database_utils import format_datetime from tests.helpers.unittest_base import BaseTestCase from rdr_service.message_broker.message_broker import ...
11469450
import scrapy from bs4 import BeautifulSoup from utils.text_cleansing import clean_ep_data class ImdbEpisodeSummarySpider(scrapy.Spider): """Spider for scraping the episode summaries of a TV show on IMDb.""" name = 'imdb_episode_summary_spider' def __init__(self, start_urls, *args, **kwargs): su...
11469496
import docutils import os import pytest import sphinx from packaging.version import Version from django.conf import settings from django.core.cache import cache from django.urls import reverse from .utils import srcdir @pytest.mark.django_db @pytest.mark.embed_api class TestEmbedAPIv3ExternalPages: @pytest.f...
11469497
import configparser import requests import os.path import os import sys import time import json import click from ..utils.misc_utils import walk_up, printDebug USER_DIR = os.path.expanduser("~/.dimensions/") # for API credentials USER_CONFIG_FILE_NAME = "dsl.ini" USER_CONFIG_FILE_PATH = os.path.expanduser(USER_DIR ...