id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1728550 | import logging,json
import os
import time
from typing import Dict
import azure.functions as func
import requests
from azureml.core import Experiment, Workspace
from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.pipeline.core import PipelineRun
from ..shared.aml_helper import ... |
1728554 | import numpy
from numba import jit
from . import best_split
from . import misc_functions as m
#from importlib import reload
#reload(m)
#reload(best_split)
cache = False
class _tree:
"""
This is the recursive binary tree implementation.
"""
def __init__(self, feature_index=-1, feature_threshold=None,... |
1728556 | from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.decorators import method_decorator
from django.utils import timezone
from rest_... |
1728590 | class Solution:
"""
@param nums: an array containing n + 1 integers which is between 1 and n
@return: the duplicate one
"""
def findDuplicate(self, nums):
# write your code here
if not nums or len(nums) == 0:
return 0
lo, hi = 1, len(nums) - 1
while lo + ... |
1728702 | import requests
from fastapi import FastAPI
from fastapi.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
from error_handlers.warnings import WarningJSON
from error_handlers.exceptions import ExceptionJSON
from training.training import train_models
from datab... |
1728706 | from scenarios import *
scenario = (
send_stanza("<iq from='{jid_one}/{resource_one}' to='#foo%{irc_server_one}' id='1' type='get'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>"),
expect_stanza("/iq[@from='#foo%{irc_server_one}'][@to='{jid_one}/{resource_one}'][@type='result']/disco_info:query",
... |
1728714 | import pytest
import raccoon as rc
from raccoon.utils import assert_series_equal
try:
# noinspection PyUnresolvedReferences
from blist import blist
except ImportError:
pytest.skip("blist is not installed, skipping tests.", allow_module_level=True)
def test_assert_series_equal():
srs1 = rc.Series([1,... |
1728756 | import json
from whyis.test.api_test_case import ApiTestCase
testdata = [
{"id":1,"name":"<NAME>","age":"12","col":"red","dob":""},
{"id":2,"name":"<NAME>","age":"1","col":"blue","dob":"14/05/1982"},
{"id":3,"name":"<NAME>","age":"42","height":0,"col":"green","dob":"22/05/1982","cheese":"true"},
{"id":... |
1728788 | from sanic import Sanic
from sanic.response import file
from idom import component, html
from idom.backend.sanic import Options, configure
app = Sanic("MyApp")
@app.route("/")
async def index(request):
return await file("index.html")
@component
def IdomView():
return html.code("This text came from an IDO... |
1728856 | from setuptools import find_packages, setup
description = \
'Elasticsearch buffer for collecting and batch inserting Python data and pandas DataFrames'
with open('README.md') as f:
long_description = f.read()
requirements = [
'elasticsearch',
]
extras = {
'pandas': ['pandas']
}
keywords = [
'ela... |
1728888 | INTERFACES = [
"encoder",
"gpio",
"timer",
"uart",
"pwm",
]
MODULES = {
"hal-stm32cubef4" : {
"path" : "hal/stm32cubef4",
"namespace" : "HAL::STM32CubeF4",
"cond" : "AVERSIVE_TOOLCHAIN_STM32F4",
},
"hal-atxmega" : {
"path" : "hal/atxmega",
"namesp... |
1728902 | import kfp.dsl as dsl
from kubernetes import client as k8s_client
@dsl.pipeline(
name='GameOfThrones',
description='Game of Thrones Tensorflow image classification demo'
)
def got_image_pipeline(
trainingsteps=4000,
learningrate=0.01,
trainbatchsize=100,
):
persistent_volume_name = 'azure-file... |
1728906 | import pytest
from unittestmock import UnitTestMock
import numpy as np
from cykhash import none_int64, none_int64_from_iter, Int64Set_from, Int64Set_from_buffer
from cykhash import none_int32, none_int32_from_iter, Int32Set_from, Int32Set_from_buffer
from cykhash import none_float64, none_float64_from_iter, Float64Se... |
1728907 | import logloader
import argparse
import re
import os
import time
import util
import sys
import parser as TemplateParser
import header
if __name__ == "__main__":
t1 = time.time()
parser = argparse.ArgumentParser()
parser.add_argument("--Input", "-I", help="The input log sample")
parser.add_argument("--T... |
1728926 | HEADER = 'header'
PATH = 'path'
QUERY = 'query'
HEALTH = 'HEALTH'
class EndPoint(object):
"""Base object representation of an endpoint"""
# Default host to use unless otherwise specified by a derived class
host = 'REST'
# Path needs to be a Path object
path = ()
# the HTTP verb to use for th... |
1728965 | def do_stuff(nm):
with open('/tmp/'+nm,'w') as f:
f.write('hello, {0}.\ngoodbye, {0}.\n'.format(nm))
|
1728968 | from pyknp.evaluate.mrph import morpheme
from pyknp.evaluate.dep import dependency
from pyknp.evaluate.phrase import phrase
from pyknp.evaluate.scorer import Scorer
|
1728969 | import torch.nn as nn
from builder import ConvBuilder
LENET5_DEPS = [20, 50, 500]
class LeNet5(nn.Module):
def __init__(self, builder:ConvBuilder, deps):
super(LeNet5, self).__init__()
self.bd = builder
stem = builder.Sequential()
stem.add_module('conv1', builder.Conv2d(in_channel... |
1728983 | from nbconvert.preprocessors import Preprocessor
def has_html(output):
return "text/html" in output.get("data", {})
# based off of
# https://github.com/jupyter/nbconvert/blob/master/nbconvert/preprocessors/tagremove.py
class Diffable(Preprocessor):
def preprocess_cell(self, cell, resources, cell_index):
... |
1729037 | from setuptools import setup
setup(name='hb_downloader',
version='0.5.0',
description='an unofficial api client for humblebundle',
url='https://github.com/MayeulC/hb-downloader/releases',
author='<NAME>',
license='MIT',
packages=[
'hb_downloader',
'hb_downloader.... |
1729047 | import os
import unittest
import tensorflow as tf
import mvg_distributions.covariance_representations as cov_rep
from mvg_distributions.covariance_representations.tests.test_covariance_matrix import CovarianceTest, \
declare_inv_method_test_classes
class CovarianceCholTest(CovarianceTest):
def setUp(self):
... |
1729055 | from typing import Hashable
import dask.array as da
import numpy as np
from xarray import Dataset
from sgkit import variables
from sgkit.stats.aggregation import call_allele_frequencies
from sgkit.utils import (
conditional_merge_datasets,
create_dataset,
define_variable_if_absent,
)
def identity_by_sta... |
1729060 | import logging
from typing import Any, Dict, List
from hypermodel import hml
from hypermodel.hml import hml_app, model_container
from hypermodel.platform.local import services
from hypermodel.platform.local.config import TstConfig
from hypermodel.tests.utilities import data_frame_utility, general
from xgboost import X... |
1729103 | from i3pystatus import IntervalModule
class Tlp(IntervalModule):
"""
Shows the current mode of TLP (Linux power management tool), either
battery, AC or unknown.
.. rubric:: Available formatters
* `{output}` - one of the strings configured through the `*_text` settings
"""
last_pwr_file =... |
1729130 | from __future__ import annotations
__VERSION__ = '0.6.2'
import re
from typing import Type, Union
from . import utils
from .exceptions import TakiyashaException
from .ncm import NCM
from .ncmcache import NCMCache
from .qmc import QMCv1, QMCv2
from .sniff import sniff_audio_file
SupportsCrypter = Union[NCM, NCMCache... |
1729148 | import numpy as np
import time
def Fuzzy(error):
sign = np.sign(error)
error =abs(error)
k1 = 0.35
x = 50
k2 = 0.55
angle = 0
if error<x:
angle = k1*error
else:
angle = (error-x)*k2+k1*x
if angle>60:
angle = 60
return -angle*sign
error_arr = np.zeros(5)
... |
1729194 | from ..check import Check
import re
class CheckNoPadding(Check):
'''Ensure frontmatter string tags doesn't contain leading empty lines'''
ID = 'NOPADDING'
def __init__(self):
self.noPadding = re.compile(r"^(?![\r\n])[\s\S]*")
def run(self, name, meta, source):
if not meta:
... |
1729198 | from ..graph import get_default_graph
from ..tensors import *
from ..ops.array_ops import *
from ..ops.ctrl_ops import *
from ..ops.constant import *
from ..ops.math_ops import *
from ..ops.placeholder import *
from ..ops.variable import *
def constant(name, out_shape, value=None, graph=None):
if graph is None:
... |
1729228 | from oper import Webfinger, AccessToken
from oper import Discovery
from oper import Registration
from oper import Authn
from testfunc import resource, set_jwks_uri, set_op_args
from testfunc import expect_exception
from testfunc import set_request_args
from oic.exception import IssuerMismatch
__author__ = 'roland'
O... |
1729249 | import numpy
try:
from scipy import special
available_cpu = True
except ImportError as e:
available_cpu = False
_import_error = e
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Erfcx(function_node.FunctionNode)... |
1729260 | state.ram.store(0x08, 8, 0x0000000000414141)
state.ram.store(0x10, 8, 0x0000000000333231)
state.ram.store(0x18, 8, 0x0000000000000000)
state.ram.store(0x20, 8, 0x0041414141414141)
|
1729268 | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PATH_DATA = os.path.join(BASE_DIR, "data")
PATH_BIN = os.path.join(BASE_DIR, "data-bin")
PATH_CP = os.path.join(BASE_DIR, "checkpoints")
PATH_TB = os.path.join(BASE_DIR, "runs")
PATH_USER = os.path.join(BASE_DIR, "user")
|
1729280 | import logging
import random
from slackbot.bot import respond_to
from slackbot import settings
import slacker
from haro.botmessage import botsend
HELP = '''
- `$random`: チャンネルにいるメンバーからランダムに一人を選ぶ
- `$random active`: チャンネルにいるactiveなメンバーからランダムに一人を選ぶ
- `$random help`: randomコマンドの使い方を返す
'''
logger = logging.getLogger(__... |
1729291 | import os
from sandbox.gkahn.gcg.envs.rccar.square_env import SquareEnv
class SquareClutteredEnv(SquareEnv):
def __init__(self, params={}):
params.setdefault('model_path', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models/square_cluttered.egg'))
SquareEnv.__init__(self, params=para... |
1729329 | import pandas as pd
import torch
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
from typing import Tuple, List, Callable
class Corpus(Dataset):
"""Corpus class"""
def __init__(self, filepath: str, transform_fn: Callable[[str], List[int]]) -> None:
"""Instantiating Cor... |
1729340 | from rest_framework import serializers
from .models import TestModel
class TestSerializer(serializers.Serializer):
name = serializers.CharField(required=False, allow_blank=True)
def create(self, validated_data):
pass
def update(self, instance, validated_data):
pass
class TestModelSeri... |
1729351 | import numpy as np
import onnxruntime
import pandas as pd
import torch
from pathlib import PosixPath
from pickle import load
from sklearn.preprocessing import MinMaxScaler
from make_us_rich.pipelines.preprocessing import extract_features_from_dataset
from make_us_rich.pipelines.converting import to_numpy
class Onnx... |
1729367 | from ._pyimports import levenshtein, fast_comp
def ilevenshtein(seq1, seqs, max_dist=-1):
"""Compute the Levenshtein distance between the sequence `seq1` and the series
of sequences `seqs`.
`seq1`: the reference sequence
`seqs`: a series of sequences (can be a generator)
`max_dist`: if provided and > 0, only... |
1729385 | import jwt
from jwksutils import rsa_pem_from_jwk
# To run this example, follow the instructions in the project README
# obtain jwks as you wish: configuration file, HTTP GET request to the endpoint returning them;
jwks = {
"keys": [
{
"kid": "<KEY>",
"nbf": 1493763266,
... |
1729388 | from django.conf.urls import include, url
from django.contrib import admin
from swag.views import *
from users.views import *
urlpatterns = [
# Examples:
url(r'^$', home_page, name='home_page'),
url(r'^form/$', FormView, name='form_page'),
url(r'^login/$', LoginView, name='form_page'),
url(r'^regi... |
1729423 | import pytest
import random
import torch
from torch.optim import Adam
import numpy as np
import gym
import torch_testing as tt
from rlil.approximation import VNetwork, FeatureNetwork
from rlil.environments import State, Action, GymEnvironment
from rlil.memory import ExperienceReplayBuffer, GaeWrapper
from rlil.presets.... |
1729453 | import torch
import torch.distributions as dist
import os
from im2mesh.encoder import encoder_temporal_dict
from im2mesh.onet4d import models, training, generation
from im2mesh import data
def get_decoder(cfg, device, c_dim=0, z_dim=0):
''' Returns a decoder instance.
Args:
cfg (yaml): yaml config
... |
1729456 | import json, argparse, os
from .db import Node, Edge, dbgraph
from .mx.utils import MxUtils
from .gherkin_stride import create_gherkins_from_threats, create_feature_file_for_gherkins
class ThreatMaterializer(object):
@classmethod
def get_flows_with_threats(cls):
SPOOFING = 'spoofing'
TAMPER... |
1729459 | import os
import sys
import random
import warnings
import math
import numpy as np
import pylab
import scipy.ndimage as ndi
from concurrent.futures import ThreadPoolExecutor
import PIL
from PIL import Image, ImageDraw
from tqdm import tqdm
def autoinvert(image):
assert np.amin(image) >= 0
assert np.amax(imag... |
1729506 | from dataclasses import dataclass
import dataclass_factory
from dataclass_factory import Schema
@dataclass
class Book:
title: str
price: int
extra: str = ""
data = {
"title": "Fahrenheit 451",
"price": 100,
"extra": "some extra string"
}
# using `only`:
factory = dataclass_factory.Factory(... |
1729552 | import sys
from PySide.QtCore import *
from PySide.QtGui import *
from image import SegmentedImage
class Main(QWidget):
def __init__(self, image_path, parent=None):
super(Main, self).__init__(parent)
layout = QVBoxLayout(self)
picture = PictureLabel(image_path, self)
picture.s... |
1729650 | from datetime import timedelta
from django.urls import reverse
from django.utils import timezone
from applications.questions import DEFAULT_QUESTIONS
def test_access_apply_view(client, future_event, future_event_form):
apply_url = reverse(
'applications:apply', kwargs={'city': future_event.page_url})
... |
1729673 | from hsi_toolkit.util import img_det
from sklearn.mixture import GaussianMixture
def gmm_anomaly(hsi_img, n_comp, mask = None):
"""
Gaussian Mixture Model Anomaly Detector
fits GMM assuming entire image is background
computes negative log likelihood of each pixel in the fit model
Inputs:
hsi_image - n_row x ... |
1729721 | import numpy
class Embeddings:
def __init__(self):
"""
Initializes the embeddings database.
"""
self.Vectors = []
self.Labels = []
def Add(self, vector, label):
"""
Adds embedding to embeddings database.
Args:
vector: Vector
... |
1729742 | import tensorflow as tf
import numpy as np
import sys
import os
class S2parser():
""" defined the Sentinel 2 .tfrecord format """
def __init__(self):
self.feature_format= {
'x10/data': tf.FixedLenFeature([], tf.string),
'x10/shape': tf.FixedLenFeature([4], tf.int64),
... |
1729744 | import numpy as np
def generate_random_policy(env):
n_states = env.observation_space.n
n_actions = env.action_space.n
policy = np.ones([n_states, n_actions]) / n_actions
policy[0, :] = 0
policy[n_states - 1, :] = 0
return policy
def policy_evaluation(policy, env, V=None, gamma=1, theta=1e-8,... |
1729746 | from pyws.errors import ET_CLIENT
__all__ = ('Protocol', )
class Protocol(object):
"""
Abstract protocol class. Implements basic constructor, context and error
handling.
"""
def __init__(
self, context_data_getter=None, common_context_data_getter=None):
"""
Both argum... |
1729749 | import unittest
from testutils import compileErroneousZserio, assertErrorsPresent
class ApiClashingErrorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.errors = {}
compileErroneousZserio(__file__, "top_level_package_clashing/top_level_package_typing_clash_error.zs",
... |
1729752 | from __future__ import division
from past.utils import old_div
import unittest2 as unittest
import numpy as np
from vsm.spatial import *
#TODO: add tests for recently added methods.
def KL(p,q):
return sum(p*np.log2(old_div(p,q)))
def partial_KL(p,q):
return p * np.log2(old_div((2*p), (p+q)))
def JS(p,q):
... |
1729775 | from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.fairplay.fairplay_api import FairplayApi
from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.fairplay.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.fairplay.fair_play_drm_list_query_params import F... |
1729784 | from xwing.network.transport.socket.server import Server
from xwing.network.transport.stream import (
StreamConnection, DummyStreamConnection)
class StreamServer(Server):
async def accept(self):
stream_connection = StreamConnection(self.loop, await super(
StreamServer, self).accept())
... |
1729792 | from jivago.event.config.annotations import EventHandler, EventHandlerClass
from jivago.lang.annotations import Override
from jivago.lang.runnable import Runnable
@EventHandler("event")
def handler_function():
pass
@EventHandlerClass
class HandlerClass(object):
@EventHandler("event")
def handler_method... |
1729800 | from Prescient.models.user import User, load_user
from Prescient.models.watchlist import (WatchlistItems,
Watchlist_Group,
default_date)
from Prescient.models.db_securities import (Available_Securities,
... |
1729810 | from io import StringIO
import pyjion
def test_single_yield():
def gen():
x = 1
yield x
g = gen()
assert next(g) == 1
assert not pyjion.info(gen).failed
def test_double_yield():
def gen():
x = 1
yield x
yield 2
g = gen()
assert next(g) == 1
a... |
1729823 | import bpy
from bpy.types import Operator
from bl_ui_label import *
from bl_ui_button import *
from bl_ui_checkbox import *
from bl_ui_slider import *
from bl_ui_up_down import *
from bl_ui_drag_panel import *
from bl_ui_draw_op import *
class DP_OT_draw_operator(BL_UI_OT_draw_operator):
bl_idname = "o... |
1729838 | import unittest
import tempfile
import os
from FMMC import SDFWriter
class TestSDFWriter(unittest.TestCase):
def test_basics(self):
# Get a new temporary directory for each test in this class
tempdir = tempfile.mkdtemp()
# Assert that it's empty
self.assertEqual(0, len(os.... |
1729851 | import logging
import urllib.parse
from datetime import timezone
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
import dateutil.parser
import twitter
from nefelibata.announcers import Announcer
from nefelibata.announcers import Response
from nefelibata.post import Post... |
1729873 | import sys
from sys import *
class Hello(object):
def __init__(self):
object.__init__(self)
def hello(self):
print >> sys.stderr, "Hi there!"
None, True, False
r'raw \' \
string'
r"""raw multiline \"""
string"""
Hello().hello()
"""@package docstring
Documentation ... |
1729875 | import socket
s=socket.socket()
s.bind(('127.0.0.1', 8888))
print('Server is listening and waiting for a connection')
s.listen(1)
c,addr=s.accept()
#c1, addr=s.accept()
print("A client is connected")
def ADD():
c.send(("Enter number 1").encode())
a=int(c.recv(2048).decode())
c.send(("Enter number 2").encode... |
1729883 | import os
import glob
from pathlib import Path
from .textgrid_utils import build_hashtable_textgrid, get_textgrid_sa
import soundfile as sf
import numpy as np
def hash_librispeech(librispeech_traintest):
hashtab = {}
utterances = glob.glob(os.path.join(librispeech_traintest, "**/*.wav"), recursive=True)
... |
1729890 | import logging
import codecs
import re
from sortedcontainers import SortedSet
from dse.cqlengine import columns
from dse.cqlengine.models import Model
from dse import ConsistencyLevel
from nltk.corpus import stopwords
class SearchVideo():
def __init__(self, user_id, added_date, video_id, name, preview_image_locat... |
1729900 | import base64
from blacksmith import (
AsyncClientFactory,
AsyncConsulDiscovery,
AsyncHTTPAuthorizationMiddleware,
)
class AsyncBasicAuthorization(AsyncHTTPAuthorizationMiddleware):
def __init__(self, username, password):
userpass = f"{username}:{password}".encode("utf-8")
b64head = b... |
1729930 | from argparse import Namespace
import torch
from nlpmodels.utils.elt.transformer_dataset import TransformerDataset
from nlpmodels.utils.vocabulary import NLPVocabulary
def test_padded_string_to_integer_conversion():
token_list = [["the", "cow", "jumped", "over", "the", "moon"]]
vocab = NLPVocabulary.build_v... |
1729942 | import six
import random as rnd
from bpe import BpePair, PAR_CHILD_PAIR, ORD_PAIR, UNORD_PAIR
TOK_WORD = '<?>'
SKP_WORD = '<sk>'
RIG_WORD = '<]>'
SKIP_OP_LIST = ['lambda', 'exists', 'argmin', 'argmax',
'min', 'max', 'count', 'sum', 'the']
class STree(object):
def __init__(self, in... |
1729954 | import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from torch.utils.data import DataLoader
import math
import json
import logging
import time
import tensorflow as tf
from tensorfl... |
1730058 | import os
from setuptools import setup, find_packages
from setuptools.command.install import install
class CustomInstallCommand(install):
# This is only run for "python setup.py install" (not for "pip install -e .")
def run(self):
print("--------------------------------")
print("Writing enviro... |
1730081 | import json
import os
import ravinos
cfg = ravinos.get_config()
stats_ravin = ravinos.get_stats()
stats_json_path = os.path.join(cfg['miner_dir'], 'data', 'stats.json')
if not os.path.isfile(stats_json_path):
stats_ravin['shares'] = {
'accepted': 0,
'invalid': 0,
'rejected': 0
}
else:... |
1730089 | from subprocess import getoutput
from pathlib import Path
from transonic.util import timeit
statements = {
("cmorph", "_dilate"): "_dilate(image, selem, out, shift_x, shift_y)",
(
"_greyreconstruct",
"reconstruction_loop",
): "reconstruction_loop(ranks, prev, next_, strides, current_idx, i... |
1730123 | from six import PY3
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from dark.reads import Reads, DNARead
from dark.utils import asHandle
class FastqReads(Reads):
"""
Subclass of L{dark.reads.Reads} providing access to FASTQ reads.
@param _files: Either a single C{str} file name or file handle, or... |
1730167 | import numpy as np
from py_diff_stokes_flow.env.env_base import EnvBase
from py_diff_stokes_flow.common.common import ndarray
class FlowAveragerEnv3d(EnvBase):
def __init__(self, seed, folder):
np.random.seed(seed)
cell_nums = (64, 64, 4)
E = 100
nu = 0.499
vol_tol = 1e-2
... |
1730215 | import pickle
import torch
from torchtext.data import Iterator
from tqdm import tqdm
class BucketByLengthIterator(Iterator):
def __init__(self, *args, max_length=None, example_length_fn=None,
data_paths=None, **kwargs):
batch_size = kwargs['batch_size']
self.boundaries = self._b... |
1730226 | def concat_dict(x, y):
z = {}
z.update(x)
z.update(y)
return z
def concat_dict_and_select(x, select_cmd):
result = {}
for key in select_cmd.keys():
result[key] = concat_dict(x, select_cmd[key])
return select(result)
|
1730228 | import numpy as np
import vaex
def test_mutual_information():
df = vaex.example()
# A single pair
xy = yx = df.mutual_information('x', 'y')
expected = np.array(0.068934)
np.testing.assert_array_almost_equal(xy, expected)
np.testing.assert_array_almost_equal(df.mutual_information('y', 'x'), ... |
1730230 | import torch
import io
import posixpath
class ClassificationSummary:
""" Simple class to keep track of summaries of a classification problem. """
def __init__(self, num_outcomes=2, device=None):
""" Initializes a new summary class with the given number of outcomes.
Parameters
--------... |
1730266 | from graph.graph_types import Edge, Vertex
from typing import List
class Graph:
def __init__(self) -> None:
self.edges: List[Edge] = []
self.vertices: List[Vertex] = []
self.outneighbors: List[List[int]] = []
self.inneighbors: List[List[int]] = []
def add_edge(self, edge: Edge... |
1730326 | from .DataPool import DataPool
import os
import numpy as np
class Preprocessor(object):
def __init__(self, vocab, tags):
self.vocab = vocab
self.vocab.insert(0, "[PAD]")
if '[CLS]' not in self.vocab:
self.vocab.append('[CLS]')
if '[SEP]' not in self.vocab:
se... |
1730407 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('Data_age_salary.csv');
dataset.iloc[:1] |
1730427 | class MagicDict(object):
def __init__(self):
super(MagicDict, self).__setattr__('internal', {})
def __setattr__(self, key, value):
self.internal[key] = value
def __getattr__(self, key):
return self.internal[key]
def __iter__(self):
return iter(self.internal)
def v... |
1730432 | import numpy as np
from astropy.table import Table
from btk.metrics import get_detection_match
def test_true_detected_catalog():
"""Test if correct matches are computed from the true and detected tables"""
names = ["x_peak", "y_peak"]
cols = [[0.0, 1.0], [0.0, 0.0]]
true_table = Table(cols, names=nam... |
1730470 | import copy
import csv
import numpy as np
import traceback
import requests
import json
import time
import boto
import alog
import logging
from boto.s3.key import Key
from StringIO import StringIO
from datetime import datetime
from django.db.utils import IntegrityError
from firecares.utils.arcgis2geojson import arcgis2g... |
1730471 | from sklearn.cluster import KMeans, MiniBatchKMeans
true_k=5
km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
kmini = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1,
init_size=1000, batch_size=1000, verbose=opts.verbose)
# we are using the same test,train ... |
1730503 | import pytest
import cv2
import numpy as np
from transformers.ascii_art import ASCIIArt
@pytest.fixture
def ascii_art():
return ASCIIArt()
def test_object_default_params(ascii_art):
assert ascii_art.color_min == "green"
assert ascii_art.color_max == "pink"
assert ascii_art.bgcolor == "white"
assert ascii_a... |
1730504 | import os
def drag_and_drop(driver, source, target):
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__))
)
f = open(os.path.join(__location__, "drag_and_drop.js"), "r")
javascript = f.read()
f.close()
driver.execute_script(javascript, source, target)
... |
1730507 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
class patcher(patcher):
def __init__(self, body='./body/body_noy.png', **options):
super().__init__('ノイ', body=body, pantie_position... |
1730513 | from typing import List
from powergate.admin.v1 import admin_pb2, admin_pb2_grpc
from pygate_grpc.errors import ErrorHandlerMeta
class WalletClient(object, metaclass=ErrorHandlerMeta):
def __init__(self, channel, get_metadata):
self.client = admin_pb2_grpc.AdminServiceStub(channel)
self.get_meta... |
1730527 | import pygame
pygame.init()
window = pygame.display.set_mode((1200, 400))
track = pygame.image.load('track.png')
car = pygame.image.load('tesla.png')
car = pygame.transform.scale(car, (30, 60))
carX = 150
carY = 300
focalDis = 25
camX_offset = 0
camY_offset = 0
direction = 'up'
drive = True
clock = pygame.time.Clock()
... |
1730529 | from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import librosa, librosa.display
def generate_spectrogram(filepath):
data, sampling_rate = librosa.load(filepath)
plt.figure(figsize=(1, 1))
plt.axis('off')
melspectrogram = librosa.feature.melspectrogram(y=data, sr=sampling_rat... |
1730537 | import datetime
from influxdb_client.client.flux_table import FluxTable, FluxColumn, FluxRecord
from tests.base_test import BaseTest
class FluxObjectTest(BaseTest):
def test_create_structure(self):
_time = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
table = FluxTable()
... |
1730571 | from typing import Tuple
import jax
from ..custom_types import Bool, DenseInfo, PyTree, Scalar
from ..local_interpolation import LocalLinearInterpolation
from ..misc import ω
from ..solution import RESULTS
from ..term import AbstractTerm
from .base import AbstractItoSolver, AbstractSolver
_ErrorEstimate = None
_Sol... |
1730601 | from flask import g
from . import database as db
from OBlog import app
from .blueprint.posts.main import getPostForShow
from .blueprint.admin.main import getSiteConfigDict
import re
def getSite():
if not hasattr(g, 'getSite'):
res = getSiteConfigDict()
from .blueprint.pages.main import ge... |
1730640 | import struct
import ctypes
import capstone as cp
from typing import (
List,
Set,
Dict,
Tuple,
Generator
)
from ..extraction_context import ExtractionContext
from ..macho.macho_context import MachOContext
from ..converter import (
slide_info,
stub_fixer
)
from ..objc.objc_structs import (
objc_category_t,
o... |
1730737 | import uuid
from .types import FSharpRef
def parse(string: str) -> uuid.UUID:
return uuid.UUID(string)
def try_parse(string: str, def_value: FSharpRef[uuid.UUID]) -> bool:
try:
def_value.contents = parse(string)
return True
except Exception:
return False
def to_string(guid: uui... |
1730799 | from trapper.data.data_adapters.data_adapter import DataAdapter
from trapper.data.data_adapters.question_answering_adapter import (
DataAdapterForQuestionAnswering,
)
|
1730803 | import tensorflow as tf
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name='W')
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name='B')
|
1730843 | from setuptools import setup, find_packages
setup(name='vipriors-reid',
version='0.0.1',
description='Deep Learning Library for Person Re-identification for the VIPriors Challenge',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/VIPriors/vipriors-challenges-toolkit',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.