id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11569131 | import pytest
import os
class TestChatAndStudent:
chat_files_data_regular = [
"chat_file_valid_english_nba_7_students.txt",
"chat_file_valid_hebrew_7_students.txt"
]
@pytest.mark.parametrize("chat_file_name", chat_files_data_regular)
def test_create_chat_df_validation_regular(self, ... |
11569161 | from PwnContext import *
if __name__ == '__main__':
context.terminal = ['tmux', 'splitw', '-h'] # I always use tmux
context.log_level = 'info'
#-----function for quick script-----#
s = lambda data :ctx.send(str(data)) #in case that data is a int
sa = lambda d... |
11569181 | from graphql import GraphQLSchema, GraphQLResolveInfo
import frappe
def bind(schema: GraphQLSchema):
schema.mutation_type.fields["deleteDoc"].resolve = delete_doc_resolver
def delete_doc_resolver(obj, info: GraphQLResolveInfo, **kwargs):
doctype = kwargs.get("doctype")
name = kwargs.get("name")
doc... |
11569227 | from erde.io.gpkg import driver as dr
from erde import read_df
from time import sleep
import errno
import geopandas as gpd
import os
import pytest
d = 'tests/io/data/'
points_file = d + 'blocks-points.gpkg'
match_points = d + 'match-points.gpkg'
def silentremove(filename):
filename, *rest = filename.split(':')
t... |
11569242 | from inspect import getmembers, getmodule
from typing import Set, Tuple, Type
from .schemes import BaseScheme
class TouchUp:
_registry: Set[Tuple[Type, str]] = set()
@classmethod
def run(cls, app):
for target, method_name in cls._registry:
method = getattr(target, method_name)
... |
11569248 | from abaqus import *
from abaqusConstants import *
import config
from src.builders import MODEL_NAME, STEP_NAME
from src.builders.base_builder import BaseBuilder
class DynamicFieldOutputRequestBuilder(BaseBuilder):
def __init__(self):
super(DynamicFieldOutputRequestBuilder, self).__init__()
self.... |
11569249 | class TimeZoneDBPlugin:
def __init__(self, config):
super(TimeZoneDBPlugin, self).__init__()
self.config = config
# pylint: disable=no-self-use
def generate(self, result):
datetime = result["datetime"]
location = result["location"]
return {
"text": "It... |
11569263 | chart_options = dict(
mode="vega-lite",
renderer="svg",
actions={"export": True, "source": True, "editor": True},
theme="light",
tooltip={"theme": "light"},
)
|
11569274 | import pytest
from cluster_toolkit import sigma_reconstruction as SR
from os.path import dirname, join
import numpy as np
import numpy.testing as npt
|
11569360 | from __future__ import print_function, division, unicode_literals
import os
import operator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from math import sqrt
from scipy.spatial import Delaunay, ConvexHull
from pymatgen.core.composition import Composition
from pymatgen... |
11569370 | from build.management.commands.export_publications import Command as ExportPublications
class Command(ExportPublications):
pass |
11569375 | from django import forms
class ShellForm(forms.Form):
code = forms.CharField(
required=False,
widget=forms.Textarea(attrs={'class': 'codearea'}),
)
error_css_class = 'error'
|
11569379 | from citrination_client.data import DatasetVersion
def test_can_crud_number():
"""
Tests that full get/set/delete functionality is
available for the number property
"""
d = DatasetVersion(1)
number = 2
assert d.number is 1
d.number = number
assert d.number is number
del(d.numbe... |
11569380 | from .convert import config_to_classifier, classifier_to_pipeline, obtain_classifier, runhistory_to_trajectory, setups_to_configspace, modeltype_to_classifier, scale_configspace_to_log
from .connect import task_counts, obtain_runhistory_and_configspace, cache_runhistory_configspace
from .filesystem import obtain_margin... |
11569392 | from typing import Dict
from flask import request
from flask_accepts import accepts, responds
from flask_restx import Namespace, Resource
from werkzeug.exceptions import BadRequest, Unauthorized
from werkzeug.security import check_password_hash
from .models import Token
from .schema import TokenSchema, UserSchema
fro... |
11569403 | import os
import sys
import copy
import logging
from checker import *
from .utils import create_section_name
from .ofp import OfpBase
from .utils import get_attrs_without_len
# YAML:
# - min_rate:
# rate: 0
SCE_PROPERTIES = "properties"
class OfpQueuePropCreator(OfpBase):
@classmethod
def create(cls... |
11569444 | def minion_game(string):
con, vow, l = "bcdfghjklmnpqrstvwxyz", "euioa", len(string)
p1, p2 = {"name": "Stuart", "score": 0}, {"name": "Kevin", "score": 0}
for i, char in enumerate(string.lower()):
if char in con:
p1["score"] += l - i
elif char in vow:
p2["score"] += ... |
11569455 | import unittest
import numpy
from nlcpy import testing
nan_dtypes = (
numpy.float32,
numpy.float64,
numpy.complex64,
numpy.complex128,
)
shapes = (
(4,),
(3, 4),
(2, 3, 4),
)
@testing.parameterize(*(
testing.product({
'shape': shapes,
})
))
class TestPtp(unittest.TestCase... |
11569491 | import requests
import lxml
from lxml import etree
from lxml.html import fromstring
root = etree.parse(r'C:\Users\Kiril\PycharmProjects\Diploma2020\data\corpus.xml')
root = root.getroot()
corpus = etree.SubElement(root, "corpus")
source_examples = dict()
text_num = dict()
status_codes = dict()
failed_elements = dict(... |
11569509 | import logging
from scanner import barcode_reader
# simple usage - in python 3
if __name__ == '__main__':
try:
while True:
upcnumber = barcode_reader()
print(upcnumber)
except KeyboardInterrupt:
logging.debug('Keyboard interrupt')
except Exception as err:
l... |
11569546 | from collections import OrderedDict
from .tensor import weighted_sum
def average_state_dicts(dicts, weights=None):
if not weights:
weights = (1 / len(dicts),) * len(dicts)
averaged = OrderedDict()
for k in dicts[0]:
averaged[k] = weighted_sum([d[k] for d in dicts], weights)
return averaged
|
11569554 | import lime
import lime.lime_tabular
import matplotlib as plt
from django.core.management.base import BaseCommand
from sklearn.externals import joblib
from src.core.core import get_encoded_logs
from src.encoding.common import retrieve_proper_encoder
from src.jobs.models import Job
class Command(BaseCommand):
hel... |
11569558 | from PyQt5.QtWidgets import QApplication
from client.client_gui import ClientWindow
if __name__ == '__main__':
import sys
if len(sys.argv) < 5:
print(f"Usage: {sys.argv[0].split('/')[-1]} <file name> <host address> <host port> <RTP port>")
exit(-1)
file_name, host_address, host_port, rt... |
11569567 | from .__about__ import (
__license__,
__copyright__,
__url__,
__contributors__,
__version__,
__doc__
)
# user-facing classes are exposed via __all__
from .data_types import *
from .logging import make_logger
from .runtime import *
from .wiring import *
# standard library
from . import lib
|
11569582 | import logging
import glob
import os
import os.path
import sys
import re
import subprocess
import datetime
import imp
import warnings
import traceback
import importlib
import inspect
import sqlparse
import click
log = logging.getLogger('mschematool')
DEFAULT_CONFIG_MODULE_NAME = 'mschematool_config'
# Ignore warn... |
11569615 | import unittest
from types import SimpleNamespace
class TestCaseWithState(unittest.TestCase):
state = SimpleNamespace()
|
11569672 | def task_checker():
return {'actions': ["pyflakes sample.py"],
'file_dep': ["sample.py"]}
|
11569723 | import json
import os
import csv
import io
import shutil
def parseSong(song, extremeJSON):
if (song['name_translation'] == ''):
songName = song['name']
else:
songName = song['name_translation']
for root, dirnames, filenames in os.walk('Songs'):
if (songName in dirnames):
... |
11569747 | import traceback
import util
import sys
import logging
from onnx import numpy_helper
from pb_wrapper import OnnxNode
from type_converter import dtype_onnx2tl
def new_opname(optype):
if not hasattr(new_opname, 'opname_count'):
new_opname.opname_count = {}
if optype in new_opname.opname_count:
ne... |
11569765 | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.autograd import Variable
import torch.nn.functional as F
import sk... |
11569778 | import hashlib
import string
from typing import (
Any,
Dict,
Hashable,
Iterable,
Iterator,
List,
Mapping,
Optional,
Tuple,
TypeVar,
)
T = TypeVar('T')
K = TypeVar('K')
V = TypeVar('V')
H = TypeVar('H', bound=Hashable)
# Based on: https://stackoverflow.com/a/2704866
# Perhaps o... |
11569779 | from torch import nn
magic_number = -1.0E+10
def run_lstm(module, H):
H = nn.utils.rnn.pack_sequence(H, enforce_sorted=False)
Y, _ = module(H)
Y, lengths = nn.utils.rnn.pad_packed_sequence(Y, batch_first=True)
Y = [Y[i, :length] for i, length in enumerate(lengths)]
return Y
|
11569806 | import sys
from fractions import gcd
def lcm(a,b):
return (a*b)/gcd(a, b)
n, m = raw_input().strip().split(' ')
n, m = [int(n), int(m)]
a = map(int, raw_input().strip().split(' '))
b = map(int, raw_input().strip().split(' '))
count=0
lcm=reduce(lcm, a)
gcd=reduce(gcd, b)
lcm_copy = lcm
while(lcm<=gc... |
11569813 | import datetime
from quantdsl.domain.model.market_simulation import MarketSimulation
from quantdsl.domain.model.simulated_price import make_simulated_price_id, SimulatedPrice
from quantdsl.defaults import DEFAULT_PRICE_PROCESS_NAME
from quantdsl.tests.test_application import ApplicationTestCase
class TestMarketSimul... |
11569823 | from omni_reports.client.fields import AttributeReportField, MetricReportField, SegmentReportField
from omni_reports.google_reports.base import GoogleAdsReportType
BOOLEAN_VALUES = {
'true': True,
'false': False
}
def to_bool(val):
return BOOLEAN_VALUES.get(val)
class GoogleAdsAccountPerformanceReportT... |
11569824 | from keras.models import Model
from utils.layers import Conv1D, _activation
from keras.layers import Input, Concatenate, Reshape, Dense, Add,\
Activation, Flatten, Dropout, BatchNormalization,\
Flatten, RepeatVector, LocallyConnected1D, ZeroPadding1D,\
... |
11569830 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='scatnetgpu',
version='1.1',
description='Scattering Network for Python and CUDA',
long_description=readme(),
url='http://github.com/oinegue/scatnetgpu',
author='<NAME>',
... |
11569854 | import re
# 去除字符中不可见的控制字符
def remove_control_chars(s):
ctl_list = list(range(0, 32)) + list(range(127, 160))
# 排除 \n 10 与 \r 13
ctl_list.remove(10)
ctl_list.remove(13)
control_chars = ''.join(map(chr, ctl_list))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
return control... |
11569865 | import requests
from functools import wraps
from .auth import OAuth
from . import endpoints
class Client:
prefix = 'https://api.spotify.com/v1'
api = endpoints # So static analysis is useful
def __init__(self, auth: OAuth, requests_session=None):
self.session = requests_session or requests.Ses... |
11569886 | class VM_Disassembler:
def __init__(self, code, disassembler, entry_point, look_ahead_len = 0):
# code is a list of ints
self.code = code
# this the core disassembler function
# the user needs to write it
self.disassembler = disassembler
self.entry_point = entry... |
11569940 | from .. import utils as test_utils
teamocil_yaml = test_utils.read_config_file("config_teamocil/test2.yaml")
teamocil_dict = {
"windows": [
{
"name": "sample-four-panes",
"root": "~/Code/sample/www",
"layout": "tiled",
"panes": [{"cmd": "pwd"}, {"cmd": "pwd"}... |
11569953 | import os
from dotenv import load_dotenv
from flask import Flask, jsonify
load_dotenv()
def create_app():
app = Flask(__name__, static_folder="./../dist/static")
app.config.from_object(os.getenv("APP_SETTINGS"))
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
register_extensions(app)
regi... |
11569967 | import numpy as np
import logging
from FixedBase import FixedBase
class FixedPredict(FixedBase):
def __init__(self, iterations=1):
super().__init__(iterations)
def predict(self, X, feature_names):
return self.work()
|
11569991 | from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Web Site"),
"items": [
{
"type": "doctype",
"name": "Website Info",
"description": _("Website Info"),
}
]
}
]
|
11570035 | import unittest
from twstock.proxy import get_proxies, configure_proxy_provider, reset_proxy_provider
from twstock.proxy import SingleProxyProvider
from twstock.proxy import RoundRobinProxiesProvider
class ProxyProviderTest(unittest.TestCase):
def setUp(self):
reset_proxy_provider()
def tearDown(se... |
11570039 | import io
import logging
import sys
from contextlib import contextmanager
from test_junkie.decorators import synchronized
class LogJunkie:
__LOGGER = None
__ENABLED = False
__PRIORITY = logging.ERROR
__NAME = "TestJunkieLogger"
__FORMAT = "%(asctime)s [%(levelname)s] (%(filename)s, %(funcName)s(... |
11570080 | from copy import copy
import os
from schemer import ValidationException
from ..compiler.spec_assembler import get_specs_path, get_specs_from_path
from ..log import log_to_client
from ..schemas import app_schema, bundle_schema, lib_schema
from ..schemas.base_schema_class import notifies_validation_exception
from .. im... |
11570141 | from transformers import T5ForConditionalGeneration, T5Tokenizer
# initialize the model architecture and weights
model = T5ForConditionalGeneration.from_pretrained("t5-base")
# initialize the model tokenizer
tokenizer = T5Tokenizer.from_pretrained("t5-base")
article = """
<NAME> and <NAME>, welcome to parenthood.
The... |
11570204 | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=250)
nickname = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
publication_date = models.DateField()
isbn = models... |
11570209 | import os
import time
import numpy as np
from airobot import Robot
from airobot.utils.common import euler2quat
from airobot.utils.pb_util import TextureModder
def main():
"""
This function demonstrates how to move the robot arm
to the desired joint positions.
"""
dir_path = os.path.dirname(os.pa... |
11570223 | import numpy as np
import torch
def mixup_vae_data(image, z_mean, z_log_sigma, disc_log_alpha, optimal_match=True):
'''Returns mixed inputs, pairs of targets, and lambda'''
lam = np.random.beta(2.0, 2.0)
batch_size = image.size()[0]
if optimal_match:
# use the optimal match to provide match in... |
11570230 | from base64 import b64encode
from asgi_webdav.constants import DAVPath, DAVUser
from asgi_webdav.config import update_config_from_obj, get_config
from asgi_webdav.auth import DAVAuth
from asgi_webdav.request import DAVRequest
config_data = {
"account_mapping": [
{"username": "user1", "password": "<PASSWO... |
11570239 | from typing import List
import spacy
from fastapi import FastAPI
from pydantic import BaseModel
import edsnlp
app = FastAPI(title="EDS-NLP", version=edsnlp.__version__)
nlp = spacy.blank("eds")
nlp.add_pipe("eds.sentences")
config = dict(
regex=dict(
covid=[
"covid",
r"covid[-\... |
11570257 | import Pyro5.api
import Pyro5.core
import Pyro5.client
import Pyro5.server
import Pyro5.nameserver
import Pyro5.callcontext
import Pyro5.serializers
from Pyro5.serializers import SerializerBase
def test_api():
assert hasattr(Pyro5.api, "__version__")
assert Pyro5.api.config.SERIALIZER == "serpent"
assert ... |
11570266 | from setuptools import setup, find_packages
import glob
import zhuaxia.zxver as zxver
setup(
name = 'zhuaxia',
version = zxver.version,
install_requires=['pycrypto', 'requests','mutagen','beautifulsoup4' ],
packages = find_packages(),
package_data={'zhuaxia':['conf/default.*']},
#data_files=[('c... |
11570292 | import requests
from bgmi import config
from bgmi.plugin.download import BaseDownloadService, DownloadStatus, RpcError
class DelugeRPC(BaseDownloadService):
def __init__(self):
self._id = 0
self._session = requests.session()
self._call("auth.login", [config.DELUGE_RPC_PASSWORD])
@sta... |
11570302 | from tests.helm_template_generator import render_chart
import pytest
import yaml
from . import git_root_dir
with open(f"{git_root_dir}/tests/default_chart_data.yaml") as file:
default_chart_data = yaml.load(file, Loader=yaml.SafeLoader)
template_ids = [template["name"] for template in default_chart_data]
@pyte... |
11570348 | import numpy as np
class DataFormatConverter():
def __init__(self, pose_config_source, pose_config_target):
self.pose_config_source = pose_config_source
self.pose_config_target = pose_config_target
self.num_source_kpts = len(self.pose_config_source['KEYPOINT_NAMES'])
self.num_targ... |
11570350 | import json
import logging
from typing import Dict, List, Tuple, Union
from repro.common import util
from repro.common.docker import DockerContainer
from repro.common.io import read_jsonl_file
from repro.data.types import MetricsType, TextType
from repro.models import Model
from repro.models.scialom2021 import DEFAULT... |
11570362 | import argparse
import random
import cv2
import numpy as np
import pickle
import math
from sklearn import preprocessing
from collections import OrderedDict
class ClassifierANN(object):
def __init__(self, feature_vector_size, label_words):
self.ann = cv2.ml.ANN_MLP_create()
# Number of centroids use... |
11570413 | import argparse
import torch
from torch import Tensor
from pl_bolts.models.rl.sac_model import SAC
def test_sac_loss():
"""Test the reinforce loss function."""
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser = SAC.add_model_specific_args(parent_parser)
args_list = [
"--... |
11570430 | from .base_primitive import BasePrimitive
class Group(BasePrimitive):
def __init__(self, name, values):
"""
This primitive represents a list of static values, stepping through each one on mutation. You can tie a block
to a group primitive to specify that the block should cycle through all ... |
11570472 | from __future__ import absolute_import, unicode_literals
import importlib
import re
import binascii
from json import JSONDecodeError
from djangoTrade.celery import app
from ccxt import ExchangeNotAvailable, RequestTimeout
from celery.schedules import crontab
from celery.task import periodic_task
import datetime
import ... |
11570483 | import machine
import pytest
@pytest.fixture
def timer():
return machine.Timer(0)
def test_timer_does_not_run_on_construction(timer):
assert not timer.is_running_for_testing
def test_timer_runs_on_init(timer):
timer.init(period=1000)
assert timer.is_running_for_testing
|
11570517 | from django.conf import settings
DEFAULT_CONDITIONS = [
('django_email_multibackend.conditions.MatchAll', {})
]
EMAIL_BACKENDS_CONDITIONS = getattr(settings, 'EMAIL_BACKENDS_CONDITIONS', {})
EMAIL_BACKENDS_WEIGHTS = getattr(settings, 'EMAIL_BACKENDS_WEIGHTS', tuple())
EMAIL_BACKENDS = getattr(settings, 'EMAIL_BAC... |
11570540 | import warnings
import sys
import os
from distutils.version import StrictVersion
def warn(msg):
print msg
warnings.warn(msg)
warn.count += 1
warn.count = 0
def check_import(package_name, version=None):
try:
pkg = __import__(package_name)
except ImportError:
warn("Package {0} is no... |
11570570 | import os
from dash_slicer.docs import get_reference_docs, md_seperator
HERE = os.path.dirname(os.path.abspath(__file__))
def test_that_the_docs_build():
x = get_reference_docs()
assert "VolumeSlicer(app, vol" in x
assert "create_overlay_data(mask" in x
assert "performance" in x.lower()
def test_... |
11570580 | class Pizza:
def ingredientes(self):
return 'Ingredientes'
class Mussarela(Pizza):
def ingredientes(self):
return ['quejo mussarela',
'molho de tomate',
'oregano']
|
11570599 | import os, json
import ipfsapi
from web3 import Web3, IPCProvider
from populus.utils.wait import wait_for_transaction_receipt
w3 = Web3(IPCProvider('/tmp/geth.ipc'))
common_password = '<PASSWORD>'
accounts = []
with open('accounts.txt', 'w') as f:
for i in range(4):
account = w3.personal.newAccount(commo... |
11570646 | from contextlib import contextmanager
from bearlibterminal import terminal as _terminal
from .nice_terminal import NiceTerminal
from .state import blt_state
from clubsandwich.geom import Point
class BearLibTerminalContext(NiceTerminal):
"""
A class that acts like :py:attr:`clubsandwich.blt.nice_terminal.ter... |
11570655 | import numpy as np
from deepnet.utils import softmax
from deepnet.layers import Conv, FullyConnected
def l2_regularization(layers, lam=0.001):
reg_loss = 0.0
for layer in layers:
if hasattr(layer, 'W'):
reg_loss += 0.5 * lam * np.sum(layer.W * layer.W)
return reg_loss
def delta_l2_re... |
11570725 | import matplotlib.pylab as plt
import os
import sys
print sys.path
import numpy
import scipy
import os
from scipy import interpolate
from scipy import integrate
def intercec(A,B):
if A[0] < B[0]:
ini = B[0]
else:
ini = A[0]
if A[-1] < B[-1]:
fin = A[-1]
else:
fin = B[-1]
return ini,fin
def CCF(L... |
11570733 | from typing import List
import hid
import mystic_why.common.const as const
from mystic_why.common.enums import LightArea
from mystic_why.common.exception import DeviceNotFound, AreaNotFound
class Color:
@staticmethod
def create_by_hex(hex_value):
hex_value = hex_value.lstrip('#')
return Colo... |
11570741 | from backend.common.consts.model_type import ModelType
from backend.common.models.account import Account
from backend.common.models.favorite import Favorite
from backend.common.queries.favorite_query import FavoriteQuery
def test_no_favorites() -> None:
account = Account(id="uid")
favorites = FavoriteQuery(ac... |
11570775 | import kfp.dsl as dsl
import kfp.gcp as gcp
def evaluate_op(
*,
gcs_bucket,
pose_estimation_gcs_path,
log_dir,
docker_image,
memory_limit,
num_gpu,
gpu_type,
checkpoint_file=None,
):
""" Create a Kubeflow ContainerOp to train an estimator on the cube sphere dataset.
Args:
... |
11570787 | def launchTensorBoard():
import os
PATH = os.getcwd()
os.system('tensorboard --logdir=' + 'embedding-logs')
return
import threading
t = threading.Thread(target=launchTensorBoard, args=([]))
t.start()
#In your browser, enter http://localhost:6006 as the URL
#add #projector to the URL if necessary: ... |
11570808 | import os
from collections import namedtuple
import pytest
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.actor import addupgradebootentry
from leapp.libraries.common.config.architecture import ARCH_X86_64, ARCH_S390X
from leapp.libraries.common.testutils import CurrentActorMocked
from leap... |
11570827 | from django.conf.urls import url
from corehq.messaging.smsbackends.apposit.views import AppositIncomingView
urlpatterns = [
url(r'^in/(?P<api_key>[\w-]+)/$', AppositIncomingView.as_view(), name=AppositIncomingView.urlname),
]
|
11570828 | import copy
import importlib
import sys
try:
from unittest import mock
except ImportError:
import mock
import unittest2
import rollbar
from rollbar.lib._async import AsyncMock
from rollbar.test import BaseTest
ALLOWED_PYTHON_VERSION = sys.version_info >= (3, 5)
ASYNC_REPORT_ENABLED = sys.version_info >= (3,... |
11570928 | import unittest
import numpy as np
import kinpy as kp
class TestFkIk(unittest.TestCase):
def test_fkik(self):
data = '<robot name="test_robot">'\
'<link name="link1" />'\
'<link name="link2" />'\
'<link name="link3" />'\
'<joint name="joint1" type="revolute">'\
'<or... |
11570932 | from .mapper import ApiResponse
from .model.collection import CollectionInterface
__all__ = ['CreateCollectionResponse']
class CreateCollectionResponseInterface(CollectionInterface):
pass
class CreateCollectionResponse(ApiResponse, CreateCollectionResponseInterface):
pass
|
11570935 | from rolling_grid_search import rolling_grid_search_ML
import pandas as pd
import numpy as np
from pandas import *
from numpy import *
from sklearn import svm
from sklearn.model_selection import TimeSeriesSplit,ParameterGrid
from sklearn.neighbors import KNeighborsRegressor
from sklearn import svm
data = p... |
11570940 | from pyschema import Record, no_auto_store
from pyschema.types import Text
@no_auto_store()
class TestRecord(Record):
_namespace = "my.namespace"
a = Text()
|
11570952 | from selenium import webdriver
import time
PATH = 'PATH OF CHROME DRIVER LOCATED IN YOUR MACHINE'
driver = webdriver.Chrome(PATH)
driver.get('https://web.whatsapp.com/')
print('----------------------------------------------------------------\n'
'| WELCOME TO WHATSAPP AUTOMATION |\n'... |
11570964 | from websockets.exceptions import (
ConnectionClosed,
ConnectionClosedOK,
InvalidStatusCode
)
class UnsuccessfulConnection(Exception):
'''
Unsuccessful connection to an endpoint (e.g., ws)
'''
pass
class MaximumRetriesReached(Exception):
'''
Maximum retries reached while fetching ... |
11570972 | import torch
from torch.utils.data import DataLoader
import pandas as pd
from tqdm import tqdm
from dataset.patch_extraction import PANDAPatchExtraction
import json
torch.backends.cudnn.benchmark = False
def main():
tiff_dir=SETTINGS['RAW_DATA_DIR']+"train_images/"
mask_dir=SETTINGS['RAW_DATA_DIR']+"... |
11570986 | from attrdict import AttrDict
config = AttrDict()
config.log_path = '/rebryk/kaggle/protein/logs'
config.data_path = '/rebryk/kaggle/protein/dataset'
config.model_path = '/rebryk/kaggle/protein/models'
config.submission_path = '/rebryk/kaggle/protein/submissions'
config.tensorboard_path = '/rebryk/logs'
config.exp =... |
11570987 | import h5py
import numpy as np
from pathlib import Path
import warnings
"""
Code to transform the original dataset into a form that has faster data IO.
This is especially important for non-SSD storage.
For most systems, File I/O is the bottleneck for training speed.
"""
def check_chunk_size(data, chunk, file):
... |
11571072 | from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
from checkov.common.models.enums import CheckCategories
class GKENetworkPolicyEnabled(BaseResourceValueCheck):
def __init__(self):
name = "Ensure Network Policy is enabled on Kubernetes Engine Clusters"
... |
11571113 | import torch
from registry import registry
from eval_settings.eval_setting_base import EvalSetting, StandardDataset, accuracy_topk
from eval_settings.eval_setting_subsample import class_sublist_1_8
registry.add_eval_setting(
EvalSetting(
name = 'val',
dataset = StandardDataset(name='val'),
... |
11571130 | def main():
if a := 1:
print(a)
if c := "":
print(c)
if d := b"":
print(d)
if e := "Hello":
print(e)
if f := b"Goodbye":
print(f)
if g := 1.0:
print(g)
if h := 1j:
print(h)
if i := 0.0:
print(i)
if j := 0j:
... |
11571146 | from optimus.tests.base import TestBase
class TestLoadPandas(TestBase):
def test_json(self):
df = self.load_dataframe("examples/data/foo.json", type="json", multiline=True)
self.assertEqual(df.rows.count(), 19)
self.assertEqual(df.cols.names(), ["id", "firstName", "lastName", "billingId",... |
11571147 | from __future__ import absolute_import
from sqlalchemy import MetaData
import six
from ..db import db
class DialectOperations(object):
dialect_map = {}
option_defaults = None
def __init__(self, engine, bind_name, options=None):
# this engine is tied to a particular "bind" use it instead of db.e... |
11571148 | import arboretum
import numpy as np
from sklearn.datasets import load_boston
import json
import pytest
import utils
@pytest.mark.parametrize("double_precision", [True, False])
@pytest.mark.parametrize("method", ['hist', 'exact'])
@pytest.mark.parametrize("hist_size", [12, 15, 16, 31, 32, 63, 64, 127, 128, 255, 256, 5... |
11571167 | from validation import vworkspace
with vworkspace() as w:
w.props.memory_effects_only = False
w.fun.main.validate_phases("privatize_module", "internalize_parallel_code", "localize_declaration");
|
11571186 | import discord
from discord.ext import commands
import asyncio
import utils
class Moderation(metaclass=utils.MetaCog, colour=0xffd0b5, thumbnail='https://i.imgur.com/QJiga6E.png'):
"""Nothing like a good spanking! These commands should give your mods a good feeling inside.
Most of these commands require, [M... |
11571247 | from typing import Optional
class ColumboException(Exception):
"""Base exception for exceptions raised by Columbo"""
class DuplicateQuestionNameException(ColumboException):
"""Multiple questions use the same name."""
class CliException(ColumboException):
"""An error occurred while processing command l... |
11571252 | import unittest
import gfapy
class TestApiComments(unittest.TestCase):
def test_initialize(self):
l = gfapy.line.Comment("# hallo")
self.assertEqual("# hallo", str(l))
l = gfapy.line.Comment(["#", "hallo", "\t"])
self.assertEqual("#\thallo", str(l))
def test_fields(self):
l = gfapy.line.Comment("#... |
11571267 | import sys
import time
sys.path.insert(1, __file__.split("tests")[0])
from test_junkie.runner import Runner
from tests.junkie_suites.Reporting import LoginSessions, Login, Dashboard
def test_reporting():
f = __file__.replace("test_reporting.py", "test_{}".format(int(time.time())))
html = "{}.html".format(f)... |
11571318 | from itertools import tee, izip, chain
def cycle_pairs(iterable):
"""
Cycles through the given iterable, returning an iterator which
returns the current and the next item. When reaching the end
it returns the last and the first item.
"""
first, last = iterable[0], iterable[-1]
a, b = tee(i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.