id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3206035 | import unittest
from main import *
class StringsTests(unittest.TestCase):
def test_main(self):
self.assertIsInstance(fccSet, set)
self.assertEqual(len(fccSet), 14)
|
3206104 | class LineOutput:
"""
default output class, output key and value
as (key, value) pair separated by separator
"""
@staticmethod
def collect(key, value, separator = '\t'):
"""
collect the key and value, output them to
a line separated by a separator character
... |
3206111 | import pathlib
from io import BytesIO
from PIL import Image
from html2docx.image import DEFAULT_DPI
TEST_DIR = pathlib.Path(__file__).parent.resolve(strict=True)
PROJECT_DIR = TEST_DIR.parent
def generate_image(width: int, height: int, dpi=(DEFAULT_DPI, DEFAULT_DPI)) -> BytesIO:
data = BytesIO()
with Image... |
3206171 | import numpy as np
import torch as t
from torch.utils.data import DataLoader
import cv2
from os.path import exists
from os import mkdir
from model import student_teacher
import dataset.dataset as dataset
import dataset.mit1003 as mit1003
import dataset.mit300 as mit300
import dataset.DHF1K as dhf1k
from metrics.utils ... |
3206180 | import json
from asyncio import BaseEventLoop
from typing import Optional, List, Type
from asyncpg import create_pool
from asyncpg.connection import Connection
from asyncpg.pool import Pool
from postDB.model.meta import ModelMeta
from postDB.types import Serial
def format_missing(missing):
def fmt_single(name) ... |
3206192 | title = 'methoxy decomposition to H + CH2O'
description = ''
frequencyScaleFactor = 1.0
"""
This example illustrates how to manually set up an Arkane input file for a small P-dep reaction system [using only the
RRHO assumption, and without tunneling, although this can be easily implemented]. Such a calculation is desi... |
3206225 | import os, pdb
d={'m' : ['.mp3','.m4a','.wav','.flac'],
'v' : ['.mp4','.flv','.mkv','.3gp','.mpeg'],
'p' : ['.jpg','.png','.jpeg']
}
p=input('\tPath : \n\t')
print("\n\n\t For Music : Enter 'm' \n\t For Videos : Enter 'v' \n\t For Pictures : Enter 'p' \n\t Or give the file extention with '.' like : '.py','.pdf','.xl... |
3206329 | import unittest
import pytest
from supportal.shifter.management.commands.update_prioritization_meta import (
PRIORITIZATION_DOC_URL_COLUMN_NAME,
STATE_CODE_COLUMN_NAME,
USE_PRIORITIZE_DOC_COLUMN_NAME,
Command,
)
from supportal.shifter.models import State
@pytest.mark.django_db
def test_handle():
... |
3206343 | from __future__ import print_function
import numpy as np
import torch
import torch.utils.data
import torch.nn as nn
from torch.nn import Linear
from utils.nn import GatedDense, NonLinear
from models.AbsModel import AbsModel
class VAE(AbsModel):
def __init__(self, args):
super(VAE, self).__init__(args)
... |
3206344 | import torch
import torch.nn as nn
import torch.nn.functional as F
class SSIM(nn.Module):
"""Layer to compute the SSIM loss between a pair of images
"""
def __init__(self):
super(SSIM, self).__init__()
self.mu_x_pool = nn.AvgPool2d(3, 1)
self.mu_y_pool = nn.AvgPool2d(3, 1)
... |
3206397 | description = 'Vacuum gauges in the neutron guide'
devices = dict(
vac1 = device('nicos.devices.generic.VirtualMotor',
description = 'Vacuum sensor 1 in neutron guide',
abslimits = (0, 1000),
pollinterval = 10,
maxage = 12,
unit = 'mbar',
curvalue = 1.1e-4,
f... |
3206431 | import logging
import os
import re
import pandas as pd
import gamechangerml.src.text_classif.utils.entity_mentions as em
from gamechangerml.src.text_classif.utils.predict_glob import predict_glob
from gamechangerml.src.text_classif.utils.top_k_entities import top_k_entities
logger = logging.getLogger(__name__)
cla... |
3206433 | import urllib
import urllib2
import requests
import threading
import json
from time import sleep
url = 'http://localhost:8545/'
import os.path
def get_result(json_content):
content = json.loads(json_content)
try:
return content["result"]
except Exception as e:
print e
print json_con... |
3206437 | from flask import Flask, jsonify, request
from kryptobot.portfolio.manager import Manager
app = Flask(__name__)
manager = Manager()
# NOTE: This is more an example of how to build a rest server
# rather than a module to import
@app.route('/launch_strategy', methods=['POST'])
def launch_strategy():
params = requ... |
3206446 | import os
import re
import logging
from unidecode import unidecode
from onecodex.exceptions import OneCodexException, UploadException
R1_FILENAME_RE = re.compile(".*[._][Rr]?[1][_.].*")
R2_FILENAME_RE = re.compile(".*[._][Rr]?[2][_.].*")
log = logging.getLogger("onecodex")
def _check_for_ascii_filename(filename, co... |
3206506 | import numpy as np
class CameraIntr():
def __init__(self, u0, v0, fx, fy, sk=0, dtype=np.float32):
camera_xyz = np.array([
[fx, sk, u0],
[0, fy, v0],
[0, 0, 1],
], dtype=dtype).transpose()
pull_back_xyz = np.array([
[1 / fx, 0, -u0 / fx],
... |
3206507 | from typing import Optional
import torch.nn as nn
from torch import Tensor
from deep_table.nn.encoders.embedding.layer.base import BaseEmbeddingLayer
from deep_table.nn.layers.utils import get_activation_module
class ContinuousEmbedding(BaseEmbeddingLayer):
def __init__(
self,
n_features: int,
... |
3206557 | from configuration.utils import get_connection_helper_from_env
from common.utils.s3 import S3Utils
import datetime
from enum import Enum
class CheckpointedJobType(Enum):
CRAWLER_UPLOAD = 'crawler-upload'
MANUAL_UPLOAD = 'manual-upload'
class Config:
TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S"
# TODO: th... |
3206577 | import oauth
import json
import sys
import argparse
def __parse_entity_results(resp):
ents = resp['batch'].get('entityResults') or []
ret = []
for ent in ents:
ent = ent['entity']
copy = {
'key': {
'path': ent['key']['path']
},
'properties... |
3206662 | from typing import Optional
import time as time_stdlib
import structlog
import contextlib
_logger = structlog.get_logger()
@contextlib.contextmanager
def time(description: Optional[str] = None, **logging_args):
start = time_stdlib.time()
yield
elapsed = time_stdlib.time() - start
_logger.info(f"Elap... |
3206664 | from ewah.operators.base import EWAHBaseOperator
from ewah.constants import EWAHConstants as EC
from ewah.hooks.sharepoint import EWAHSharepointHook
class EWAHSharepointOperator(EWAHBaseOperator):
_NAMES = ["sharepoint"]
_ACCEPTED_EXTRACT_STRATEGIES = {
EC.ES_FULL_REFRESH: True,
EC.ES_INCREM... |
3206696 | from mutagenmonlib.local.run import *
from mutagenmonlib.local.file import *
global_session_config = {}
def session_config():
return global_session_config
def mutagen_sync_list():
st = run(
[cfg('MUTAGEN_PATH'), 'sync', 'list'],
shell=True,
interactive_error=False)
st = st.repla... |
3206709 | from sys import path
from os.path import dirname as dir
path.append(dir(path[0]))
from optimization.genOptimized import optimizeCode
# print(result[0].execute(None))
# print(result[1].execute(None))
# print(grammar.returnPostgreSQLErrors())
s = '''
from goto import with_goto
from interpreter import execution
from c3... |
3206742 | import time
from unittest.mock import Mock, patch
from flask.testing import FlaskClient
from lms.lmsweb.config import CONFIRMATION_TIME
from lms.lmsdb.models import Course, User
from lms.models.users import generate_user_token
from tests import conftest
class TestRegistration:
@staticmethod
def test_invalid... |
3206800 | from unittest import TestCase
import numpy as np
import nucleoatac.NucleosomeCalling as Nuc
import pyatac.VMat as V
from pyatac.chunkmat2d import BiasMat2D
from pyatac.chunk import ChunkList
from pyatac.bias import InsertionBiasTrack
class Test_variance(TestCase):
"""class for testing variance calculation on back... |
3206848 | import os
from textwrap import dedent
from nipype import Workflow, Node, Function
from traits.api import TraitError
import pytest
from .. import frontend
class TestFrontend(object):
@pytest.fixture
def lyman_dir(self, execdir):
lyman_dir = execdir.mkdir("lyman")
os.environ["LYMAN_DIR"] = str... |
3206855 | from .user_factory import UserFactory
from .user_profile_factory import (
UserProfileFactory,
fake_app_reviewer,
profile_for_org_and_group_names,
profile_for_slug_in_groups,
app_reviewer,
followup_user,
monitor_user
)
from .organization_factory import (
ExistingOrganizationFactory, F... |
3206871 | from numpy.testing import assert_equal
import numpy as np
import skvideo.io
import skvideo.datasets
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
def _vreader(backend):
reader = skvideo.io.vreader(skvideo.datasets.bigbuckbunny(), backend=backend)
T = 0
... |
3206889 | from django.contrib import admin
from .models import Item, WishList
admin.site.register(Item)
admin.site.register(WishList)
|
3206985 | import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'... |
3207010 | from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
... |
3207026 | import spacy
# Carga el modelo es_core_news_md
nlp = spacy.load("es_core_news_md")
# Procesa un texto
doc = nlp("Hoy hice pan de banano")
# Obtén el vector para el token "banano"
banano_vector = doc[4].vector
print(banano_vector)
|
3207031 | print('<NAME>') # Name
print('123 Full Circle Drive') # Street address
print('Asheville, NC 28899') # City, state, and ZIP
|
3207062 | import argparse
import glob
from os.path import join
from loguru import logger
from tokenizers import CharBPETokenizer
"""
The original BPE tokenizer, as proposed in Sennrich, Haddow and Birch, Neural Machine Translation
of Rare Words with Subword Units. ACL 2016
https://arxiv.org/abs/1508.07909
https://github.com/rse... |
3207067 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# coding=utf-8
import stylize
import os
import base64
import json
import re
import time
import glob
import shutil
from io import BytesIO
from PIL import Image
# Flask utils
from flask import Flask, redirect,... |
3207085 | import torch
import torch.nn as nn
import tridepth_renderer.cuda.rasterize as rasterize_cuda
from . import vertices_to_faces, rasterize_image
def flip(x, dim):
"""
Flip tensor in specified dimension.
"""
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
... |
3207118 | from tamtam import Bot, Dispatcher, run_poller
from tamtam.types import Message, BotStarted
from tamtam.dispatcher.filters import MessageFilters
bot = Bot("put token")
dp = Dispatcher(bot)
@dp.bot_started()
async def new_user(upd: BotStarted):
await upd.respond(f"Hello! {upd.user.name}.\nNice to see you!")
@d... |
3207138 | from typing import List, Dict, cast
import numpy as np
from ...math.matrix import Matrix
from ...common.config import Config
from ...collision.algorithm.gjk import PointPair
from ...collision.detector import Collsion
from ..body import Body
# FIXME:
def generate_relation(bodya: Body, bodyb: Body) -> int:
# Comb... |
3207181 | import vel.util.intepolate as interpolate
from vel.api.base import Schedule
class LinearSchedule(Schedule):
""" Interpolate variable linearly between start value and final value """
def __init__(self, initial_value, final_value):
self.initial_value = initial_value
self.final_value = final_va... |
3207194 | class ReadConcern(object):
def __init__(self, level=None):
self._document = {}
if level is not None:
self._document['level'] = level
@property
def level(self):
return self._document.get('level')
@property
def ok_for_legacy(self):
return True
@prope... |
3207196 | import graphene
from graphene_django.types import DjangoObjectType
from rx import Observable
from graphene_subscriptions.events import CREATED, UPDATED, DELETED
from tests.models import SomeModel
CUSTOM_EVENT = "custom_event"
class SomeModelType(DjangoObjectType):
class Meta:
model = SomeModel
class... |
3207200 | def expand(maze, fill):
n = len(maze)
beg = n / 2
end = n + beg
fill_row = [fill for _ in xrange(n * 2)]
cap = fill_row[:beg]
maze_iter = iter(maze)
return [cap + next(maze_iter) + cap if beg <= a < end else fill_row
for a in xrange(n * 2)]
|
3207205 | from django.core.exceptions import (
MultipleObjectsReturned,
ObjectDoesNotExist,
ValidationError,
)
def get_model_by_id_or_name(model, value, name_attr="name"):
if isinstance(value, model):
return value
try:
try:
value = value.lstrip("#").strip()
except Attribu... |
3207247 | try:
use_agg = False
import matplotlib
if use_agg:
matplotlib.use("Agg", warn=False)
except Exception:
print("Failed to import matplotlib")
__version__ = "0.1.2.2"
|
3207256 | import random
import pytest
from relevanceai import Client
from relevanceai.dataset import Dataset
from relevanceai.utils.datasets import (
get_iris_dataset,
get_online_ecommerce_dataset,
get_palmer_penguins_dataset,
)
from relevanceai.utils.decorators.vectors import catch_errors
from tests.globals.cons... |
3207260 | from .preprocessor import FortranPreprocessor
import re
from .smartopen import smart_open
UNIT_REGEX = re.compile(r"^\s*(?P<unit_type>module(?!\s+procedure)|program)\s*(?P<modname>\w*)",
re.IGNORECASE)
END_REGEX = re.compile(r"^\s*end\s*(?P<unit_type>module|program)\s*(?P<modname>\w*)?",
... |
3207261 | import os.path
from kafka import KafkaProducer
from kafka.errors import KafkaError
def loadToKafka(json_list, topic, server_list):
producer = KafkaProducer(bootstrap_servers=server_list)
for json in json_list:
producer.send(topic, json)
producer.flush()
return
def loadToFile(json_list, fi... |
3207276 | import copy
import json
import logging
import unittest
from datetime import datetime
from datetime import timedelta
from queue import Queue
from unittest import mock
import pika
import pika.exceptions
from freezegun import freeze_time
from parameterized import parameterized
from src.data_store.redis import RedisApi
f... |
3207296 | import os
import sys
import time
from argparse import ArgumentParser
import math
import numpy as np
import time
import torch
from torch.optim.lr_scheduler import MultiStepLR
import torch.utils.data.distributed
from src.model import model, Loss
from src.utils import dboxes300_coco, Encoder
from src.evaluate import ev... |
3207306 | from face_lib import my_api, inference
import csv
import multiprocessing
import tensorflow as tf
class LFW_TEST:
def __init__(self,sia,se):
self.sia = sia
self.se = se
def csv_write(self,path, data):
out_test = open(path, 'w', newline='')
csv_test_writer = csv.writer(out_test,... |
3207319 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import (Transform, TransformedDistribution,
AffineTransform, Distribution)
from torch.distributions import constraints
from torch.distributions.normal import Normal
from torch.distributions.multiv... |
3207329 | import matplotlib.pyplot as plt
import os
def get_all_metrics(history):
metrics = set()
for metric in history.history:
if 'val_' in metric:
metric = metric.replace(metric, 'val_')
metrics.add(metric)
return metrics
def plot_history(history, result_dir, prefix):
"""
Pl... |
3207340 | from apiwrapper.endpoints.endpoint import Endpoint
class TabAttachment(Endpoint):
__endpoint_tab = "tab"
__endpoint_tab_attachment = "attachment"
__endpoint_tab_attachment_content = "content"
@classmethod
def _get_base_endpoint(cls, tab_id, attachment_id):
return "/%s/%s/%s/%d" % (
... |
3207362 | from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from mptt.forms import MPTTAdminForm
from parler.admin import TranslatableAdmin
from parler.forms import TranslatableModelForm
from .models import Category
class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm):
"""
Form for catego... |
3207392 | from typing import Dict, Any
import dill
import msgpack
def save_module(file_name: str, **config):
"""
Serializes the module with the specified file name into MessagePack format.
:param file_name: The name of the file (without the extension).
:param config: Properties of the module to be serialized.
... |
3207475 | from typing import List, Optional, Union
import numpy as np
import pandas as pd
import pytest
import scipy.sparse as sps
import tabmat as tm
from tabmat import from_pandas
from tabmat.constructor import _split_sparse_and_dense_parts
from tabmat.dense_matrix import DenseMatrix
from tabmat.ext.sparse import csr_dense_s... |
3207561 | import maya.cmds as cmds
import maya.utils as utils
import maya.mel as mel
def createBaseRenderSettings(job='', seq='', shot=''):
vrayLoaded = False
#let's load VRay
try:
# load up vray plugin
cmds.loadPlugin('vrayformaya', quiet=True)
# Autoload vray
cmds.pluginInfo('v... |
3207578 | import socket
import threading
import SocketServer
import time
import sys
reqs = []
num = int(sys.argv[1])
finished = 0
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
self.data = self.rfile.readline().strip()
cur_thread = threading.current_thread()
c... |
3207585 | from scripts.build import _has_extension
import pytest
@pytest.mark.parametrize(
"file_name, extension, expected",
[
("palette.gpl", ".gpl", True),
("palette.json", ".json", True),
("palette.txt", ".txt", True),
("palette.gpl", ".txt", False),
("palette.gpl", ".json", ... |
3207587 | import random
import pytest
import trio
from ddht.resource_queue import ResourceQueue
async def _yield(num: int = 10, base: int = 0):
for _ in range(random.randint(0, num) + base):
await trio.lowlevel.checkpoint()
@pytest.mark.trio
async def test_resource_queue_fuzzy():
known_resources = {"a", "b"... |
3207591 | import pytest
import hyperopt.pyll.base
from matchzoo.engine import hyper_spaces
@pytest.fixture(scope='module', params=[
lambda x: x + 2,
lambda x: x - 2,
lambda x: x * 2,
lambda x: x / 2,
lambda x: x // 2,
lambda x: x ** 2,
lambda x: 2 + x,
lambda x: 2 - x,
lambda x: 2 * x,
... |
3207595 | from .imdb import IMDB
from .mpii import mpii
from .hm36 import hm36
from .hm36_eccv_challenge import hm36_eccv_challenge |
3207601 | class Student:
def __init__(self, std):
self.count = std
def go(self):
for i in range(self.count):
print(i)
return
if __name__ == '__main__':
Student(5).go()
|
3207603 | import json, random, copy
'''
NOTE: You must run this script from within the amt directory. If you are importing and
calling generate_usernames as a function, make sure to run os.chdir(<path to amt directory>)
Adjectives Source:
https://github.com/dariusk/corpora/raw/master/data/humans/descriptions.json
https://raw.g... |
3207605 | import subprocess
import time
from socket import socket as Socket
from typing import List
import pytest
def run_devnet(devnet: List[str], port: int) -> subprocess.Popen:
command = devnet + [
"--host",
"localhost",
"--port",
str(port),
]
# pylint: disable=consider-using-wit... |
3207606 | from rouge import Rouge
def rouge(sys, ref):
rouge = Rouge()
return rouge.get_scores(sys, ref, avg=True)
|
3207610 | import http.client
import logging
from telegram import Update, ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Chat
from telegram.ext import TypeHandler, CallbackContext, CommandHandler, MessageHandler, Filters
from bot import settings
from bot.const import TELEGRAM_BOT_TOKEN, DATABASE_FILE, DEBUG
from bot.git... |
3207612 | from pyspark import SparkContext, SparkConf
import re
class Utils():
COMMA_DELIMITER = re.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''')
if __name__ == "__main__":
conf = SparkConf().setAppName('StackOverFlowSurvey').setMaster("local[*]")
sc = SparkContext(conf = conf)
# Initialize accumulators
# Ac... |
3207626 | import cv2
import pyrealsense2 as rs
import numpy as np
import threading, time, logging
'''
-----------------------------------
@ Auther : LiaoSteve
@ Adapted from <NAME>.
-----------------------------------'''
class RealSense():
def __init__(self):
# Realsense Logger
self.__realsense... |
3207636 | import os
import numpy as np
from time import time
import joblib
import theano
import theano.tensor as T
from foxhound.theano_utils import sharedX, floatX, intX
from foxhound.rng import np_rng
class W2VEmbedding(object):
def __init__(self, data_dir):
self.data_dir = data_dir
def __call__(self, vocab... |
3207638 | import sqlite3
import urllib
FILENAME = "/tmp/toc.db"
stream = urllib.urlopen("https://sqlite.org/toc.db")
with open(FILENAME, "wb") as f:
f.write(stream.read())
con = sqlite3.connect("/tmp/toc.db")
cur = con.cursor()
cur.execute("select name from toc where type='constant' and name not in ('SQLITE_SOURCE_ID', '... |
3207692 | import yaml
from markdown import markdown
from jinja2 import Environment, FileSystemLoader
# from time import sleep
# import os
def renderIndex():
# Loading the template
templateLoader = FileSystemLoader(searchpath="./templates/")
templateEnv = Environment(loader=templateLoader)
template = templateEnv... |
3207712 | from pony.orm import Required, Database, Set, Optional, Json
from flask_login import UserMixin
from datetime import datetime
from enum import Enum
from pony.orm.dbapiprovider import StrConverter
from dinamit.core.constants import DomainCategory, DomainAction
from flask import request, url_for
db = Database()
class E... |
3207717 | import numpy as np
import tqdm
import geohash
import hnswlib
import random
import sys
from collections import defaultdict
base_alphabet = '0123456789abcdefghijklmnopqrstuv'
geo_alphabet = '0123456789bcdefghjkmnpqrstuvwxyz'
trantab = str.maketrans(geo_alphabet, base_alphabet)
def cosine_similarity(vector, matrix):
... |
3207744 | import gamma
import os
#
# create a main scene
#
mainScene = gamma.Scene()
#
# add some resources
#
gamma.resourceManager.addImage('heart', os.path.join('images', 'heart.png'))
gamma.resourceManager.addImage('player', os.path.join('images', 'player', 'vita_00.png'))
#
# create a heart entity that moves automativca... |
3207775 | for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
newsquares = [value**2 for value in range(1,11)]
print(newsquares) |
3207846 | from sys import modules
from copy import deepcopy
import numpy as np
import tensorflow as tf
from gpflow import actions, settings
from gpflow.training.tensorflow_optimizer import _TensorFlowOptimizer, _REGISTERED_TENSORFLOW_OPTIMIZERS
### Imports optimizers from TF contrib, uses same code as in GPflow
def _register... |
3207855 | from hurricane.metrics.registry import MetricsRegistry
from hurricane.metrics.requests import (
HealthMetric,
ReadinessMetric,
RequestCounterMetric,
RequestQueueLengthMetric,
ResponseTimeAverageMetric,
StartupTimeMetric,
)
registry = MetricsRegistry()
registry.register(RequestCounterMetric)
re... |
3207887 | import unittest
from pkg_resources import resource_filename
import numpy as np
try:
import fitsio
missing_fitsio = False
except ImportError:
missing_fitsio = True
from desisim import lya_spectra
class TestLya(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.infile = resource... |
3207894 | import pytest
def test_add_quicktest_session(test_platform):
if test_platform.Platform == 'linux':
test_platform.Authenticate('admin','admin')
test_platform.info('Creating a linux api server quicktest session')
session = test_platform.Sessions.add(ApplicationType='quicktest')
assert(session.ApplicationType =... |
3207909 | class Solution:
def partition(self, s):
res = []
if not s:
return res
self.dfs(0, s, [], res)
return res
def dfs(self, k, s, p, res):
l = len(s)
if k == l:
res.append([e for e in p])
return
for i in range(k, l):
... |
3207945 | import cv2
import albumentations as A
from typing import Any
from typing import Tuple
from typing import Union
from typing import Optional
from albumentations.pytorch import ToTensorV2
from .general import ToRGB
from .general import ToGray
from .general import BatchWrapper
from .....data import Transforms
from ........ |
3207947 | from __future__ import print_function
import os
import configparser
import numpy as np
import tensorflow as tf
from keras import backend as K
import random as rn
from time import strftime
import TCGDB
import train
config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), 'config', 'config.ini'))
os... |
3207953 | from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f: readme = f.read()
setup(
name='skrobot',
version='1.0.13',
license='MIT',
author="<NAME>",
author_email="<EMAIL>",
... |
3207955 | import os
import time
from mindspore.common import set_seed
from src.dataset import data_to_mindrecord_byte_image
from src.model_utils.config import config
set_seed(1)
rank = 0
device_num = 1
def generate_coco_mindrecord():
""" train_fasterrcnn_ """
# It will generate mindrecord file in config.mindrecord_... |
3207956 | import cv2
import glob
import keras
import numpy as np
import pandas as pd
from keras import backend as K
from keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Input, AlphaDropout, Dropout
from keras.models import Model
from settings import IMAGE_SIZE
df = pd.read_pickle('../data/all_obs.pkl', compression='g... |
3207960 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum... |
3207963 | from .object import Object
from typing import Dict, Any
class Project(Object):
def __init__(self, path: str) -> None:
super().__init__()
self._path = path
@property
def path(self):
return self._path
def dump(self) -> Dict[str, Any]:
return {"path": self._path}
d... |
3207970 | import discord
from discord.ext import commands
from utils import MyContext
async def can_mute(ctx: MyContext) -> bool:
"""Check if someone can mute"""
if ctx.bot.database_online:
return await ctx.bot.get_cog("Servers").staff_finder(ctx.author, "mute")
else:
return ctx.channel.permissions_... |
3207979 | from flask import Blueprint
from flask_restful import Api
account_blueprint = Blueprint('account', __name__, url_prefix='/account')
account_api = Api(account_blueprint)
info_blueprint = Blueprint('info', __name__, url_prefix='/info')
info_api = Api(info_blueprint)
from .auth import Auth, Refresh
account_api.add_res... |
3208006 | import numpy as np
class Distance_metrics:
"""
Calculate distance between each corresponding points
of two arrays using different distance metrics
"""
def Eucledian_Distance(X1,X2):
""""
Returns the list of eucledian distance
between two corresponding points of
two ... |
3208078 | class Paginator(object):
"""
Paginate through all entries:
>>> paginator = Paginator(api, 'trends.listThreads', forum='disqus')
>>> for result in paginator:
>>> print result
Paginate only up to a number of entries:
>>> for result in paginator(limit=500):
>>> print result
"... |
3208116 | from django.core.management.base import BaseCommand
from cantusdata.models.folio import Folio
from cantusdata.models.manuscript import Manuscript
from django.core.management import call_command
from optparse import make_option
import csv
class Command(BaseCommand):
"""
Import a folio mapping (CSV file)
Sa... |
3208166 | from django.shortcuts import render
from account.models import Account
from datetime import datetime
def home(request):
# Editing Earl of the Day ID should update all data on home page
earl_of_the_day_id = 2
month = datetime.today().month
upcoming_birthdays = Account.objects.filter(birthday__month=mon... |
3208232 | from unittest import TestCase
from unittest.mock import patch, ANY
import responses
import azkaban_cli.azkaban
from azkaban_cli.exceptions import FetchFlowExecutionUpdatesError, SessionError
class AzkabanFetchFlowExecutionTest(TestCase):
def setUp(self):
"""
Creates an Azkaban instance and set a... |
3208258 | class Solution:
"""
@param nums: an array
@return: the Next Greater Number for every element
"""
def nextGreaterElements(self, nums):
# Write your code here
St = []
n = len(nums)
result = [-1] * n
for i in range(2 * n - 1):
while St and nums[St[-1]... |
3208263 | from requests import Session
if __name__ == '__main__':
s = Session()
s.trust_env = False
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.post('http://1... |
3208286 | import pexpect
class Spike:
PROMPT = r': $'
CODE_BASE_ADDRESS = 0xffffffff80000000
def __init__(self, cmd_line):
self.cmd_line = cmd_line
def __enter__(self):
self.proc = pexpect.spawnu(self.cmd_line)
self.proc.expect(Spike.PROMPT)
self.proc.setecho(False)
sel... |
3208318 | import os
import argparse
import numpy as np
import math as ma
import music21 as m21
THREE_DOTTED_BREVE = 15
THREE_DOTTED_32ND = 0.21875
MIN_VELOCITY = 0
MAX_VELOCITY = 128
MIN_TEMPO = 24
MAX_TEMPO = 160
MAX_PITCH = 128
def load(datapath, sample_freq=4, piano_range=(33, 93), transpose_range=10, stretching_ra... |
3208347 | def get_word_states(word):
"""
Args:
word: string
Returns:
word_states: list, ['B', 'E']
"""
word_states = []
if len(word) == 1:
word_states.append('S')
else:
for idx, c in enumerate(word):
if idx == 0:
word_states.append('B')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.