id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1600494 | import argparse
import os
import pickle
import random
import time
from tqdm import tqdm
from multiprocessing import Pool
import torch
import numpy as np
import matplotlib.pyplot as plt
from util.bioinformatics_algorithms.edit_distance import cross_distance_matrix
from util.data_handling.string_generator import Indepen... |
1600505 | import os
import matplotlib
matplotlib.use("Agg")
from crazydoc import CrazydocParser, CrazydocSketcher, records_to_genbank
example_path = os.path.join("tests", "data", "test_sample.docx")
protein_path = os.path.join("tests", "data", "test_protein_seq.docx")
def test_crazydocparser(tmpdir):
parser = CrazydocPa... |
1600540 | from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.distributions import OneHotCategorical
from torchsupport.training.state import (
NetNameListState, TrainingState
)
from torchsupport.training.multistep_training import MultistepTraining, step_descriptor
from t... |
1600541 | self.description = "Read a package DB with several PGP signatures"
for i in range(1000):
sp = pmpkg("pkg%03d" % i)
sp.desc = "test description for package %d" % i
sp.pgpsig = "asdfasdfsdfasdfsdafasdfsdfasd"
self.addpkg2db("sync", sp)
self.args = "-Ss"
self.addrule("PACMAN_RETCODE=0")
|
1600571 | from savu.plugins.plugin_tools import PluginTools
class ImageLoaderTools(PluginTools):
"""Load tomographic data in image format (tiff)
"""
def define_parameters(self):
"""
data_prefix:
visibility: basic
dtype: [None,str]
description: A file prefix for the... |
1600590 | import math
# Input number of test cases.
t = int(input())
for _ in range(t):
# Input integer value.
n = int(input())
# Iterate until the GCD Sum became greater than 1.
while True:
s = 0
val = n
# Loop to calculate the sum of digits. It removes last digit in one iteration.
... |
1600596 | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, TextAreaField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Regexp, EqualTo
# 登录表单
class loginForm(FlaskForm):
phone = StringField('电话号码', validators=[DataRequired()])
password = PasswordFiel... |
1600612 | import socket
from armada_backend import api_base
from armada_backend.hermes_init import HERMES_DIRECTORY
from armada_backend.utils import get_container_ssh_address
class SshAddress(api_base.ApiCommand):
def on_get(self, req, resp):
container_id, error = self.get_get_parameter(req, 'container_id')
... |
1600628 | import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning.core.lightning import LightningModule
from sklearn.datasets import load_breast_cancer, load_diabetes
from torch.utils.data import Dataset
from pyrelational.data.data_manager import GenericDataManage... |
1600640 | import logging
import pytest
import asyncio
from starkware.starknet.public.abi import get_selector_from_name
from starkware.starknet.testing.starknet import Starknet
from utils import (
Signer, uint, str_to_felt, ZERO_ADDRESS, TRUE, FALSE, assert_revert, assert_event_emitted,
get_contract_def, cached_contract, ... |
1600674 | from Data.execl_data import ExeclData
from core.rest_client import RestClient
class Train(RestClient):
def train_get(self, path_dict):
self.api_root_url = ''
self.url = "https://api.jisuapi.com/train/station2s?start={start}&end={end}&ishight={ishigh}".format(
**path_dict)
respo... |
1600697 | from enum import Enum
class Colors(Enum):
success = 0x71cd40
failure = 0xe74a3c
blurple = 0x738bd7
@staticmethod
def generate_color(red, green, blue):
return int("0x{:02X}{:02X}{:02X}".format(red, green, blue), base=16)
@staticmethod
def get_default(bot):
color = bot.confi... |
1600722 | from benchmarks.htap.lib.controller import HTAPController
def add_parser(subparsers):
parser = subparsers.add_parser('htap')
parser.add_argument(
'--oltp-workers', default=32, type=int, help=(
'The number of OLTP workers executing TPC-C-like transactions (i.e. simulated clients), default: 32.'... |
1600735 | import time
import threading
import queue
import urllib.request, urllib.error
class Receiver(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
url = self._queue.get()
if isinstan... |
1600740 | from pylons.events import NewRequest, NewResponse, subscriber
@subscriber(NewRequest)
def add_reggy(event):
event.request.reg = True
@subscriber(NewResponse)
def add_respy(event):
event.response.reg = True
|
1600770 | from iris_model import __version__
from setuptools import setup
from os import path
# Get the long description from the README file
with open(path.join(path.abspath(path.dirname(__file__)), 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='iris_model',
version=__version__,
... |
1600780 | from ramda.find_last import find_last
from ramda.private.asserts import assert_equal
def positive(x):
return x > 0
def find_last_nocurry_test():
assert_equal(find_last(positive, [-2, -1, 0, 1, 2, -2]), 2)
def find_last_curry_test():
assert_equal(find_last(positive)([-2, -1, 0, 1, 2, -1, -2]), 2)
def... |
1600781 | FW_IV = [0x42,0xea,0xff,0xf7,0x7c,0xc2,0x4f,0x2b,0x9b,0xc9,0x9d,0xe0,0x5c,0xba]
# FwVersion: 1.1.18;p:HillstarV01;DSP:ID9000r2151;i:B;f:22500;nMsg;s:Rel_1r1223:MO;c:JKS;t:2014/05/20 15:37:05;
FW_VERSION = [0x31,0x2e,0x31,0x2e,0x31,0x38,0x3b,0x70,0x3a,0x48,0x69,0x6c,0x6c,0x73,0x74,0x61,
0x72,0x56,0x30,0x31,... |
1600783 | pif_search = 'search/pif_search'
pif_multi_search = 'search/pif/multi_pif_search'
dataset_search = 'search/dataset' |
1600811 | from __future__ import absolute_import
from chainer import backend
from chainer import Variable
import numpy as np
class ReplayBuffer(object):
""" Buffer for handling the experience replay.
Args:
size (int): buffer size
p (float): probability to evoke the past experience
return_variab... |
1600833 | class componentElement:
def details(self):
pass
class LeafElement:
def __init__(self, *args):
# Toma el primer argumento posicional y lo asigna a la variable miembro posición
self.posicion = args[0]
def details(self): # Devuelve la posición del elemento hijo
# print("\t", ... |
1600866 | import logging
log = logging.getLogger(__name__)
try:
import pymongo
from pymongo.errors import ConnectionFailure
except ImportError:
mongo_error = """pysteem does not ship with MongoDB driver by default. Please install it by running:\n
pip install pymongo
"""
log.error(mongo_error)
class Ste... |
1600915 | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
adjacency = collections.defaultdict(list)
for a, b in tickets:
adjacency[a].append(b)
for i in adjacency:
adjacency[i].sort(reverse=True)
res = []
def dfs(cur):
... |
1600918 | import boto3
import moto
from flask import json
from mock import call
from app.models import Notification
from datetime import datetime
from app import db, sms_wrapper
from app.job.sms_jobs import send_sms, fetch_sms_status
from app.connectors.sms.clients import ClientException
@moto.mock_sqs
def test_should_send_sms... |
1600975 | from satella.configuration import sources
from satella.configuration.sources import EnvVarsSource, OptionalSource, AlternativeSource, \
EnvironmentSource, \
StaticSource, MergingSource
from .utils import SourceTestCase, mock_env
class TestEnvVarsSource(SourceTestCase):
@mock_env('satella', '{"a":2}')
... |
1601006 | from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("bikesharing", "0037_auto_20201012_1352"),
]
operations = [
migrations.RemoveField(
model_name="lock",
name="mac_address",
),... |
1601037 | import re
import demistomock as demisto
from CommonServerPython import * # noqa: F401
args = demisto.args()
flags = 0
if argToBoolean(args.get('ignore_case', False)):
flags |= re.IGNORECASE
input_text = args['value']
pattern = re.compile(r'{}'.format(args['regex']), flags=flags)
output_text = pattern.sub(args... |
1601043 | import random
import numpy as np
import math
location=np.loadtxt('city_location.txt')
num_ant=200 #蚂蚁个数
num_city=30 #城市个数
alpha=1 #信息素影响因子
beta=1 #期望影响因子
info=0.1 #信息素的挥发率
Q=1 #常数
count_iter = 0
iter_max = 500
#dis_new=1000
#==========================================
#对称矩阵,两个城市之间的距离
def distance_p... |
1601082 | import siliconcompiler
chip = siliconcompiler.Chip('hello_world')
chip.write_manifest('hello_world.json')
|
1601085 | import tensorflow as tf
import tensorflow_probability as tfp
from tqdm import tqdm
import matplotlib.pyplot as plt
def em(dataset, n_clusters, n_iter=100):
# Infer from the dataset
n_samples, n_dims = dataset.shape
# Draw initial guesses
cluster_probs = tfp.distributions.Dirichlet(tf.ones(n_clusters))... |
1601093 | import argparse
import json
import os
from importlib.resources import read_text
from .CheggScraper import CheggScraper
def main():
"""
User Friendly Downloader for chegg homework help pages
:return: Nothing
:rtype: None
"""
conf = json.loads(read_text('cheggscraper', 'conf.json'))
defau... |
1601155 | class Solution(object):
def flatten(self, head):
stack, cur, root = [], head, head
while stack or cur:
if cur.child:
if cur.next:
stack.append(cur.next)
new = cur.child
new.prev = cur
cur.child = None
... |
1601161 | from redshells.contrib.model.factorization_machine import FactorizationMachineGraph, FactorizationMachine
from redshells.contrib.model.feature_aggregation_similarity_model import FeatureAggregationSimilarityModel
from redshells.contrib.model.graph_convolutional_matrix_completion import GraphConvolutionalMatrixCompletio... |
1601218 | from .errors import UnmarshalError
from .event import Event
from .point import Point
from .detail import Detail
from .geochat import GeoChat
from .teams import Teams
from .takuser import TAKUser
from .takuser import TAKDevice
__all__ = [
"UnmarshalError",
"Event",
"Point",
"Detail",
"GeoChat",
... |
1601245 | import numpy as np
from .Observable import Subject
class ObservableArray(np.ndarray, Subject):
def __init__(self, *args, **kwargs):
Subject.__init__(self)
np.ndarray.__init__(self)
def _notify(self, to_return):
"""
if hasattr(to_return, "_observers") and hasattr(sel... |
1601278 | from collections import namedtuple
from functools import partial
import tensorflow as tf
slim = tf.contrib.slim
_DEFAULT = {
"type": None, # ["conv", "separable"]
"kernel": [3, 3],
"stride": [1, 1],
"depth": None,
"scope": None,
}
_Block = namedtuple("Block", _DEFAULT.keys())
Block = partial(_... |
1601285 | from pyfaidx import Fasta
import sys
import argparse
import random
import math
def parse_args():
parser = argparse.ArgumentParser(
description="Generates molecules")
parser.add_argument("-r",
"--reference",
type=str,
required=True... |
1601314 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.nlschools import nlschools
def test_nlschools():
"""Test module nlschools.py by downloading
nlschools.csv and testing shape of
extracted d... |
1601356 | from .uuids import get_uuid, set_uuid
import logging
logger = logging.getLogger(__name__)
def unproxy(uuid_mapping):
"""This is a convenience for unproxying a lot of objects at once.
"""
for uuid, obj in uuid_mapping.items():
if isinstance(obj, GenericLazyLoader):
uuid_mapping[uuid] = ... |
1601362 | import mxnet as mx
import numpy as np
import os
import cPickle
class Detector(object):
def __init__(self, symbol, ctx=None,
arg_params=None, aux_params=None):
self.symbol = symbol
self.ctx = ctx
if self.ctx is None:
self.ctx = mx.cpu()
self.executor = N... |
1601389 | from struct import pack
from mesh.generic.nodeHeader import headers, createHeader, packHeader
from mesh.generic.cmdDict import CmdDict
from mesh.generic.customExceptions import CommandIdNotFound
class Command(object):
def __init__(self, cmdId, cmdData, header=[], txInterval=[], lastTxTime=0.0):
self.cmdId ... |
1601427 | from kube_hunter.plugins import hookimpl
return_string = "return_string"
@hookimpl
def parser_add_arguments(parser):
return return_string
@hookimpl
def load_plugin(args):
return return_string
|
1601502 | import re
import subprocess
from pathlib import Path
EXEC = re.compile(r', \[.*\]')
IP = re.compile(r'inet_addr\(\".+\"\)')
PORT = re.compile(r'htons\([0-9]+\)')
KNOWN_CONNECT = {
'127.0.0.53:53', # DNS Lookup
'192.168.3.11:443', # PyPI
'172.16.58.3:443', # PyPI
'172.16.17.32:443', # PyPI
'192.168... |
1601521 | import requests, json
from datetime import datetime
from pytz import timezone
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from wagtail.core.signals import page_published, page_unpublished
from graphene import Node
from wagtail.core.mo... |
1601529 | import numpy as np
from ..util.backend_functions import backend as bd
from .diffractive_element import DOE
from ..util.image_handling import convert_graymap_image_to_hsvmap_image, rescale_img_to_custom_coordinates
from PIL import Image
from pathlib import Path
"""
MPL 2.0 License
Copyright (c) 2022, <NAME>
All righ... |
1601531 | import codecs
# 类文件开头的固定代码
def getAutoCode(newLine):
extraStr = \
'''
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SDP AutoR tool .
* It should not be modif... |
1601552 | from abc import ABC, abstractmethod
import jinja2
class Template(ABC):
@abstractmethod
def render(self, session):
pass
@classmethod
def get_template(cls):
origin_cls = cls
while cls is not Template:
if cls.__doc__:
return cls.__doc__
el... |
1601553 | import os
from glob import glob
import h5py
import numpy as np
import pandas as pd
import re
import xarray as xr
from pathlib import Path
from tqdm import tqdm
from brainio_base.stimuli import StimulusSet
from brainio_base.assemblies import NeuronRecordingAssembly
from brainio_collection.packaging import package_st... |
1601563 | import subprocess
from time import sleep
from kubernetes import client
from mlbench_core.cli.chartbuilder import ChartBuilder
def _get_master_pod(release_name, pods):
"""Given a release name and a list of pods, returns the master pod of the release
Args:
release_name (str): Release name
pod... |
1601589 | def ages():
# read lines of data
lines = []
with open('ages_data.csv') as f:
lines = f.read().splitlines()
# get numbers from strings
ages = [int(age) for age in lines]
for age in ages:
yield age
def age_segment(age):
if age < 12: return 0
elif age < 18: return 1
elif age < 28: return 2
eli... |
1601602 | from tests.helper.voctomix_test import VoctomixTest
from lib.videomix import VideoMix
class VideomixerSetSources(VoctomixTest):
def setUp(self):
super().setUp()
self.videomixer = VideoMix()
def test_can_set_source_a(self):
self.videomixer.setVideoSourceA(42)
self.assertEqual(s... |
1601605 | import json
import pytest
from carim_discord_bot.discord_client import discord_service
@pytest.mark.parametrize('fields,expected_messages,expected_fields', [
(['a' * 2000], 1, 2),
(['a' * 1000] * 8, 2, 8)
])
def test_build_fields(fields, expected_messages, expected_fields):
messages = discord_service.bu... |
1601618 | import torch
from .torchpoints import ball_query_partial_dense
import numpy as np
import numba
from typing import List
@numba.jit(nopython=True)
def _grow_proximity_core(neighbours, min_cluster_size):
num_points = int(neighbours.shape[0])
visited = np.zeros((num_points,), dtype=numba.types.bool_)
clusters... |
1601622 | import os
import numpy as np
import scipy.io
import torch
from einops import repeat
from torch.utils.data import DataLoader, Dataset
from .base import Builder
class NSZongyiBuilder(Builder):
name = 'ns_zongyi'
def __init__(self, data_path: str, train_size: int, test_size: int,
ssr: int, n_... |
1601644 | import numpy as np
import progressbar
from terminaltables import AsciiTable
from scratch_ml.utils import bar_widget, batch_iterator
class NeuralNetwork():
"""Neural Networ base model."""
def __init__(self, optimizer, loss, validation_data=None):
self.optimizer = optimizer
self.layers = []
... |
1601685 | from pwn import *
import subprocess
key_re = re.compile(".*\"(.*)\".*")
r = remote("172.16.17.32", 31337)
first = r.recv()
key = key_re.match(first).group(1)
print("Using key: {}".format(key))
subprocess.check_call(["python3", "../../assembler/assembler.py", "{}".format(key), "../asms/decrypt.pstc", "./out.pasticciot... |
1601694 | s=input("Enter array in form [n1,n2,n3,..] : ")
s=s[1:len(s)-1]
a=s.split(",")
n=[]
for i in a:
n.append(int(i))
su=0
for i in range(0,len(n)):
m=0
for j in range(0,len(n)):
if n[i]==n[j]:
m+=1
if m<2:
su=su+n[i]
print(su)
|
1601716 | import time
import os
import torch
import logging as logger
def load_model(model, model_file, depth_input=False, is_restore=False):
t_start = time.time()
if isinstance(model_file, str):
if not os.path.exists(model_file):
logger.warning("Model file:%s does not exist!"%model_file)
... |
1601751 | import csv
import tomlkit
import os
# Set to False to start over on info files.
merge = True
state_by_fips = {}
# Get states for state.txt which has more outlying areas.
f = open("geodata/state.txt", "r")
reader = csv.reader(f, delimiter="|")
for row in reader:
if row[0] == "STATE":
continue
fips, po... |
1601759 | import numpy as np
from tf_rl.env.continuous_gridworld.env import GridWorld
dense_goals = [(13.0, 8.0), (18.0, 11.0), (20.0, 15.0), (22.0, 19.0)]
env = GridWorld(max_episode_len=500, num_rooms=1, action_limit_max=1.0, silent_mode=True,
start_position=(8.0, 8.0), goal_position=(22.0, 22.0), goal_reward=... |
1601765 | import math
import pickle
import xgboost as xgb
from Utils.Base.RecommenderGBM import RecommenderGBM
from Utils.Eval.Metrics import ComputeMetrics as CoMe, CustomEvalXGBoost
class XGBoost(RecommenderGBM):
# ---------------------------------------------------------------------------------------------------
#... |
1601804 | import io
from typing import Dict
import attr
import pytest
from Pegasus.braindump import Braindump, dump, dumps, load, loads
fields = attr.fields_dict(Braindump)
@pytest.mark.parametrize(
"s, obj",
(
("user: a", {"user": "a"}),
('user: "a"', {"user": "a"}),
('{"user": "a"}', {"user... |
1601821 | import copy
import json
from flask_restful import abort
from flask import request, Response
import requests
import logging
__author__ = 'andreap'
CHUNK_SIZE = 1024
ALLOWED_HEADERS = ['Content-Type']
class ProxyHandler():
def __init__(self,
allowed_targets = {},
allowed_domains =... |
1601841 | import pytest
from openapi_tester import SchemaTester
from openapi_tester.exceptions import CaseError, DocumentationError
from openapi_tester.validators import (
validate_enum,
validate_format,
validate_max_items,
validate_max_length,
validate_max_properties,
validate_maximum,
validate_min_... |
1601877 | import mock
import unittest
from .helper import _ResourceMixin
class RefundTest(_ResourceMixin, unittest.TestCase):
def _getTargetClass(self):
from .. import Refund
return Refund
def _getLazyCollectionClass(self):
from .. import LazyCollection
return LazyCollection
def ... |
1601879 | import json
import unittest
from cert_core import BlockcertVersion
from cert_core import Chain
from cert_core.cert_store import helpers
from cert_core.cert_model import model
from cert_core.cert_model.model import ProofType, parse_date
from cert_core.cert_model.model import SignatureType
class TestModel(unittest.Tes... |
1601926 | from helper import *
def doTest():
_withEnter()
_withoutEnter()
def _withoutEnter():
parser = CssParser('@import url(xxxx);@charset utf-8;.test {_width : 100px;}')
parser.doParse()
ok(parser is not None, 'parser is not None')
ok(parser.styleSheet is not None, 'parser.styleSheet is not None')
... |
1601971 | def extractBlueSilverTranslations(item):
"""
# Blue Silver Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Douluo Dalu' in item['tags']:
proc_str = '%s %s' % (item['tags'], item['titl... |
1601995 | from decimal import Decimal
import unittest.mock
import hummingbot.strategy.celo_arb.start as strategy_start
from hummingbot.connector.exchange_base import ExchangeBase
from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap
from test.hummingbot.strategy import assign_config_de... |
1602012 | from collections import namedtuple
import click
from main import run
@click.command()
@click.option('--train', is_flag=True, help="Train phase.")
@click.option('--save_dir', default='.save', help="Directory of saved object files.",
show_default=True)
@click.option('--file', default='', help="Path of s... |
1602055 | import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from theano.tensor.nnet.conv import conv2d
from theano.tensor.signal.downsample import max_pool_2d
from theano.tensor.shared_randomstreams import RandomStreams
import numpy as np
from toolbox import *
from modelbase import *
... |
1602085 | from functools import partial
from .encentry import EncEntry
def EncEntryTemplate(**kwargs):
return partial(EncEntry, **kwargs)
|
1602120 | import unittest
from lizard import analyze_file, FileAnalyzer, get_extensions
from lizard_languages import JavaScriptReader
def get_js_function_list(source_code):
return analyze_file.analyze_source_code("a.js", source_code).function_list
class Test_tokenizing_ES6(unittest.TestCase):
def check_tokens(self, ... |
1602214 | from .base import create_node
from .base import update_node
def insert_child(pipe, parent_id, index, child_id):
pipe.send('insert_child', (child_id, ), dict(
child_id=child_id,
parent_id=parent_id,
index=index,
))
def change_root(pipe, id):
pipe.send('change_root', (id, ), dict(
... |
1602233 | from contracts.models import Contract, Offence, Penalty, Termination
import datetime
def get_contract(contract_id):
contract = Contract.objects.get(pk=contract_id)
return contract
def get_penalty(penalty_id):
penalty = Penalty.objects.get(pk=penalty_id)
return penalty
def get_termination(terminati... |
1602250 | import collections
try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
import base64
import six
import webtest
from daybed import __version__
from daybed.tokens import get_hawk_credentials
class PrefixedRequestClass(webtest.app.TestRequest):
@classmethod
def blank(cls, pat... |
1602256 | import argparse
import importlib
import json
import math
import os
import matplotlib
import numpy as np
import tensorflow as tf
import utils
from config_rnn import defaults
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# -----------------------------------------------------------------------------
parser = ... |
1602304 | from grapl_analyzerlib.grapl_client import GraphClient
from grapl_analyzerlib.prelude import (
BaseView,
)
from graplinc.grapl.api.graph.v1beta1.types_pb2 import MergedNode
def view_from_proto(graph_client: GraphClient, node: MergedNode) -> BaseView:
return BaseView(
node.uid,
node.node_key,
... |
1602321 | from __future__ import absolute_import, division, print_function
# LIBTBX_SET_DISPATCHER_NAME phenix.real_space_diff_map
from scitbx.array_family import flex
import sys
import iotbx.pdb
from libtbx.utils import Sorry
import mmtbx.utils
from cctbx import maptbx
from cctbx import miller
from cctbx import uctbx
from cctb... |
1602349 | import os
from typing import Callable, List, Optional
import aiofiles
from starlette.datastructures import UploadFile
from fastapi_admin.exceptions import FileExtNotAllowed, FileMaxSizeLimit
class FileUpload:
def __init__(
self,
uploads_dir: str,
allow_extensions: Optional[List[str]] = N... |
1602366 | import json
import os
import responses
from django.contrib.auth.models import User, Group
from django.contrib.messages.storage.fallback import FallbackStorage
from django.forms import inlineformset_factory
from django.test import TestCase, Client, RequestFactory
from django.urls import reverse
from products.forms imp... |
1602369 | import logging
import lxml.etree
from packaging.version import parse as version_parser
from virt_backup.domains import get_xml_block_of_disk
from . import definition as definition_compat
logger = logging.getLogger("virt_backup")
def convert(pending_info):
converters = (ToV0_4(), V0_4ToV0_5_2())
for c in c... |
1602385 | import json
import os
from backend.settings import USE_STATIC_DATA, PERSIST_TO_STATIC_FILES
from backend.util.http_client import HttpClient
def fetch_and_persist(url, file_name, default=None):
if USE_STATIC_DATA is True:
if os.path.exists(file_name):
with open(file_name) as f:
... |
1602430 | import logging
import xbmc
import xbmcaddon
ADDON_ID = xbmcaddon.Addon().getAddonInfo("id")
def level_to_kodi(level): # type: (int) -> int
return (level - logging.DEBUG) // 10
class KodiHandler(logging.Handler):
def emit(self, record): # type: (logging.LogRecord) -> None
msg = self.format(record... |
1602464 | from .models import User, Group
from ..sites.models import Site, SiteHost, Domain
from ..sites.helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_nginx_config
from ...utils.tjldap import get_uid, get_full_name
def generate_debug_id(username):
"""Used in development en... |
1602474 | from __future__ import unicode_literals
import datetime
from django import test
from cacheops import invalidation
from django.core.cache import cache
from django.utils import timezone
from django.utils.encoding import force_text
from mock import patch
from tracker import views, models, utils
class TestCase(test.T... |
1602482 | import asyncio
async def connect(ip, semaphore):
async with semaphore:
print(f"Подключаюсь к {ip}")
await asyncio.sleep(1)
print(f"Ответ от {ip}")
async def main():
sem = asyncio.Semaphore(20)
coroutines = [connect(i, sem) for i in range(500)]
await asyncio.gather(*coroutines... |
1602486 | import os
import time
import argparse
import torch
import pickle
import copy
import numpy as np
from tqdm import tqdm
import rdkit
from rdkit.Chem import AllChem
from rdkit import Chem
from confgf import utils, dataset
import multiprocessing
from functools import partial
def generate_conformers(mol, num_confs):
... |
1602514 | import time
def main(args):
if 'sleep' in args:
time.sleep(args['sleep'])
return {'result': args.get('echo', None)}
|
1602519 | import importlib
from shutil import rmtree
from transonic import Transonic, mpi
from transonic.compiler import wait_for_all_extensions
from transonic.config import backend_default
from transonic.mpi import Path
def test_not_transonified():
path_for_test = (
Path(__file__).parent.parent / "_transonic_tes... |
1602555 | import os
from ..utils.terminal import run_command
from .. import ErsiliaBase
class AppBase(ErsiliaBase):
def __init__(self, config_json=None):
ErsiliaBase.__init__(self, config_json=config_json)
self.cards = None
self.APP_SCRIPT = self.cfg.HUB.APP_SCRIPT
def _load_model_cards(self):
... |
1602599 | import atexit
import contextlib
import functools
import glob
import itertools
import os
import sys
from itertools import izip
from math import exp, log
import pomagma.util
function = type(lambda x: x)
def intern_keys(string_dict):
return {intern(str(key)): val for key, val in string_dict.iteritems()}
def DELE... |
1602603 | class Solution:
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
table = collections.defaultdict(list)
for w in strings:
pattern = ""
for i in range(1, len(w)):
if ord(w[i]) - ord(w[i - 1... |
1602606 | def get_website_url(file_id, **kwargs):
return f"https://drive.google.com/drive/folders/{file_id}"
|
1602635 | from os import kill, sep
from os.path import join
from shutil import move
from signal import SIGHUP
from subprocess import check_output
import json
import re
import yaml
from jinja2 import Template
from tempfile import NamedTemporaryFile
from cloudify.utils import setup_logger
logger = setup_logger('cloudify.monito... |
1602637 | import numpy as np
import nibabel as nib
from scipy import ndimage
from utils import *
def segment_airway(params, I, I_affine, Mlung):
#####################################################
# Initialize parameters
#####################################################
Radius = params['airwayRadiusMask']
... |
1602647 | from collections import OrderedDict
import ujson
from django.conf import settings
from utils import solr
from utils.camel_case import render, parser
from .uris import APIUris
from .simpleserializers import SimpleSerializer, SimpleSerializerWithLookups
import logging
# set up logger, for debugging
logger = logging.g... |
1602648 | import torch
from torch.optim import Optimizer
from torch.distributions import Normal
import numpy as np
class SGLD(Optimizer):
def __init__(self, params, lr, norm_sigma=0.0, alpha=0.99, eps=1e-8, centered=False, addnoise=True, p=True):
weight_decay = 1/(norm_sigma ** 2 + eps)
if weight_de... |
1602655 | import tensorflow as tf
import numpy as np
from PIL import Image
from tensorflow.core.framework import graph_pb2
from tensorflow.python.platform import gfile
from tensorflow.python.data.experimental import parallel_interleave
from tensorflow.python.data.experimental import map_and_batch
def read_graph(input_graph):
... |
1602671 | import xml.etree.ElementTree as ET
from ..dictionary import Dictionary
from ..constants import SINGLE_AXIS_MINIMUM_SUBNODES
from .register import CanopenRegister, REG_ACCESS, REG_DTYPE
from ingenialink.utils._utils import *
from .._ingenialink import lib
class CanopenCategories:
"""Contains all categories from a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.