id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11573400 | import threading
from dataclasses import dataclass
from traceback import FrameSummary
from typing import List, Optional
import rx
from rx.disposable import Disposable
from rxbp.init.initobserverinfo import init_observer_info
from rxbp.observable import Observable
from rxbp.observablesubjects.observablesubjectbase imp... |
11573408 | from cms.models.pluginmodel import CMSPlugin
from django.db import models
class FloatModel(CMSPlugin):
FLOAT_CHOICES = (
('left', 'float left'),
('right', 'float right'),
)
FLOAT_BREAKPOINT_CHOICES = (
('', 'very small'),
('sm-', 'small'),
('md-', 'medium'),
... |
11573442 | from werkzeug.security import generate_password_hash
from app.models import db, User
def seed_users():
demo = User(username='Demo', email='<EMAIL>',
password='password')
db.session.add(demo)
db.session.commit()
def undo_users():
db.session.execute('TRUNCATE users CASCADE;')
db... |
11573470 | import os
import datetime
import numpy as np
from keras.utils import to_categorical
from keras.preprocessing.image import Iterator
from .image_io_utils import load_image, save_to_image
from .image_augmentation_utils import image_randomcrop, image_centercrop
from ..vis_utils import plot_image_label
from ...configures i... |
11573474 | import setuptools
from setuptools.extension import Extension
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="dbscan",
version="0.0.9",
author="<NAME>",
author_email="<EMAIL>",
description="Theoretically efficient and practical parallel ... |
11573478 | import pickle
from functools import partial
from typing import Union, Callable, Optional, List, Dict
from .. import uwsgi
from ..typehints import Strint
from ..utils import decode, decode_deep, listify
__offloaded_functions: Dict[str, Callable] = {}
TypeMuleFarm = Union[Strint, 'Mule', 'Farm']
def _get_farms() ->... |
11573494 | from avalon import api
class FusionSelectContainers(api.InventoryAction):
label = "Select Containers"
icon = "mouse-pointer"
color = "#d8d8d8"
def process(self, containers):
import avalon.fusion
tools = [i["_tool"] for i in containers]
comp = avalon.fusion.get_current_comp... |
11573512 | from transformers import BertTokenizer, AdamW, BertModel, BertPreTrainedModel
import torch.nn as nn
class BertForQuestionAnswering(BertPreTrainedModel):
def __init__(self, config):
super(BertForQuestionAnswering, self).__init__(config)
self.bert = BertModel(config)
self.qa_outputs = nn.Line... |
11573520 | from matplotlib import pyplot as plt
from matplotlib.axes import Axes
import pandas as pd
import numpy as np
from typing import *
from yo_fluq_ds._fluq._common import *
def default_ax(ax):
if ax is None:
_, ax = plt.subplots(1,1)
return ax
|
11573545 | import numpy as np
import sys,os
import cv2
import caffe
dataset="voc"
net_file= dataset+'/MobileNetSSD_deploy.prototxt'
caffe_model=dataset+'/MobileNetSSD.caffemodel'
net = caffe.Net(net_file,caffe_model,caffe.TEST)
CLASSES = ('background','aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat',... |
11573562 | import pytest
from flex.constants import (
INTEGER,
NUMBER,
STRING,
)
from flex.error_messages import MESSAGES
from flex.exceptions import ValidationError
from flex.loading.definitions.schema import schema_validator
from tests.utils import (
assert_path_not_in_errors,
assert_message_in_errors,
)
... |
11573604 | from abc import ABC, abstractmethod
class SessionFragment(ABC):
def __init__(self, session):
self.session = session
@abstractmethod
def is_busy(self):
"""Whether the fragment is doing work"""
def close(self):
"""Close the fragment state"""
pass
|
11573607 | import os
import re
from datetime import datetime
from functools import cached_property
from http import HTTPStatus
from flask import current_app, abort
from sqlalchemy.orm import joinedload
from template_support.file_storage import FileStorage
from thumbnail.cache import ThumbnailCache
from ..config import Config
fr... |
11573612 | from typing import (
List,
Tuple,
Dict,
)
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
try:
import constants
except:
from .. import constants
from ner import utils
USE_SMA... |
11573637 | import pytest
from flex.constants import (
STRING,
)
from flex.error_messages import MESSAGES
from flex.exceptions import ValidationError
from tests.utils import (
assert_message_in_errors,
assert_path_not_in_errors,
)
from flex.loading.common.reference import (
reference_object_validator,
)
def ... |
11573645 | import torch
import numpy
import abc
from typing import *
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
class _BaseBuffer(object):
nsteps: int
def __init__(self, nsteps: int):
self.nsteps = nsteps
def append(self, transitio... |
11573648 | from pyscf.pbc.gto import Cell
from pyscf.pbc.scf import KRKS
from pyscf.pbc.tdscf import KTDDFT
from pyscf.pbc.tdscf import kproxy_supercell
from pyscf.tdscf.common_slow import eig, format_frozen_k, format_frozen_mol
from test_common import retrieve_m, ov_order, assert_vectors_close
import unittest
from numpy import... |
11573651 | from ignite.contrib.handlers.param_scheduler import ParamScheduler
class ManualParamScheduler(ParamScheduler):
"""A class for updating an optimizer's parameter value manually.
Args:
optimizer (`torch.optim.Optimizer`): the optimizer to use
param_name (str): name of optimizer's parameter to up... |
11573683 | from keras.layers import Conv1D,Multiply
class GatedConv1D():
'''门控线性单元 https://arxiv.org/abs/1612.08083'''
def __init__(self, filters, kernel_size, strides=1, padding='same',kernel_initializer = "he_normal"):
self.filters = filters
self.kernel_size = kernel_size
self.strides = strides... |
11573703 | import math
import torch
def bitreversal_permutation(n, device=None, dtype=None):
"""Return the bit reversal permutation used in FFT.
By default, the permutation is stored in numpy array.
Parameter:
n: integer, must be a power of 2.
Return:
perm: bit reversal permutation, pytorch tenso... |
11573726 | import numpy as np
import paddle
# 缓存容器:内容为{obs, act, obs_, reward, done}五元组
class ReplayBuffer(object):
def __init__(self, state_dim, action_dim, max_size=int(1e4)):
self.max_size = max_size
self.cur = 0
self.size = 0
self.states = np.zeros((max_size, state_dim))
self.act... |
11573746 | from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from PIL import ImageFilter
import random
import io
import base64
def getRandomColor():
c1 = random.randint(0,255)
c2 = random.randint(0,255)
c3 = random.randint(0,255)
return (c1,c2,c3)
def getImageBytes(num):
image = Ima... |
11573799 | import warnings
from typing import Collection, Optional, Tuple
from typing import Union
import cftime
import pandas as pd
import xarray as xr
from xcube.core.gridmapping import GridMapping
from xcube.util.assertions import assert_given
# The MIT License (MIT)
# Copyright (c) 2021 by the xcube development team and co... |
11573830 | from loguru import logger
from chronos.metadata import Setting, Session
def get_setting(key):
"""Get setting value from database. Return None or value."""
session = Session()
value = session.query(Setting).get(key)
session.close()
return value
def set_setting(key, value):
"""Update setting... |
11573831 | from __future__ import unicode_literals
from moya import expose
@expose.macro("macro.expose.double")
def double(n):
return n * 2
@expose.macro("macro.expose.tripple")
def tripple(n):
return n * 3
@expose.filter("cube")
def cube(n):
return n ** 3
|
11573841 | NLP_CONFIG = {'system_entity_recognizer': {}}
ENTITY_RESOLVER_CONFIG = {'model_type': 'exact_match'}
|
11573845 | import pytest
from computation.automata.pda import (
DPDA,
NPDA,
DPDADesign,
DPDARulebook,
NPDADesign,
NPDARulebook,
PDAConfiguration,
PDARule,
Stack,
)
# check parentheses
rulebook = DPDARulebook(
[
PDARule(1, "(", 2, "$", ["b", "$"]),
PDARule(2, "(", 2, "b", [... |
11573876 | import os
import shutil
import tempfile
import numpy as np
import numpy.random as npr
import torch
from torch.utils.data.dataset import Dataset
class TTensorDictDataset(Dataset):
def __init__(self, tensors, in_place_shuffle = True):
super(TTensorDictDataset, self).__init__()
self.in_place_shuffle = in_plac... |
11573938 | import os
from setuptools import Extension
from setuptools import setup
setup(
name="greenlet",
version='0.3.1',
description='Lightweight in-process concurrent programming',
long_description=open(
os.path.join(os.path.dirname(__file__), 'README'), 'r').read(),
maintainer="<NAME>",
maint... |
11573966 | import ee, getpass, time, math, sys
from flask import Flask, render_template, request
from eeMad import imad
from eeWishart import omnibus
ee.Initialize()
app = Flask(__name__, static_url_path='/static')
def simon(path):
images = ee.List(
[ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160305T171... |
11574013 | from dynamic_preferences.types import BooleanPreference, StringPreference, IntegerPreference, ChoicePreference
from dynamic_preferences.preferences import Section
from dynamic_preferences.registries import global_preferences_registry
from dynamic_preferences.users.registries import user_preferences_registry
from YtMan... |
11574046 | import os
import copy
import string
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils import data
import torch.nn.functional as F
from librosa import output
class ConfigObject:
def __init__(self, **entries):
self.__dict__.update(entries)
def reserve_pop(x):
... |
11574075 | import copy
import tensorflow as tf
import networks.vgg16 as vgg16
import networks.vgg11 as vgg11
import networks.mobilenet_for_cifar as mobilenet_for_cifar
import networks.mobilenet_for_imagenet as mobilenet_for_imagenet
import networks.resnet18 as resnet18
import networks.resnet32 as resnet32
import datasets.cifar1... |
11574081 | from Utility import logger
class Executor:
def __init__(self):
self.NLUQueue = None
def initialize(self,instructID):
director,env,start,dest,txt,set = instructID.split('_')
if self.NLUQueue:
self.NLUQueue.put(('Director',director))
self.NLUQueue.put(('Start ... |
11574116 | import os, shutil
from django.core.files.base import File
from django.conf import settings
from django.test import TestCase
from django.utils.encoding import force_bytes
from test_app.models import FileTesting, ImageTesting, DependencyTesting, RenameFileTesting
def add_base(path):
return os.path.join(settings.BA... |
11574186 | import Program.GlobalVar as gv
from CommonDef.DefStr import *
from Program.Common import *
from Program.ProcessData import *
from builtins import int
from numpy import NaN
from Statistics_TechIndicators.CalcStatistics import *
from sklearn import datasets
from sklearn import preprocessing
from sklearn.model_selection ... |
11574214 | from collections import deque
def splitby(pred, seq):
trues = deque()
falses = deque()
iseq = iter(seq)
def pull(source, pred, thisval, thisbuf, otherbuf):
while 1:
while thisbuf:
yield thisbuf.popleft()
newitem = next(source)
# uncommen... |
11574239 | import os
import tempfile
from pathlib import Path
def local_file_path(name):
directory = tempfile.mkdtemp()
return str(Path(directory, name))
def remove_file(file_path):
os.remove(file_path)
|
11574249 | from unittest import TestCase
from svtools.bedpe import Bedpe
from svtools.cluster import Cluster
class ClusterTests(TestCase):
def test_can_add(self):
bedpe = [ '1', '200', '300', '2', '300', '400', '777_1', '57', '+', '-', 'BND', 'PASS', '.', '.', '.', '.', '.', '.', 'MISSING', 'SVTYPE=BND;AF=0.2' ]
... |
11574265 | from flask import Flask
from flask import request
from flask import jsonify
app = Flask(__name__)
import json
from jittor.utils.pytorch_converter import convert
@app.route('/', methods=["GET", "POST"])
def hello():
msg = request
data = msg.data.decode("utf-8")
try:
data = json.loads(data)
... |
11574275 | import math
from glob import glob
import tensorflow as tf
from tensorflow.keras import initializers
import numpy as np
import random
from utils import *
class RelationModule(tf.keras.Model):
def __init__(self, channels=128, output_dim=128, key_dim=128, **kwargs):
super(RelationModule, self).__init__(**kwa... |
11574290 | import unittest
from datetime import datetime
from datetime import timedelta
from keydra.providers.base import BaseProvider
from keydra.providers.base import exponential_backoff_retry
@exponential_backoff_retry(1, delay=1)
def _failing_function():
raise Exception('Boom')
@exponential_backoff_retry(1, delay=1)... |
11574293 | from abc import ABC, abstractmethod
from typing import Optional, Union
import numpy as np
class Arm(ABC):
"""Arm
:param Optional[str] name: alias name
"""
def __init__(self, name: Optional[str]):
self.__name = self._name() if name is None else name
@property
def name(self) -> str:
"""Arm name"... |
11574304 | import time
from qibullet import SimulationManager
from qibullet import NaoVirtual
from qibullet import NaoFsr
if __name__ == "__main__":
simulation_manager = SimulationManager()
client = simulation_manager.launchSimulation(gui=True)
nao = simulation_manager.spawnNao(client, spawn_ground_plane=True)
... |
11574338 | from collections import namedtuple
Root = namedtuple('Root', 'root_node root_parser')
Creds = namedtuple('Creds', 'username password')
root_node = Root('rtr1', 'CiscoBaseParser')
credentials = Creds('user1', '<PASSWORD>1')
ignore_regex = r'(^NA\-|^SEP|^ACVD|^ACWD|^ACPDC|^AP|WAP|WLC|CMP)'
django_app_name = 'net_syste... |
11574363 | import os
from datetime import datetime
import numpy as np
from mapcache import NumpyCache, compute_parallel
from LSSTsims import LSSTsims
from gatspy.periodic import (LombScargleMultiband,
SuperSmootherMultiband,
LombScargleMultibandFast)
class SuperSmoothe... |
11574432 | from distutils.core import setup
setup(name='BEE',
version='0.1',
py_modules=['BEE'],
)
|
11574519 | import csv
import inspect
import logging
import os
from contextlib import redirect_stdout
from os.path import join
import matplotlib as mpl
mpl.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import keras
from qac.evaluation import evaluation
from qac.experiments import preprocessing... |
11574557 | from glob import glob
from os.path import basename
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
setup(
name='test_pkg',
packages=find_packages(where='src'),
package_dir={'': 'src'},
py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],... |
11574579 | import subprocess
import optparse
import re
def mac_changer(iface, mac):
print("[*]changing mac address for " + iface + " to " + mac)
subprocess.call(["ifconfig", iface, "down"])
subprocess.call(["ifconfig", iface, "hw", "ether", mac])
subprocess.call(["ifconfig", iface, "up"])
print("[*]mac address... |
11574585 | import torch
from collections import OrderedDict
from utils import misc
from models.base_models import BaseModel
from models.modules.base_modules import ModuleFactory
class ModelCombine(BaseModel):
def __init__(self, opt):
super(ModelCombine, self).__init__(opt)
self._opt = opt
self.... |
11574589 | import struct
def read(filename):
with open(filename, 'rb') as file:
entries = []
if file.read(4) != b'RMAP':
return
name = file.read(8)
if name != b'resource':
return
catalog_size = struct.unpack('<i', file.read(4))[0]
if catalog_size % 1... |
11574590 | from typing import Any, Callable, List, Union
from tartiflette.coercers.arguments import coerce_arguments
from tartiflette.coercers.outputs.common import complete_value_catching_error
from tartiflette.execution.types import build_resolve_info
from tartiflette.types.helpers.get_directive_instances import (
compute_... |
11574650 | import abc
import re
from decimal import Decimal, InvalidOperation
from django.core import exceptions
from .validator import (
Validator,
ValidatorOutput,
UnsupportedException,
UnsupportedContentTypeException,
)
from ..ingest_settings import UPLOAD_SETTINGS
from .. import utils
class RowwiseValidator... |
11574737 | import iam_floyd as statement
import importlib
import os
import sys
import inspect
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
helperDir = '%s/../../helper/python' % currentdir
sys.path.insert(0, helperDir)
test = importlib.import_module('python_test')
out = getattr(tes... |
11574778 | import unittest
from pandas import DataFrame
import pandas as pd
from .data_explorer import SignNames
from .data_explorer import DataExplorer
from .traffic_data import TrafficDataSets
from .traffic_data import TrafficDataProviderAutoSplitValidationData
from .traffic_data import TrafficDataRealFileProviderAutoSplitValid... |
11574788 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor, ble_client
from esphome.const import (
STATE_CLASS_MEASUREMENT,
UNIT_BECQUEREL_PER_CUBIC_METER,
CONF_ID,
CONF_RADON,
CONF_RADON_LONG_TERM,
ICON_RADIOACTIVE,
)
DEPENDENCIES = ["ble_client"... |
11574865 | import numpy as np
from matplotlib import pyplot as plt
import sys
import os
def run(seq='00',folder="/media/l/yp2/KITTI/odometry/dataset/poses/"):
pose_file=os.path.join(folder,seq+".txt")
poses=np.genfromtxt(pose_file)
poses=poses[:,[3,11]]
inner=2*np.matmul(poses,poses.T)
xx=np.sum(poses**2,1,kee... |
11574885 | import os
import tensorflow as tf
from tensorflow.python.framework import ops
_current_path = os.path.dirname(os.path.realpath(__file__))
_primitive_gen_module = tf.load_op_library(os.path.join(_current_path, 'libprimitive_gen.so'))
# octree ops
octree_database = _primitive_gen_module.octree_database
octree_conv = _p... |
11574896 | import mxnet as mx
import numpy as np
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def init_from_vgg16(ctx, rpn_symbol, vgg16fc_args, vgg16fc_auxs):
fc_args = vgg16fc_args.copy()
fc_auxs = vgg16fc_auxs.copy()
for k, v in fc_args.items():
if v.context != ctx:
... |
11574897 | import pytest
# basic test
def test_basic():
assert True
# test with configration parameters (see conftest.py)
def test_withFixture( unium_endpoint ):
assert isinstance( unium_endpoint, str )
|
11574908 | from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
from activity_grid.models import ActivityCard, ActivityPairCard
from twitterbot.constants import RESPONSE_TYPE_SINGLE_OFFICER, RESPONSE_TYPE_COACCUSED_PAIR
class ActivityGridUpdater():
def process(self, response):
if ... |
11574930 | from . import function_type
from . import string_utilities
from . import utilities
from . import trampoline
from . import error
from . import parser
def evaluate(ast, functions={}):
return _evaluate_entity_list(ast, functions)
def evaluate_code(code, functions={}, target='evaluation'):
result, errors = parser... |
11574940 | from PyQt5.QtCore import QObject, pyqtSignal, qInstallMessageHandler
import argparse
class QtWarningHandler(QObject):
sigGeometryWarning = pyqtSignal(object)
def _resizeWarningHandler(self, msg_type, msg_log_context, msg_string):
if msg_string.find('Unable to set geometry') != -1:
self.sig... |
11574959 | from .options import Options
class Header:
def __init__(self, _type: str, title: str, options: Options = None):
self.type = _type
self.title = title
self.options = options.__dict__ if options is not None else {}
|
11574983 | from staffjoy.resource import Resource
class MobiusTask(Resource):
PATH = "internal/tasking/mobius/{schedule_id}"
ID_NAME = "schedule_id"
ENVELOPE = None
|
11574994 | from functools import partial
from ox.ast import Tree
from ox.ast.utils import intersperse
from ox.target.python.operators import Inplace as InplaceOpEnum
from sidekick import curry, alias
from .expr_ast import (
Expr,
Name,
Void,
ArgDef,
Starred,
Tuple,
to_expr,
Atom,
As,
to_ex... |
11575001 | from . import IBaseDev
from torch.cuda import empty_cache
class IBaseDevTorch(IBaseDev):
"""PyTorch specific base interface for development."""
def train(self, *args, **kwargs):
empty_cache()
return super(IBaseDevTorch, self).train(*args, **kwargs)
def eval(self, *args, **kwargs):
... |
11575004 | from collections import namedtuple
CommandOption = namedtuple('CommandOption', ['option', 'value'])
CommandOptionWithNoValue = namedtuple('CommandOptionWithNoValue', ['option'])
ExecuteCommand = namedtuple('ExecuteCommand', ['bin', 'bin_value'])
def command_option_string_from(command):
if isinstance(command, Com... |
11575018 | import os
import Myloss
import dataloader
from modeling import model
import torch.optim
from modeling.fpn import *
from option import *
from utils import *
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # GPU only
device = get_device()
class Trainer():
def __init__(self):
self.scale_factor = args.... |
11575027 | from typing import Dict, NamedTuple, Iterable
from evaluation.metric import Metric
class EvaluationAverages(NamedTuple):
inputs: float
outputs: float
conversions: float
moves: float
overall: float
class Evaluation:
def __init__(self, scores: Dict[int, "QuestionScores"]) -> None: # type: ig... |
11575036 | from __future__ import print_function
import os
import tempfile
from piecash import open_book, create_book, GnucashException
FILE_1 = os.path.join(tempfile.gettempdir(), "not_there.gnucash")
FILE_2 = os.path.join(tempfile.gettempdir(), "example_file.gnucash")
if os.path.exists(FILE_2):
os.remove(FILE_2)
# open... |
11575071 | from secml.ml.scalers.tests import CScalerTestCases
from sklearn.preprocessing import StandardScaler
from secml.ml.scalers import CScalerStd
class TestCScalerStd(CScalerTestCases):
"""Unittests for CScalerStd."""
def test_forward(self):
"""Test for `.forward()` method."""
# mean should not ... |
11575095 | from . import models
def authenticate(chat):
"""
Authenticating an user means:
1. Getting the chat id.
2. Creating the user if it doesn't exist.
3. Updating the user info. Useful to get the latest username, first name & last name values.
4. Reporting the date and time of the latest user action... |
11575146 | import asyncio
from .constants import *
from .wireformat import *
from .hosts import HostsResolver
from .system import SystemResolver
from .mdns import MulticastResolver
class SmartResolver(object):
def __init__(self):
self.sys = SystemResolver()
self.hosts = HostsResolver()
self.mdns = M... |
11575192 | from collections import OrderedDict
from datetime import timedelta
import django.utils.timezone
import sal.plugin
class NewMachines(sal.plugin.Widget):
description = 'New machines'
def _get_range(self):
today = django.utils.timezone.now() - timedelta(hours=24)
ranges = OrderedDict(Today=to... |
11575217 | from itertools import permutations
# 产生0-6的所有排列组合,写入numbers.txt
with open("numbers.txt", "w") as f:
for i in permutations(range(7), 7):
line = str(i).strip("()")
line = line.split(",")
line = "".join(line)
f.write(line)
f.write("\n")
|
11575323 | from imutils.video import VideoStream
import numpy as np
import cv2
import imutils
import time
from sklearn.metrics import pairwise
from PIL import ImageGrab
from imutils.video import FPS
import copy
font = cv2.FONT_HERSHEY_SIMPLEX
# def all_lines(img, lines, store):
# height, width = img.shape
# try:
# for line... |
11575344 | import envi
import envi.bits as e_bits
import struct
# from disasm import H8ImmOper, H8RegDirOper, H8RegIndirOper, H8AbsAddrOper, H8PcOffsetOper, H8RegMultiOper, H8MemIndirOper
import envi.archs.h8.regs as e_regs
import envi.archs.h8.const as e_const
import envi.archs.h8.operands as h8_operands
bcc = [
('bra... |
11575444 | import pytest
@pytest.fixture(scope="session", autouse=True)
def setupsuite():
print("STARTING TESTS")
yield
print("FINISHED TESTS")
@pytest.fixture
def random_number_generator():
import random
def _number_provider():
return random.choice(range(10))
yield _number_provider
|
11575475 | import numpy
def main():
print('''numpy:
- {}'''.format(numpy.__version__))
if __name__ == "__main__":
main()
|
11575531 | import os
from argparse import Namespace
from copy import copy
from pathlib import Path
from luscious_dl.logger import logger_file_handler, logger
from luscious_dl.parser import is_a_valid_integer
from luscious_dl.start import start
from luscious_dl.utils import cls, create_default_files, open_config_menu, get_config_... |
11575542 | import logging
import json
import datetime
from datetime import timedelta
import decimal
import boto3
from queue import Queue
from queue import Empty
from transfixed import gainfixtrader as gain
import base64
import hmac
import hashlib
import os
import smtplib
import atexit
from email.mime.multipart import MIMEMultipar... |
11575555 | from __future__ import absolute_import, division, print_function
class DBError(Exception):
pass
|
11575572 | description = 'setup for the status HTML monitor'
group = 'special'
_expcolumn = Column(
Block('Experiment', [
BlockRow(
Field(name='Current status', key='exp/action', width=40,
istext=True, maxlen=40),
Field(name='Data file', key='exp/lastpoint'))])... |
11575596 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [0]*(len(s)+1)
dp[0] = 1
dic = set(wordDict)
for j in range(1,len(s)+1):
for i in range(j):
if dp[i] == 1 and s[i:j] in dic:
dp[j] = 1
return dp[-1]
... |
11575599 | def counting_sort(l):
largest = 0
for num in l:
if num < 0:
return []
elif num > largest:
largest = num
tracker = [0 for i in range(largest + 1)]
final = [0 for i in range(len(l))]
for num in l:
tracker[num] += 1
for i in range(len(tracker)):
... |
11575610 | from django.core.management.base import BaseCommand
from waldur_mastermind.marketplace.models import (
Attribute,
AttributeOption,
Category,
Section,
)
def get_category_prefix(category):
if category.sections.exists():
# if at least one section exist, take its sections first prefix as cate... |
11575659 | from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Test module used to create some initial site data for experimentation and manual testing
"""
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright 2014, <NAME>"
__license__ = "MIT (http://opens... |
11575678 | from bisect import bisect_left
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x: [x[0], -x[1]])
def lcs(nums):
cells = []
for idx, val in enumerate(nums):
if not cells or val > cells[-1]:
... |
11575680 | from relay_ftdi import *
import time
import sys
RELEASE_TIME = .5
ON_TIME = 1
OFF_TIME = 6
def initialize_power():
#open_serial()
#reset_device()
pass
def power_on(device):
print "powering on device %d..." % device
close_relay(device)
time.sleep(RELEASE_TIME)
open_relay(device)
time.s... |
11575707 | import sys
import os
from subprocess import check_output
sys.path.insert(
0,
os.path.join(
os.path.dirname(os.path.abspath(__file__)), os.path.join("..", "..")
),
)
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx_click"]
project = "Testplan"
copyright = "2018, <NAME>"
author = ... |
11575711 | from datetime import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
import sys
class ExecutionLoggerManager(object):
"""Logger to log all the ir commands with all the parameters. """
FILE_ARGUMENTS = ['--from-file']
def __init__(self,
ansible_config_p... |
11575718 | import re
import string
def normalize_span(s):
if not s:
return ""
# Lower text and remove punctuation, articles and extra whitespace.
def remove_articles(text):
regex = re.compile(r"\b(a|an|the)\b", re.UNICODE)
return re.sub(regex, " ", text)
def white_space_fix(text):
... |
11575750 | from magichour.api.local.modelgen import preprocess
from magichour.api.local.util.log import get_logger, log_time
logger = get_logger(__name__)
def read_transforms_substep(transforms_file):
# These transforms are tailored to this dataset.
# You will likely need to write your own transforms for your own data.... |
11575808 | from subprocess import run
# test snpeff annotation
command = 'python ../helpers/snpeff.py -i sample.1000.vcf'
#run(command, shell=True)
|
11575820 | import sys
# we need Python 3.4+ for __del__ to work with circular references
assert sys.hexversion >= 0x03040000
from .idldsl import define_winrt_com_method, funcwrap, _new_rtobj
from .winstring import HSTRING
from .types import *
# unknwn
class IUnknown(c_void_p):
IID = '00000000-0000-0000-C000-000000000046'
... |
11575822 | import json
from pathlib import Path
__all__ = ["__version__", "__js__"]
__js__ = json.load(
(Path(__file__).parent.resolve() / "labextension/package.json").read_bytes()
)
__version__ = __js__["version"]
|
11575842 | import argparse
import sys
from custom_image_cli import __version__
# Parses command line arguments and assigns values to global variables
class ArgsParser(argparse.ArgumentParser):
def error(self, msg):
sys.stderr.write('Error: %s \n' % msg)
self.print_help()
sys.exit(2)
def parse_comma... |
11575854 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "ELI"
addresses_name = "2021-03-29T14:54:03.784744/Democracy_Club__06May2021.csv"
stations_name = "2021-03-29T14:54:03.784744/Democracy_Club__06May2021.csv"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.