id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11498706 | import math
import time
# TODO add Color() and simplify code (create rainbow once, then move it)
class RainbowAnimation:
def __init__(self,
led_strip,
brightness=1,
loop_limit=None,
duration_ms=1000,
pause_ms=None):
self... |
11498721 | class Scale(object):
# 常用的字母代表数字的字典
dic = {'10': 'A',
'11': 'B',
'12': 'C',
'13': 'D',
'14': 'E',
'15': 'F'}
# 将weight进制的某一位的值对应的十进制的值算出来
@staticmethod
def place_value(n_value, scale, digits):
# 某一位的权值,初始为1
weight = 1
fo... |
11498732 | import tensorflow as tf
import numpy as np
import math
from tensorflow.python.util import nest
tf.set_random_seed(20160408)
# log probability
def probability(min_embed, max_embed):
# min_embed: batchsize * embed_size
# max_embed: batchsize * embed_size
# log_prob: batch_size
# numerically stable log pr... |
11498736 | from seamless.highlevel import Context, Cell
ctx = Context()
ctx.v = "test"
ctx.v_schema = Cell()
ctx.v_schema.celltype = "plain"
ctx.translate()
ctx.link(ctx.v.schema, ctx.v_schema)
ctx.translate()
ctx.v_schema.set({'type': 'integer'})
ctx.compute()
print(ctx.v.schema)
print("*" * 50)
print(ctx.v.exception)
print("*"... |
11498746 | import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.models.vgg import vgg19
from nets.srgan import Discriminator, Generator
from utils.dataloader import SRGAN_dataset_collate, SRGANDatas... |
11498789 | import numpy as np
try:
from utils.darts_utils import compute_latency_ms_tensorrt as compute_latency
print("use TensorRT for latency test")
except:
from utils.darts_utils import compute_latency_ms_pytorch as compute_latency
print("use PyTorch for latency test")
import torch
import torch.nn as nn
import... |
11498856 | import math
from functools import reduce
from internal import utility as utility
from internal.terrain.cloud import Cloud
class Weather:
def __init__(self, cells, parent):
self.cells = cells
self.water_cells = []
self.clouds = []
self.cells_x = utility.S_WIDTH // utility.CELL_S... |
11498862 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
return self.val == other.val and self.next == other.next
def __repr__(self):
return '<Node {} {}>'.format(self.val, self.next)
class LinkedList(ListNode):
def __init__(self, ... |
11498886 | from matplotlib import gridspec
from matplotlib import pyplot
import skimage.transform
import numpy
def create_pascal_label_colormap():
"""Creates a label colormap used in PASCAL VOC segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
colormap = numpy.zeros((... |
11498907 | import unittest
import tempfile
import os
import caffe
class ElemwiseScalarLayer(caffe.Layer):
"""A layer that just multiplies by ten"""
def setup(self, bottom, top):
self.layer_params_ = eval(self.param_str_)
self.value_ = self.layer_params_['value']
if self.layer_params_['op'].lowe... |
11498922 | import torch
import torch.nn as nn
import torch.nn.functional as F
from builtins import NotImplementedError
from mmcv.cnn import kaiming_init, normal_init, trunc_normal_init
from ..utils import accuracy, accuracy_mixup
from ..registry import HEADS
from ..builder import build_loss
@HEADS.register_module
class ClsMixu... |
11498927 | import logging
from uuid import UUID
from typing import List
from sqlalchemy import select, func, desc, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from acapy_client.api.revocation_api import RevocationApi
from acapy_client.model.revoke_request import RevokeRequest
f... |
11498936 | from typing import Optional, Sequence, TypeVar, Union, cast
import numpy as np
from rpcq.messages import ParameterAref
from pyquil.api._qam import QAM, QAMExecutionResult, QuantumExecutable
T = TypeVar("T")
class StatefulQAM(QAM[T]):
_loaded_executable: Optional[QuantumExecutable]
_result: Optional[QAMExecu... |
11498942 | import sys
import binascii
import socket
import struct
def ip_to_hex(ip):
return binascii.hexlify(socket.inet_aton(ip)).decode('utf-8')
def carry_around_add(a, b):
c = a + b
return (c & 0xffff) + (c >> 16)
def compute_checksum(data):
s = 0
for i in range(0, len(list(data)), 2):
w = ord(da... |
11498951 | c = get_config()
c.ServePostProcessor.ip = u'*'
c.ServePostProcessor.port = 8000
c.ServePostProcessor.open_in_browser = False
|
11498976 | import numpy as np
friends_details_dtypes = {
"contributors_enabled": np.int8,
"created_at": np.datetime64,
"default_profile": np.int8,
"default_profile_image": np.int8,
"description": str,
"entities_description_urls": str,
"entities_url_urls": str,
"favourites_count": np.int64,
"f... |
11498983 | from server import db, bcrypt
from server.models.orm import TeacherModel
from server.config import RestErrors
import email_validator
from datetime import datetime
import os
from werkzeug.datastructures import FileStorage
from server.parsing import parser
from server.parsing.utils import create_chat_df, create_students_... |
11498996 | import copy
import time
import joblib
from functools import wraps
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.cluster import KMeans
# from sklearn.externals import joblib as skjoblib
from sklearn.preprocessing i... |
11499006 | import numpy as np
'''
See paper: Sensors 2018, 18(4), 1055; https://doi.org/10.3390/s18041055
"Divide and Conquer-Based 1D CNN Human Activity Recognition Using Test Data Sharpening"
by <NAME> & <NAME>
This code checks the data size & activity label constitution of the
Opportunity UCI Dataset data used in the exper... |
11499007 | from wolframclient.evaluation import WolframLanguageSession
import logging
# set the root level to INFO
logging.basicConfig(level=logging.INFO)
try:
session = WolframLanguageSession()
# this will trigger some log messages with the process ID, the sockets
# address and the startup timer.
session.start(... |
11499022 | from mock import Mock, patch, call
from sqlalchemy import Column, String, Integer, Table, MetaData
from monitorrent.db import DBSession
from monitorrent.upgrade_manager import core_upgrade, upgrade, _operation_factory
from tests import UpgradeTestCase
class CoreUpgradeTest(UpgradeTestCase):
def upgrade_func(self,... |
11499025 | from chalice import Blueprint
from chalicelib import _overrides
from chalicelib.blueprints import bp_authorizers
from chalicelib.utils import assist_helper
app = Blueprint(__name__)
_overrides.chalice_app(app)
@app.route('/v1/assist/credentials', methods=['GET'], authorizer=bp_authorizers.api_key_authorizer)
def ge... |
11499027 | import pytest
from tinkoff.dolyame import Dolyame
pytestmark = [pytest.mark.django_db]
@pytest.fixture(autouse=True)
def _credentials(settings):
settings.DOLYAME_LOGIN = 'root'
settings.DOLYAME_PASSWORD = '<PASSWORD>'
settings.DOLYAME_CERTIFICATE_PATH = 'tinkoff/tests/.fixtures/testing.pem'
@pytest.fi... |
11499050 | REGION = 'us-east-1'
SEARCH_CHECKPOINT_TABLE_NAME = 'Checkpoint'
SEARCH_TEXT = '#searchtext'
TWEET_PROCESSOR_FUNCTION_NAME = 'TweetProcessor'
BATCH_SIZE = '2'
STREAM_MODE_ENABLED = 'false'
SSM_PARAMETER_PREFIX = 'ssm_prefix'
CONSUMER_KEY = 'key'
CONSUMER_SECRET = 'secret'
ACCESS_TOKEN = 'token'
ACCESS_TOKEN_SECRET = '... |
11499085 | import sys,os,argparse
import torch
# Arguments
parser=argparse.ArgumentParser(description='Renaming script (runs over preprocessed files)')
parser.add_argument('--dataset',type=str,required=True,help='(default=%(default)s)',
choices=['vctk','librispeech','nsynthp'])
parser.add_argument('--path',de... |
11499115 | import torch
import torch.nn as nn
import torch.nn.functional as F
from model.bert_things.pytorch_pretrained_bert import BertConfig, BertModel, BertPreTrainedModel
import numpy as np
class BertTextModel(BertPreTrainedModel):
def __init__(self, config):
super(BertTextModel, self).__init__(config)
se... |
11499142 | import cli_parser
import json
from file_operations import load_bookmarks_file
from file_operations import write_to_file
from deduplicator_utils import deduplicate
from deduplicator_utils import directory_merge
from fetch import get_bookmarks_from_toolbar
from fetch import get_bookmarks_from_menu
from fetch import get_b... |
11499145 | from urllib.parse import quote
from django.conf import settings
from django.conf.urls import include, url
from django.shortcuts import render
from django.urls.conf import path
from django.views.static import serve
def seo(request, su, huasu=None, im=None):
return pangboo(
request, status=200,
tit... |
11499243 | from py_tests_common import *
def CharLiteral_Test0():
c_program_text= """
// short-form literal
static_assert( "str"[1u] == "t"c8 );
"""
tests_lib.build_program( c_program_text )
def CharLiteral_Test1():
c_program_text= """
// short-form literal, type is char16
var char16 constexpr c= "Ё"c16;
static_... |
11499294 | from spartan import expr, util
from spartan.examples.als import als
import test_common
from test_common import millis
from datetime import datetime
<EMAIL>
#def test_als(ctx):
def benchmark_als(ctx, timer):
print "#worker:", ctx.num_workers
#USER_SIZE = 100 * ctx.num_workers
USER_SIZE = 320
#USER_SIZE = 200 * ... |
11499299 | import json
import os
import re
import sys
from typing import List, Dict
from collections import OrderedDict, defaultdict
from rapidstream.BE.Device import U250
class TimingReportParser:
def __init__(self, direction: str, timing_report_path: str) -> None:
"""
direction: Literal['to_anchor', 'from_anchor']... |
11499381 | from pysoa.common.transport.redis_gateway.constants import REDIS_BACKEND_TYPE_STANDARD
SOA_SERVER_SETTINGS = {
'heartbeat_file': '/srv/echo_service-{{fid}}.heartbeat',
'middleware': [], # TODO
'transport': {
'path': 'pysoa.common.transport.redis_gateway.server:RedisServerTransport',
'kwarg... |
11499384 | import requests, re, json
from colorama import init, Fore, Back, Style
from terminaltables import SingleTable
warning = "["+Fore.RED+"!"+Fore.RESET+"]"
question = "["+Fore.YELLOW+"?"+Fore.RESET+"]"
found = "["+Fore.GREEN+"+"+Fore.RESET+"]"
wait = "["+Fore.MAGENTA+"*"+Fore.RESET+"]"
def bssidFinder():
bssid = input... |
11499385 | import json
import json.decoder
import logging
import os
from copy import deepcopy
from functools import wraps
from typing import Callable, Dict, Final, Optional
import click
import docker
from alembic import __version__ as __alembic_version__
from alembic.config import Config as AlembicConfig
from .utils import buil... |
11499405 | def get_sp(key, default_value=None):
accessed(key)
property_value = sys_prop.get(key)
return default_value if property_value is None else property_value
|
11499435 | from __future__ import division
from __future__ import print_function
from past.utils import old_div
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm
# In this test, I will check and make sure the scoring history me... |
11499461 | import peewee
import sqlite3
import Peewee
import PeeweeLocation
import PeeweeEpisode
import pprint
import ClaseCharacter
import ClaseLocation
import ClaseEpisode
def get_personajes():
char = Peewee.CharacterP.select(Peewee.CharacterP.id,Peewee.CharacterP.name,Peewee.CharacterP.status,Peewee.CharacterP.species,Pe... |
11499473 | from espnet2.torch_utils.pytorch_version import pytorch_cudnn_version
def test_pytorch_cudnn_version():
print(pytorch_cudnn_version())
|
11499479 | from multiprocessing import Process
from time import sleep
import webview
from server import serve
from http.client import HTTPConnection
# Constants
HOST = 'localhost'
PORT = 37128
URL = f'http://{HOST}:{PORT}'
# Server
server = Process(target=serve)
# Frontend
webview.create_window(
'Junction',
f'http://... |
11499480 | import argparse
import math
import random
import sys
import os
import json
import numpy as np
import time
import operator
scatter_word_list = ['scatter', "'scatter'", '"scatter"', 'scatter_kws', "'o'", "'bo'", "'r+'", '"o"', '"bo"', '"r+"']
hist_word_list = ['hist', "'hist'", '"hist"', 'bar', "'bar'", '"bar"', 'count... |
11499501 | import numpy as np
from prediction_flow.transformers.column import LogTransformer
def test_normal():
log_transformer = LogTransformer()
x = np.array([100, 10, 32])
log_transformer.fit(x)
np.testing.assert_array_almost_equal(
log_transformer.transform(x), np.array([4.615121, 2.397895, 3.4965... |
11499509 | import pymongo
import json
import sys
# Local Files
sys.path.append("..")
from scripts import settings
client = pymongo.MongoClient(settings.mongo_server, settings.mongo_id)
db = client[settings.mongo_client]
db.authenticate(settings.mongo_user, settings.mongo_pass)
def save(account, datatype, data):
d = db.posi... |
11499520 | import io
import ujson
from .log import logger
class Buffer:
def __init__(self, buffer_limit=5000):
self.buffer_limit = buffer_limit
self.buffer = io.BytesIO()
self.counter = 0
self.full = False
def __len__(self):
return self.counter
def prepare(self):
sel... |
11499524 | import spacy
# load word embedding model
nlp = spacy.load('en')
# define word embedding vectors
happy_vec = nlp('happy').vector
print(happy_vec)
sad_vec = nlp('sad').vector
print(sad_vec)
angry_vec = nlp('angry').vector
print(angry_vec)
# find vector length here
vector_length = len(happy_vec)
print(vector_length) |
11499559 | from PIL import Image
from src.models.cc0 import patcher
import numpy as np
import skimage.io as io
from src.utils.imgproc import *
from skimage.color import rgb2hsv, hsv2rgb
class patcher(patcher):
def __init__(self, body='./body/body_sakurana.png', **options):
try:
options = options['options... |
11499577 | from abc import ABC, abstractmethod
import asyncio
from typing import Any, Awaitable, Callable, Type, cast
import trio
from lahja import AsyncioEndpoint, EndpointAPI, TrioEndpoint
from lahja.base import EventAPI
Driver = Callable[["EngineAPI"], Awaitable[None]]
class EngineAPI(ABC):
endpoint_class: Type[Endpoi... |
11499665 | import datetime
import logging
import random
from unittest.mock import call
import pytest
from bloop.exceptions import ShardIteratorExpired
from bloop.stream.shard import (
CALLS_TO_REACH_HEAD,
Shard,
last_iterator,
reformat_record,
unpack_shards,
)
from . import (
build_get_records_responses... |
11499667 | from io import BytesIO
import json
import os
import pymongo
import requests
from collections import deque
import zipfile
from datanator.util import mongo_util
import datanator.config.core
class TaxonTree(mongo_util.MongoUtil):
def __init__(self, cache_dirname, MongoDB, db, replicaSet=None,
verbose=False... |
11499704 | import networkx as nx
from networkx import pagerank, pagerank_numpy, pagerank_scipy
import time, json, os
output_folder = 'comparison_selected'
'''
!!! EGO !!!
'''
# ego_path = os.path.join(os.getcwd(), '../../ego_networks/')
ego_path = '../../ego_networks/'
ego_output_path = './comparison_ego_graphs/'
# print(ego_p... |
11499720 | import datetime
import os
import subprocess
import numpy
from scipy.stats import norm
from . import romannumerals
# ToDo: Bring back scale bar
# ToDo: Add option for solid fill of vectors
def roundto(num, nearest):
"""
Rounds :param:`num` to the nearest increment of :param:`nearest`
"""
return int... |
11499729 | import colt
@colt.register("plugh", constructor="plugh_constructor")
class Plugh:
def __init__(self, x: str, y: str) -> None:
self.x = x
self.y = y
@classmethod
def plugh_constructor(cls, x: str, y: str) -> "Plugh":
x += "_x"
y += "_y"
return cls(x, y)
def test_c... |
11499730 | import numpy as np
from scipy.ndimage import distance_transform_edt
def visualize_masks(mask, mask_pred):
m = np.ones((256, 256, 3))
m[np.logical_and(mask, mask_pred)] = np.array([0.1, 0.5, 0.1])
m[np.logical_and(mask, np.logical_not(mask_pred))] = np.array([1, 0, 0])
m[np.logical_and(np.logical_not(m... |
11499747 | import os
from lingvo import model_registry
from lingvo.core import base_model_params
from lingvo.core import datasource
from lingvo.core import program
from lingvo.core import py_utils
from lingvo.core import schedule
from lingvo.core import tokenizers
from lingvo.tasks.asr import input_generator
from lingvo.tasks.as... |
11499786 | import asyncio
from .azip import azip
from .active_aiter import active_aiter
from .map_filter_aiter import map_filter_aiter
from .push_aiter import push_aiter
class gated_aiter:
"""
Returns an aiter that you can "push" integer values into.
When a number is pushed, that many items are allowed out through ... |
11499791 | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.di... |
11499800 | import torch
import argparse
import os
import numpy as np
from misc.utils import set_log, make_env, set_policy
from tensorboardX import SummaryWriter
def main(args):
# Create directories
if not os.path.exists("./logs"):
os.makedirs("./logs")
if not os.path.exists("./pytorch_models"):
os.ma... |
11499803 | def get_funds(json):
j = json
financial_org_name = j['name']
financial_org_permalink = j['permalink']
funds = j['funds']
fds = []
for f in funds:
fund_name = f['name']
funded_year = ifnull(f['funded_year'],1900)
funded_month = ifnull(f['funded_month'],1)
... |
11499830 | from Utils.Eval.Metrics import ComputeMetrics
class LGBMImportance:
def __init__(self, model=None, model_path=None):
if model_path is not None:
self.model = self.load_model(model_path)
elif model is not None:
self.model = model
def load_model(self, path):
from... |
11499858 | from enum import Enum
from marshmallow import Schema, fields
from marshmallow_enum import EnumField
class SurfboardMetricModel:
def __init__(self, status, speed_in_mph, altitude_in_feet, water_temperature_in_f):
# We will automatically generate the new id
self.id = 0
self.status = status
... |
11499881 | import unittest
import os
class TestdriverDecline(unittest.TestCase):
def test_driver_decline(self):
from MaaSSim.simulators import simulate as simulator_driver_decl
from MaaSSim.traveller import travellerEvent
from MaaSSim.utils import get_config
from MaaSSim.decisions import dumm... |
11499887 | import numpy as np
from collections import OrderedDict
import matplotlib.pyplot as plt
import seaborn as sns
def getStats(name):
ff = open('{}.pol_scores'.format(name),'r')
scores = []
for line in ff.readlines():
scores.append(float(line))
ff.close()
print('\n=== Politeness Scores in {} ==... |
11499901 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from skimage.io import imread
from scipy.misc import imresize
from util import log
__IMAGENET_IMG_PATH__ = './datasets/tiny_imagenet/tiny-imagenet-200/'
__IMAGENET_LIST_PATH_... |
11499933 | import warnings
from collections import namedtuple
from functools import partial
import numpy
from scipy import stats
import pandas
import statsmodels.api as sm
from statsmodels.tools.decorators import cache_readonly
try:
from tqdm import tqdm
except ImportError: # pragma: no cover
tqdm = None
from wqio imp... |
11499934 | import sqlite3
class DBHandler:
def __init__(self, db_path, debug=False):
self._debug = debug
self._connect = sqlite3.connect(db_path)
self._cursor = self._connect.cursor()
def execute(self, sql):
if self._debug:
print("[Longan Debug]", end='\t')
print... |
11499948 | data_tidy = data.reset_index().melt(id_vars=["datetime"], var_name='station', value_name='no2')
data_tidy.head() |
11499969 | from metrics import calculate_metrics
import torch
from torch import nn
import sklearn
import sklearn.metrics
import numpy as np
from tqdm import tqdm
import wandb
import datetime
import pickle
from PIL import Image
import PIL
from collections import defaultdict
import mxnet as mx
from mxnet import ndarray as nd
#devi... |
11499973 | import pytest
print(pytest.main(["-qqs", "pytests/test_factory.py"]))
print(pytest.main(["-qqs", "pytests/test_db.py"]))
print(pytest.main(["-qqs", "pytests/test_auth.py"]))
print(pytest.main(["-qqs", "pytests/test_blog.py"]))
print(pytest.main(["-qqs", "pytests/test_reply.py"]))
print(pytest.main(["-qqs", "pytests/t... |
11500003 | import enum
import multiprocessing as mp
from typing import Dict
import numpy as np
import torch
from cid.rollouts.base import BaseRolloutGenerator
class ParallelRolloutGenerator(BaseRolloutGenerator):
"""Generator producing multiple environment rollouts in parallel
Parallel rollouts are generated in worke... |
11500029 | import logging
import json
import re
from pyenvisalink.dsc_envisalinkdefs import *
from pyenvisalink import AlarmState
_LOGGER = logging.getLogger(__name__)
loggingconfig = {'level': 'DEBUG',
'format': '%(asctime)s %(levelname)s <%(name)s %(module)s %(funcName)s> %(message)s',
'datef... |
11500030 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .rnn_cnn_listener import RNNCNNListener
class GRUCNNListener(RNNCNNListener):
def __init__(self,kwargs, obs_shape, vocab_size=100, max_sentence_length=10, agent_id='l0', logger=None):
"""
:param obs_shape: tuple defining the ... |
11500060 | from pathlib import Path
import nltk
from nltk.stem import WordNetLemmatizer
from rake_nltk import Rake
from .common import load_data, run, GetWords
def main():
run(GetRakeWords(), 'rake')
class GetRakeWords(GetWords):
def __init__(self):
super(GetRakeWords, self).__init__()
self.rake = R... |
11500071 | import random
import numpy as np
import torch
def set_all_random_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed)
|
11500080 | from rest_framework.exceptions import APIException
class BaseException(APIException):
pass
class FileException(BaseException):
pass
|
11500137 | import unittest
import tableauserverclient as TSC
class WorkbookModelTests(unittest.TestCase):
def test_invalid_project_id(self):
self.assertRaises(ValueError, TSC.WorkbookItem, None)
workbook = TSC.WorkbookItem("10")
with self.assertRaises(ValueError):
workbook.project_id = No... |
11500152 | from util.ffi import cimport, Struct
from ctypes.wintypes import DWORD, WCHAR
from ctypes import windll, byref, create_unicode_buffer, create_string_buffer
from ctypes import c_ushort, sizeof
from gui.native.win.winutil import WinStruct
from gui.textutil import default_font
from cgui import PyGetFontUnicodeRanges
# ... |
11500202 | import asyncio
import contextlib
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from http.cookies import Morsel # noqa
from pathlib import Path
from types import SimpleNamespace
from typing import (
Any,
Awaitable,
Dict,
Iterator,
List,
Mapping,
Optio... |
11500203 | def main():
year = int(raw_input("Enter the year: "))
if year % 4 == 0 and year % 100 != 0:
print "Its a leap year"
elif year % 4 == 0 and year % 400 == 0:
print "Its a leap year"
else:
print "Its not a leap year"
main()
|
11500228 | import os
import time
import numpy as np
import nibabel as nb
# import nilearn.image as image
# import nipype.interfaces.utility as util
# import nipype.pipeline.engine as pe
# import scipy as sp
# from nilearn import datasets
# from nilearn.image import resample_img
# from nilearn.image.image import mean_img
# from ... |
11500253 | from os.path import join, dirname
from setuptools import setup, find_packages
from version import get_version
setup(
name='git-lfs',
version=get_version(),
description='A lightweight Git Large File Storage fetcher',
author='Changaco',
author_email='<EMAIL>',
url='https://github.com/liberapay/... |
11500263 | import logging
import onnx
from onnx import numpy_helper
from onnx.helper import make_model, make_tensor_value_info, make_opsetid
from furiosa_sdk_quantizer.frontend.onnx.quantizer.utils import __PRODUCER__
from furiosa_sdk_quantizer.frontend.onnx import __DOMAIN__, __OPSET_VERSION__
logger = logging.getLogger("Furio... |
11500301 | from urllib.parse import urlparse
from researchhub.settings import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
def get_s3_url(bucket, key, with_credentials=False):
s3 = 's3://'
if with_credentials is True:
return (
f'{s3}{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@{bucket}{key}'
)
... |
11500303 | from elasticapm.conf.constants import TRANSACTION
from elasticapm.processors import for_events
@for_events(TRANSACTION)
def filter_processor(client, event):
return event
# TODO: Resolve key error
# event_url = event['context']['request']['url']['full']
# if ('ignore_apm' in event_url) or ('/health/' i... |
11500338 | import datetime
from webuntis.utils.timetable_utils import table
from .. import WebUntisTestCase
class StubPeriod(object):
def __init__(self, start, end):
self.start = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M')
self.end = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M')
class BasicUsag... |
11500366 | import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import stochastic_pooling
fX = theano.config.floatX
def test_stochastic_pool_2d_node_serialization():
tn.check_serialization(stochastic_pooling.StochasticPool2D... |
11500372 | import numpy as np
## Policies
def p_exposed_growth(params, substep, state_history, prev_state):
exposed_population = params['infection_rate']*prev_state['infected']*(prev_state['susceptible']/(prev_state['susceptible']+ prev_state['exposed'] + prev_state['infected'] + prev_state['recovered']))
return {'exp... |
11500385 | import cake.system
from cake.test.framework import caketest
@caketest(fixture="scriptinclude")
def testScriptIncludeMissingTraceback(t):
out = t.runCake()
out.checkFailed()
out.checkHasLineMatching("Failed to include cake script missing\\.cake:")
out.checkHasLinesInOrder([
" from include2.cake",
" fr... |
11500390 | import torch
from torch import nn
class multilabel_cross_entropy(nn.Module):
def __init__(self):
super().__init__()
def forward(self,y_pred, y_true):
y_true = y_true.float()
y_pred = torch.mul((1.0 - torch.mul(y_true,2.0)),y_pred)
y_pred_neg = y_pred - torch.mul(y_true,1e12)
... |
11500407 | variables = {}
while(True):
line = input().split()
if line == ["0"]:
break
if "=" in line:
variables[line[0]] = int(line[2])
else:
additions = [x for x in line if x != "+"]
digits = [item for item in additions if item.isdigit()]
undefined = [item for ite... |
11500411 | import pygame
import math
import numpy as np
import random
import time
def checkpattern(col, row):
if row % 2:
if col % 2: #If unequal
return True
else: #if equal
return False
else:
if col % 2: #If unequal
return False
else: #if equal
... |
11500420 | import os
from dataclasses import dataclass
from optimize_images_x.calcs import human
@dataclass
class Task:
filepath: str
status: int
original_filesize: int = 0
final_filesize: int = 0
@property
def filename(self):
return os.path.basename(self.filepath)
@property
def orig_f... |
11500450 | from sklearn import linear_model
from sklearn.neighbors import NearestNeighbors
import pandas as pd
from dowhy.causal_estimator import CausalEstimate
from dowhy.causal_estimators.propensity_score_estimator import PropensityScoreEstimator
class PropensityScoreMatchingEstimator(PropensityScoreEstimator):
""" Estima... |
11500463 | from typing import Tuple
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.utils.extmath import weighted_mode
from .math import sigmoid
def k_neighbors_classify(X_train: np.ndarray,
y_train: np.ndarray,
X_test: np.ndarray,
... |
11500474 | from unittest import TestCase
from altimeter.core.graph.field.util import camel_case_to_snake_case
class TestCamelCaseToSnakeCase(TestCase):
def test_snake_case_input(self):
test_str = "snake_case_input"
self.assertEqual(test_str, camel_case_to_snake_case(test_str))
def test_camel_case_input... |
11500480 | from kines import date_util
from freezegun import freeze_time
import datetime as dt
@freeze_time("2020-11-01 7:00:00", tz_offset=+dt.timedelta(hours=5, minutes=30))
def test_to_iterator_timestamp():
print("now = ", dt.datetime.now())
assert dt.datetime(2020, 11, 1, 5, 55) == date_util.to_iterator_timestamp("1... |
11500541 | import pandas as pd
from rebar import arrdict
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.distributions
import torch.testing
from torch import nn
import geotorch
from . import expectations, common
from logging import getLogger
log = getLogger(__name__)
μ0 = 0
σ0 = 10
def pairwise_ind... |
11500549 | from nose.tools import eq_, ok_
from tornado.httpclient import HTTPRequest
import json
import mockito
from astral.api.client import TicketsAPI
from astral.api.tests import BaseTest
from astral.models import Ticket, Stream, Node
from astral.models.tests.factories import TicketFactory
class TicketHandlerTest(BaseTest):... |
11500558 | import re
import json
import fnmatch
import sys
config = json.load(open('config.json'))
test_error_set = set(config['TestErrorMap'].keys())
obsolete_disabled_tests = set()
all_tests = set()
failing_tests = set()
unimpl_tests = set()
disabled_tests = set()
passed_tests = set()
for line in sys.stdin:
m = re.match(... |
11500563 | import operator
import tempfile
import os
import inspect
import pytest
import pytest
import ast_tools
import fault
from hwtypes import UIntVector
import magma as m
from magma.testing import check_files_equal
Register = m.Register
from ast_tools import SymbolTable
class DualClockRAM(m.Circuit):
io = m.IO(
... |
11500565 | import numpy as np
l_2d = [[0, 1, 2], [3, 4, 5]]
print(l_2d)
# [[0, 1, 2], [3, 4, 5]]
print(type(l_2d))
# <class 'list'>
arr = np.array([[0, 1, 2], [3, 4, 5]])
print(arr)
# [[0 1 2]
# [3 4 5]]
print(type(arr))
# <class 'numpy.ndarray'>
arr = np.arange(6)
print(arr)
# [0 1 2 3 4 5]
arr = np.arange(6).reshape((2, ... |
11500573 | import serial
import time
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser(prog='read_himax', description='Himax image sensor downloader')
parser.add_argument('--baud', type=int, default=460800)
parser.add_argument('-l', '--loop', action='store_true')
parser.add_argument('-o', '--out', d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.