id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4812148 | import discord
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
import math as m
class Mathematics(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Mathematics comm... |
4812151 | import networkx as nx
import EoN
import matplotlib.pyplot as plt
r'''Each time the infected population hits 40000, we'll introduce an intervention.
To do this, we run it for short intervals until we overshoot, but then backtrack to the time at which
40000 is hit, and then run again with intervention in place.'''
|
4812164 | class PointArc2Error(Exception):
""" """
pass
class AngleArc2Error(Exception):
""" """
pass
class NbPointArc2DError(Exception):
""" """
pass
class AngleRotationArc2Error(Exception):
""" """
pass
class PointTranslateArc2Error(Exception):
""" """
pass
|
4812188 | import torch
from .grid import *
from .cartesian import *
''' Image (I) spatial derivatives '''
def dI_du(img):
right_pad = (0, 1, 0, 0)
tensor = torch.nn.functional.pad(img, right_pad, mode="replicate")
gu = tensor[:, :, :, :-1] - tensor[:, :, :, 1:] # NCHW
return gu
def dI_dv(img):
... |
4812193 | SAS_config_names = ['viya4']
viya4 = {
'url':'https://binder.demo.sas.com',
'verify': False,
'context':'SAS Job Execution compute context',
'client_id' : "SASPy",
'client_secret' : "7c301751-3114-4554-ad82-e20e3466bb17",
}
|
4812198 | from PIL import Image
import numpy as np
import os
import torch
import torch.nn as nn
import torch.utils.data as utils
import torch.nn.functional as F
import higher
import pickle
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import datasets, transforms
from torch.autograd import grad
from tq... |
4812214 | from pathlib import Path
from time import sleep
import pytest
from cloudpathlib.local import LocalGSPath, LocalS3Path, LocalS3Client
from cloudpathlib.exceptions import (
CloudPathFileExistsError,
CloudPathNotADirectoryError,
OverwriteNewerCloudError,
)
@pytest.fixture
def upload_assets_dir(tmpdir):
... |
4812224 | from inky import InkyPHAT
from PIL import Image, ImageFont, ImageDraw
from font_fredoka_one import FredokaOne
import subprocess
inky_display = InkyPHAT("red")
inky_display.set_border(inky_display.WHITE)
img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)
font = ImageFont.truetyp... |
4812228 | import unittest
import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'network-config-analyzer'))
def main():
loader = unittest.TestLoader()
start_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'tests',
... |
4812239 | from app.users import bp
from app.models import Users
from app.schemas import UsersSchema
from app.errors.handlers import bad_request
from flask_jwt_extended import jwt_required, current_user
# Declare database schemas so they can be returned as JSON objects
user_schema = UsersSchema(exclude=("email", "password_hash"... |
4812260 | import cirq
import numpy
class C3SXGate(cirq.Gate):
def __init__(self):
super(C3SXGate, self).__init__()
def _num_qubits_(self):
return 4
def _unitary_(self, dtype=None):
exp1 = (1+1j)/2
exp2 = (1-1j)/2
mat = numpy.array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
4812261 | import hashlib
from typing import (
Any,
Callable,
Iterable,
)
from eth_utils.toolz import (
curry,
identity,
)
from .loading import (
find_fixtures,
)
#
# Pytest fixture generation
#
def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names fo... |
4812304 | from PIL import Image
import os, subprocess, pickle
import torch
import numpy as np
def unpickle(file, lineSize):
img_size2 = lineSize * lineSize
with open(file, 'rb') as fo:
d = pickle.load(fo)
x = d['data']
y = d['labels']
x = np.dstack((x[:, :img_size2], x[:, img_size2:2 * img_size2], x... |
4812320 | from seamless.highlevel import Context, Cell, Transformer, Link, load_graph
from seamless.highlevel import stdlib
import os, json
ctx = Context()
ctx.include(stdlib.merge)
ctx.initial_graph = Cell("plain").mount("initial-graph.seamless", "r")
ctx.seamless2webform = Cell("code").mount("../seamless2webform.py", "r")
ctx... |
4812321 | import os
import random
import tempfile
import numpy as np
import pandas as pd
from pycytominer import consensus
random.seed(123)
# Get temporary directory
tmpdir = tempfile.gettempdir()
output_test_file = os.path.join(tmpdir, "test.csv")
input_test_file = os.path.join(tmpdir, "example_input.csv")
# Set example data... |
4812324 | import argparse
from collections import defaultdict
import datetime
import requests
import socket
import sys
import time
import ujson
from elasticsearch import Elasticsearch
from eventmaster_pb2 import *
from eventmaster_pb2_grpc import *
BATCH_LIMIT = 200
parser = argparse.ArgumentParser(description='Configuration ... |
4812344 | from __future__ import absolute_import
import vtk
import numpy as np
from ..data.volume import load_volume
from ..data.volume import centering
from ..data.volume import numpy_to_volume
from ..data.surface import label_to_surface
from ..actor import Actor
from ..utils.vtk.transforms import centered_transform
class Is... |
4812393 | from typing import Dict
from typing import List
from typing import Optional
from .style import Style
class StyleSet(object):
"""
A set of styles used by the formatter.
"""
def __init__(self, styles=None): # type: (Optional[List[Style]]) -> None
if styles is None:
styles = []
... |
4812505 | class KubeException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class KubeHTTPException(KubeException):
def __init__(self, response, errmsg, *args, **kwargs):
self.response = response
data = response.json()
message = data['message... |
4812514 | from bs4 import BeautifulSoup
import requests
import argparse
import re
import os
import sys
import time
import random
parser = argparse.ArgumentParser(
description="""Crawler for past twitter tweets.
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-q", "--query", type=str,
... |
4812539 | import torch
import torch.nn as nn
import torch.nn.functional as F
class InitialConv(nn.Module):
def __init__(self, out_channels=16):
super().__init__()
self.out_channels = out_channels
self.conv = nn.Conv3d(in_channels=1, out_channels=out_channels, kernel_size=5, stride=1, padding=2)
... |
4812566 | import sys
import tensorflow as tf
from main_model.abstract_main_model import AbstractMainModel
class ComplExModel(AbstractMainModel):
def __init__(self, args, dat, rng, aux_model=None, log_file=sys.stdout):
AbstractMainModel.__init__(
self, args, dat, rng, aux_model=aux_model, log_file=log_f... |
4812572 | from gurobipy import*
employee,min,max,cost,avs,ave=multidict({
("SMITH"):[6,8,30,6,20],("JOHNSON"):[6,8,50,0,24],('WILLIAMS'):[6,8,30,0,24],
('JONES'):[6,8,30,0,24],('BROWN'):[6,8,40,0,24],('DAVIS'):[6,8,50,0,24],
('MILLER'):[6,8,45,6,18],('WILSON'):[6,8,30,0,24],('MOORE'):[6,8,35,0,24],
('TAYLOR'):[6... |
4812601 | from sanic import Blueprint
from .v1 import api_v1
api_v1 = Blueprint.group(api_v1, url_prefix='/api') |
4812632 | from django.contrib import admin
from . import models
class CompanyAdmin(admin.ModelAdmin):
list_display = ('name_cn', 'name_en', 'code', 'order')
class RegionAdmin(admin.ModelAdmin):
list_display = ('name_cn', 'name_en', 'order')
class ServiceAdmin(admin.ModelAdmin):
list_display = ('endpoint', 'cod... |
4812640 | from core.settings import SITE_BASE_URL
from weedid.models import Dataset, WeedidUser
from weedid.utils import send_email
from textwrap import dedent
def upload_notification(upload_id):
upload_entity = Dataset.objects.get(upload_id=upload_id)
uploader = upload_entity.user
email_body = f"""\
User {uplo... |
4812645 | from pytest import fixture, raises
from sqlalchemy import text
from sqlalchemy.exc import NoSuchTableError
@fixture(autouse=True, scope="module")
def setup_tear_down(engine):
with engine.connect() as connection:
connection.execute(
text("CREATE TABLE IF NOT EXISTS test_table (id integer primar... |
4812649 | import ast
import collections
import marshal
import sys
FLOAT_TYPES = (int, float)
COMPLEX_TYPES = FLOAT_TYPES + (complex,)
STR_TYPES = (bytes, str)
# Primitive Python types (not containers)
PRIMITIVE_TYPES = (type(None), bool, int, float, complex, bytes, str)
# Iterable types
ITERABLE_TYPES = (str, bytes, tuple, f... |
4812681 | from gtfparse import read_gtf
from data import data_path
REFSEQ_GTF_PATH = data_path("refseq.ucsc.small.gtf")
def _check_required_columns(gtf_dict):
assert "feature" in gtf_dict, "Expected column named 'feature' in RefSeq GTF"
assert "gene_id" in gtf_dict, "Expected column named 'gene_id' in RefSeq GTF"
a... |
4812682 | from gamechangerml.src.search.ranking import features as ft
def add_pagerank_r(doc_dict):
doc_dict["pagerank_r"] = ft.get_pr(doc_dict["id"])
return doc_dict
def add_popscore_r(doc_dict):
doc_dict["pop_score"] = ft.get_pop_score(doc_dict["filename"])
return doc_dict
def add_orgs_rs(doc_dict):
d... |
4812716 | import shutil
from genrl.agents import A2C
from genrl.environments import VectorEnv
from genrl.trainers import OnPolicyTrainer
class TestA2C:
def test_a2c_discrete(self):
env = VectorEnv("CartPole-v0", 1)
algo = A2C("mlp", env, rollout_size=128)
trainer = OnPolicyTrainer(
algo... |
4812812 | import unittest
import numpy as np
from xmca.array import MCA
class TestArray(unittest.TestCase):
def setUp(self):
np.random.seed(7)
self.A = np.random.rand(500, 20, 15)
np.random.seed(8)
self.B = np.random.rand(500, 15, 10)
np.random.seed(9)
self.C = np.random.ran... |
4812821 | import pytest
from ....tests.utils import get_graphql_content
WEBHOOKS_QUERY = """
query {
apps(first:100) {
edges {
node {
webhooks {
id
name
targetUrl
isActive
asyncEvents {
... |
4812843 | from nvidia import dali
import nvidia.dali.tfrecord as tfrec
from nvidia.dali import ops
from nvidia.dali import types
class CommonPipeline(dali.pipeline.Pipeline):
def _input(self, tfrecord_path, index_path, shard_id=0):
return ops.TFRecordReader(
path=tfrecord_path,
index_path=i... |
4812847 | import unittest
from mock import Mock
from representor.translator import Translator
def adapter():
adapter = Mock()
adapter.media_type = "application/hal+json"
adapter.parse.return_value = "parsed"
adapter.build.return_value = "built"
return adapter
class TestInit(unittest.TestCase):
def test... |
4812871 | from .tlv_type import *
from .tlv_var import *
from .name import *
from .signer import *
from .tlv_model import *
from .ndn_format_0_3 import *
from .ndnlp_v2 import *
__all__ = []
__all__.extend(tlv_type.__all__)
__all__.extend(tlv_var.__all__)
__all__.extend(name.__all__)
__all__.extend(signer.__all__)
__all__.exte... |
4812888 | def test_disabled_pandas(spacy_disabled_pandas_doc):
# ensure that pandas extension is not set
assert not spacy_disabled_pandas_doc.has_extension("conll_pd")
for sent in spacy_disabled_pandas_doc.sents:
assert not sent.has_extension("conll_pd")
for token in spacy_disabled_pandas_doc:
as... |
4812903 | import json
from collections import defaultdict
import argparse
parser = argparse.ArgumentParser(description='main', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', default='MAG', choices=['MAG', 'MeSH'])
args = parser.parse_args()
folder = f'../{args.dataset}/'
thrs = 5
left... |
4812993 | import os
from os.path import join
import sys
import mock
import pynealScanner_helper_tools as helper_tools
# get dictionary with relevant paths for tests within this module
paths = helper_tools.get_pyneal_scanner_test_paths()
for path in [paths['pynealDir'], paths['pynealScannerDir']]:
if path not in sys.path:
... |
4813013 | from gailtf.baselines.common.mpi_running_mean_std import RunningMeanStd
import gailtf.baselines.common.tf_util as U
import tensorflow as tf
import gym
from gailtf.baselines.common.distributions import make_pdtype
import tensorflow.contrib.layers as layers
import numpy as np
from datetime import datetime
import random
i... |
4813022 | import pytest
from applications.models import Application, Form, Score
@pytest.fixture
def future_event_form(future_event):
return Form.objects.create(event=future_event)
@pytest.fixture
def scored_applications(future_event_form, admin_user):
Application.objects.bulk_create(
Application(form=future... |
4813052 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext = Extension("mod_cyMigrate", ["mod_cyMigrate.pyx"],
include_dirs = [np.get_include()])
setup(ext_modules=[ext],
cmdclass = {'build_ext': build_ext})
|
4813054 | import os
import sys
import json
import requests
class OpenWeatherAPI(object):
"""
Performs requests to the OpenWeather API Service.
Documentation : https://openweathermap.org/api
# NOTE: - Add more features to this API
- Publish to PyPi
"""
def __init__(self, key, headers=None... |
4813068 | from pale.arguments.base import BaseArgument, ListArgument
from pale.errors import ArgumentError
class StringArgument(BaseArgument):
allowed_types = (str, unicode)
min_length = None
max_length = None
def validate(self, item, item_name):
if item is None:
# TODO: should we also set t... |
4813071 | from .mesh import RenderObject, InstanceObject
from .scene import Scene
from .renderer import Renderer
from .viewer import Viewer
|
4813101 | import time
import redis
from django.core.management.base import BaseCommand
from watchtower.db import dispatch
from watchtower.db.redis import getHits, getEvents
from watchtower.conf import FREQUENCY, VERBOSITY
class Command(BaseCommand):
help = 'Start Watchtower collector'
def handle(self, *args, **options... |
4813179 | import os
from typing import TYPE_CHECKING
# TYPE_CHECKING默认False,如果为True,就引入数据库管理
if TYPE_CHECKING:
from vnpy.trader.database.database import BaseDatabaseManager
# 如果在环境变量中没有发现VNPY_TESTING,也就是测试
if "VNPY_TESTING" not in os.environ:
# 引入配置
from vnpy.trader.setting import get_settings
# 引入初始化
from ... |
4813182 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.entries_list, name='entries'),
url(r'^(?P<page>\d+)/$', views.entries_list, name='entries'),
url(r'^(?P<mode>unread|stars)/$', views.entries_list, name='entries'),
url(r'^(?P<mode>unread|stars)/(?P<page>\d+)/$',
... |
4813276 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
template_name = 'registration/user-detail.html'
def get_obje... |
4813303 | import pandas as pd
import networkx as nx
def weighted_degree(G, weight):
result = dict()
for node in G.nodes():
weight_degree = 0
for n in G.edges([node], data=True):
weight_degree += n[2]["weight"]
result[node] = weight_degree
return result
def correlation_centralit... |
4813335 | from __future__ import with_statement
## import profilehooks
## profile = profilehooks.profile(filename="profile.prf", immediate=False)
# from Enum import Enumeration
import sys, os, string, re, traceback, locale, time, urllib
from os.path import join, exists, splitext, abspath
from cStringIO import StringIO
... |
4813381 | import matplotlib.pyplot as plt
import numpy as np
import util
from p05b_lwr import LocallyWeightedLinearRegression
def main(tau_values, train_path, valid_path, test_path, pred_path):
"""Problem 5(b): Tune the bandwidth paramater tau for LWR.
Args:
tau_values: List of tau values to try.
trai... |
4813383 | import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from gcn.graph.dependency_graph import DependencyGraph
class AttentionDrawer():
def __init__(self, graph_builder):
self.graph_builder = graph_builder
def draw(self, sentence, attention=()):
edge_matrix = ()
node... |
4813386 | import os, sys
import inspect
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import numpy as np
import pytest
import librosa
import pathlib
import soundpy as sp
audio_dir = 'test_audio/'
test_audiofile =... |
4813398 | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login, logout_then_login
from django.views.i18n import JavaScriptCatalog
from mymoney.core.forms import MyMoneyAuthenticationForm
from mymoney.core.views import HomePageRedi... |
4813420 | import webapp2
from updateSchema import updateSchema
from google.appengine.ext import deferred
import logging
import config
class UpdateHandler(webapp2.RequestHandler):
def get(self):
logging.info("HIT HANDLER")
if config.isAdmin():
deferred.defer(updateSchema)
self.response... |
4813457 | class Config:
SHOW = False
SERVER = ""
URL_QUERY = ""
SIZE_LIST = sorted([(728, 90), (300, 250), (320, 100), (320, 50)], key=lambda size: size[0] * size[1], reverse=True) |
4813488 | from FreeTAKServer.model.FTSModel.fts_protocol_object import FTSProtocolObject
#######################################################
#
# Mission.py
# Python implementation of the Class Mission
# Generated by Enterprise Architect
# Created on(FTSProtocolObject): 11-Feb-2020 11(FTSProtocolObject):08(FTSProtocolOb... |
4813500 | import Weapon
import WeaponGlobals
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from pirates.uberdog.UberDogGlobals import InventoryType
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadSfx
hitSfxs = None
missSfxs = None
def getHitSfx():
global hit... |
4813527 | from __future__ import absolute_import
from sentry.models import ProjectKey
from sentry.web.frontend.base import ProjectView
class ProjectKeysView(ProjectView):
def get(self, request, organization, team, project):
key_list = list(ProjectKey.objects.filter(
project=project,
).order_by(... |
4813551 | from django.core.validators import ValidationError
from django.test import TestCase
from ..validators import ExactLengthsValidator
class ExactLengthsValidatorTestCase(TestCase):
def test_validator_message(self):
"""
Validator returns corrrect error message.
"""
validator = ExactLe... |
4813566 | from yarl import URL
def test_session_not_found(ui):
ui.driver.get(str(URL(ui.driver.current_url).with_fragment('/sessions/blap')))
assert ui.driver.find_element_by_css_selector(".error-details h1").text.lower() == 'not found'
|
4813622 | from unittest import TestCase
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from QueryUniprotExtended import QueryUniprotExtended as QUEx
class QueryUniprotExtendedTestCase(TestCase):
def test_get_protein_name(self):
name = QUEx.get_pr... |
4813655 | import pytest
from itmlogic.statistics.avar import avar
def test_avar(
setup_prop_to_test_avar,
setup_prop_to_test_avar_uarea,
):
"""
Test the statistics generating function avar which finds the quantiles of attenuation
(Section V of "The ITS Irregular Terrain Model, version 1.2.2: The Algorith... |
4813668 | import numpy as np
from collections import defaultdict
from copy import deepcopy
class RepresentativeClustering:
def __init__(self, random=True, max_itr=200, tolerance=0.001):
"""
:param max_itr: Maximum number of iterations if convergence is not reached. default = 200
:param tolerance: Pe... |
4813676 | import tensorflow as tf
import unittest
from xcenternet.model.preprocessing.batch_preprocessing import BatchPreprocessing
class TestImagePreprocessing(unittest.TestCase):
def setUp(self):
self.bboxes = tf.constant([[[2.0, 4.0, 30.0, 16.0], [12.0, 20.0, 32.0, 35.0], [0.0, 0.0, 30.0, 4.0]]])
def test_... |
4813689 | from __future__ import (absolute_import, division, print_function,
with_statement, unicode_literals)
import socket, select, json
import threading
from operator import itemgetter
CLIENT_CONNECT_CHANGES = [
"Client.OnConnect",
"Client.OnDisconnect",
]
CLIENT_VOLUME_CHANGES = [
"Client.OnVolumeCh... |
4813691 | from fbpca import pca
import numpy as np
import os
import pandas as pd
from scanorama import *
from scipy.sparse import vstack
import seaborn as sns
from sklearn.preprocessing import LabelEncoder, scale
from experiments import *
from process import load_names
from utils import *
NAMESPACE = 'artificial_density'
METHO... |
4813726 | class ZigzagIterator:
def __init__(self, v1: List[int], v2: List[int]):
i = j = 0
self.v = []
while i< len(v1) and j < len(v2):
self.v.append(v1[i])
self.v.append(v2[j])
i+=1
j+=1
if i < len(v1):
self.v.extend(v1[i:])
... |
4813803 | import pandas as pd
import sys
def main(train_filename, dev_filename, eval_filename):
train = pd.read_json(train_filename)
dev = pd.read_json(dev_filename)
eval = pd.read_json(eval_filename)
passages = {}
pid = 0
for row in train.itterrows():
for passage in row[1]['passages']:
... |
4813824 | from django.conf import settings
from django.db import models
from User import models as user_models
from helper import modelHelper
if settings.HAS_REFERRAL_APP:
class Referral(user_models.AbstractTimeStamp):
user = models.OneToOneField(
user_models.User, on_delete=models.CASCADE, null=False,... |
4813827 | import json
from django.test import TestCase
from cabinet.factories import UserFactory, BookOwnFactory
from factories import ClientFactory, AccessTokenFactory
class BookOwnTest(TestCase):
fixtures = ['users.json', 'client.json', 'books.json',
'bookownerships.json']
def setUp(self):
... |
4813846 | import utils
import os
import unittest
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import ihm.protocol
class Tests(unittest.TestCase):
def test_step(self):
"""Test protocol Step class"""
s = ihm.protocol.Step(assembly='foo', dataset_grou... |
4813862 | import numpy as np
import numpy.linalg as LA
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from tqdm import tqdm, trange
from torch.utils.data import TensorDataset
from plotly.subplots import make_subplots
import plotly.graph_objects as go
def visualize3D(vis_net, x, y, dir1, dir2, dir3, len1 = 1,... |
4813874 | import re
from typing import List, Dict
from pathlib import Path
from tree_sitter import Tree, Node, TreeCursor
from tree_hugger.core.code_parser import BaseParser, match_from_span
from tree_hugger.core.queries import Query
class PHPParser(BaseParser):
QUERY_FILE_PATH = Path(__file__).parent / "queries.yml"
... |
4813904 | from piecewisecrf.datasets.dataset import Dataset
from piecewisecrf.datasets.labels import Label
class KittiDataset(Dataset):
'''
Kitti dataset abstraction
'''
def __init__(self, train_dir=None, val_dir=None, test_dir=None):
super(KittiDataset, self).__init__(train_dir, val_dir, test_dir)
... |
4813909 | from unittest.mock import patch
from programy.security.linking.accountlinker import BasicAccountLinkerService
from programytest.client import TestClient
from programytest.security.linking.extension_asserts import AccountLinkerExtensionAsserts
from programytest.security.linking.test_accountlinker_mocked import MockStor... |
4813928 | from collections import defaultdict
import random
import sys
import numpy as np
class EBC2D:
def __init__(self, matrix, n_clusters, max_iterations=10, jitter_max=1e-10, objective_tolerance=0.01):
""" To initialize an EBC object.
Args:
matrix: a instance of numpy ndarray that represen... |
4813934 | from unittest.mock import Mock
from django.db.models import NOT_PROVIDED
from django.test import TestCase
from model_utils.fields import UrlsafeTokenField
class UrlsaftTokenFieldTests(TestCase):
def test_editable_default(self):
field = UrlsafeTokenField()
self.assertFalse(field.editable)
de... |
4813959 | import json
from pymongo import MongoClient
client = MongoClient('proximus.modulusmongo.net:27017')
client.tepO9seb.authenticate('nasahack', 'hacking4nasa')
db = client.tepO9seb
if __name__ == '__main__':
counts = json.load(open('kw_counts.json'))
nasa_kwds = counts['http://data.nasa.gov/data.json'].keys()
... |
4813965 | from pytest import fixture, raises
from taskit.application.models.project import Project
from taskit.application.models.task import Task
from taskit.application.repositories.project_repository import (
ProjectRepository, MemoryProjectRepository)
from taskit.application.repositories.task_repository import (
Task... |
4813995 | import json
import os
import codecs
def process_file(file_name):
data = json.load(codecs.open(file_name, 'r', 'utf-8'))
data = data["data"]
print("in total there are ", len(data), " documents")
train = data[:-23]
valid = data[-23:]
return train, valid
train, valid = process_file("squad1.1/t... |
4814050 | from __future__ import absolute_import, division, print_function, unicode_literals
"""
Notes: For triangle faces there were two way of implementation.
(1) Triangle faces are two triangle face per tetrahedron (if it
shares a faces with another tetrahedron)
(2) just one triangle face but normal to surfac... |
4814053 | from ztk.api.base import RestApi
class ZtkAlipayAgentPayRequest(RestApi):
'''__init__(self, password, alipay_account, alipay_name, money, remark, domain='api.zhetaoke.com', port=10001)
password 付安全秘钥代付设置
alipay_account 支付宝账号
alipay_name 支付宝真实姓名
money 代付金额,单位:元,最少0.1元/笔,只... |
4814061 | from test import multibytecodec_support
import unittest
class Test_CP949(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'cp949'
tstring = multibytecodec_support.load_teststring('cp949')
codectests = (b'abc\x80\x80\xc1\xc4', 'strict', None), (b'abc\xc8',
'strict', None), (b'abc\x80... |
4814070 | import re, itertools
print("xxxxxx")
def demo():
print("demo")
try:
import baconhameggs
except ImportError:
pass
try:
import guido.python.ham
except ImportError:
pass |
4814085 | import pytest
from unittest import mock
from keep_current_storage.domain.document import Document
from keep_current_storage.use_cases import request_objects as ro
from keep_current_storage.use_cases import document_use_cases as uc
from keep_current_storage.shared import response_object as res
@pytest.fixture
def dom... |
4814099 | import unittest
from reverse_string import reverseString
class TestReverseString(unittest.TestCase):
def test_zeroLengthInput(self):
"""We expect an empty string to be returned"""
self.assertEqual(reverseString(None),None)
def test_positiveLengthInput(self):
"""We expect the reverse ... |
4814159 | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
... |
4814177 | import heapq
import time
from netdice.common import Flow, FwGraph
from netdice.igp import IgpProvider
from netdice.my_logging import log
from netdice.problem import Problem, Solution
class Explorer:
"""
Implementation of NetDice's failure exploration.
"""
def __init__(self, p: Problem, full_trace=Fa... |
4814182 | import neowise.activations
import neowise.cost_function
import neowise.functional
import neowise.layers
import neowise.optimizers
import neowise.plots
import neowise.regularizers
from neowise.neural_net import Model
|
4814200 | class OkApiException(Exception):
pass
class ApiError(OkApiException):
def __init__(self, message):
self.message = message
class OkUploadException(OkApiException):
pass
class UploadPhotoError(OkUploadException):
def __init__(self, message):
self.message = message
class UploadVid... |
4814210 | import inspect
from importlib import import_module
from guniflask.annotation import AnnotationMetadata, AnnotationUtils
from guniflask.beans.definition import BeanDefinition
from guniflask.beans.definition_registry import BeanDefinitionRegistry
from guniflask.beans.factory_post_processor import BeanDefinitionRegistryP... |
4814235 | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, writers
from scipy import *
from scipy import integrate
from scipy.integrate import ode, odeint
import numpy as np
plt.close()
fig,ax = plt.subplots(1,1,figsize=(8,8))
#Vector field
xmin,xmax = -2,3
ymin,ymax = -2,2
gridpoints = 500
mu = ... |
4814255 | import random
import numpy as np
from tqdm import tqdm
class MaskImputationValues:
"""
Mask known beta values from input pd.DataFrame to evaluate imputation accuracy
Keyword Arguments
methylation_array (np.array): input pd.DataFrame of methylation values
masking_proportion (flo... |
4814257 | import numpy as np
def uniform_grid(n_centers, low, high):
"""
This function is used to create the parameters of uniformly spaced radial
basis functions with 25% of overlap. It creates a uniformly spaced grid of
``n_centers[i]`` points in each ``ranges[i]``. Also returns a vector
containing the ap... |
4814268 | import FileDialog
import aip
f = open(FileDialog.getOneFile(), 'rb')
client = aip.AipSpeech("Enter Your APP_ID", "Enter Your API_KEY", "Enter Your SECRET_KEY")
print(client.asr(f.read(), options={})["result"][0])
|
4814275 | import logging
from datetime import timedelta
from homeassistant.components.light import LightEntity
from homeassistant.helpers.entity import Entity
from custom_components.miele import DATA_CLIENT, DATA_DEVICES
from custom_components.miele import DOMAIN as MIELE_DOMAIN
PLATFORMS = ["miele"]
_LOGGER = logging.getLog... |
4814307 | from __future__ import print_function
import sys
import json
import time
import click
import pyutu.client as pyutu
pass_pc = click.make_pass_decorator(pyutu.PricingContext, ensure=True)
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
regions = sorted(pyutu.regions.keys())
services = sorted(pyutu.svcs.key... |
4814365 | from influxable import settings
class TestSettings:
def check_if_variable_exist(self, variable_name):
return hasattr(settings, variable_name)
def test_check_url_exist(self):
assert self.check_if_variable_exist('INFLUXDB_URL')
def test_check_user_exist(self):
assert self.check_if_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.