id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11430559 | from baselayer.app.handlers.base import BaseHandler
from ..ext.sklearn_models import model_descriptions
class SklearnModelsHandler(BaseHandler):
def get(self):
self.success(model_descriptions)
|
11430566 | import numpy as np
from pathlib import Path
import torch
import torch.utils.data as data
from utils.worker import Worker
__author__ = 'Andres'
class BaseDataset(data.Dataset):
def __init__(self, root, window_size, audio_loader, examples_per_file=8, blacklist_patterns=None, loaded_files_buffer=10,
... |
11430569 | import torch
from torch2trt_dynamic.torch2trt_dynamic import tensorrt_converter
from .ReLU6 import convert_ReLU6
@tensorrt_converter('torch.nn.functional.relu6')
def convert_relu6(ctx):
ctx.method_args = (torch.nn.ReLU6(), ) + ctx.method_args
convert_ReLU6(ctx)
|
11430617 | import importlib
import re
def load_plugin(name):
module, coroutine = name.rsplit(".", 1)
module = importlib.import_module(module)
coro = getattr(module, coroutine)
return coro
def at_bot(func):
def inner(bot, message: "message"):
match = re.match(
r"<@{}>(?::)? (.*)".format(... |
11430632 | from kdl_template import *
train, valid, test = fetch_binarized_mnist()
X = train[0].astype(theano.config.floatX)
y = convert_to_one_hot(train[1], n_classes=10)
# graph holds information necessary to build layers from parents
graph = OrderedDict()
X_sym, y_sym = add_datasets_to_graph([X, y], ["X", "y"], graph)
# rand... |
11430642 | import cv2, os, dlib, sys
import numpy as np
from py_utils.face_utils import lib
from concurrent.futures import ProcessPoolExecutor
seed = 100
# Employ dlib to extract face area and landmark points
pwd = os.path.dirname(os.path.abspath(__file__))
front_face_detector = dlib.get_frontal_face_detector()
lmark_predictor =... |
11430645 | from flask import Flask, request, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin.contrib import sqlamodel
from flask.ext import admin
# Create application
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
# Create in-memory databa... |
11430655 | import pytest
from ambianic.util import ManagedService, ThreadedJob
class MockManagedService(ManagedService):
def __init__(self):
super().__init__()
self._healthcheck_called = False
self._heal_called = False
def healthcheck(self):
super().healthcheck()
self._healthchec... |
11430665 | import logging
import fmcapi
import time
def test__ikev1(fmc):
logging.info(
"Test IKEv1Policies and IKEv1IpsecProposals."
" Post, get, put, delete IKEv1Policies and IKEv1IpsecProposals Objects."
)
starttime = str(int(time.time()))
namer = f"_fmcapi_test_{starttime}"
ipsec1 = fm... |
11430698 | from matplotlib.animation import FuncAnimation
from anesthetic import NestedSamples
root = 'plikHM_TTTEEE_lowl_lowE_lensing_NS/NS_plikHM_TTTEEE_lowl_lowE_lensing'
nested = NestedSamples.read(root=root)
plotter = nested.gui(['omegam', 'H0', 'sigma8'])
plotter.param_choice.buttons.set_active(1)
plotter.param_choice.butt... |
11430709 | from __future__ import print_function
import os
import sys
import tempfile
import socket
import copy
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from . import session
from .. import lib
from .. import paths
from .. import test
class Test_Istream(session.make_sessions_mixi... |
11430724 | from django_celery_results.models import TaskResult
from service_catalog.models import Request, Instance, TowerServer
from tests.test_service_catalog.base import BaseTest
class BaseTestTower(BaseTest):
def setUp(self):
super(BaseTestTower, self).setUp()
self.test_task_result = TaskResult.object... |
11430790 | import pandas as pd
def load_dataset(path):
df = pd.read_csv(path)
df.loc[:, "DATE_TIME"] = pd.to_datetime(df["DATE_TIME"])
df["HOUR"] = df["DATE_TIME"].apply(lambda _: _.hour)
df["MONTH"] = df["DATE_TIME"].apply(lambda _: _.month)
agg = df.groupby(["MONTH"]).agg({"AC_POWER": "sum", "DC_POWER": ... |
11430832 | import pytest
from arnparse import arnparse
from arnparse.arnparse import MalformedArnError
def test__definition():
arn = arnparse('arn:partition:service:region:account-id:resource')
assert arn.partition == 'partition'
assert arn.service == 'service'
assert arn.region == 'region'
assert arn.accou... |
11430846 | import dpkt, socket
from binascii import hexlify
def convert_to_readable_mac( eth_src ) :
""" converts eth.src and eth.dst to readable mac address """
mac_addr = hexlify(eth_src)
"""This function accepts a 12 hex digit string and converts it to a colon separated string"""
s = list... |
11430863 | import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'khkpwoifqiumbnoyopwe')
CACHE_TYPE = os.environ.get('CACHE_TYPE', 'simple')
CACHE_REDIS_URL = os.environ.get('REDIS_URL')
DEBUG = os.environ.get('DEBUG', True)
S3_INDEX_DOCUMENT = os.environ.get('S3_INDEX_DOCUMENT', 'index.html')
... |
11430869 | import sentry_sdk
from starlette.concurrency import run_in_threadpool
from starlette.graphql import GraphQLApp
async def capture_and_reraise(e):
sentry_sdk.capture_exception(e)
raise e
class GraphQLSentryMiddleware(object):
"""
Middleware for Sentry - used in conjunction with GraphQLAppWithMiddlewa... |
11430913 | from nonebot import on_command, CommandSession, permission
from sqlalchemy.orm.exc import NoResultFound
import config
__plugin_name__ = '查询信息'
__plugin_usage__ = r"""查询信息
例:#查询
或者 #info"""
from database.Player import Player
@on_command('info', aliases='查询', only_to_me=False, permission=permission.GROUP)
async def ... |
11430915 | from django.conf import settings
from django.conf.urls.defaults import include, patterns
from django.http import HttpResponse
from django.utils.encoding import smart_unicode
if 'debug_toolbar' not in settings.INSTALLED_APPS:
class DebugMiddleware(object):
pass
else:
import debug_toolbar.urls
from d... |
11430923 | import logging
import re
import pymel.core as pm
import pymetanode as meta
from . import colors
from . import joints
from . import links
from . import nodes
from .vendor.mayacoretools import preservedSelection
LOG = logging.getLogger(__name__)
MIRROR_METACLASS = 'pulse_mirror'
MIRROR_THRESHOLD = 0.0001
class Mirr... |
11430934 | import json
convo = {}
class GPTJ:
def __init__(self, user_bot_input_output_example):
assert isinstance(user_bot_input_output_example, dict), "User bot examples must be a dictionary"
self.user_input_example = [key for key in user_bot_input_output_example]
self.bot_output_exampl... |
11430937 | EASYCART_CART_CLASS = 'tests.common.Cart'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'tests',
]
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.m... |
11430947 | from confluent_kafka.avro import CachedSchemaRegistryClient
from .avroserdebase import AvroSerDeBase
class Deserializer:
"""
Base class for all key and value deserializers.
This default implementation returns the value intact.
"""
def __init__(self, **kwargs):
pass
def deserialize(s... |
11431026 | from unimodals.common_models import GRU, MLP
from robustness.all_in_one import general_train, general_test
from get_data_robust import get_dataloader
from fusions.common_fusions import Concat
from training_structures.Simple_Late_Fusion import train, test
import torch
import sys
import os
sys.path.append(os.path.dirname... |
11431048 | from __future__ import absolute_import
from math import log
import operator
from .. import ROOT
from .canvas import _PadBase
from .hist import _Hist, Hist, HistStack
from .graph import _Graph1DBase, Graph
from ..context import preserve_current_canvas, do_nothing
from ..extern.six.moves import range
__all__ = [
'... |
11431052 | import base64
import hashlib
import hmac
from datetime import timedelta
from flask_unchained import Service, current_app, injectable
from itsdangerous import BadSignature, SignatureExpired
class SecurityUtilsService(Service):
"""
The security utils service. Mainly contains lower-level encryption/token handli... |
11431080 | import alpaca_trade_api as tradeapi
api = tradeapi.REST(key_id="YOURKEY",secret_key="YOURSECRET")
# Get data from alpaca and align dates
gld = api.get_barset('GLD', 'day', limit=252)
gdx = api.get_barset('GDX', 'day', limit=252)
uso = api.get_barset('USO', 'day', limit=252)
glddf = gld.df[('GLD', 'close')].rename("... |
11431114 | import frappe
def get_context(context):
context.no_cache = 1
try:
sketch_id = frappe.form_dict["sketch"]
except KeyError:
context.template = "www/404.html"
return
sketch = get_sketch(sketch_id)
if not sketch:
context.template = "www/404.html"
return
co... |
11431124 | try:
from django.urls import re_path
except ImportError:
# Django 1.11 - switch to simple path after dropping support of 1.11
from django.conf.urls import url as re_path
from django.contrib.contenttypes.views import shortcut
from custom_reviews import views
urlpatterns = [
re_path(r'^post/$', views.... |
11431145 | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from model_mommy import mommy
from common.tests.test_views import LoginMixin
from common.models import (
Ward,
ContactType,
Town,
Contact)
from ..models import (
OwnerType,
Owner,
FacilityStatus,
... |
11431149 | import os
import warnings
import numpy as np
from pdb2sql import StructureSimilarity
def __compute_target__(decoy, targrp, tarname, save_file=False):
"""Calcuate CAPRI metric IRMSD, LRMSD or FNAT.
Args:
decoy(bytes): pdb data of the decoy
targrp(hdf5 file handle): HDF5 'targets' group
... |
11431155 | import vplanet
import numpy as np
import os
import pytest
import functools
import inspect
import astropy.units as u
def recursive_getattr(obj, attr, *args):
_getattr = lambda obj, attr: getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split("."))
class Benchmark:
def test_benchma... |
11431168 | from configparser import ConfigParser
import glob
import json
import pickle
import sys
import time
from storage import StorageInterface
class PyDictStorage(StorageInterface):
def __init__(self, config: ConfigParser):
self.config = config
self.data = {}
self.contestKey = 'contests'
... |
11431238 | class ModelTranslation(object):
"""
Collects all model fields that would be translated
using 'makemessages --domain database' management command
"""
_registry = {}
@classmethod
def register(cls, model, fields):
if model in cls._registry:
raise ValueError("Model ... |
11431257 | import os
import tensorflow as tf
import numpy as np
from compressible_model import DTYPE, Compressible
import cifar10_data
from cifar10_data import img_size, num_channels, num_classes
img_size_cropped = 32
cfg = {
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B': [64, 64, 'M', 128, ... |
11431303 | from ...base import *
from ...dialog import *
from ...dialogs import *
from ...panel import *
from ...button import *
class ObjectTypes:
_types = {}
@classmethod
def add_type(cls, obj_type_id, obj_type_name):
cls._types[obj_type_id] = obj_type_name
@classmethod
def get_types(cls):
... |
11431325 | import torch as th
import torch.nn as nn
import contextlib
import itertools
from .basic_controller import BasicMAC
from modules.agents import REGISTRY as agent_REGISTRY
class LowRankMAC (BasicMAC):
""" Implements a low-rank Q-value approximation for MARL (Boehmer et al., 2020)."""
# ==========================... |
11431382 | from janus.partition.partition import Partition
from janus.partition.distance import DistancePartition
from janus.partition.hysteretic import HystereticPartition
|
11431415 | import sys
sys.path.append('src')
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import random
import urllib.request
from werkzeug.utils import secure_filename
from PIL import Image
from flask import Flask, flash, request, redirect, url_for, render_template
from tensorflow.keras.models import load_model... |
11431422 | from data_layers.tpn_data_eval import DataEval
import numpy as np
if __name__ == '__main__':
net = '/home/rhou/tcnn/models/jhmdb/tpn_rec_eval_v3.prototxt'
model = '/home/rhou/jhmdb_rec_240_320_v2_iter_25000.caffemodel'
r = DataEval(net, model)
while(1):
flag = r.forward()
if (flag):
break
'''
... |
11431463 | import pprint
import numpy as np
from yggdrasil.metaschema.datatypes import get_type_class
def get_test_data(typename):
r"""Determine a test data set for the specified type.
Args:
typename (str): Name of datatype.
Returns:
object: Example of specified datatype.
"""
typeclass = g... |
11431550 | from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ListMixin, ObjectDeleteMixin, SaveMixin
__all__ = [
"DeployKey",
"DeployKeyManager",
"ProjectKey",
"ProjectKeyManager",
]
class DeployKey(... |
11431568 | from ._aura import aura
from ._ayu import ayu
from ._challenger_deep import challenger_deep
from ._dhaitz import pacoty, pitaya_smoothie
from ._dracula import dracula
from ._dufte import dufte, dufte_bar, duftify
from ._github import github
from ._gruvbox import gruvbox
from ._nord import nord
from ._onedark import one... |
11431571 | import remi.gui
import widgets.htmltemplate
# https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
# https://github.com/susam/texme/blob/master/README.md
# https://github.com/executablebooks/markdown-it-py
class Container(remi.gui.Container):
def __init__(self, AppInst=None, *args, **kwargs):
... |
11431611 | from .lasso import (lasso,
data_carving as data_carving_lasso,
additive_noise as additive_noise_lasso)
from .sqrt_lasso import (choose_lambda as choose_lambda_sqrt_lasso,
solve_sqrt_lasso)
from .forward_step import (forward_step,
... |
11431647 | from django.contrib import admin
from tworaven_apps.call_captures.models import ServiceCallEntry
class ServiceCallEntryAdmin(admin.ModelAdmin):
save_on_top = True
search_fields = ('call_type',)
list_display = ('service_type',
'call_type',
'success',
... |
11431705 | from django.core import exceptions
from django.test import TestCase
from common.testhelpers.random_test_values import a_string, a_float
from newcomers_guide.parse_data import (parse_taxonomy_terms, parse_taxonomy_files,
parse_topic_files, parse_file_path, TaxonomyTermReference)
f... |
11431746 | from functools import wraps
from flask import Flask
from flask import request, Response
from subprocess import call
from flask import render_template
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import random
fro... |
11431754 | import warnings
from bento.parser.nodes import Node
#-------------
# Grammar
#-------------
def p_stmt_list(p):
"""stmt_list : stmt_list stmt"""
p[0] = p[1]
if p[2].type not in ("newline",):
p[0].children.append(p[2])
def p_stmt_list_term(p):
"""stmt_list : stmt"""
p[0] = Node("stmt_lis... |
11431767 | from alembic import op
import sqlalchemy as sa
"""Updated columns for dual-language
Revision ID: 11c83a1168c
Revises: <PASSWORD>
Create Date: 2015-06-19 19:08:00.678224
"""
# revision identifiers, used by Alembic.
revision = '11c83a1168c'
down_revision = '<PASSWORD>'
def upgrade():
# commands auto generated by... |
11431770 | import os
import copy
from recognize import ShapeRecognizer
from extract_features import process_image
from commons import *
def eval_dataset(input_dir, output_file, need_latex=True, sketch=False):
recognizer = ShapeRecognizer()
confusion_matrix = {}
for shape in shape_list:
confusion_matrix[shap... |
11431781 | import pickle
import collections
import msgpack
import msgpack_numpy
from redis import Redis
from qtpy.QtCore import QObject, Signal
from .util import KeyItem
def msgpack_pack(data):
return msgpack.packb(data, use_bin_type=True, default=msgpack_numpy.encode)
def msgpack_unpack(buff):
return msgpack.unpac... |
11431789 | import os
import shutil
import json
import stat
import pathlib
import multiprocessing
import itertools
import pathlib
import re
import fnmatch
from urllib.parse import urlparse
from functools import lru_cache
from pbpy import pblog
from pbpy import pbconfig
from pbpy import pbtools
missing_version = "not installed"
... |
11431827 | import random
import itertools
import pytest
import string
from hypothesis.strategies import composite, text, integers, sampled_from, floats, lists
from hypothesis import given, settings
from operon_analyzer import rules
from operon_analyzer.genes import Feature, Operon
from typing import List
def _get_repositionable... |
11431849 | from django.contrib import admin
from .models import PriceBook, Price
admin.site.register(PriceBook)
admin.site.register(Price)
|
11431868 | from slugify import slugify
from sqlalchemy import event
from app.database import db
class Entity(db.Model):
__tablename__ = 'entity'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(1000), nullable=False, unique=True)
slug = db.Column(db.String(1000))
content = db.Column(d... |
11431920 | from bc211.views import Bc211VersionView
from config import documentation
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_view... |
11432002 | from __future__ import absolute_import, unicode_literals
import logging
from leonardo.module.web.widgets.utils import get_widget_from_id
from django.forms import modelform_factory
from feincms._internal import get_model
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
fro... |
11432103 | import numpy as np
from hott import sparse_ot
def wmd(p, q, C, truncate=None):
""" Word mover's distance between distributions p and q with cost M."""
if truncate is None:
return sparse_ot(p, q, C)
# Avoid changing p and q outside of this function
p, q = np.copy(p), np.copy(q)
to_... |
11432119 | from setuptools import setup, find_packages
from codecs import open
from os import path
import sys
from astra import __version__
from setuptools.command.test import test as TestCommand
here = path.abspath(path.dirname(__file__))
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize... |
11432121 | class ValidationError(Exception):
"""
A class for validation errors.
"""
def __init__(self, message):
super().__init__(message)
self.message = message
def __unicode__(self):
return self.message
def __str__(self):
return self.message.encode("utf-8")
|
11432128 | from click import Group
class AliasedGroup(Group):
"""Class for supporting aliased click groups.
Example: spotify v -> spotify volume
"""
def get_command(self, ctx, cmd_name):
rv = Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x fo... |
11432199 | from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.template.response import TemplateResponse
from django.utils import translation
from django.utils.translation import check_for_language, pgettext
from django.views.decorators.cache import never_cache
from django.view... |
11432256 | import requests
class NftStorage:
def __init__(self, api_key):
self.api_key = api_key
self.url = 'https://api.nft.storage/upload'
self.headers = {'Authorization': 'Bearer ' + self.api_key}
def upload(self, file_list, file_type):
files = []
for i in file_lis... |
11432353 | from .choices import OrderStatus
from .models import Order, OrderLine, Product
def create_order(*, lines: dict) -> Order:
order = Order.objects.create()
for line in lines:
create_order_line(order=order, **line)
return order
def create_order_line(*, order: Order, product: Product, quantity: int) ... |
11432382 | import yaml
from typing import Any, Dict, List
from collections import defaultdict
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from sovereign import discovery, config, stats, poller, template_context
from sovereign.discovery import Discov... |
11432501 | import pytest
from opa_wasm import OPAPolicy
def test_entrypoint_by_id():
policy = OPAPolicy('./policy_simple.wasm')
assert policy.evaluate({}, entrypoint=0) == [{'result': {"allow": False}}]
assert policy.evaluate({}, entrypoint=1) == [{'result': False}]
assert policy.evaluate({}, entrypoint=2) == [... |
11432567 | import os
import ee
import geemap.foliumap as geemap
import streamlit as st
def app():
st.title("NAIP Imagery")
st.markdown(
"""
NAIP: National Agriculture Imagery Program. See this [link](https://developers.google.com/earth-engine/datasets/catalog/USDA_NAIP_DOQQ) for more information.
"""
... |
11432581 | from cocoa.core.kb import KB as BaseKB
class KB(BaseKB):
def __init__(self, attributes, items):
super(KB, self).__init__(attributes)
self.items = items
self.entity_set = set([value.lower() for item in items for value in item.values()])
self.entity_type_set = set([attr.value_type for... |
11432588 | from listallobjects import handle_listallobjects
from fetchobject import handle_fetchobject
from listallchannels import handle_listallchannels
from listdbhash import handle_listdbhash
|
11432620 | import os
import sys
import tensorflow as tf
def create_path(__model__, dataset):
'''
Directory base folder
'''
export_path_base = os.path.dirname(sys.argv[0])
'''
Define model version
'''
# Obtain most recent version
export_base_path = os.path.join(export_path_base, '_versions', dataset, __model__)
# V... |
11432629 | import abc
import json
import pathlib
from pprint import pprint
import pytest
import requests
from soccerapi.api import Api888Sport, ApiBet365, ApiUnibet
filename = pathlib.Path(__file__).parent.absolute() / 'urls.json'
with open(filename) as f:
urls = json.load(f)
class BaseTest(abc.ABC):
@abc.abstractmeth... |
11432634 | import pytest
import os
import fnmatch
import tarfile
import numpy as np
import dask
from contextlib import contextmanager
import py
import tempfile
import hashlib
try:
import urllib.request as req
except ImportError:
# urllib in python2 has different structure
import urllib as req
from xmitgcm.file_utils ... |
11432638 | import numpy as np
import os
# APOGEE-APOKASC overlap
inputf = "/home/annaho/TheCannon/examples/example_apokasc/apokasc_DR12_overlap.npz"
apogee_apokasc = np.load(inputf)['arr_0']
# APOGEE-LAMOST overlap
inputf = "/home/annaho/TheCannon/examples/example_DR12/Data"
apogee_lamost = np.array(os.listdir(inputf))
# APO... |
11432653 | import numpy as np
import pandas as pd
from sklearn.linear_model import *
from sklearn.tree import *
from sklearn.naive_bayes import *
from sklearn.svm import *
from sklearn.neural_network import *
from sklearn.ensemble import *
from sklearn.dummy import *
from sklearn.calibration import CalibratedClassifierCV
import... |
11432688 | import copy
import csv
def generate(dates, output_filename, *, state_info=None, name=None, description=None, uid=None, states=None, counties=None):
columns = ["date", "key", "election_key", "type", "subtype", "name", "original_date", "state", "county", "postmark_too_late"]
with open(output_filename, "w") as f:... |
11432711 | from base import DatadogBaseAction
from datadog import api
class DatadogGraphSnapshot(DatadogBaseAction):
def _run(self, **kwargs):
return api.Graph.create(**kwargs)
|
11432717 | from ..models import Notice
def create_notice(**kwargs):
defaults = {
'title': 'Hello!',
'body': 'World!',
}
if kwargs:
defaults.update(kwargs)
return Notice.objects.create(**defaults)
|
11432726 | import boto3
from moto import mock_iot
from moto.core import ACCOUNT_ID
@mock_iot
def test_create_thing():
client = boto3.client("iot", region_name="ap-northeast-1")
name = "my-thing"
thing = client.create_thing(thingName=name)
thing.should.have.key("thingName").which.should.equal(name)
thing.sh... |
11432772 | from torch import nn
from blazeface import BlazeBlock
def initialize(module):
# original implementation is unknown
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight.data)
nn.init.constant_(module.bias.data, 0)
elif isinstance(module, nn.BatchNorm2d):
nn.init.... |
11432792 | def _fresh_http_archive_impl(repository_ctx):
url = repository_ctx.attr.url
sha256 = repository_ctx.attr.sha256
strip_prefix = repository_ctx.attr.strip_prefix
repository_ctx.download_and_extract(url, sha256 = sha256, stripPrefix = strip_prefix)
args = [
"python",
repository_ctx.path... |
11432823 | import pytest
from tenable_io.client import TenableIOClient
from tenable_io.exceptions import TenableIOApiException, TenableIOErrorCode
from tests.base import BaseTest
class TestTenableIOClient(BaseTest):
@pytest.mark.vcr()
def test_client_bad_keys(self):
try:
TenableIOClient('bad', 'key... |
11432865 | import os
import json
from ..globals import RESOURCE_DIR
from ..models import init_model
PREPROCESS_CACHE_DIR = os.path.join(RESOURCE_DIR, 'COMPASS')
if not os.path.isdir(PREPROCESS_CACHE_DIR):
os.mkdir(PREPROCESS_CACHE_DIR)
# Keys are tuple of (model, media)
_cache = {}
_new_cache = {}
def load(model, media=Non... |
11432889 | import matplotlib.pyplot as plt
from math import log10, floor
from matplotlib import rc
import matplotlib.gridspec as gridspec
from matplotlib.colors import LogNorm
plt.rc('text', usetex=True)
# rc('text.latex', preamble = ','.join('''\usepackage{txfonts}'''.split()))
plt.rc('font', family='serif')
import numpy as np
... |
11432900 | import sys
sys.path.insert(0, '..')
import unittest
import json
import numpy as np
import torch
from model import BaselineDurIAN, DurIAN
from loss import DurIANLoss
from base import suite, BaseModelBackwardPassTest
seed = 0
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
cl... |
11432939 | from typing import Optional
from typing_extensions import Literal
from pathlib import Path
from os import PathLike
import logging
from logging import Logger
TLogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
LogLevels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
_LOG_FORMAT = "%(asctime)-15... |
11432949 | from getpass import getuser
import os
import posixpath
import pysftp
import pytest
from airflow_fs.hooks import SftpHook
from airflow_fs.testing import MockConnection
@pytest.fixture
def sftp_conn(mocker):
conn = MockConnection(
host="localhost", login="root", extra={"ignore_hostkey_verification": True}... |
11432962 | import logging
import googleapiclient.discovery
from google.oauth2 import service_account
from ..abc.connection import Connection
L = logging.getLogger(__name__)
# https://developers.google.com/identity/protocols/OAuth2ServiceAccount
class GoogleDriveConnection(Connection):
"""
GoogleDriveConnection allows BSP... |
11432993 | import csv
import os
channel_list = []
for file in os.scandir("DataCollection/SullyGnomeChannelData"):
with open(file, encoding='utf-8') as csvFile:
reader = csv.DictReader(csvFile)
for row in reader:
channel_list.append(row['Channel'])
for index, streamer in enumerate(channel_list):
... |
11432997 | import os
import time
from shutil import copyfile
import traceback
import xmltodict as x2d
#Specify all folders containing wav or xml files
data_dirs = ['birdCLEF2017/xml/', 'birdCLEF2017/wav/']
#Specify target folder
#Files will be sorted into folders according to genus, species and class id
class_dir = 'dataset/tr... |
11433019 | import os
import time
import platform
import getpass
import time
print("Getting necessary stuff...")
time.sleep(5)
os_name = platform.platform()
usr_accnt = getpass.getuser()
currn_dir = os.getcwd()
py_ver = platform.python_version()
if os_name.startswith("Linux"):
os.system("clear")
os.system("python3 -m pi... |
11433035 | from pathlib import Path
import numpy as np
from time import sleep
import importlib
import logging
from time import time
from typing import Any
#
from .generator import noise
def computenoise(
ntype: str, fs: int, nsec: int, nbitfloat: int, nbitfile: int, verbose: bool = False
) -> np.ndarray:
nsamp = int(fs... |
11433051 | from ..factory import Type
class messageGameScore(Type):
game_message_id = None # type: "int53"
game_id = None # type: "int64"
score = None # type: "int32"
|
11433058 | import itertools
import operator
class Solution(object):
def reconstructQueue(self, people):
res = []
people.sort(reverse=True)
for k, g in itertools.groupby(people, key=operator.itemgetter(0)):
for person in sorted(g):
res.insert(person[1], person)
retu... |
11433070 | class Error(Exception):
pass
class ParameterNotDefinedError(Error):
def __init__(self, parameters):
self.message = '{} is required'.format(parameters)
class NotFoundFieldError(Error):
def __init__(self, parameters, table):
self.message = '{} is not in the {} table'.format(parameters, t... |
11433081 | def reconstruction(xhat, x):
return torch.pow(
xhat - x, 2
).sum(dim=(1, 2, 3)).mean()
def kl_div_gauss(log_var, mean):
kl_loss = -0.5 * (1 + log_var - torch.pow(mean, 2) - torch.exp(log_var))
kl_loss = kl_loss.sum(dim=1).mean()
return kl_loss
|
11433105 | import os
import logging
from ast2vec.repo2.uast import repos2uast_entry
from ast2vec.enry import install_enry
def pylib2uast_entry(args):
log = logging.getLogger("pylib2uast")
module_names = args.input
module_dirs = []
for lib_name in args.input:
try:
module = __import__(lib_name)... |
11433106 | from django import forms
from django.forms import ModelForm, ValidationError, ClearableFileInput
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.contrib.auth import views as auth_view
from django.contrib.auth.forms import AuthenticationForm, PasswordResetFo... |
11433154 | import math
import torch
import torch.nn as nn
class LinearReluFunctionalChild(nn.Module):
def __init__(self, N):
super().__init__()
self.w1 = nn.Parameter(torch.empty(N, N))
self.b1 = nn.Parameter(torch.zeros(N))
torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5))
def fo... |
11433205 | from urllib.request import urlopen,urlretrieve
from bs4 import BeautifulSoup
#File path to store the webpages
FILE_PATH = ""
URL = ""
PAGES = []
IMAGES = []
#Function to fetch web page
def fetch_page(link):
#Main page HTTP response
html = urlopen(URL+"/"+link)
#Extracting HTML from the resp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.