id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3349665 | from app.extensions import db
from app.api.utils.models_mixins import AuditMixin, Base
class ExplosivesPermitMagazineType(AuditMixin, Base):
__tablename__ = 'explosives_permit_magazine_type'
explosives_permit_magazine_type_code = db.Column(db.String(3), primary_key=True)
description = db.Column(db.String... |
3349679 | import datetime
def checkio(year):
return sum(
[1 for i in range(1, 13) if datetime.datetime(year, i, 13).weekday() == 4]
)
if __name__ == '__main__': # pragma: no cover
# These "asserts" using only for self-checking and not necessary for
# auto-testing
assert checkio(2015) == 3, "First... |
3349681 | import distutils.util
import cv2
import numpy as np
import paddle
from tqdm import tqdm
def print_arguments(args):
print("----------- Configuration Arguments -----------")
for arg, value in sorted(vars(args).items()):
print("%s: %s" % (arg, value))
print("----------------------------------------... |
3349692 | from otp.level.EntityTypes import *
class CogdoLevelMgr(LevelMgr):
type = 'levelMgr'
class CogdoBoardroomGameSettings(Entity):
type = 'cogdoBoardroomGameSettings'
attribs = (('TimerScale', 1.0, 'float'),)
class CogdoCraneGameSettings(Entity):
type = 'cogdoCraneGameSettings'
attribs = (('GameDur... |
3349694 | from ssh2net.core.cisco_iosxe.driver import IOSXEDriver
my_device = {"setup_host": "172.18.0.11", "auth_user": "vrnetlab", "auth_password": "<PASSWORD>"}
iosxe_driver = IOSXEDriver
with IOSXEDriver(**my_device) as conn:
output = conn.send_command("show version")
# send_inputs returns a list of results; print... |
3349798 | import asyncio
from contextlib import ExitStack, closing
from .refcounting import RefManager
from .allocator import RemoteShmemRepo, BlockManager, ShmemAllocator
class Context:
def __init__(self, messenger):
self.messenger = messenger
self.name = self.messenger.name
self.next_id = 0
... |
3349823 | import numpy as np
from opytimark.markers.boolean import Knapsack
import opytimizer.math.random as r
from opytimizer import Opytimizer
from opytimizer.core import Function
from opytimizer.optimizers.boolean import BPSO
from opytimizer.spaces import BooleanSpace
# Random seed for experimental consistency
np.random.see... |
3349829 | import json
import shutil
from pathlib import Path
from distutils.version import StrictVersion
def parse_new_types(release, item_type):
new_items = []
if release.get(item_type):
for key,value in release[item_type].items():
if value["Type"] == 'New':
new_items.append(f"- [{k... |
3349840 | from setuptools import setup
from codecs import open
from os import path
from pathlib import Path
from typing import List
from pip_check_reqs import __version__
here = path.abspath(path.dirname(__file__))
def _get_dependencies(requirements_file: Path) -> List[str]:
"""
Return requirements from a requirement... |
3349845 | import pybullet as p
import igibson
from igibson.render.mesh_renderer.mesh_renderer_settings import MeshRendererSettings
from igibson.robots.turtlebot import Turtlebot
from igibson.scenes.gibson_indoor_scene import StaticIndoorScene
from igibson.scenes.stadium_scene import StadiumScene
from igibson.simulator import Si... |
3349846 | from lib import *
audio = Audio('MIT-Missing-Semester-lec-mit-0000-2020jan15-1406-Adhoc Section_1.mp4', delay=6/30)
tracking = Fullscreen('MIT-Missing-Semester-lec-mit-0000-2020jan15-1406-Adhoc Section_1.mp4', delay=-1/30)
screen_only = Fullscreen('MIT-Missing-Semester-lec-mit-0000-2020jan15-1406-Adhoc Section_2.mp4',... |
3349851 | import sys
from functools import wraps
from django.forms import fields
_has_been_patched = False
TESTING = (len(sys.argv) > 1 and sys.argv[1] == "test") or sys.argv[0].endswith("py.test")
class DateWidget(fields.DateField.widget):
input_type = "date"
class TimeWidget(fields.TimeField.widget):
input_type ... |
3349867 | import os
from kokki import Execute, Package
# if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]):
# apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
# Execute("apt-update-postgresql9",
# command = "apt-get update",
# action = "nothing")
#... |
3349899 | import os
import sys
import time
import socket
import traceback
import subprocess
try:
import socks
socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1081)
socket.socket = socks.socksocket
except ImportError:
sys.exit("You must install `socks` to run test.\nlike run `pip install pysocks`")... |
3349943 | import argparse
from data_loader import DATASET_CHARACTERISTIC
from experiments import *
from learners import *
LEARNERS = {
"xgb": XGBoostLearner,
"lgb": LightGBMLearner,
"cat": CatBoostLearner
}
def default_num_iterations(experiment_name):
num_samples = DATASET_CHARACTERISTIC[experiment_name][0]
... |
3349945 | import sys
sys.path.append('../')
import torch
import torch.nn as nn
import argparse
import os
import time
from torchvision import models, transforms
from torch.utils.data import DataLoader
import shutil
import json
import collections
import datetime
import my_optim
import torch.nn.functional as F
from models import *... |
3349953 | import buildindex
import re
#NEED TO TEST MORE.
#input = [file1, file2, ...]
#res = {word: {filename: {pos1, pos2}, ...}, ...}
class Query:
def __init__(self, filenames):
self.filenames = filenames
self.index = buildindex.BuildIndex(self.filenames)
self.invertedIndex = self.index.totalIndex
self.regularInde... |
3349961 | from mmcv.runner.utils import master_only
from mmcv.runner import Hook
class CheckpointHook(Hook):
def __init__(self,
interval=-1,
save_optimizer=True,
out_dir=None,
**kwargs):
self.interval = interval
self.save_optimizer = save_... |
3349984 | from kafka import KafkaProducer
from kafka import KafkaConsumer
from kafka import KafkaAdminClient
from operator import itemgetter
import json
from json import dumps
from json import loads
import time
import requests
import GE_GSCH_most_define as mostDefine
'''
{'requestID': 'req-f6720a0e-e3df-455a-825d-f8c80cedc2d9... |
3349999 | import math
from abc import ABC, abstractmethod
import torch # noqa
import torch.nn as nn # noqa
class ActionNoise(ABC):
"""
Base class for Action Noise
:param mean: Mean of noise distribution
:param std: Standard deviation of noise distribution
:type mean: float
:type std: float
"""
... |
3350021 | import codecs
import os
from setuptools import setup, find_packages
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with codecs.open(os.path.join(HERE, *part... |
3350052 | pt_none = 0
pt_rescued_prisoners = 1
pt_enemy = 2
pt_hero_party = 3
pt_village_defenders = 4
pt_cattle_herd = 5
pt_looters = 6
pt_manhunters = 7
pt_steppe_bandits = 8
pt_taiga_bandits = 9
pt_desert_bandits = 10
pt_forest_bandits = 11
pt_mountain_bandits = 12
pt_sea_raiders = 13
pt_deserters = 14
pt_merchant_caravan = 1... |
3350074 | from typing import List, Dict
from overrides import overrides
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import DatasetReader, Instance
from allennlp.data.tokenizers import SpacyTokenizer
from allennlp.models import Model
from allennlp.predictors.predictor import Predictor
from allennlp.da... |
3350125 | import os
from setuptools import setup
setup(
name = "pyscribe",
version = "1.0.0",
author = "<NAME>",
author_email = "<EMAIL>",
description = ("PyScribe makes print debugging easier and more efficient"),
license = "MIT",
keywords = "python pyscribe debug print",
url = "https://github.co... |
3350132 | from flask_socketio_grid_game import socketio, app
def test_connect():
client = socketio.test_client(app, namespace='/grid-game')
received = client.get_received('/grid-game')
g = received[0].get
assert g('name') == 'message'
assert g('args').get('userId') is not None
assert g('args').get('sym... |
3350155 | import hashlib
import logging
import os
import shutil
from uuid import uuid4
from lakesuperior import env
from lakesuperior.store.ldp_nr.base_non_rdf_layout import BaseNonRdfLayout
from lakesuperior.exceptions import ChecksumValidationError, IndigestibleError
logger = logging.getLogger(__name__)
class DefaultLayo... |
3350180 | from pypy.annotation.annrpython import RPythonAnnotator
from pypy.annotation import model as annmodel
from pypy.rpython.ootypesystem import ooregistry # side effects
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.test.test_llinterp import interpret
def test_oostring_annotation():
def oof():
... |
3350197 | import fileinput
from collections import defaultdict
REGS = defaultdict(int)
HIGHEST_VAL = 0
for line in fileinput.input():
a, op, x, _, b, eq, y = line.strip().split()
if eval('REGS["{}"] {} {}'.format(b, eq, y)):
REGS[a] += int(x) * (1 if op == 'inc' else -1)
HIGHEST_VAL = max(HIGHEST_VAL, ... |
3350203 | import numpy as np
from numba import njit
from scipy import sparse
from sklearn.utils import check_array
def solver_path(X, y, datafit, penalty, eps=1e-3, n_alphas=100, alphas=None,
coef_init=None, max_iter=20, max_epochs=50_000,
p0=10, tol=1e-4, use_acc=True, prune=0,
... |
3350232 | from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token
from . import views
user_patterns = [
path("signup/", views.SignUpView.as_view(), name="signup"),
path("token/", obtain_jwt_token, name="jwt_token"),
path("me/", views.UserProfileView.as_view(), name="profile"),
... |
3350243 | import argparse
import subprocess
import sys
import time
import torch
import datetime
from .runner import get_nn_runners
def run_rnn(name, rnn_creator, nloops=5,
seqLength=100, numLayers=1, inputSize=512, hiddenSize=512,
miniBatch=64, device='cuda', seed=None):
def run_iter(modeldef):
... |
3350315 | from lib import placekeyLib
from lib._version import __version__
def test_init():
assert placekeyLib.__version__ == __version__
assert hasattr(placekeyLib, 'h3_is_valid')
assert hasattr(placekeyLib, 'placekey_to_h3')
assert hasattr(placekeyLib, 'h3_to_placekey')
assert hasattr(placekeyLib, 'placek... |
3350427 | import numpy as np
from ._mie import dmiess_module as dmiess
from ._mie import bhmie_module as bhmie
from ._mie import dmilay_module as dmilay
#: Density of pure water, in kg/m^3
RHO_WATER = 1e3
__all__ = ["bhmie_scatter", "core_shell_scatter", "integrate_mode", ]
def bhmie_scatter(particle_radius, radiation_lambd... |
3350433 | import numpy as np
import bpy
from mathutils import Matrix, Vector
import bmesh
import mathutils
import copy
def normalise_vector_batch(vector):
'''
normalising vectors so that (a**2 + b**2 + c**2 == 1**2)
'''
vector_s = vector ** 2
vector_s = np.sum(vector_s, axis=1)
vector_s =... |
3350454 | import itertools
import logging
import random
import re
from common.universal_templates import COMPILE_WHAT_TO_TALK_ABOUT
from common.animals import ANIMALS_FIND_TEMPLATE
from common.universal_templates import if_chat_about_particular_topic
from common.utils import is_no, is_yes
from common.wiki_skill_scenarios import ... |
3350491 | from qtpy import QtWidgets
class LabelQListWidget(QtWidgets.QListWidget):
def __init__(self, *args, **kwargs):
super(LabelQListWidget, self).__init__(*args, **kwargs)
self.canvas = None
self.itemsToShapes = []
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
... |
3350499 | from django.test import TestCase
from django.urls import reverse
from devilry.project.develop.testhelpers.corebuilder import UserBuilder
# from develop.testhelpers.soupselect import cssFind
# from develop.testhelpers.soupselect import cssGet
# from develop.testhelpers.soupselect import cssExists
from devilry.project.d... |
3350528 | from common.python.simulations import BlockSimulation, properties_from_ini, \
TYPE_CHECKING
if TYPE_CHECKING:
from typing import Dict
VALUE = 0
RISING = 1
FALLING = 2
EITHER = 3
NAMES, PROPERTIES = properties_from_ini(__file__, "lut.block.ini")
class LutSimulation(BlockSimulation):
INPA, INPB, INPC, ... |
3350537 | from math import sqrt, ceil
def prime_sieve(n):
if n < 2:
return []
primes = [True] * n
primes[0], primes[1] = False, False
for i in range(2, ceil(sqrt(n))):
if primes[i]:
for j in range(i * i, n, i):
primes[j] = False
return [num for num, val in enu... |
3350594 | import numpy as np
from src.DH.Channel import ChannelParams, Channel
from src.DH.State import DHState
from src.ModelStats import ModelStats
from src.base.GridActions import GridActions
from src.base.GridPhysics import GridPhysics
class DHPhysicsParams:
def __init__(self):
self.channel_params = ChannelPar... |
3350599 | from collections import namedtuple
from typing import List
Point = namedtuple('Point', 'x y')
def simple_polygon_area(points: List[Point]) -> float:
"""
Calculates area of simple polygon given by a list of points.
Assumes that points is a list of points in either clockwise
or counter-clockwise order... |
3350676 | import random
from time import time
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
from kornia import augmentation as augs, kornia, Resample
from kornia import filters
import torch.nn as nn
import torch.nn.functional as F
# Wrapper for a DLAS Dataset class that applies random ... |
3350704 | import pytest
from flask_restful_swagger import swagger
@pytest.mark.parametrize(
"test_input,expected",
[
("Hey\n", "Hey<br/>"),
("\n/n\n/n\n", "<br/>/n<br/>/n<br/>"),
("No Change", "No Change"),
],
)
def test_string_sanitize_doc(test_input, expected):
assert swagger._sanitiz... |
3350710 | import sys
import os
import sys
import re
import os.path
import platform
import subprocess
def replace(filename, pattern, replacement):
f = open(filename)
s = f.read()
f.close()
s = re.sub(pattern, replacement, s)
f = open(filename, 'w')
f.write(s)
f.close()
dbms_cfg = ["config-std.h", "c... |
3350727 | def process_form(request, form_class, form_dict=None, save_kwargs=None, *a, **kw):
'''
Optional:
=========
You can pass kwargs to the form save function in a 'save_kwargs' dict.
Example Usage:
==============
success, form = process_form(request, DiscussionForm, in... |
3350775 | def multiply_then_add(x, y, z, /, print_this='Nothing'):
print(print_this)
return x * y + z
print(multiply_then_add(5, 10, 20, print_this='Something')) |
3350778 | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from EffectController import EffectController
class ChrysanthemumEffect(NodePath, EffectController):
def __init__(self):
NodePath.__init__(self, 'ChrysanthemumEffect')
EffectController.__init__(self)
self.effect... |
3350791 | import databases
import sqlalchemy
import ormar
database = databases.Database("sqlite:///db.sqlite")
metadata = sqlalchemy.MetaData()
class Course(ormar.Model):
class Meta(ormar.ModelMeta):
database = database
metadata = metadata
id: int = ormar.Integer(primary_key=True)
name: str = orm... |
3350819 | import bpy
from ..goldsrc_shader_base import GoldSrcShaderBase
from ...shader_base import Nodes
from .....library.goldsrc.mdl_v10.structs.texture import MdlTextureFlag
class GoldSrcShaderMode5(GoldSrcShaderBase):
SHADER: str = 'goldsrc_shader_mode5'
def create_nodes(self, material_name: str, rad_info=None):... |
3350862 | import argparse
from gpt2bot.telegram_bot import run as run_telegram_bot
from gpt2bot.console_bot import run as run_console_bot
from gpt2bot.dialogue import run as run_dialogue
from gpt2bot.utils import parse_config
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
... |
3350876 | import pybullet as pb
from . import collision
from .dynamics import Dynamics
from .joint import JointInfo, Joint
from .shape import VisualShape, CollisionShape
class Link(object):
def __init__(self, body_id, link_index, client_id):
self._body_id = body_id
self._link_index = link_index
sel... |
3350883 | import json
import os
import subprocess
import six
from . import constants
from . import errors
from .utils import create_environment_dict
from .utils import find_executable
class Store(object):
def __init__(self, program, environment=None):
""" Create a store object that acts as an interface to
... |
3350893 | import pytest
import copy
from src.base.bbox import Bbox
from src.base.node import Node
@pytest.fixture(scope="module")
def rappi():
return Bbox(left=8.81372, bottom=47.218788, right=8.852430, top=47.239654)
def test_instantiate():
bottom = 47.0
left = 8.0
top = 48.0
right = 9.0
bbox = Bbox(... |
3350894 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.infert import infert
def test_infert():
"""Test module infert.py by downloading
infert.csv and testing shape of
extracted data has 248 row... |
3350900 | import yaml
from torch import optim
from os import path
from gan_training.models import generator_dict, discriminator_dict, encoder_dict
# from gan_training.train import toggle_grad_D
# General config
def load_config(path, default_path):
''' Loads config file.
Args:
path (str): path to config file
... |
3350906 | from malcolm.yamlutil import check_yaml_names, make_block_creator
shutter_block = make_block_creator(__file__, "shutter_block.yaml")
scan_runner_block = make_block_creator(__file__, "scan_runner_block.yaml")
attribute_block = make_block_creator(__file__, "attribute_block.yaml")
directory_monitor_block = make_block_cre... |
3350908 | from ELFExceptions import *
from ELFStructures import *
from struct import pack, unpack
from copy import deepcopy
# if new_header is == True, build a header with standard/appropriate values in the corresponding
# fields. If new_header == False, simply read the raw header values into the ELF header dictionary
# TODO: ... |
3350924 | import pytest
from tests.acceptance import run_gitlabform
@pytest.fixture(scope="class")
def schedules(gitlab, group_and_project):
another_branch = "scheduled/new-feature"
gitlab.create_branch(group_and_project, another_branch, "main")
# fmt: off
schedules = [
("Existing schedule", "main",... |
3350939 | import torch.nn.functional as F
from collections import OrderedDict
import numpy as np
class InputPadder:
"""Pads images such that dimensions are divisible by 8 , from RAFT."""
def __init__(self, dims, mode='sintel'):
self.ht, self.wd = dims[-2:]
pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) ... |
3350990 | import functools
import logging
import time
from typing import List, Union, Dict
from urllib.parse import urlparse
import requests
import yaml
from ogame.api.client import OGameAPI
from ogame.game.const import (
Mission,
CoordsType,
Resource,
Ship,
Technology,
CharacterClass
)
from ogame.game.... |
3351031 | import argparse
import os
import csv
from PIL import Image, ImageFont, ImageDraw
parser = argparse.ArgumentParser()
parser.add_argument("-inputdir", help="location of directory to traverse")
parser.add_argument("-outputfile", help="location of directory to traverse")
args = parser.parse_args()
input_dir = args.inputd... |
3351032 | from pathlib import Path
import numpy as np
import pytest
import ctd
data_path = Path(__file__).parent.joinpath("data")
@pytest.fixture
def spiked_ctd():
yield ctd.from_cnv(data_path.joinpath("CTD-spiked-unfiltered.cnv.bz2"))
@pytest.fixture
def filtered_ctd():
yield ctd.from_cnv(data_path.joinpath("CTD-... |
3351042 | import numpy as np
import cv2
import glob
def webcam_gui(filter_func, video_src=0):
cap = cv2.VideoCapture(video_src)
cap.set(6, 100)
key_code = -1
while(key_code == -1):
# read a frame
ret, frame = cap.read()
# run filter with the arguments
frame... |
3351087 | from chainer_compiler.elichika.typing.types import *
__all__ = [ 'builtin_func_ty' ]
def ty_len(ty_args, ty_kwargs):
x_type, = ty_args
if isinstance(x_type, TyList):
return TyInt()
if isinstance(x_type, TyTuple):
return TyInt(x_type.size())
if isinstance(x_type, TyTensor):
... |
3351115 | import torch
import torch.nn.functional as F
def mm_normalize(x, min=0, max=1):
x_min = x.min()
x_max = x.max()
x_range = x_max - x_min
x_z = (x - x_min) / x_range
x_out = x_z * (max - min) + min
return x_out
def rand_range(size, min, max):
return torch.rand(size)*(max-min)+min
def ran... |
3351160 | import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd
import os
import numpy as np
import torch
import math
from PIL import Image
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
class Visualizer(object):
"""docstring for Visualizer"""
def __init__(s... |
3351170 | VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def split_text(text):
result = []
temp_text = ''
for i in text:
if i.isalpha() or i.isdigit():
temp_text += i.upper()
else:
result.append(temp_text)
temp_text = ''
if temp_text:
result.app... |
3351194 | import os
def writeANNProperties(in_scaler,out_scaler):
try:
assert os.path.isdir('ANNProperties')
except:
os.mkdir('ANNProperties')
ANNProperties = open('ANNProperties/ANNProperties', 'w')
with open('ANNProperties/top', encoding='utf-8') as f:
for line in f.readlines():
... |
3351195 | from __future__ import absolute_import
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_text
from django.utils.functional import cached_property
from compressor.exceptions import ParserError
from compressor.parser import ParserBase
class Html5LibParser(ParserBase):
... |
3351217 | from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, BatchNormalization, MaxPooling2D, Activation, ReLU
from unit_test.helper import tf_random_seed
model_list = []
for model_depth in [1, 2]:
tf_random_seed()
placeholder = x = Input((32, 32, 3), name='data'... |
3351237 | import re
from youtrackutils.fbugz.fogbugz import FogBugz
from youtrackutils.fbugz import FBUser, FBArea, FBMilestone, FBIssue, FBComment, FBAttachment
from datetime import datetime
import calendar
class FBClient(object):
def __init__(self, source_url, source_login, source_password):
self._source_url = so... |
3351274 | from unittest import TestCase
import tempfile
import os
from wifi import Cell
from wifi.scheme import extract_schemes, Scheme
from wifi.exceptions import ConnectionError
NETWORK_INTERFACES_FILE = """
# This file describes the network interfaces available on your system
# and how to activate them. For more informatio... |
3351286 | import decimal
from hypothesis import given
from hypothesis import strategies as st
import pytest
from eth_utils.currency import MAX_WEI, MIN_WEI, from_wei, to_wei, units
@given(
amount_in_wei=st.integers(min_value=MIN_WEI, max_value=MAX_WEI),
intermediate_unit=st.sampled_from(tuple(units.keys())),
)
def te... |
3351319 | v1_push_schema = {
"definitions": {
"person": {
"required": [
"name"
],
"type": "object",
"description": "A person that is a contributor to the research object.",
"properties": {
"affiliation": {
... |
3351327 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^foobar$', views.example, name='example'),
]
|
3351329 | import pytest
import os, shutil
import numpy as np
from flare.utils.element_coder import _Z_to_mass, _Z_to_element, _element_to_Z
from flare.ase.atoms import FLARE_Atoms
from ase.calculators.lammpsrun import LAMMPS
from ase.io import read, write
from .get_sgp import get_sgp_calc, get_random_atoms
n_species_list = [1,... |
3351350 | import tensorflow as tf
import numpy as np
from tensorflow.python.client import timeline
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file
from input_pipelines.input_pipeline_cityscapes import inference_input
from model import PanopticSegmentationModel
from config import Params
fr... |
3351355 | import edge_boxes as edges
windows = edges.get_windows(['/home/zawlin/data/indoor.jpg'])
print windows
|
3351382 | import urllib
import requests
import traceback
from imgurpython import ImgurClient
import secret_keys
imgur_client = None
def init_imgur_client():
global imgur_client
imgur_client = ImgurClient(secret_keys.imgur_client_id, secret_keys.imgur_client_secret)
def is_supported_image_url(url):
image_types = ... |
3351397 | from gremlin_python.driver import client
from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import (
DriverRemoteConnection
)
d... |
3351415 | import unittest
from tests.lib.client import SingletonClient
from tests.lib.card_products import CardProducts
from marqeta.errors import MarqetaError
class TestCardProductsFind(unittest.TestCase):
"""Holds tests for the card_products.find endpoint"""
@classmethod
def setUpClass(cls):
"""Setup fo... |
3351417 | from typing import List, cast
from pyClarion import nd
from pprint import pprint
from random import gauss
# A basic form of reverse-mode automatic differentiation is supported in
# pyClarion with an API similar to that of Tensorflow 2.
###################
### Basic Usage ###
###################
# The basic tool ... |
3351427 | import base64
from datetime import datetime, timedelta
import json
import pickle
import requests
retrieve_token_url = 'https://api.nrgsystems.com/api/RetrieveToken?code=y2/bWG4hRNf1E00lWICOp7nqLvpNPOtaiFf9Wq2bi1iUpdyQdjwicQ=='
data_catalog_url = 'https://api.nrgsystems.com/api/DataCatalog'
convert_url = 'https://api... |
3351461 | from .xmlUtils import map_type
from .PlivoXMLElement import PlivoXMLElement
from .ConferenceElement import ConferenceElement
from .DTMFElement import DTMFElement
from .MultiPartyCallElement import MultiPartyCallElement
from .hangupElement import HangupElement
from .messageElement import MessageElement
from .numberEleme... |
3351531 | from .main import Fit, Muggeo
from .model_selection import ModelSelection
from .davies import davies_test
__all__ = ['Fit', 'Muggeo', 'ModelSelection', 'davies_test']
|
3351538 | import numpy
import torch
import librosa
class LogMel(torch.nn.Module):
def __init__(self):
super().__init__()
self._eps = 1e-8
def transform(self, audio):
m = librosa.feature.melspectrogram(audio/numpy.abs(audio).max())
m = numpy.log(m + self._eps)
return torch.Tensor... |
3351555 | from enum import IntEnum
class AppAlgorithmType(IntEnum):
"""
App algorithm type
"""
AppAlgorithmType_Not = 0
AppAlgorithmType_SM2 = 1 # SM2
AppAlgorithmType_R1 = 2 # ECDSA(secp256r1)
AppAlgorithmType_K1 = 3 # ECDSA(secp256K1)
class AppCaType(IntEnum):
"""
Type of key mode
... |
3351576 | from xml.sax.saxutils import quoteattr
from mwlib import expander
from mwlib.templ import parser
def mark_infobox(self, name, raw):
res = parser.parse(raw, replace_tags=self.replace_tags)
if not name.lower().startswith("infobox"):
return res
print "marking infobox %r" % name
return (u"<div te... |
3351632 | from math import isclose
class Circle:
def __init__(self, **kwargs):
if "p1" in kwargs and "p2" in kwargs and "p3" in kwargs:
self.from_three_points(kwargs["p1"], kwargs["p2"], kwargs["p3"])
# elif "c" in kwargs and "r" in kwargs:
# self.from_center_radius(kwargs["c"], kwargs["r"])
else:
... |
3351645 | from __future__ import print_function
from vnc_api.vnc_api import VncApi
import json
api = VncApi()
GSC = 'default-global-system-config'
def dump(res_type, fq_name):
obj = api._object_read(res_type=res_type, fq_name=fq_name)
dumpobj(obj)
def dumpobj(obj):
print(json.dumps(api.obj_to_dict(obj), indent=4))... |
3351671 | import numpy as np
import scipy as sp
import scipy.ndimage as ndimage
import math
from skimage import exposure,filters
from matplotlib import pyplot as plt
import cv2
import matplotlib.pyplot as plt
from skimage.transform import hough_circle, hough_circle_peaks,hough_ellipse
from skimage.feature import canny
from skim... |
3351673 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQM.SiPixelPhase1Common.HistogramManager_cfi import *
import DQM.SiPixelPhase1Common.TriggerEventFlag_cfi as trigger
SiPixelPhase1TrackClustersOnTrackCharge = DefaultHistoTrack.clone(
name = "charge",
title = "... |
3351686 | import gc
import json
import os
import re
import warnings
import unittest
import pymysql
from .._compat import CPYTHON
if CPYTHON:
import atexit
gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
@atexit.register
def report_uncollectable():
import gc
if not gc.garbage:
print("No garbag... |
3351721 | import unittest
from deepstar.util.parse import parse_range
class TestParse(unittest.TestCase):
"""
This class tests the parse module.
"""
def test_parse_range(self):
self.assertEqual(parse_range('1'), [1])
self.assertEqual(parse_range('1-3'), [1, 2, 3])
self.assertEqual(pars... |
3351751 | from flask import Flask, render_template, abort
from calendar import Calendar
from datetime import date
app = Flask(__name__)
@app.route('/', defaults={'year': None})
@app.route('/<int:year>/')
def index(year):
cal = Calendar(0)
try:
if not year:
year = date.today().year
cal_list ... |
3351757 | import pymel.core as pm
import pulse.nodes
import pulse.spaces
import pymetanode as meta
from pulse.buildItems import BuildAction, BuildActionError
from pulse.views.contextmenus import PulseNodeContextSubMenu
class CreateSpaceAction(BuildAction):
def validate(self):
if not self.node:
raise B... |
3351760 | class WrappaText:
def __init__(self, text):
self._text = text
@property
def text(self):
return self._text
|
3351801 | import numpy as np
import random
class MovementController:
GOING_STRAIGHT = 0
TURNING_RIGHT = 1
TURNING_LEFT = 2
TURN_CAPACITY_MAX = 30
MAX_SPEED = 6
THRESHOLD_PROXIMITY = 0.15
THRESHOLD_PROB_TURN = 0.1
SENSOR_ERROR = 0.1
def __init__(self):
self.status = self.GOING_STRAI... |
3351858 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
from scripts.core.base_classes.ui import UI
from scripts.core.constants import SceneType
if TYPE_CHECKING:
from scripts.core.game import Game
__all__ = ["Scene"]
class Scene(ABC):
"""
Handles Scene ... |
3351861 | import requests
from nife.core.phpCodeFun import *
from nife.core.fakeUseAgent import fake_agent
import json
import os
from django.conf import settings
from lxml import etree
import base64
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WCnife.settings")
class SendCode(object):
def __init__(self, url, pwd):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.