id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
57404 | import sys
def inline_validate_1(s):
from valid8 import validate
validate('s', s, instance_of=str, min_len=1)
validate('s', s, equals=s.lower())
def inline_validate_2(s):
from valid8 import validate
validate('s', s, instance_of=str, min_len=1, custom=str.islower)
def inline_validate_3(s):
... |
57411 | import tensorflow as tf
import numpy as np
import os
class TFModel(object):
'''
This class contains the general functions for a tensorflow model
'''
def __init__(self, config):
# Limit the TensorFlow's logs
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '4'
# tf.logging.set_verbosi... |
57412 | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def index():
image_files = request.files.getlist('image')
video_files = request.files.getlist('video')
if not image_files and not video_files:
return jsonify({
"code": -1,
... |
57413 | import logging
from dataclasses import dataclass
from unittest.mock import patch
import pytest
from tests.utils.mock_backend import (
ApiKey,
BackendContext,
Run,
Project,
Team,
User,
)
from tests.utils.mock_base_client import MockBaseClient
###################################... |
57430 | import codecs
import importlib
import logging
import os
import sys
import time
import html
import accounts
import config
import log
import storage
from args import args
from vkapi import VkApi
from vkbot import createVkApi
from scripts import runScript, runInMaster
os.chdir(os.path.dirname(os.path.realpath(sys.argv[... |
57502 | import cv2
import numpy as np
thres = 0.45
nms_threshold = 0.2
#Default Camera Capture
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
cap.set(10, 150)
##Importing the COCO dataset in a list
classNames= []
classFile = 'coco.names'
with open(classFile,'rt') as f:
classNames = f.read().rstrip('\n').spli... |
57507 | from openmdao.api import ExplicitComponent
from gebtaero import *
import numpy as np
class SouplesseMat(ExplicitComponent):
def setup(self):
self.add_input('El',val=125e9,units='Pa')
self.add_input('Et',val=9.3e9,units='Pa')
self.add_input('Nult',val=0.28)
self.add_input('Glt',... |
57536 | import torch
import torch.nn as nn
from torch.nn import Parameter as P
from torchvision.models.inception import inception_v3
import torch.nn.functional as F
# Module that wraps the inception network to enable use with dataparallel and
# returning pool features and logits.
class WrapInception(nn.Module):
def __init... |
57543 | import tensorflow as tf
def maxPoolLayer(x, ksize, stride, padding='VALID', name=None):
return tf.nn.max_pool(x,
ksize=[1, ksize, ksize, 1],
strides=[1, stride, stride, 1],
padding=padding,
name=name)
def LRN... |
57580 | import pandas as pd
import time
from contextlib import contextmanager
from tqdm import tqdm
tqdm.pandas()
# nice way to report running times
@contextmanager
def timer(name):
t0 = time.time()
yield
print(f'[{name}] done in {time.time() - t0:.0f} s')
def get_named_entities(df):
"""
Count the name... |
57601 | import numpy as np
import sys,os,glob
######################################### INPUT ########################################
root = '/simons/scratch/fvillaescusa/pdf_information/Pk'
folders = ['Om_p', 'Ob_p', 'Ob2_p', 'h_p', 'ns_p', 's8_p',
'Om_m', 'Ob_m', 'Ob2_m', 'h_m', 'ns_m', 's8_m',
'Mnu_p... |
57608 | from copy import deepcopy
from logics.utils.parsers import parser_utils
from logics.classes.exceptions import NotWellFormed
from logics.classes.predicate import PredicateFormula
from logics.utils.parsers.standard_parser import StandardParser
class PredicateParser(StandardParser):
"""Parser for predicate language... |
57639 | import hashlib
import os
import pickle
from zoltpy.quantile_io import json_io_dict_from_quantile_csv_file
from zoltpy import util
from zoltpy.connection import ZoltarConnection
from zoltpy.covid19 import COVID_TARGETS, covid19_row_validator, validate_quantile_csv_file
import glob
import json
import sys
UPDATE = False
... |
57653 | import MetaTrader5 as _mt5
from collections import namedtuple
from typing import Callable
from typing import Iterable
from typing import Tuple
from typing import Union
from typing import Any
from typing import Optional
from typing import Type
# custom namedtuples
CopyRate = namedtuple("CopyRate", "time, open, high, l... |
57667 | import torch
from torch.nn.functional import leaky_relu
from rational.torch import Rational
import numpy as np
t = torch.tensor([-2., -1, 0., 1., 2.])
expected_res = np.array(leaky_relu(t))
inp = torch.from_numpy(np.array(t)).reshape(-1)
cuda_inp = torch.tensor(np.array(t), dtype=torch.float, device="cuda").reshape(-... |
57676 | import random as random_lib
import copy
from opsbro.evaluater import export_evaluater_function
FUNCTION_GROUP = 'random'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def random():
"""**random()** -> Returns a random float between 0 and 1
<code>
Example:
random()
Returns:
... |
57681 | import locale
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
import tornado.options
import json
import ipaddress
import functools
import subprocess
import user_agents
from collections import namedtuple
import models
import dispatch
import en... |
57704 | FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/"
LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels"
SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"
COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.c... |
57736 | import click
import os
import yaml
from panoptes_client import Panoptes
@click.version_option(prog_name='Panoptes CLI')
@click.group()
@click.option(
'--endpoint',
'-e',
help="Overides the default API endpoint",
type=str,
)
@click.option(
'--admin',
'-a',
help=(
"Enables admin mode... |
57765 | from torchvision import models
import numpy as np
import torch
import os
from moviepy.editor import VideoFileClip
SKIP_FRAME_RATE = 10
MINIMAX_FRAME = 4
# 함수에서 documentaiton 읽기
model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
model.eval()
os.environ['KMP_DUPLICATE_LIB_OK']='True'
def extract_boxes(re... |
57775 | from common.BaseCommand import BaseCommand
from common.ResultAndData import *
from models.CalEvent import CalEvent
import argparse
from argparse import Namespace
from msgraph import helpers
from tabulate import tabulate
import datetime
import os
class WeekCommand(BaseCommand):
def add_parser(self, sub... |
57778 | from fastapi.routing import APIRouter
from lnbits.db import Database
db = Database("database")
core_app: APIRouter = APIRouter()
from .views.api import * # noqa
from .views.generic import * # noqa
from .views.public_api import * # noqa
|
57832 | from __future__ import division, absolute_import, print_function
from .prototype import *
from .repeating import *
|
57838 | from ..tweet_sentiment_classifier import Classifier, tokenizer_filter
import pickle as pkl
import numpy as np
import json
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection i... |
57857 | import numpy as np
arr = np.array([[2, 5], [1, 3]])
arr_inv = np.linalg.inv(arr)
print(arr_inv)
# [[ 3. -5.]
# [-1. 2.]]
mat = np.matrix([[2, 5], [1, 3]])
mat_inv = np.linalg.inv(mat)
print(mat_inv)
# [[ 3. -5.]
# [-1. 2.]]
mat_inv = mat**-1
print(mat_inv)
# [[ 3. -5.]
# [-1. 2.]]
mat_inv = mat.I
print(mat_... |
57868 | import os
import time
import subprocess
import pyblish.api
class MyAction(pyblish.api.Action):
label = "My Action"
on = "processed"
def process(self, context, plugin):
self.log.info("Running!")
class MyOtherAction(pyblish.api.Action):
label = "My Other Action"
def process(self, contex... |
57908 | EVENT_ALGO_LOG = "eAlgoLog"
EVENT_ALGO_SETTING = "eAlgoSetting"
EVENT_ALGO_VARIABLES = "eAlgoVariables"
EVENT_ALGO_PARAMETERS = "eAlgoParameters"
APP_NAME = "AlgoTrading"
|
57916 | from django.shortcuts import render
from django.http import HttpResponse
# Include the `fusioncharts.py` file which has required functions to embed the charts in html page
from ..fusioncharts import FusionCharts
from ..fusioncharts import FusionTable
from ..fusioncharts import TimeSeries
import requests
# Loading Dat... |
57917 | from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='pymixconsole',
version='0.0.1',
description='Headless multitrack mixing console in Python',
long_description=long_description,
long_description_content_type="text/markdow... |
57947 | import qq
class MyClient(qq.Client):
async def on_ready(self):
print(f'以 {self.user} 身份登录(ID:{self.user.id})')
print('------')
async def on_message(self, message):
# 我们不希望机器人回复自己
if message.author.id == self.user.id:
return
if message.content.startswith('!... |
57983 | from tests.unit import base
from src import database
class AppActiveRepositoryTest(base.TestCase):
def test_has_db(self):
self.assertTrue(hasattr(database.AppActiveRepository, 'db'))
def test_has_db_default_none(self):
# TODO: How to test this? Because the import of initialize on test base m... |
58001 | def incrementing_time(start=2000, increment=1):
while True:
yield start
start += increment
def monotonic_time(start=2000):
return incrementing_time(start, increment=0.000001)
def static_time(value):
while True:
yield value
|
58039 | from typing import List
class ReportIndice():
def __init__(self, alias, nombre, tipo,columnas:List[str], consideracion, fila, columna):
self.alias = alias
self.nombre = nombre
self.tipo = tipo
self.columnas:List[str] = columnas
self.consideracion = consideracion
s... |
58064 | from typing import Optional
import pandas as pd
from episuite import data
class GoogleMobility:
"""This is a class implementing a client for the Google
Community Mobility Reports.
.. seealso::
`Google Community Mobility Report <https://www.google.com/covid19/mobility/>`_
Community M... |
58090 | import os
import re
import time
import shutil
from tempfile import mkdtemp
import operator
from collections.abc import Mapping
from pathlib import Path
import datetime
from .log import Handle
logger = Handle(__name__)
_FLAG_FIRST = object()
class Timewith:
def __init__(self, name=""):
"""Timewith contex... |
58108 | import sys
sys.path.append('../../')
import keras2caffe
DATA_DIR='../../data/'
import caffe
import cv2
import numpy as np
import sys
sys.path.append('/media/toshiba_ml/models/keras-models/keras-squeezenet')
from keras_squeezenet import SqueezeNet
#TensorFlow backend uses all GPU memory by default, so we need limit... |
58123 | import sys
#print sys.argv[0], len( sys.argv )
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f_in:
result = 0
for line in f_in:
data = line.strip().split()
# print('data:', data)
if data[0] == "+":
result += float(data[1])
... |
58174 | import sys
class CommandError(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
class BaseCommand:
def run(self):
parser = self.get_optparser()
(options, names) = parser.parse_args()
try:
self.handle(names, options)
... |
58175 | import pytest
# from https://github.com/ethereum/tests/blob/c951a3c105d600ccd8f1c3fc87856b2bcca3df0a/BasicTests/txtest.json # noqa: E501
TRANSACTION_FIXTURES = [
{
"chainId": None,
"key": "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4",
"nonce": 0,
"gasPrice": 1... |
58189 | import tarfile
import os
tar_content_files = [ {"name": "config", "arc_name": "config"},
{"name": "out/chart-verifier", "arc_name": "chart-verifier"} ]
def create(release):
tgz_name = f"chart-verifier-{release}.tgz"
if os.path.exists(tgz_name):
os.remove(tgz_name)
with tarfile.ope... |
58193 | import numpy as np
import pandas as pd
import pytest
from sklearn.base import is_classifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import OneHotEncoder
from sklearndf.classification import RandomForestClassifierDF
from sklearndf.pipeline import ClassifierPipelineDF
from test.skl... |
58197 | from yaml.serializer import Serializer as YamlSerializer
from yaml.events import DocumentStartEvent, DocumentEndEvent
# override serialzier class to store data needed
# for extra data on anchor lines
class Serializer(YamlSerializer):
def __init__(self, encoding=None,
explicit_start=None, explicit_end=... |
58230 | from librosa import cqt, icqt
import numpy as np
def gl_cqt(S, n_iter=32, sr=22050, hop_length=512, bins_per_octave=12, fmin=None, window='hann',
dtype=np.float32, length=None, momentum=0.99, random_state=None, res_type='kaiser_fast'):
if fmin is None:
fmin = librosa.note_to_hz('C1')
... |
58263 | import math
import numpy
def hill_chart_parametrisation(h, turbine_specs):
"""
Calculates power and flow rate through bulb turbines based on Aggidis and Feather (2012)
f_g = grid frequency, g_p = generator poles,
t_cap = Turbine capacity, h = head difference, dens = water density
"""
turb_sp ... |
58406 | import numpy as np
import pathlib
import Vox
import os
import sys
sys.path.append("../base")
import JSONHelper
def save_output(batch_size, rootdir, samples, outputs, is_testtime=False):
for i in range(batch_size):
is_match = outputs["match"][i].item()
if True:
sdf_scan = samples["sdf... |
58441 | from SEAL import SplineSpace, create_knots
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
p = 2
n = 10
t = create_knots(0, 1, p, n)
S = SplineSpace(p, t)
c = [(0, 1, 0), (1, 2, 1), (1.5, 3, 2), (1.7, -1, 3), (1, -1.5, 4), (3, 3, 3), (4, 4, 3), (5, 2, 2), (6, 5, 4), (7, -1, 5)]
f = S(c)
x = S.... |
58460 | from base64 import b64encode
def get_token(custos_settings):
tokenStr = custos_settings.CUSTOS_CLIENT_ID + ":" + custos_settings.CUSTOS_CLIENT_SEC
tokenByte = tokenStr.encode('utf-8')
encodedBytes = b64encode(tokenByte)
return encodedBytes.decode('utf-8')
|
58514 | from kairon import cli
import logging
if __name__ == "__main__":
logging.basicConfig(level="DEBUG")
cli()
|
58524 | import sys
import pyshorteners
def shorten_url(url):
s = pyshorteners.Shortener()
short_url = s.tinyurl.short(url)
return short_url
def get_code(authorize_url):
sys.stderr.write("\x1b[2J\x1b[H")
short_url = shorten_url(authorize_url)
"""Show authorization URL and return the code the user wrote... |
58611 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
k %= len(nums)
if k > 0:
for i, v in enumerate(nums[-k:] + nums[0:-k]):
nums[i] = v
|
58615 | import pathlib
import typing
import urllib.parse
_PLUGIN_DIR = pathlib.Path(__file__).parent
PLUGIN_DIR = str(_PLUGIN_DIR)
CONFIGS_DIR = str(_PLUGIN_DIR.joinpath('configs'))
SCRIPTS_DIR = str(_PLUGIN_DIR.joinpath('scripts'))
def scan_sql_directory(root: str) -> typing.List[pathlib.Path]:
return [
path
... |
58696 | from __future__ import print_function
import os
from setuptools import setup, find_packages
here = os.path.dirname(os.path.abspath(__file__))
node_root = os.path.join(here, 'js')
is_repo = os.path.exists(os.path.join(here, '.git'))
from distutils import log
log.set_verbosity(log.DEBUG)
log.info('setup.py ... |
58702 | from . import halos as hal
from .pyutils import deprecated
@deprecated(hal.HaloProfileNFW)
def nfw_profile_3d(cosmo, concentration, halo_mass, odelta, a, r):
"""Calculate the 3D NFW halo profile at a given radius or an array of radii,
for a halo with a given mass, mass definition, and concentration,
at a ... |
58708 | import numpy as np
import json
from os.path import join
from tqdm import tqdm
from scipy.optimize import least_squares
from pose_optimize.multiview_geo import reproject_error
DEBUG=False
def reproject_error_loss(p3d, p4, p6, cam_proj_4, cam_proj_6, num_kpt=23):
'''
Return:
kp4_e, kp6_e: error array, ... |
58765 | from django.conf import settings
from rest_framework.permissions import IsAdminUser
from rest_framework import status, viewsets, decorators
from quser.permissions import CURDPermissionsOrReadOnly
from rest_framework.response import Response
from . import models, serializers
from .filters import FileFilter
class TagV... |
58780 | from django.conf.urls.defaults import patterns, url, include
from pycash.controllers import TaxController as controller
urlpatterns = patterns('',
(r'^upcomingList$', controller.upcomingList),
(r'^upcoming$', controller.upcoming),
url(r'^pay$', controller.pay, name="tax_pay"),
(r'^list$', controller.li... |
58818 | import sphinx_rtd_theme
project = 'Bitcoin DCA'
copyright = '2021, <NAME>'
author = '<NAME>'
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
pygments_style = 'sphinx'
html_theme_path = [sphinx_rtd_the... |
58829 | from typing import Optional
class TransactionFailedError(Exception):
"""
Base exception for transaction failure
"""
def __init__(
self,
code: Optional[str] = None,
message: Optional[str] = "Unknown starknet error",
):
self.code = code
self.message = message... |
58838 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def loss2(logits, labels, num_classes, scope, head=None):
with tf.name_scope(scope):
logits = tf.reshape(logits, (-1, num_classes))
softmax = tf.nn.softmax(logits) + ... |
58865 | import json
import logging
import os
import re
from collections import namedtuple
from copy import deepcopy
from typing import Any, Dict, List, Tuple
import numpy as np
import pandas as pd
import spacy
from scirex_utilities.analyse_pwc_entity_results import *
from scirex_utilities.entity_utils import *
from spacy.toke... |
58906 | from .parseexp_koff_a import get as get_a
from .parseexp_koff_b import get as get_b
from .parseexp_koff_c import get as get_c
def parse_exp(input_str):
index_a = get_a(input_str)
index_b = get_b(input_str)
index_c = get_c(input_str)
return list(map(float, [index_a, index_b, index_c]))
|
58915 | import sys
import os
from PyQt5.QtWidgets import (QTabWidget, QMessageBox)
from codeeditor import CodeEditor
from widgets import MessageBox
class TabWidget(QTabWidget):
def __init__(self, parent=None):
super().__init__()
self.mainWindow = parent
self.setStyleSheet(
''... |
58924 | import copy as _copy
import math as _math
import os as _os
import cv2 as _cv2
import numpy as _np
from PIL import Image as _IMG
from easytorch.utils.logger import *
"""
##################################################################################################
Very useful image related utilities
##############... |
58930 | from zeus.config import db
from zeus.db.mixins import ApiTokenMixin, RepositoryMixin, StandardAttributes
from zeus.db.utils import model_repr
class RepositoryApiToken(StandardAttributes, RepositoryMixin, ApiTokenMixin, db.Model):
"""
An API token associated to a repository.
"""
__tablename__ = "repos... |
58934 | from .__version__ import __description__, __title__, __version__
from ._exceptions import LifespanNotSupported
from ._manager import LifespanManager
__all__ = [
"__description__",
"__title__",
"__version__",
"LifespanManager",
"LifespanNotSupported",
]
|
58969 | import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.cross_validation import train_test_split
import theanets
import climate
climate.enable_default_logging()
X_orig = np.load('/Users/bzamecnik/Documents/music-processing/music-processing-experiments/c-scale-piano_spectrogram_2... |
59021 | from di.container import Container
from di.dependant import Dependant, Injectable
from di.executors import SyncExecutor
class UsersRepo(Injectable, scope="app"):
pass
def endpoint(repo: UsersRepo) -> UsersRepo:
return repo
def framework():
container = Container()
solved = container.solve(
... |
59059 | from LoopStructural.utils import LoopImportError, LoopTypeError, LoopValueError
try:
from LoopProjectFile import ProjectFile
except ImportError:
raise LoopImportError("LoopProjectFile cannot be imported")
from .process_data import ProcessInputData
import numpy as np
import pandas as pd
import networkx
from L... |
59079 | from twisted.internet import reactor
from twisted.trial import unittest
from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint
class coerce_to_client_endpoint_TestCase(unittest.TestCase):
HOST, PORT, DEFAULT_PORT = "test", 1234, 4321
def test_good_tcp_parse(self):
ep = coerce... |
59119 | from unittest.mock import patch
import slack
from harvey.messages import Message
@patch('harvey.messages.SLACK_CHANNEL', 'mock-channel')
@patch('harvey.messages.SLACK_BOT_TOKEN', '<PASSWORD>')
@patch('logging.Logger.debug')
@patch('slack.WebClient.chat_postMessage')
def test_send_slack_message_success(mock_slack, m... |
59139 | from __future__ import division
import os
import cv2 as cv
import numpy as np
from cv_bridge import CvBridge
def map_linear(value, in_min, in_max, out_min, out_max):
return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def process_image(img, equalize_hist=False):
gray = cv.cvtColor(... |
59142 | import json
import logging
import tempfile
import shapely.geometry as sgeo
import shapely.ops as ops
from pyproj.crs import CRS
from pywps import FORMATS, ComplexOutput, LiteralInput, Process
from ravenpy.utilities.analysis import dem_prop
from ravenpy.utilities.checks import boundary_check, single_file_check
from rav... |
59176 | from hashlib import blake2s
def hash(x):
return blake2s(x).digest()[:32]
def get_primes(givenNumber):
# Initialize a list
primes = []
for possiblePrime in range(2, givenNumber + 1):
# Assume number is prime until shown it is not.
isPrime = True
for num in range(2, int(possibleP... |
59180 | import magma as m
import magma.testing
def test_2d_array_from_verilog():
main = m.define_from_verilog(f"""
module transpose_buffer (
input logic clk,
output logic [2:0] index_inner,
output logic [2:0] index_outer,
input logic [3:0] input_data [63:0],
input logic [2:0] range_inner,
input logic [2:0] ra... |
59184 | import torch
import os
from glob import glob
import numpy as np
from torch.nn import functional as F
import time
class Generator(object):
def __init__(self, model, exp_name, threshold = 0.1, checkpoint = None, device = torch.device("cuda")):
self.model = model.to(device)
self.model.eval()
s... |
59194 | import numpy as np
def process_actions(actions, l_action):
n_steps = len(actions)
actions_1hot = np.zeros([n_steps, l_action], dtype=int)
actions_1hot[np.arange(n_steps), actions] = 1
return actions_1hot
def get_action_others_1hot(action_all, agent_id, l_action):
action_all = list(a... |
59210 | import pandas as pd
import os, sys
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
from sklearn.utils import check_array
import numpy as np
from datetime import timedelta
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))+'/'
def mean_absolute_pe... |
59227 | import bourgeon
import ragnarok_client as client
from bourgeon import ui
from ragnarok_client import Mode
class BasicInfoWindow:
def __init__(self, name: str) -> None:
self._hp_text = ui.Text("--")
self._sp_text = ui.Text("--")
self.window = ui.Window(name, [[
ui.Text("HP"),
... |
59250 | import os
import ssl
import socket
from tempfile import NamedTemporaryFile
try:
from httplib import HTTPSConnection
except ImportError:
from http.client import HTTPSConnection
class ValidatedHTTPSConnection(HTTPSConnection):
CA_ROOT_CERT_FALLBACK = '''
DigiCert Global Root G2
-----BEGIN ... |
59449 | pkgname = "firmware-ipw2100"
pkgver = "1.3"
pkgrel = 0
pkgdesc = "Firmware for the Intel PRO/Wireless 2100 wifi cards"
maintainer = "q66 <<EMAIL>>"
license = "custom:ipw2100"
url = "http://ipw2100.sourceforge.net"
source = f"http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz"
sha256 = "e1107c455e48d324a6... |
59493 | import torch
import numpy as np
import torch.nn as nn
import torch.distributed as dist
import torch.nn.functional as F
from torch import Tensor
from typing import Any
from typing import Dict
from typing import Tuple
from typing import Optional
from cftool.misc import update_dict
from cftool.misc import shallow_copy_d... |
59494 | from __future__ import absolute_import
# external modules
from past.builtins import basestring
import numpy as num
# ANUGA modules
import anuga.utilities.log as log
from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a, \
netcdf_float
from .asc2dem import asc2dem
... |
59502 | from typing import List
import pytest
from pathlib import Path
from graphtik.sphinxext import DocFilesPurgatory, _image_formats
@pytest.fixture
def img_docs() -> List[str]:
return [f"d{i}" for i in range(3)]
@pytest.fixture
def img_files(tmpdir) -> List[Path]:
files = [tmpdir.join(f"f{i}") for i in range(... |
59507 | from collections import namedtuple
from itertools import chain
from typing import List, Dict, Tuple, Any
from valacefgen import utils
from valacefgen.vala import VALA_TYPES, VALA_ALIASES, GLIB_TYPES
TypeInfo = utils.TypeInfo
EnumValue = namedtuple("EnumValue", 'c_name vala_name comment')
class Type:
def __init_... |
59523 | import pytest
import tempfile
import os
import io
import logging
from cellpy import log
from cellpy import prms
from cellpy import prmreader
from . import fdv
log.setup_logging(default_level="DEBUG")
config_file_txt = """---
Batch:
color_style_label: seaborn-deep
dpi: 300
fig_extension: png
figure_type: unlim... |
59539 | import asyncio
class Barrier(object):
def __init__(self, parties, action=lambda: None):
self._parties = parties
self._action = action
self._cond = asyncio.Condition()
self._count = 0
async def wait(self):
self._count += 1
with (await self._cond):
if... |
59550 | import datetime
import json
from nameko.events import EventDispatcher, event_handler
from simplebank.chassis import init_logger, init_statsd
class FeesService:
name = "fees_service"
statsd = init_statsd('simplebank-demo.fees', 'statsd')
logger = init_logger()
@event_handler("market_service", "order... |
59680 | import sys
sys.path.append('..')
import torch as th
import torch.nn as nn
import geoopt as gt
from util.hyperop import *
class hyperRNN(nn.Module):
def __init__(self, input_size, hidden_size, d_ball, default_dtype=th.float64):
super(hyperRNN, self).__init__()
self.input_size = inp... |
59686 | from threading import Lock
from typing import Dict, Set, Union
from zemberek.core.turkish.phonetic_attribute import PhoneticAttribute
class AttributeToSurfaceCache:
def __init__(self):
self.attribute_map: Dict[int, str] = {}
self.lock = Lock()
def add_surface(self, attributes: Set[PhoneticA... |
59691 | from .embedding.pca import run_pca
from .embedding.umap import run_umap
from .embedding.ica import run_ica
# from .embedding.scvi import run_ldvae
from .embedding.fa import run_fa
from .embedding.diffmap import run_diffmap
|
59724 | import click
import svdtools
@click.group()
@click.version_option(svdtools.__version__, prog_name="svdtools")
def svdtools_cli():
pass
@click.command()
@click.argument("yaml-file")
def patch(yaml_file):
"""Patches an SVD file as specified by a YAML file"""
svdtools.patch.main(yaml_file)
@click.comman... |
59776 | from flask import g, current_app, jsonify
from sqlalchemy import asc, desc, func
from apps.interface.models.interfaceapimsg import InterfaceApiMsg
from apps.interface.models.interfacecase import InterfaceCase
from apps.interface.models.interfacemodule import InterfaceModule
from apps.interface.models.interfaceproject ... |
59811 | from django import template
register = template.Library()
@register.simple_tag
def format_date_range(date_from, date_to, separator=" - ",
format_str="%B %d, %Y", year_f=", %Y", month_f="%B", date_f=" %d"):
""" Takes a start date, end date, separator and formatting strings and
returns a pretty date ran... |
59815 | from typing import Optional
from infrastructure.cqrs.decorators.requestclass import requestclass
from domain.common.request_parameter.OrderByParameter import OrderByParameter
from domain.common.request_parameter.PagingParameter import PagingParameter
@requestclass
class GetDataOperationJobListRequest(PagingParameter... |
59872 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
import json
import os
import codecs
from collections import Counter
import numpy as np
import tensorflow as tf
from parser.structs.vocabs.base_vocabs import CountVocab
from parser.struc... |
59876 | from __future__ import print_function, absolute_import
import os.path as osp
import numpy as np
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json, read_json
from ..utils.data.dataset import _pluck
class SynergyReID(Dataset):
md5 = '05050b5d... |
59908 | from pathlib import Path
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "very-secret"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3"}}
ROOT_URLCONF = "tests.urls"
DJANGO_APPS = [
"django.contrib.admin",
"djan... |
59920 | import pickle
import pandas as pd
method_columns = ['model_class', 'config', 'loss_function', 'q_dist', 'sample_from_q',
'detach', 'add_noise', 'noise_type', 'warm_up', 'is_loaded', 'method_name']
hparam_columns = ['grad_l1_penalty', 'grad_weight_decay',
'lamb', 'loss_function_par... |
60006 | from datetime import datetime, date
from marqeta.response_models import datetime_object
import json
import re
class Pos(object):
def __init__(self, json_response):
self.json_response = json_response
def __str__(self):
return json.dumps(self.json_response, default=self.json_serial)
@stati... |
60011 | import numpy as np
from deap import benchmarks
from BayesOpt import BO
from BayesOpt.Surrogate import RandomForest
from BayesOpt.SearchSpace import ContinuousSpace, OrdinalSpace, NominalSpace
from BayesOpt.base import Solution
np.random.seed(42)
def obj_func(x):
x_r, x_i, x_d = np.array(x[:2]), x[2], x[3]
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.