id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3289971 | import sys
sys.path.insert(0, '/home/ihab/ihabgit/zevision')
import lib.util as train
train.train_face_model("data/raw")
|
3289973 | import warnings
from typing import List, Union
import pandas as pd
from sklearn.model_selection import cross_validate
from feature_engine.dataframe_checks import _is_dataframe
from feature_engine.selection.base_selector import BaseSelector
from feature_engine.validation import _return_tags
from feature_engine.variabl... |
3290037 | import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser('NAS benchmark downloader')
parser.add_argument('benchmark_name', choices=['nasbench101', 'nasbench201', 'nds'])
args = parser.parse_args()
from .utils import download_benchmark
download_benchmark(args.benchmark_name)
|
3290092 | import os
import collections
import json
import attr
import copy
import numpy as np
import torch
import torch.utils.data
from text2qdmr.model.modules import abstract_preproc
from text2qdmr.utils import registry
from text2qdmr.utils.serialization import ComplexEncoder, ComplexDecoder
from text2qdmr.datasets.qdmr imp... |
3290098 | from transformers import GPT2LMHeadModel, GPTNeoForCausalLM, GPTJForCausalLM
from mkultra.soft_prompt import SoftPrompt
import torch
import torch.nn as nn
class GPTPromptTuningMixin:
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
model = super().from_pretrained(pretrain... |
3290101 | import logging
import math
import os
from typing import Optional
import numpy as np
from remat.core.dfgraph import DFGraph
from remat.core.enum_strategy import SolveStrategy, ImposedSchedule
from remat.core.schedule import ILPAuxData, ScheduledResult
from remat.core.solvers.strategy_optimal_ilp import ILPSolver
from ... |
3290106 | pkgname = "python-snowballstemmer"
pkgver = "2.2.0"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
depends = ["python"]
pkgdesc = "Snowball stemming library collection for Python"
maintainer = "q66 <<EMAIL>>"
license = "BSD-3-Clause"
url = "https://github.com/shibukawa/snowball_py"
sou... |
3290112 | import pytest
async def test_fixture_test_server_get_properties(sanic_server):
assert sanic_server.is_running is True
assert sanic_server.has_started() is True
assert sanic_server.port is not None
url = sanic_server.make_url('/test')
assert url == 'http://127.0.0.1:{port}/test'.format(port=str(san... |
3290140 | class DataObject:
'''
This class represents the scraped data as a python object.
'''
def __init__(self, content, title, source, date):
'''
__init__ initializes the data object.
@param content will be the content of the scraped data.
@param title will be the title of the ... |
3290146 | import digitalio
import board
done = digitalio.DigitalInOut(board.A4)
done.direction = digitalio.Direction.OUTPUT
done.value = False
#pylint: disable=wrong-import-position,wrong-import-order
import time
import pwmio
import busio
from adafruit_epd.epd import Adafruit_EPD
from adafruit_epd.il0373 import Adafruit_IL0373... |
3290171 | from __future__ import division
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('Agg')
def generator_conditional(z, conditioning): # Convolution Generator
with tf.variable_scope("generator", reuse=tf.AUTO_REUSE):
z_combine = tf.concat([z, conditioning], -1)
conv1_g = tf... |
3290176 | from __future__ import unicode_literals
import django
if django.VERSION[:2] < (1, 6): # unittest-style discovery isn't available
from .test_get_setting import SettingsTestCase
from .test_http_server import HttpServerTestCase
from .test_regression import RegressionTestCase
from .test_storage import... |
3290188 | import boto3
import json
from storage.memcached import memcached_operator
def handler(event, context):
function_name = "lambda_core"
# dataset setting
dataset_name = 'higgs'
data_bucket = "higgs-10"
dataset_type = "dense_libsvm"
n_features = 30
host = "127.0.0.1"
por... |
3290197 | import torch
from torch.autograd import Variable
import torchvision
from torchvision import transforms as T
from PIL import Image
import numpy as np
class Img_loader(object):
def __init__(self, path, bsz, is_cuda=True, img_size=224, evaluation=False):
self.bsz = bsz
self.data = [line.strip().spl... |
3290211 | from utils import CanadianJurisdiction
class Calgary(CanadianJurisdiction):
classification = 'legislature'
division_id = 'ocd-division/country:ca/csd:4806016'
division_name = 'Calgary'
name = '<NAME>'
url = 'https://www.calgary.ca'
|
3290218 | from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, PatternFill, colors
from openpyxl.utils.dataframe import dataframe_to_rows
def create_workbook_from_dataframe(df):
"""
1. Create workbook from specified pandas.DataFrame
2. Adjust columns width to ... |
3290230 | import os
import numpy as np
run_id = 3
root_dir = '/is/cluster/work/pghosh/gif1.0'
checkpoint_dir = os.path.join(root_dir, 'checkpoint', str(run_id))
smpl_dir = os.path.join(root_dir, 'sample', str(run_id))
smpl_files = os.listdir(smpl_dir)
fids = []
smpl_png_files = []
for smpl_file in smpl_files:
if smpl_file.... |
3290277 | from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure
output_file("stacked_split.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
exports = {'fruit... |
3290285 | import pytest
import scipy.io.wavfile
from spafe.utils import vis
from spafe.features.rplp import rplp, plp
from spafe.utils.spectral import stft, display_stft
@pytest.fixture
def sig():
__EXAMPLE_FILE = 'test.wav'
return scipy.io.wavfile.read(__EXAMPLE_FILE)[1]
@pytest.fixture
def fs():
__EXAMPLE_FILE ... |
3290292 | from __future__ import absolute_import, division, print_function, unicode_literals
from AdaptivePELE.simulation import simulationrunner
import AdaptivePELE.adaptiveSampling as adaptiveSampling
import argparse
import os
def automateSimulation(args):
"""
Run multiple AdaptivePELE simulation with the same pa... |
3290296 | from datetime import datetime, timezone
import json
def test_get_match_by_slug(client, collection):
collection.insert_one(
{
"sport": "basketball",
"tournament": "test-league",
"tournament_nice": "Test League",
"teams": [
"Test FC",
... |
3290299 | import boto3
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
from .config import PlannerConfig
class EsConnector:
"""
ES request sign.
https://github.com/aws-samples/amazon-textract-comprehend-OCRimage-search-and-analyze/blob/master/lambda/comprehend... |
3290328 | import asyncio
import logging
import re
import sys
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from functools import partial
from os import environ
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, Optional, Union
import aiohttp
from aiohttp_socks import ProxyConnector
f... |
3290382 | import argparse
import os
import subprocess # nosec
import unittest
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.test.runner import DiscoverRunner
class RenderPagesRunner(DiscoverRunner):
"""Test ru... |
3290402 | import os
from geomeppy.io.obj import export_to_obj
EXAMPLES_DIR = "C:/EnergyPlusV9-1-0/ExampleFiles"
def test_export_to_obj(base_idf):
export_to_obj(base_idf, "test.obj")
assert os.path.isfile("test.obj")
assert os.path.isfile("test.mtl")
os.remove("test.obj")
os.remove("test.mtl")
|
3290414 | import datetime
from randluck.strategies.bazi import get_bazi_num_from_utc_datetime
from randluck.strategies.lucky_num import get_lucky_num_from_birth_year
def get_random_seed(utc_datetime=datetime.datetime.utcnow(), strategy="bazi"):
random_seed = None
if strategy == "bazi":
random_seed = g... |
3290444 | from __future__ import absolute_import
# pylint: disable=wildcard-import
from reinforceflow.agents.deepq import DeepQ
from reinforceflow.agents.actorcritic import ActorCritic
# pylint: enable=wildcard-import
|
3290446 | from torchcv.models.retinanet.fpn import FPN50
from torchcv.models.retinanet.net import RetinaNet
from torchcv.models.retinanet.box_coder import RetinaBoxCoder
|
3290463 | from typing import Sequence
from libcst import Arg, Call, Integer
from django_codemod.constants import DJANGO_3_1, DJANGO_4_0
from django_codemod.utils.calls import find_keyword_arg
from django_codemod.visitors.base import BaseFuncRenameTransformer
class GetRandomStringTransformer(BaseFuncRenameTransformer):
""... |
3290466 | import logging
import socket
import threading
log = logging.getLogger(__name__)
class ELM327Proxy(threading.Thread):
TERMINATOR = b"\r"
PROMPT = b"\r>"
def __init__(self):
super(ELM327Proxy, self).__init__()
self.name = "elm327_proxy_{:}".format(id(self))
#self.daemon = True
... |
3290472 | import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import seaborn as sns
import matplotlib.pyplot as plt
from utils import *
from torch.nn.utils.rnn import pad_sequence
from sklearn.preprocessing import QuantileTransformer
import os
import torch.nn.functional as F
from utils import *
def get_free_gpu():
os.sy... |
3290519 | from unittest import skip
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate
from api.tests.factories import UserFactory, AnonymousUserFactory
from api.v2.views import ReportingViewSet
class ReportingTests(APITestCase):
def setUp(self)... |
3290531 | import sys, os
collection_basename = sys.argv[1]
output_prefix_name = sys.argv[2]
bins_directory = sys.argv[3]
strategies = [
# "opt",
"block_interpolative",
"block_qmx",
# "block_simple16",
"block_optpfor",
# "block_vbyte",
... |
3290533 | import numpy as np
import math
from scipy import ndimage
import shutil
import tempfile
from osgeo import osr, gdal
import geopandas as gpd
from shapely.geometry import Polygon
from dask import config
from dask_geomodeling.config import defaults
from dask_geomodeling.geometry import GeometryBlock
from dask_geomodeling... |
3290567 | import os
from typing import List, Tuple, Union
import nibabel as nib
import numpy as np
from deepreg.dataset.loader.interface import FileLoader
from deepreg.dataset.util import get_sorted_file_paths_in_dir_with_suffix
from deepreg.registry import REGISTRY
DATA_FILE_SUFFIX = ["nii.gz", "nii"]
def load_nifti_file(f... |
3290584 | from .base import AnnotationNode, AnnotationAttribute, key_for_cypher, AnnotationCollectionNode, \
AnnotationCollectionAttribute
class PauseAnnotation(AnnotationNode):
def __init__(self, corpus, hierarchy):
super(PauseAnnotation, self).__init__('word', corpus, hierarchy)
self.subset_labels = [... |
3290715 | import torch
from torch.utils.data import Dataset
import os
import numpy as np
import cv2
import skimage.io as io
import torchvision.transforms as transforms
import utils
import collections
from tqdm import tqdm
import dataloader.data_utils as data_utils
rand = np.random.RandomState(234)
class MegaDepthLoader():
... |
3290752 | import sys;sys.path.insert(0,'../')
# TEST
#from pycnic.core import WSGI, Handler
import pycnic.core
class JSONHandler(pycnic.core.Handler):
def get(self):
return { "message": "Hello, World!" }
class app(pycnic.core.WSGI):
routes = [
("/json", JSONHandler()),
]
|
3290758 | from rpython.jit.tl.tla import tla
code = [
tla.DUP,
tla.CONST_INT, 1,
tla.SUB,
tla.DUP,
tla.JUMP_IF, 1,
tla.POP,
tla.CONST_INT, 1,
tla.SUB,
tla.DUP,
tla.JUMP_IF, 0,
tla.RETURN
]
|
3290761 | import asyncio
import logging
import json
import traceback
import discord.utils
from discord import Emoji, PartialEmoji
from pathlib import Path
"""
Config options
[role_reactions]
role_json = event_plugins/reactions/role_reactions/testroles.json
temp_filename = event_plugins/reactions/role_reactions/roles_msg_id.tmp... |
3290796 | import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parkings', '0017_region'),
]
operations = [
migrations.RemoveField(
model_name='parkingarea',
name='region', ),
migrations.Ad... |
3290806 | from typing import Any, Callable
from haps.scopes import Scope
class SingletonScope(Scope):
"""
Dependencies within SingletonScope are created only once in
the application context.
"""
_objects = {}
def get_object(self, type_: Callable) -> Any:
if type_ in self._objects:
... |
3290808 | import unittest
from tests.app import app, db, BasicTestCase
from flask_records.decorators import query, query_by_page
from flask_records import RecordsDao
def upper(s):
return s.upper()
@app.route('/converter/user/c/<name>/<age>')
def converter_create_user(name, age):
UserDao().create({'name': name, 'age': ... |
3290813 | from network.hybrid_fcn import HybridFCN
from torch.autograd import Variable
import unittest
import torch
class TestSimpleFCN(unittest.TestCase):
def test_main(self):
net = HybridFCN()
net.eval()
input = Variable(torch.randn(1, 10, 80, 80))
output = net(input)
print(output.... |
3290818 | import logging
import time
from threading import Thread
from channels.management.commands.runworker import Command as BaseCommand
from django_redis import get_redis_connection
from django.conf import settings
from ...consumers import run_task
from ...utils import get_redis_key
logger = logging.getLogger('cq')
def... |
3290839 | from typing import Optional
from dissect.cstruct import Instance
from structlog import get_logger
from unblob.extractors.command import Command
from ...models import File, HexString, StructHandler, ValidChunk
logger = get_logger()
END_HEADER = b"\x1a\x00"
class ARCHandler(StructHandler):
NAME = "arc"
PA... |
3290850 | from setuptools import setup, find_packages
setup(
name='Flask-GZip',
version='0.1',
license='MIT',
description='Flask extension to allow easy GZip compressing of web pagess',
author='<NAME>',
author_email='<EMAIL>',
platforms='any',
install_requires=['Flask'],
packages=find_package... |
3290855 | from .obniz import Obniz
from .obniz.__version__ import __version__ as version
# __copyright__ = ""
__version__ = version
# __license__ = ""
__author__ = "yukisato"
__author_email__ = "<EMAIL>"
__url__ = "https://obniz.io/" |
3290866 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='downloader-exporter',
packages=['downloader_exporter'],
version='0.5.1',
long_description=long_description,
long_description_content_type="text/markdown",
description='Prometheus expor... |
3290910 | import gzip
import json
import logging
from io import BytesIO
from pathlib import Path
from typing import IO, List, Union
import dill
import PIL.Image
import pytest
import numpy as np
from lxml import etree
from lxml.builder import ElementMaker
from sklearn.datasets import load_sample_image
from sciencebeam_gym.utils... |
3290936 | from moai.parameters.optimization.optimizers.a2grad import (
A2GradUni,
A2GradInc,
A2GradExp
)
from moai.parameters.optimization.optimizers.acc_sgd import AccSGD
from moai.parameters.optimization.optimizers.adabelief import AdaBelief
from moai.parameters.optimization.optimizers.adabound import (
Ada... |
3291046 | import numpy as np
import cvxopt
import cvxopt.solvers
class SVM(object):
def __init__(self, C=1.0):
self.C = float(C)
def fit(self, X, y):
n_samples, n_features = X.shape
Xy = X * y[:, np.newaxis]
P = cvxopt.matrix(np.dot(Xy, Xy.T))
q = cvxopt.matrix(np.ones(n_sampl... |
3291073 | import numpy as np
from ..util.backend_functions import backend as bd
from .light_source import LightSource
class GaussianBeam(LightSource):
def __init__(self, w0):
"""
Creates a Gaussian beam with waist radius equal to w0
"""
global bd
from ..util.backend_functions import b... |
3291095 | from featuretools.primitives import AggregationPrimitive
from featuretools.variable_types import Numeric
from tsfresh.feature_extraction.feature_calculators import abs_energy
class AbsEnergy(AggregationPrimitive):
"""Returns the absolute energy of the time series
which is the sum over the squared values.
... |
3291097 | import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib.pyplot import cm
import os
import utils
def show_tfidf(tfidf, vocab, filename):
# [n_doc, n_vocab]
plt.imshow(tfidf, cmap="YlGn", vmin=tfidf.min(), vmax=tfidf.max())
plt.xticks(np.arange(tfidf.shape[1]), vocab, fontsize=6, ro... |
3291125 | import pytest
import redis as redis_client
import limitlion
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 1
@pytest.fixture
def redis():
client = redis_client.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
client.flushdb()
yield client
client.flushdb()
@pytest.fixture
def limitlion_f... |
3291129 | import re
class SendriaException(Exception):
http_code = 400
_response_code_rxp = re.compile(r'[A-Z]+[a-z0-9]+')
def __init__(self, message=None):
self.message = message
def get_response_code(self):
if hasattr(self, 'response_code'):
return self.response_code
cl ... |
3291152 | from selenium import webdriver
import os
import time
driver = webdriver.Firefox()
driver.get("http://web.whatsapp.com")
name = input("input name for search online status :")
while True:
try:
chat=driver.find_element_by_xpath("/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div")
... |
3291189 | from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
from firecares.tasks.update import calculate_story_distribution
class Command(BaseCommand):
help = """Calculates the story distribution for a specific fire department, including similar departments """
... |
3291196 | import json
import os
import pickle
from datetime import date
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from rdflib import XSD, Graph, Literal, Namespace, URIRef, ConjunctiveGraph, OWL
from rdflib.namespace import DCTERMS, VOID
from rd... |
3291199 | from hoomd.trigger import Trigger
from hoomd.operation import Operation, _TriggeredOperation
class DummySimulation:
def __init__(self):
self.state = DummyState()
self.operations = DummyOperations()
self._cpp_sys = DummySystem()
self._system_communicator = None
class DummySystem:... |
3291210 | def snakeAssembler(n):
while n!=0:
yield '*'
n-=1
if n==0:break
yield '#'
n-=1
print(''.join(list(snakeAssembler(int(input())))))
|
3291227 | from pathlib import Path
from tqdm import tqdm
if __name__ == '__main__':
images_dir = 'images'
query_list_name = 'queries/{}_queries_with_intrinsics.txt'
intrinsics_name = 'intrinsics/{}_intrinsics.txt'
sequence = 'night-rain'
h, w = 1024, 1024
intrinsics = {}
for side in ['left', 'right... |
3291262 | from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from werkzeug.middleware.proxy_fix import ProxyFix
from os import getenv
import toml
app = Flask(__name__)
if getenv("FLASK_ENV") == "development":
app.config.from_file("config_dev.toml", load=toml.load)
el... |
3291308 | def f(x):
class c:
nonlocal x
x += 1
def get(self):
return x
return c()
c = f(0)
___assertEqual(c.get(), 1)
___assertNotIn("x", c.__class__.__dict__)
|
3291334 | from urllib.request import url2pathname
from cms.models import StaticPlaceholder
from django.conf import settings
from djangocms_spa.renderer_pool import renderer_pool
from .utils import get_function_by_path
def get_frontend_data_dict_for_cms_page(cms_page, cms_page_title, request, editable=False):
"""
Ret... |
3291341 | import pytest
import requests
import diskcache
import tempfile
import os
import tarfile
import shutil
DATA_URL = 'https://data.kitware.com/api/v1/file'
@pytest.fixture(scope="module")
def test_state_file(tmpdir_factory):
tmpdir = tmpdir_factory.mktemp('state')
_id = '5dbca381e3566bda4b4f94f0'
download_u... |
3291410 | from qtop_py.serialiser import StatExtractor, GenericBatchSystem
import logging
import os
import re
import qtop_py.yaml_parser as yaml
from qtop_py.utils import CountCalls
try:
from collections import OrderedDict
except ImportError:
from qtop_py.legacy.ordereddict import OrderedDict
class OarStatExtractor(Sta... |
3291427 | from oidcmsg import oidc
from oidcmsg.oidc import JRD
from oidcmsg.oidc import Link
from oidcop.endpoint import Endpoint
OIC_ISSUER = "http://openid.net/specs/connect/1.0/issuer"
class Discovery(Endpoint):
request_cls = oidc.DiscoveryRequest
response_cls = JRD
request_format = "urlencoded"
response_... |
3291428 | import os.path
import re
import hashlib
import logging
import shlex
from collections import OrderedDict
from . import __version__, DocoptError
from .doc_ast import DocAst, Option
from .bash import Code, indent, bash_ifs_value
from .node import LeafNode, helper_list
log = logging.getLogger(__name__)
class Parser(obje... |
3291436 | import subprocess
import math
exe_path_str = 'C:/SDKs/IVANBinaries/bin/Release/'
#output_path_str = 'D:/VolumeData/VesselExperiments/'
output_path_str = 'F:/VolumeData/VesselExperiments/'
gaussian_tube_exe_str = exe_path_str + 'TestCircularBarConvolvedTube.exe'
noise_exe_str = exe_path_str + 'UtilityGaussianNoiseAdde... |
3291486 | class SchemaOption(object):
"""
Object representation of a database or table option
>>> schema.databases['sakila'].tables['rental'].options['engine'].name
'ENGINE'
>>> schema.databases['sakila'].tables['rental'].options['engine'].value
'InnoDB'
>>> schema.databases['sakila'].tables... |
3291500 | from django.test import override_settings
from nose.tools import assert_equal, assert_in
from corehq.sql_db import check_standby_configs
def test_check_standby_configs():
databases = {
'default': {},
'other': {},
's1': {
'HQ_ACCEPTABLE_STANDBY_DELAY': 1
},
's2'... |
3291516 | from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items = [] # type: List[T]
def push(self, item: T) -> None:
self.items.append(item)
stack = Stack[int]()
stack.push(1)
stack.pus... |
3291548 | import re
from g2p_en import G2p
import json
import torch
import argparse
from dataclasses import dataclass, field
from transformers import BertTokenizerFast
from transformers import BertForMaskedLM, BertConfig
from transformers import Wav2Vec2CTCTokenizer
from transformers import Wav2Vec2FeatureExtractor
from transfor... |
3291589 | from collections import defaultdict
import pytest
numpy = pytest.importorskip("numpy")
scipy = pytest.importorskip("scipy")
import networkx as nx
from networkx.testing import almost_equal
from networkx.algorithms.communicability_alg import communicability, communicability_exp
class TestCommunicability:
def tes... |
3291591 | from flask_babel import _
from wtforms import HiddenField
from app.forms import SteuerlotseBaseForm
from app.forms.steps.step import FormStep
class LogoutInputStep(FormStep):
name = 'data_input'
class Form(SteuerlotseBaseForm):
hidden = HiddenField(label='')
def __init__(self, **kwargs):
... |
3291638 | import compas
from compas.datastructures import Network
from compas_plotters import NetworkPlotter
network = Network.from_obj(compas.get('grid_irregular.obj'))
node = next(network.nodes())
nbrs = network.neighbors(node)
facecolor = {node: (255, 0, 0)}
for nbr in nbrs:
facecolor[nbr] = (0, 0, 255)
edgecolor = {}... |
3291670 | client.delete_object_store_users(names=["acc1/myobjuser"])
# Other valid fields: ids
# See section "Common Fields" for examples
|
3291701 | from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
install_requires = (this_directory / "requirements.txt").read_text().splitlines()
long_description = (this_directory / "README.md").read_text()
setup(
name="skillful_nowcasting",
version="1.2.3",
pa... |
3291706 | from datetime import timedelta as td
import json
import re
from urllib.parse import quote, urlencode
from django import forms
from django.forms import URLField
from django.conf import settings
from django.core.exceptions import ValidationError
from hc.front.validators import (
CronExpressionValidator,
Timezone... |
3291709 | import json
import requests
from plugin import plugin, require
@require(network=True)
@plugin('location')
def location(jarvis, s):
"""It gives you your current location"""
send_url = "http://api.ipstack.com/check?access_key=<KEY>"
geo_req = requests.get(send_url)
geo_json = json.loads(geo_req.text)
... |
3291773 | import numpy as np
from ..common import CartesianPosition, PolarPosition, cart, azimuth, elevation, distance # noqa: F401
def relative_angle(x, y):
"""Assuming y is clockwise from x, increment y by 360 until it's not less
than x.
Parameters:
x (float): start angle in degrees.
y (float): ... |
3291803 | import os
from flask_script import Manager, Shell, Server
from src.main import create_app, db
app = create_app()
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app and db by default.
"""
return {'app': app, 'db': db}
manager.add_command('serv... |
3291817 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Clip(Base):
@staticmethod
def export(): # type: () -> None
... |
3291828 | from pathlib import Path
import pytest
import fsspec
pyarrow = pytest.importorskip("pyarrow")
basedir = "/tmp/test-fsspec"
data = b"\n".join([b"some test data"] * 1000)
@pytest.fixture
def hdfs(request):
try:
hdfs = pyarrow.hdfs.HadoopFileSystem()
except IOError:
pytest.skip("No HDFS confi... |
3291861 | import click
from eth_wallet.cli.utils_cli import (
get_api,
)
from eth_wallet.configuration import (
Configuration,
)
@click.command()
def get_wallet():
"""Get wallet account from encrypted keystore."""
configuration = Configuration().load_configuration()
api = get_api()
address, pub_key = a... |
3291864 | from scipy.stats import scoreatpercentile
import re
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
try:
from . import plotting
except ImportError:
print( 'WARNING: unable to import "plotting" in stats. some functions may be disabled' )
from . import reshape
class BlockMath( reshape.... |
3291890 | import logging
import os
import time
import numpy as np
import torch
from scipy import sparse
from torch.utils.data import Dataset
def time_it(fn):
def wrapper(*args, **kwargs):
start = time.time()
ret = fn(*args, **kwargs)
end = time.time()
logging.info(f'Time: {end - start}')
... |
3291918 | from __future__ import annotations
from typing import Optional, Any, TYPE_CHECKING
import pandas as pd
from whyqd.base import BaseSchemaAction
if TYPE_CHECKING:
from ..models import FieldModel
class Action(BaseSchemaAction):
"""
Add a new field to the dataframe, populated with a single value.
Scrip... |
3291931 | from _Framework.ButtonMatrixElement import ButtonMatrixElement
from _Framework.ControlSurface import ControlSurface
from _Framework.InputControlElement import MIDI_CC_TYPE
from _Framework.Layer import Layer
from _Framework.ModesComponent import LayerMode
from consts import *
from Colors import *
from BackgroundCompon... |
3291935 | from typing import Container
from deeppavlov.models.go_bot.nlg.dto.nlg_response_interface import NLGResponseInterface
class BatchNLGResponse:
def __init__(self, nlg_responses: Container[NLGResponseInterface]):
self.responses: Container[NLGResponseInterface] = nlg_responses
|
3291948 | import dash
import random
import dash_html_components as html
import dash_vtk
field = [random.random()*i for i in range(10*10*10)]
content = dash_vtk.View([
dash_vtk.VolumeRepresentation([
dash_vtk.VolumeController(),
dash_vtk.ImageData(
dimensions=[10, 10, 10],
spacing=[1,1,1]... |
3291950 | from .lr_scheduler import LrScheduler
import os
if os.environ['BACKEND_TYPE'] == 'PYTORCH':
from .warmup_scheduler import WarmupScheduler
elif os.environ['BACKEND_TYPE'] == 'TENSORFLOW':
from .multistep_warmup import MultiStepLrWarmUp
from .cosine_annealing import CosineAnnealingLR
|
3291956 | import torch
import datetime
from .wordebd import WORDEBD
from .cxtebd import CXTEBD
from .avg import AVG
from .cnn import CNN
from .idf import IDF
from .meta import META
from .lstmatt import LSTMAtt
def get_embedding(vocab, args):
print("{}, Building embedding".format(
datetime.datetime.now().strftime(... |
3292009 | import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.append('\n')
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
versi... |
3292022 | from datetime import datetime
from collections import defaultdict
import requests
import pandas as pd
class ParserError(Exception):
pass
class Financials:
"""Financial data parser
Parameters:
ticker : str
Public company ticker to fetch the financial data of (e.g. 'AAPL')
"""
base_u... |
3292032 | from conf.feature import *
QUERY_DIM = 6
MODEL_CONFIG = {"UNet":
{"with_bn0" : True,
"input_channels_num" : CHANNELS_NUM,
"input_size" : WINDOW_SIZE // 2,
"blocks_num" : 5,
"condition_dim" : QUERY_DIM,
"output_dim" : CHANNELS_NUM,
},
"QueryNet":
{"blocks_num" : 2,
"input_size" : WINDOW_SIZE /... |
3292049 | from pycsp.parallel import *
import time
@process
def Process1():
time.sleep(1) # Sleep 1 second
print('process1 exiting')
@process
def Process2():
time.sleep(2) # Sleep 2 seconds
print('process2 exiting')
Parallel(Process1(), Process2()) # Blocks
print('program terminating') |
3292068 | from rastervision.core.data.vector_source.vector_source_config import (
VectorSourceConfig)
from rastervision.core.data.vector_source.geojson_vector_source import (
GeoJSONVectorSource)
from rastervision.pipeline.config import register_config, Field
@register_config('geojson_vector_source')
class GeoJSONVecto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.