id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9868246 | from .compute_cluster_penalties_cy import do_compute_penalties
from numpy import zeros, amax
__all__ = ['compute_penalties']
def compute_penalties(kk, clusters):
if clusters is None:
clusters = kk.clusters
num_clusters = amax(clusters)+1
cluster_penalty = zeros(num_clusters)
... |
9868277 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('duplicates', '0003_auto_20201130_0431'),
]
operations = [
migrations.CreateModel(
name='StoredDuplicateBackend',
fields=[
(
'id', ... |
9868362 | import math, sys, os, nltk, json, time, re
import numpy as np
def chunks_by_average(tasks: list, m: int):
n = int(math.ceil(len(tasks) / float(m)))
return [tasks[i:i + n] for i in range(0, len(tasks), n)]
def cur_file_dir():
path = sys.path[0]
if os.path.isdir(path):
return path
elif ... |
9868364 | from datetime import datetime
from rest_framework import status
from rest_framework.reverse import reverse
from ralph.access_cards.tests.factories import (
AccessCardFactory,
AccessZoneFactory
)
from ralph.accounts.tests.factories import RegionFactory
from ralph.api.tests._base import RalphAPITestCase
from ra... |
9868373 | import lm_dataformat as lmd
import hashlib
import shutil
def sha256str(s):
h = hashlib.sha256()
h.update(s)
return h.hexdigest()
def test_dat():
archive = lmd.DatArchive('test_dir')
blns = open('test/blns.txt').read()
archive.add_data(blns)
archive.add_data('testing 123')
archive.add_... |
9868378 | from html4vision import Col, imagetable
cols = [
# href can even be used on id columns, and uses the same glob pattern as for the content in img column
Col('id1', 'ID', subset=1, href='images/road_*_image.jpg'),
Col('img', 'Image + Label', 'images/road_*_image.jpg', 1, href='images/road_*_image.jpg'),... |
9868406 | import tushare as ts
ts.set_token('<PASSWORD>')
pro = ts.pro_api()
import pandas as pd
import numpy as np
# from datetime import datetime
import matplotlib.pyplot as plt
# 1获取个股历史交易数据(包括均线数据)
# data = ts.get_hist_data('002717')
# 行业分类
# data = ts.get_industry_classified()
# data.to_csv('classified.csv',mode='a',enc... |
9868444 | import os
import pytest
import yaml
import pandas as pd
import numpy as np
from surfboard import sound
from surfboard.utils import example_audio_file
from surfboard.feature_extraction import (
extract_features,
extract_features_from_paths
)
@pytest.fixture
def flat_waveform():
wave = np.ones((24000,))
... |
9868451 | from pandas.core.dtypes.dtypes import register_extension_dtype
from reciprocalspaceship.dtypes.base import MTZFloat32Dtype, MTZFloatArray
@register_extension_dtype
class AnomalousDifferenceDtype(MTZFloat32Dtype):
"""Dtype for anomalous difference data in reflection tables"""
name = "AnomalousDifference"
... |
9868515 | import pytest
import numpy as np
from typing import List, Tuple
from src.app.ml.base_predictor import BaseData, BaseDataInterface, BaseDataConverter, BasePredictor
from src.app.backend.prediction_batch import prediction_batch
test_job_id = "550e8400-e29b-41d4-a716-446655440000_0"
f_proba = [0.7, 0.2, 0.1]
f_data = [... |
9868584 | from nose.tools import assert_equal, assert_true
from numpy.testing import assert_array_equal
import numpy as np
import re
from seqlearn.evaluation import (bio_f_score, SequenceKFold,
whole_sequence_accuracy)
def test_bio_f_score():
# Check against putputs from the "conlleval" P... |
9868630 | from fitbit_to_sqlite.utils import save_heart_rate_zones
import pathlib
import sqlite_utils
from .utils import create_zip
def test_heart_rate_zones():
zf = create_zip()
db = sqlite_utils.Database(memory=True)
heart_rate_zones = [
f.filename for f in zf.filelist if "heart_rate_zones" in f.filename
... |
9868784 | import json
from itertools import chain
from auth.user import User
from utils import audit_utils
def wrap_to_server_event(event_type, data):
return json.dumps({
'event': event_type,
'data': data
})
def identify_user(request_handler):
user_id = request_handler.application.identification.... |
9868802 | import os
import bpy
import bpy_extras
import bmesh
import math
from mathutils import Vector, Matrix, Quaternion
from bpy.props import StringProperty, BoolProperty, FloatProperty
from ..utils.utils import get_data_path
from ..rsm.reader import RsmReader
class RsmImportOptions(object):
def __init__(self, should_im... |
9868837 | import struct
import crc16
from copy import deepcopy
from smartmicro.Protocols.uat.uatMain import DataFormat, MessageType
class UATv4:
"""
The class provides encode and decode functions of UAT messages for versions 4. The internal structure of the uat
version 4 format is given in the beneath ... |
9868852 | import os
import sys
import shutil
import winreg
import argparse
import logging
import subprocess
logging.basicConfig(level="INFO")
logger = logging.getLogger(__name__)
def find_vs_path():
# something like r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VC\v160"
version = [... |
9868862 | from third_party import yacc
from dsl_base import KarelDSLBase
class KarelDSLSyntax(KarelDSLBase):
def get_yacc(self):
self.yacc, self.grammar = yacc.yacc(
module=self,
tabmodule="_parsetab_syntax",
with_grammar=True)
def get_next_candidates(self, code, **kwargs):
... |
9868881 | import os
import gzip
import numpy as np
from six.moves import cPickle
from ztlearn.utils import extract_files
from ztlearn.utils import maybe_download
from ztlearn.utils import train_test_split
from ztlearn.datasets.data_set import DataSet
URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
CIFAR_10_BASE... |
9868960 | from omega_miya.database.database import BaseDB
from omega_miya.database.class_result import Result
from omega_miya.database.tables import Subscription, Group, BotGroup, GroupSub, User, Friends, UserSub
from .bot_self import DBBot
from datetime import datetime
from sqlalchemy.future import select
from sqlalchemy.orm.ex... |
9869007 | class Solution:
def reverseBits(self, n: int) -> int:
binary_str = bin(n)[2:]
binary_str = '0' * (32 - len(binary_str)) + binary_str
print(binary_str)
reverse = binary_str[::-1]
return int(reverse, base=2)
|
9869027 | import logging
import os
import subprocess
import threading
import time
from collections import OrderedDict
from configparser import SectionProxy
from shlex import quote
from tempfile import mkstemp
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
from redun.executors import aws_utils
from redun... |
9869029 | import re
from purplex.exception import TokenMatchesEmptyStringError
class TokenDef(object):
NEXT_NUM = 0
def __init__(self, regexp, ignore=False):
self.regexp = re.compile(regexp, re.UNICODE)
self.ignore = ignore
# Make sure it doesn't match the empty string
if self.regexp... |
9869046 | from pybricks.parameters import Port
class SoundSensor:
"""
LEGO® MINDSTORMS® NXT Sound Sensor.
Args:
port (Port): Port to which the sensor is connected.
"""
def __init__(self, port: Port):
if port == Port.A or port == Port.B or port == Port.C or port == Port.D:
raise... |
9869064 | import hashlib
import base64
import windows.crypto
windowscert = b"""-----<KEY>
-----END CERTIFICATE-----"""
raw_cert = base64.decodestring(b"".join(windowscert.split(b"\n")[1:-1]))
cert = windows.crypto.Certificate.from_buffer(raw_cert)
print("Analysing certificate: {0}".format(cert))
print(" * name: <{0}>".for... |
9869139 | gb = GearsBuilder()
gb.map(lambda x: x["key"]) # map the records to key names
gb.foreach(lambda x: execute("DEL", x)) # delete each key
gb.count() # count the records
gb.run("delete_me:*")
|
9869167 | from django.conf import settings
from web3 import Web3, KeepAliveRPCProvider
__all__ = ('web3',)
web3 = Web3(
KeepAliveRPCProvider(host=settings.ETHEREUM_NODE_HOST,
port=settings.ETHEREUM_NODE_PORT)
)
|
9869251 | from __future__ import absolute_import, division, print_function
import numpy as np
from toolz import concatv, drop, interleave
class SimplexPoint(object):
__slots__ = ('stencil', 'stepsize', 'halvings', 'index', 'is_reflect',
'is_doubled', 'simplex_key', 'point_key', 'point')
def __init__(... |
9869252 | import abc
import numpy as np
import socket
import pickle
import urllib.request as urllib2
from ..utils.sockets import determine_master, send, receive
class BaseParameterClient(abc.ABC):
"""BaseParameterClient
Parameter-server clients can do two things: retrieve the current parameters
from the corresp... |
9869254 | class A:
a: str
def __init__(self, val):
self.a = val
def __str__(self):
return self.a
def main():
val = A("ok")
print(val)
if __name__ == '__main__':
main()
|
9869259 | from asnake.aspace import ASpace
AS = ASpace()
repo = AS.repositories(2)
print (repo.resources(150).title)
"""
for collection in repo.resources:
print (collection.title)
# I think we should add these in somehow, maybe namespaced
print (repo.resourceID("apap101").title)
record = AS.archival_object("610555991d1ab755... |
9869270 | import numpy as np
import scipy.sparse
from pymatting.util.util import weights_to_laplacian
from numba import njit
@njit("Tuple((f8[:], i4[:], i4[:]))(f8[:,:,:], f8, i4)", cache=True, nogil=True)
def _rw_laplacian(image, sigma, r):
h, w = image.shape[:2]
n = h * w
m = n * (2 * r + 1) ** 2
i_inds = np... |
9869283 | import pytest
from datetime import datetime
from users.management.commands import merge_same_email_users
from users.models import User
@pytest.fixture
def bob_a(mixer) -> User:
return mixer.blend('users.User', username='<EMAIL>', email='<EMAIL>', date_joined=datetime(2021, 11, 1))
@pytest.fixture
def bob_b(mix... |
9869290 | from collections import defaultdict
from gensim import corpora
from gensim.models import LsiModel, TfidfModel
from .abstract_model import AbstractModel
from .gensim_model import GensimModel
from .utils.corpus import preprocess, input_to_list_string
class LSIModel(GensimModel):
"""Latent Semantic Indexing
S... |
9869303 | import pandas as pd
import numpy as np
from math import log
class Entropy:
'''
计算离散随机变量的熵
支持numpy和series数据类型
'''
@staticmethod
def entropy(x):
'''
信息熵
H(X)=-\sum p_i log2(p_i)
'''
x = pd.Series(x)
p = x.value_counts(normalize=True)
p = p[p... |
9869309 | import pytest
from unittest.mock import call, ANY
from src import bot
from freezegun import freeze_time
class TestReport:
@pytest.mark.parametrize(
"tweet",
["report for $JNJ", "analyse $AMZN info", "analyze $ETH"],
)
def test_returns_true_when_tweet_contains_report(self, tweet):
... |
9869330 | from routemaster.timezones import get_known_timezones
def test_smoke_get_known_timezones():
get_known_timezones()
|
9869360 | import pyb
@micropython.native
def f(led, n, d):
led.off()
i = 0
while i < n:
print(i)
led.toggle()
pyb.delay(d)
i += 1
led.off()
f(pyb.LED(1), 2, 150)
f(pyb.LED(2), 4, 50)
|
9869377 | import inspect, io, mmap
def convert_to_bytes(arg):
if isinstance(arg, bytes):
return arg
elif isinstance(arg, str):
return arg.encode("ascii")
elif hasattr(arg, "__iter__"):
return b" ".join(map(convert_to_bytes, arg))
else:
return str(arg).encode("ascii")
class edx_io... |
9869403 | import os
import shutil
import json
import time
from logging import getLogger
from logging import StreamHandler
from logging import FileHandler
from logging import NullHandler
from selenium import webdriver
from tags import ICSD_QUERY_TAGS, ICSD_PARSE_TAGS
logger = getLogger(__name__)
class QueryerError(Exception... |
9869413 | class FaceAnalysisError(Exception):
pass
class ImageDoesNotExist(FaceAnalysisError):
pass
class ImageAlreadyProcessed(FaceAnalysisError):
pass
|
9869440 | def _ensure_read_access(compressedfile):
"""Ensure that the compressedfile will be readable by the user after
extraction.
Some tarballs have u-x set on directories. They may as well have u-r set on
files. We reset such perms here.. so that the extracted files remain
accessible.
See also: http:... |
9869531 | import socket
socket.setdefaulttimeout(.5)
print('\n'+ '#'*50+'\n Started Executing Script'+ '\n'+ '#'*50)
def port_check(ip,port):
DEVICE_SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result_of_check = DEVICE_SOCKET.connect_ex((ip,port))
if result_of_check == 0:
print(str(ip)+ ' is... |
9869563 | from src.utilities.utils import FileOperation
from src.utilities.model_response import CustomResponse
from src.utilities.model_response import Status
from src.errors.errors_exception import WorkflowkeyError
from src.errors.errors_exception import FileErrors
from src.errors.errors_exception import ServiceError
from src.... |
9869581 | from .checks import *
from ..config import *
from ..pug import Pug
from ..team import Team
from ..utils import *
@check(not_in_pug, not_a_captain, invalid_number)
async def channel(message, pugs, user_input, client):
existing_pug = find_in_list(lambda pug: message.author in pug.players, pugs)
index = int(user... |
9869611 | import argparse
import logging
import os
import random
import shutil
import numpy as np
import tensorflow as tf
from kite.infer_attribute.data import DataFeeder, LabelTaxonomy
from kite.infer_attribute.model import GGNN, Config
VALIDATION_INTERVAL = 10
MAX_ITER = 1000 * 1000 * 10
SAVE_INTERVAL = 20000 #
MODEL_NAME ... |
9869625 | from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 *... |
9869626 | import numpy as np
import torch
import caption.encoders.vanilla
import controlimcap.encoders.gcn
import controlimcap.decoders.cfattention
import controlimcap.models.graphattn
MPENCODER = 'mp_encoder'
ATTNENCODER = 'attn_encoder'
DECODER = 'decoder'
class GraphBUTDCFlowAttnModel(controlimcap.models.graphattn.GraphBUT... |
9869644 | import tbf.utils as utils
from tbf.input_generation import BaseInputGenerator
from tbf.testcase_converter import TestConverter
name = "Dummy"
class Preprocessor:
def prepare(self, filecontent, nondet_methods_used, error_method=None):
content = filecontent
content += '\n'
con... |
9869687 | from actstream.actions import follow
from actstream.models import Follow
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_extensions.db.models import TitleSlugDescriptionModel
from guardian.s... |
9869800 | import os
import cv2
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--video1', '-v1', type=str,
help='the first video file')
parser.add_argument('--video2', '-v2', type=str,
help='the second video file')
parser.add_argument('--cache-dir', '-cd', type=str,
... |
9869807 | import sys, os, json
script_loc = os.path.realpath(__file__)
sys.path.append(os.path.join(os.path.dirname(script_loc), '..'))
import django
from operator import itemgetter
from collections import defaultdict, Counter
from numpy import arange
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
os... |
9869817 | from ctypes import CFUNCTYPE, POINTER, cast, memmove, create_string_buffer
from ctypes import c_int, c_long, c_char_p, c_void_p, c_longlong
AFUNPTR = CFUNCTYPE(None)
TRACE_BUFFER_CALLBACK = CFUNCTYPE(c_void_p, c_int, c_int, c_void_p,
c_void_p, c_longlong, c_void_p)
ROOT_THREAD_FUNC =... |
9869827 | import numpy as np
# from collections import OrderedDict as odict
import inspect
from galry import GalryWidget, show_basic_window, get_color, PaintManager,\
InteractionManager, ordict, get_next_color
import galry.managers as mgs
import galry.processors as ps
import galry.visuals as vs
__all__ = ['figure', 'Figure... |
9869836 | from __future__ import absolute_import
from flask import Flask, request, Blueprint, current_app
import os
import re
from travispy import TravisPy
import logging
LOG_LEVEL = logging.INFO
OUTPUT_FOLDER = '/tmp/pylint-server'
VALID_REPOS = []
BADGE_TEMPLATE = """<svg xmlns="http://www.w3.org/2000/svg" width="85" height... |
9869858 | import app.models as models
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from app import utils
from app.config import sqla
from app.lib import send_mail
from app.utils import Throttle
throttle = Throttle(2)
def delete_dynamic(dynamic_id):
session = sqla['session']
print("delete dynamic... |
9869939 | import matplotlib.pyplot as plt
from matplotlib import widgets
class ComplexSliderWidget(widgets.AxesWidget):
"""
A circular complex slider widget for manipulating complex
values.
References:
- https://matplotlib.org/stable/api/widgets_api.
- https://github.com/matplotlib/matplotlib/blob/
... |
9869941 | import sys
from tensorflow import flags
FLAGS = flags.FLAGS
if __name__=="__main__":
flags.DEFINE_string("train_path", "", "The directory where training files locates.")
flags.DEFINE_string("candidates", "", "The candidate methods.")
if __name__=="__main__":
candidate_methods = map(lambda x: x.strip(), FLAGS.c... |
9869954 | from collections import defaultdict
import datetime
import pickle
try:
import pylibmc
except ImportError:
pylibmc = None
try:
import redis
except ImportError:
redis = None
class GiottoKeyValue(object):
"""
Baseclass for all KeyValue object. This exists to demonstrate the API for
KeyValue ... |
9870012 | from pybamm import exp, tanh
def graphite_LGM50_ocp_Chen2020(sto):
"""
LG M50 graphite open circuit potential as a function of stochiometry, fit taken
from [1].
References
----------
.. [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. "Development of Experimental Techniques for
Par... |
9870016 | import numpy as np
from .camera import Camera
from .dataset import Dataset
import cv2
class DataLoader(object):
def __init__(self, dataset: Dataset):
self.dataset = dataset
# TODO: this part can be done with Queue
def __getitem__(self, item):
x = 30
bgrImg = cv2.imr... |
9870018 | import cadquery as cq
# X axis line length 20.0
path = cq.Workplane("XZ").moveTo(-10, 0).lineTo(10, 0)
# Sweep a circle from diameter 2.0 to diameter 1.0 to diameter 2.0 along X axis length 10.0 + 10.0
defaultSweep = (
cq.Workplane("YZ")
.workplane(offset=-10.0)
.circle(2.0)
.workplane(offset=10.0) ... |
9870022 | import os
import shutil
import numpy as np
from config_training import config
from scipy.io import loadmat
import numpy as np
import h5py
import pandas
import scipy
from scipy.ndimage.interpolation import zoom
from skimage import measure
import SimpleITK as sitk
from scipy.ndimage.morphology import binary_dilation,gen... |
9870042 | import unittest
@unittest.skip('not useful for now')
class TestJigsawPuzzle(unittest.TestCase):
def test_elementNorm(self):
# jigsaw_puzzle = JigsawPuzzle(k, secParam, dimensionality)
# self.assertEqual(expected, jigsaw_puzzle.elementNorm(u))
assert False # TODO: implement your test here
... |
9870058 | import python_jsonschema_objects as pjs
import json
import json5
__all__ = [ 'DatasetProvenance', 'DataLayerProvenance' ]
dataset_provenance_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Dataset Provenance",
"description": "Represents a dataset and its derived data layers.",
"requ... |
9870067 | from __future__ import print_function, absolute_import, division
from punch.vcs_use_cases import use_case
class VCSStartReleaseUseCase(use_case.VCSUseCase):
def __init__(self, repo):
self.repo = repo
def execute(self):
self.repo.pre_start_release()
return self.repo.start_release()
|
9870073 | from collections import Iterable
from logging import getLogger
import six
from chainer import cuda
def _to_list(a):
if isinstance(a, Iterable):
a = list(a)
else:
a = [a]
return a
def extend_node(node, out_size, axis=-1, value=0):
"""Extend size of `node` array
For now, this fun... |
9870079 | from flask_testing import TestCase
from cabotage.server import db, create_app
from cabotage.server.models import User
import testing.postgresql
app = create_app()
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('cabotage.server.config.TestingConfig')
app.config['SQLA... |
9870082 | import unittest
from wasmtime import *
def ref_types_store():
config = Config()
config.wasm_reference_types = True
engine = Engine(config)
return Store(engine)
def compile_and_instantiate(wat):
store = ref_types_store()
module = Module(store.engine, wat)
return (Instance(store, module, ... |
9870122 | import torch.nn as nn
import torch.nn.functional as F
FE_STAGE0 = 64
FE_STAGE1 = 128
BN_IO = 256
def ConvReLU(n_in, n_out, kernel_size=1, stride=1, padding=0):
return nn.Sequential(
nn.Conv2d(
n_in,
n_out,
kernel_size=kernel_size,
stride=stride,
... |
9870128 | from __future__ import print_function
from argparse import ArgumentParser, FileType
import re
import shlex
import logging
import sys
import csv
"""
MIT License
Copyright (c) 2017 <NAME>, <NAME>
Please share comments and questions at:
https://github.com/PythonForensics/PythonForensicsCookbook
or email <EMAIL>... |
9870136 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="wideboost",
version="0.3.2",
author="<NAME>",
author_email="<EMAIL>",
description="Implements Wide Boosting functions for popular boosting packages",
long_description=long_description... |
9870164 | import logging
import os
import os.path
import re
import signal
import subprocess
import time
import copy
from datetime import datetime
test_duration = 60
primer_duration = 1
wait_after_primer = 1
wait_to_start = 10
wait_after_kill = 2
now = datetime.now()
javacmd = '/usr/lib/jvm/java-11-openjdk-amd64/bin/java'
wrkcmd... |
9870317 | import dash_echarts
import dash_html_components as html
import dash_core_components as dcc
option = {
'title': {
'text': 'Line Area Stacked'
},
'tooltip': {
'trigger': 'axis',
'axisPointer': {
'type': 'cross',
'label': {
'backgroundColor': '#... |
9870345 | import doctest
import unittest
from tests import *
if __name__ == "__main__":
import tests.test_doctest
doctest.testmod(tests.test_doctest)
unittest.main()
|
9870363 | import requests
import itertools
import os
LOGO = """
_______ _______ __ __
| _ | | |_| |
| |_| | ___| |
| | | __| |
| | || | |
| _ | |_| | ||_|| |
|__| |__|_______|_| |_|"""
# All the places to look for config files and json keys
AGM_PATH = os.path.expan... |
9870402 | import urwid
from tui.components.systemMonitor import SystemMonitor
class SystemMonitors(urwid.WidgetWrap):
"""
SystemMonitors is a view to track various system level
information like CPU/Memory usage
"""
def __init__(self, model):
"""
Parameters
----------
model :... |
9870452 | import sys
from fabric.api import env, run, cd
"""
Sample fabric file. Assumes the following on production server:
- virtualenv + virtualenvwrapper
- mercurial
- supervisord (running gunicorn/uwsgi etc.)
Copy and modify as required for your own particular setup.
Keep your private settings in a separate module, fab... |
9870458 | from django_elasticsearch_dsl import Document, fields as es_fields
from django_elasticsearch_dsl.registries import registry
from discussion.models import Thread
from researchhub.settings import (
ELASTICSEARCH_AUTO_REINDEX,
TESTING
)
from search.analyzers import title_analyzer
import utils.sentry as sentry
@... |
9870459 | import torch
import torch.utils.data as data
import random
from PIL import Image
class ImageFolder(data.Dataset):
def __init__(
self,
root,
transform=None,
target_transform=None,
loader=None,
is_valid_file=None,
):
super(ImageFolder, self).__init__()
... |
9870481 | from tempfile import TemporaryDirectory
from typing import Any, Dict, Tuple
import datasets
import flair
import numpy as np
import pytest
import torch
from flair.data import Corpus
from numpy import typing as nptyping
from embeddings.data.data_loader import HuggingFaceDataLoader
from embeddings.data.dataset import Hu... |
9870520 | import milk.unsupervised.affinity
import numpy as np
def test_affinity():
np.random.seed(22)
X = np.random.randn(100,10)
X[:40] += .4
S = milk.unsupervised.pdist(X)
clusters, labels = milk.unsupervised.affinity.affinity_propagation(S)
assert labels.max()+1 == len(clusters)
assert len(labels)... |
9870549 | from ..utils import user_has_rights_on_share
from more_itertools import unique_everseen
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
from ..fields import UUIDField
from ..models import Secret_Link, Data_Store
class MoveSecretLinkSerializer(serializers.S... |
9870592 | from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Participant
@receiver(post_save, sender=Participant)
def post_save_cb(sender, instance, created, raw, update_fields, **kwargs):
"""
Set all PublicDataAccess objects' is_public to false when a user leaves t... |
9870627 | import tensorflow as tf
def attention(inputs, attention_size):
"""
Attention mechanism layer.
:param inputs: outputs of RNN/Bi-RNN layer (not final state)
:param attention_size: linear size of attention weights
:return: outputs of the passed RNN/Bi-RNN reduced with attention vector
"""
# ... |
9870644 | import torch
from torch import nn
from collections import OrderedDict
from fbnet_building_blocks.fbnet_builder import ConvBNRelu, Flatten
from supernet_functions.config_for_supernet import CONFIG_SUPERNET
class MixedOperation(nn.Module):
# Arguments:
# proposed_operations is a dictionary {operation_name :... |
9870659 | import sys
import platform
import subprocess
import distutils
import setuptools
from distutils.core import Extension
from setuptools.command.build_ext import build_ext
"""
####
#### Mini HOWTO
####
* To upload to the pypi server the most simple way is to call
```
python3 setup.py sdist
```
This command will c... |
9870660 | from restrain_jit.bejulia.julia_vm import JuVM
from restrain_jit.bejulia.jl_init import init
init()
jit = JuVM.func_info
@jit
def func1(x):
for i in range(1000):
x = x + i
return x + 1
def func2(x):
for i in range(1000):
x += i
return x + 1
assert func1(100) == func2(100)
print(... |
9870662 | from abc import ABC
from typing import Any, List, Optional, Union
import lxml
import pandas as pd
from .. import cache
from ..datahelpers.column_mapper import BattingStatsColumnMapper, ColumnListMapperFunction, GenericColumnMapper
from ..enums.fangraphs import (FangraphsBattingStats, FangraphsFieldingStats, Fangraphs... |
9870667 | import os
import pygame
import signal
import sys
from time import sleep
import paho.mqtt.client as mqtt
from alarmpanel import Motion
from alarmpanel.button import \
STATE_DEFAULT, STATE_PRESSED,\
STATE_1, STATE_2, STATE_3, STATE_4_BAD, STATE_4_GOOD,\
STATE_ACTIVE, STATE_AVAILABLE
from alarmpanel.ui impor... |
9870701 | import py
from pypy.translator.translator import TranslationContext, graphof
from pypy.jit.hintannotator.annotator import HintAnnotator
from pypy.jit.hintannotator.policy import StopAtXPolicy, HintAnnotatorPolicy
from pypy.jit.hintannotator.bookkeeper import HintBookkeeper
from pypy.jit.hintannotator.model import *
fro... |
9870767 | import sys
from typing import Union
import jinja2
import pytest
from reforms import Reforms
@pytest.fixture
def default_package() -> str:
return "reforms"
@pytest.fixture
def template_package(tmp_path) -> str:
package_name = "template_package"
package = tmp_path / package_name
package.mkdir()
... |
9870772 | from sklearn.ensemble import ExtraTreesClassifier
from commons import variables
from commons import tools
from scipy.stats import mode
def learn(x, y, test_x):
cw = {"0":variables.weight_0_rf, "1000":variables.weight_1000_rf, "1500":variables.weight_1500_rf, "2000":variables.weight_2000_rf}
clf = ExtraTreesCl... |
9870796 | import os
import sys
import shutil
import argparse
from functools import (
wraps,
partial
)
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import mne
import braindecode
import wandb
from utils.utils import (
make_dir,
read_yaml,
AttrDict,
Color,
write_js... |
9870809 | from __future__ import print_function
import sys
import struct
import six
from pypytools.jitview import Color
from capnpy import ptr
COLORS = [Color.darkred, Color.darkgreen, Color.brown,
Color.darkblue, Color.purple, Color.teal]
def print_buffer(buf, **kwds):
p = BufferPrinter(buf)
p.printbuf(end... |
9870819 | class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums) < 2: return len(nums)
down = up = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
up = down + 1
elif nums[i] < nums[i - 1]:
down = up + 1
... |
9870820 | from typing import List, Optional
from google.appengine.ext import ndb
from backend.common.consts.event_type import EventType
from backend.common.models.event import Event
from backend.common.models.event_team import EventTeam
from backend.common.models.keys import EventKey, TeamKey, Year
from backend.common.models.t... |
9870865 | import traceback
import ast
import random
from datetime import datetime
import json
import discord
from .config import config
from redbot.core import Config
from redbot.core import commands
from redbot.core import checks
defaults = {"MatchDay": 0, "Schedules": {}, "Segment": "Regular Season",
"Game": "Roc... |
9870886 | from flask_assistant import ask
from flask_assistant.response import _Response
class ask(_Response):
def __init__(self, speech, display_text=None):
"""Returns a response to the user and keeps the current session alive. Expects a response from the user.
Arguments:
speech {str} -- Text ... |
9870903 | from django import template
from django.utils.translation import ungettext, ugettext as _
import datetime
from django.utils.timezone import utc
register = template.Library()
@register.filter
def date_diff(d):
now = datetime.datetime.utcnow().replace(tzinfo=utc)
today = datetime.datetime(now.year, ... |
9870930 | from insertion import linkedList, node
class newClass(linkedList):
def rotate(self, k):
if k == 0:
return
current = self.head
count = 1
while count<k and current is not None:
count += 1
current = current.next
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.