id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
74352 | import pybullet as p
from gym import spaces
from diy_gym.addons.addon import Addon
class ExternalForce(Addon):
"""ExternalForce defines a addon that can be used to apply an external force to the base a model.
"""
def __init__(self, parent, config):
super(ExternalForce, self).__init__(parent, confi... |
74361 | import pytest
from yahooquery import Screener
def test_screener():
s = Screener()
assert s.get_screeners("most_actives") is not None
def test_available_screeners():
s = Screener()
assert s.available_screeners is not None
def test_bad_screener():
with pytest.raises(ValueError):
s = Scr... |
74381 | from collections import OrderedDict
from fcgiproto.constants import FCGI_KEEP_CONN
class RequestEvent(object):
"""
Base class for events that target a specific request.
:ivar int request_id: identifier of the associated request
"""
__slots__ = ('request_id',)
def __init__(self, request_id)... |
74390 | import spacy
nlp = spacy.load('en')
doc = nlp(u'President Trump has a dispute with Mexico over immigration. IBM and Apple are cooperating on marketing in 2014. Pepsi and Coke sell well to Asian and South American customers. He bought a Ford Escort for $20,000 and drove to the lake for the weekend. The parade was last S... |
74399 | import numpy as np
import unittest
from chainer import testing
from chainercv.experimental.links.model.pspnet import convolution_crop
class TestConvolutionCrop(unittest.TestCase):
def test_convolution_crop(self):
size = (8, 6)
stride = (8, 6)
n_channel = 3
img = np.random.uniform... |
74416 | from ._version import __version__, __js__
def _jupyter_labextension_paths():
return [{"src": "labextension", "dest": __js__["name"]}]
def _jupyter_server_extension_points():
return [{"module": "jupyterlab_pullrequests"}]
def _load_jupyter_server_extension(server_app):
"""Registers the API handler to re... |
74422 | import itertools
import numpy as np
import networkx as nx
import vocab
def coref_score(instance, property_id):
return [ instance.subject_entity["coref_score"], instance.object_entity["coref_score"] ]
def el_score(instance, property_id):
return [ instance.subject_entity["el_score"], instance.object_entity["el_scor... |
74426 | import numpy as np
from ..Delboeuf.delboeuf_parameters import _delboeuf_parameters_sizeinner, _delboeuf_parameters_sizeouter
def _ebbinghaus_parameters(illusion_strength=0, difference=0, size_min=0.25, distance=1, distance_auto=False):
# Size inner circles
parameters = _delboeuf_parameters_sizeinner(differe... |
74428 | import json
import os
from typing import List, Tuple
import pytest
@pytest.fixture(scope='module')
def here():
return os.path.abspath(os.path.dirname(__file__))
@pytest.fixture(scope='module')
def accounts(here) -> List[Tuple] or None:
"""Return account list"""
accounts_path = os.path.join(here, 'confi... |
74429 | import datetime
from typing import TYPE_CHECKING, Generator
import Evtx.Evtx as evtx
from lxml import etree
from beagle.common.logging import logger
from beagle.datasources.base_datasource import DataSource
from beagle.transformers.evtx_transformer import WinEVTXTransformer
if TYPE_CHECKING:
from beagle.transfor... |
74447 | import tempfile
import strax
import straxen
from straxen.test_utils import nt_test_run_id, DummyRawRecords, testing_config_1T, test_run_id_1T
def _run_plugins(st,
make_all=False,
run_id=nt_test_run_id,
from_scratch=False,
**process_kwargs):
"""
... |
74456 | import caffe2onnx.src.c2oObject as Node
from typing import List
import copy
def get_concat_attributes(layer):
axis = layer.concat_param.axis
attributes = {"axis": axis}
return attributes
def get_concat_outshape(layer, input_shape: List) -> List:
bottom = input_shape[0]
axis = layer.concat_param.... |
74521 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__license__ = 'MIT'
__maintainer__ = ['<NAME>']
__email__ = ['<EMAIL>']
|
74525 | from abc import ABC, abstractmethod
import gym
class BaseGymEnvironment(gym.Env):
"""Base class for all Gym environments."""
@property
def parameters(self):
"""Return environment parameters."""
return {
'id': self.spec.id,
}
class EnvBinarySuccessMixin(ABC):
"""... |
74537 | import numpy as np
def moving_average(a, n=3) :
"""
perform moving average, return a vector of same length as input
"""
a=a.ravel()
a = np.concatenate(([a[0]]*(n-1),a)) # repeating first values
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
ret=ret[n - 1:] / n
return ... |
74543 | import click
from train_anomaly_detection import main_func
import numpy as np
import os
# Define base parameters.
dataset_name = 'selfsupervised'
net_name = 'StackConvNet'
xp_path_base = 'log'
data_path = 'data/full'
train_folder = 'train'
val_pos_folder = 'val/wangen_sun_3_pos'
val_neg_folder = 'val/wangen_sun_3_neg'... |
74548 | import logging
import oscar
'''
This family is deprecated, so it is remaining unimplemented
'''
x0c_name="Translation - deprecated"
log = logging.getLogger('oscar.snac.x0c')
subcodes = {}
def x0c_init(o, sock, cb):
log.info('initializing')
cb()
log.info('finished initializing')
def x0c... |
74556 | from src.environments.slippery_grid import SlipperyGrid
import numpy as np
# A modified version of OpenAI Gym FrozenLake
# only the labelling function needs to be specified
sinks = []
for i in range(12, 16):
for j in range(15, 19):
sinks.append([i, j])
# create a SlipperyGrid object
FrozenLake = SlipperyG... |
74576 | import argparse
import imagesize
import os
import subprocess
parser = argparse.ArgumentParser(description='MegaDepth Undistortion')
parser.add_argument(
'--colmap_path', type=str, required=True,
help='path to colmap executable'
)
parser.add_argument(
'--base_path', type=str, required=True,
help='pa... |
74587 | import numpy as np
import util
from linear_model import LinearModel
def main(train_path, eval_path, pred_path):
"""Problem 1(b): Logistic regression with Newton's Method.
Args:
train_path: Path to CSV file containing dataset for training.
eval_path: Path to CSV file containing dataset for ev... |
74613 | from lightning import Lightning
from lightning.types.base import Base
from functools import wraps
import inspect
def viztype(VizType):
# wrapper that passes inputs to cleaning function and creates viz
@wraps(VizType.clean)
def plotter(self, *args, **kwargs):
if kwargs['height'] is None and kwarg... |
74656 | import os
import pytest
import shutil
import flask
from flask import Flask
import graphene
import pprint
from graphene.test import Client
from mock import patch
import responses
from gtmcore.auth.identity import get_identity_manager_class
from gtmcore.configuration import Configuration
from gtmcore.gitlib import RepoL... |
74677 | import os
import simplejson as json
from getpass import getpass
from pytezos.crypto import Key
class Keychain:
def __init__(self, path='~/.tezos-client/secret_keys'):
self._path = os.path.expanduser(path)
self._secret_keys = list()
self._last_modified = 0
def reload(self):
l... |
74696 | from topaz.module import ClassDef
from topaz.objects.objectobject import W_Object
from topaz.modules.ffi.function import W_FFIFunctionObject
from rpython.rlib import jit
class W_VariadicInvokerObject(W_Object):
classdef = ClassDef('VariadicInvoker', W_Object.classdef)
def __init__(self, space):
W_Ob... |
74697 | from recolor import Core
def main():
# Simulating Protanopia with diagnosed degree of 0.9 and saving the image to file.
Core.simulate(input_path='Examples_Check/ex_original.jpg',
return_type='save',
save_path='Examples_Check/ex_simulate_protanopia.png',
si... |
74703 | from aydin.it.normalisers.base import NormaliserBase
class IdentityNormaliser(NormaliserBase):
"""Identity Normaliser"""
def __init__(self, **kwargs):
"""Constructs a normalisers"""
super().__init__(**kwargs)
def calibrate(self, array):
"""Calibrate method
Parameters
... |
74713 | from django.test import TestCase
from django_hats.bootstrap import Bootstrapper
class RolesTestCase(TestCase):
def setUp(self, *args, **kwargs):
'''Clears `Roles` cache for testing.
'''
for role in Bootstrapper.get_roles():
setattr(role, 'group', None)
return super(Rol... |
74726 | def create_500M_file(name):
native.genrule(
name = name + "_target",
outs = [name],
output_to_bindir = 1,
cmd = "truncate -s 500M $@",
)
|
74739 | from fastapi import FastAPI
from models import User, db
app = FastAPI()
db.init_app(app)
@app.get("/")
async def root():
# count number of users in DB
return {"hello": "Hello!"}
@app.get("/users")
async def users():
# count number of users in DB
return {"count_users": await db.func.count(User.id).... |
74754 | import numpy as np
import cPickle
import os
import pdb
import cv2
def unpickle(file):
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
def load_data(train_path,order,nb_groups, nb_cl, nb_val,SubMean = False):
xs = []
ys = []
for j in range(1):
d = unpickle(train_p... |
74768 | from wayback_machine_archiver.archiver import format_archive_url
def test_archive_org():
BASE = "https://web.archive.org/save/"
URLS = (
"https://alexgude.com",
"http://charles.uno",
)
for url in URLS:
assert BASE + url == format_archive_url(url)
|
74773 | from kiwoom import config
from kiwoom.config import valid_event
from functools import wraps
from textwrap import dedent
from types import LambdaType
from inspect import (
getattr_static,
ismethod,
isfunction,
isclass,
ismodule
)
class Connector:
"""
Decorator class for mapping empty event... |
74792 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, BigInteger, String
import config
Base = declarative_base()
formFields = config.form_fields
class Register(Base):
__tablename__ = config.table_name
col1 = Column(formFields[0]['fname'], formFields[0]['ftype'], primary_key=T... |
74809 | import logging
import sys
def get_logger(filename,
logger_name='centroFlye',
level=logging.INFO,
filemode='a',
stdout=True):
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# create the logging file handler
fh = logging.FileHa... |
74821 | import os, sys
sys.path.insert(0, os.path.join(os.pardir, 'src'))
def sympy_solution():
from sympy import symbols, Rational, solve
C1, C3, C4 = symbols('C1 C3 C4')
s = solve([C1 - 1 - C3,
C1 - Rational(1,2) - C3 - C4,
2 + 2*C3 + C4], [C1,C3,C4])
return s
import numpy as np
import matplo... |
74847 | import pytest
from requests.exceptions import HTTPError
from commercetools.platform import models
def test_channel_get_by_id(old_client):
channel = old_client.channels.create(
models.ChannelDraft(
key="test-channel", roles=[models.ChannelRoleEnum.INVENTORY_SUPPLY]
)
)
assert ... |
74865 | import numpy as np
import torch
from scipy.stats import entropy as sc_entropy
class MultipredictionEntropy:
def __int__(self):
"""
Computes the entropy on multiple predictions of the same batch.
"""
super(MultipredictionEntropy, self).__init__()
def __call__(self, y, device='... |
74888 | from django.contrib import admin
# Register your models here.
from training.models import Training
admin.site.register(Training) |
74906 | import unittest
from os.path import join, dirname
from io import BytesIO
from urllib.parse import quote
from falcon_heavy.http.multipart_parser import MultiPartParser, MultiPartParserError
from falcon_heavy.http.exceptions import RequestDataTooBig, TooManyFieldsSent
from falcon_heavy.http.utils import parse_options_he... |
74936 | from __future__ import division
import datetime
import time
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
from chainer.training import extension
try:
from chainer.training.triggers import interval
except ImportError:
from chainer.training.triggers import interval_trigger as interval
class CWProgr... |
74938 | from django.conf.urls import url
from .views import (
post_model_create_view,
post_model_detail_view,
post_model_delete_view,
post_model_list_view,
post_model_update_view
)
urlpatterns = [
url(r'^$', post_model_list_view, name='list'),
url(r'^create/$', post_model_create_view, name='c... |
74944 | from django.core.cache import cache
from django.shortcuts import render, get_object_or_404
from django_redis import get_redis_connection
from .models import Image
# Create your views here.
con = get_redis_connection("default")
def index(request):
query = Image.objects.all()
images_seq = [
{'id': da... |
74951 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScCuritibanosSpider(FecamGazetteSpider):
name = "sc_curitibanos"
FECAM_QUERY = "cod_entidade:82"
TERRITORY_ID = "4204806"
|
74972 | class Test:
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
deserunt mollit anim id est laborum.
.. sourcecode:: pycon
>>> # extract 100 LDA topics, using default parameters
>>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True)
using distrib... |
74982 | import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as Data
import numpy as np
import time
import sys
import utils
print('生成测试数据')
n_train, n_test, num_inputs = 20, 100, 200
t... |
74998 | import numpy as np
import unittest
from convolution import conv2d, add_padding
class TestConvolution(unittest.TestCase):
def test_paddings_shape(self, N: int = 1000):
for _ in range(N):
m_h = np.random.randint(3, 100)
m_w = np.random.randint(3, 100)
random_matrix = np.... |
75008 | import os
from arcsv.helper import get_ucsc_name
def get_inverted_pair(pair, bam):
chrom = bam.getrname(pair[0].rname) # already checked reads on same chrom
if pair[0].pos < pair[1].pos:
left = pair[0]
right = pair[1]
else:
left = pair[1]
right = pair[0]
left_coord = ... |
75015 | from __future__ import annotations
import typing
import toolcli
from ctc import evm
from ctc import spec
from ctc.cli import cli_utils
def get_command_spec() -> toolcli.CommandSpec:
return {
'f': async_events_command,
'help': 'get contract events',
'args': [
{
... |
75025 | import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent))
import unittest
import nanopq
import numpy as np
class TestSuite(unittest.TestCase):
def setUp(self):
np.random.seed(123)
def test_property(self):
opq = nanopq.OPQ(M=4, Ks=256)
self.assertEqual... |
75105 | from typing import List
from unittest.case import TestCase
from uuid import uuid4
from eventsourcing.application import Application
from eventsourcing.persistence import Notification
from eventsourcing.system import (
AlwaysPull,
Follower,
Leader,
NeverPull,
ProcessApplication,
Promptable,
... |
75107 | import os
import os.path as osp
import random as rd
import subprocess
from typing import Optional, Tuple, Union
import click
from mim.click import CustomCommand, param2lowercase
from mim.utils import (
echo_success,
exit_with_error,
get_installed_path,
highlighted_error,
is_installed,
module_f... |
75108 | import asyncio
import logging
from timeit import default_timer as timer
from podping_hivewriter.async_context import AsyncContext
from podping_hivewriter.models.podping_settings import PodpingSettings
from podping_hivewriter.podping_settings import get_podping_settings
from pydantic import ValidationError
class Podp... |
75131 | from operator import itemgetter
from collections import defaultdict
import scipy.stats as st
import numpy as np
import pandas as pd
def k_factor(margin_of_victory, elo_diff):
init_k = 20
if margin_of_victory>0:
multiplier = (margin_of_victory+3) ** (0.8) / (7.5 + 0.006 * (elo_diff))
else:
... |
75231 | from collections.abc import (
AsyncIterator,
)
from typing import (
Any,
)
from ...database import (
DatabaseClient,
)
from .operations import (
MockedDatabaseOperation,
)
class MockedDatabaseClient(DatabaseClient):
"""For testing purposes"""
def __init__(self, *args, **kwargs):
supe... |
75239 | import torch
import numpy as np
import shutil
import os
from data import ljspeech
import hparams as hp
def preprocess_ljspeech(filename):
in_dir = filename
out_dir = hp.mel_ground_truth
if not os.path.exists(out_dir):
os.makedirs(out_dir, exist_ok=True)
metadata = ljspeech.build_from_path(in_... |
75240 | from django.core.management.base import BaseCommand, CommandError
from canvas.thumbnailer import update_all_content
from canvas.models import Content
from canvas.upload import get_fs
from configuration import Config
from django.conf import settings
class Command(BaseCommand):
args = ''
help = 'Recreates all th... |
75256 | from django.apps import AppConfig
class ProfileConfig(AppConfig):
label = "profile"
name = "edd.profile"
verbose_name = "User Profiles"
|
75275 | import h5py
import numpy as np
from keras.datasets import mnist
from keras.utils import to_categorical
# input image dimensions
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], img... |
75334 | class Model(object):
def __init__(self,configModel,utils,strTrial):
self.tag = configModel[0]
self.mode = configModel[1]
self.featureSet = configModel[2]
self.misc = configModel[3]
self.masterTest = utils.TEST_IDS_PATH
self.bootTrain = utils.MODEL... |
75362 | from moncash import constants
class Environment(object):
def __init__(self, name, host):
self.__name__ = name
self.host = host
self.protocol = "https://"
if name == 'Sandbox':
self.redirect_url = constants.SANDBOX_REDIRECT_URL
elif name == 'Production':
... |
75370 | import torch
import mmocr.utils as utils
from mmocr.models.builder import CONVERTORS
from .base import BaseConvertor
import numpy as np
@CONVERTORS.register_module()
class MasterConvertor(BaseConvertor):
"""Convert between text, index and tensor for encoder-decoder based
pipeline.
Args:
dict_typ... |
75422 | from rply.token import BaseBox
from vython.errors import error, Errors as errors
import sys
class BinaryOp(BaseBox):
def __init__(self, left, right):
self.left = left
self.right = right
if self.right.kind == "string" or self.left.kind == "string":
self.kind = "string"
el... |
75446 | import sys
from time import time
class Progress:
"""
"""
def __init__(self, iterable, size = None, interval = 0.1):
"""
Args:
iterable
size (int): max size of iterable
interval (float): update bar interval second, default is `0.1`
Attrs:
... |
75471 | from ariadne import QueryType
from neo4j_graphql_py import neo4j_graphql
query = QueryType()
@query.field('Movie')
@query.field('MoviesByYear')
def resolve(obj, info, **kwargs):
return neo4j_graphql(obj, info.context, info, **kwargs)
|
75473 | def set_fill_color(red, green, blue):
pass
def draw_rectangle(corner, other_corner):
pass
set_fill_color(red=161, green=219, blue=114)
draw_rectangle(corner=(105,20), other_corner=(60,60))
|
75545 | import pytest
import unittest
from pydu.dict import AttrDict, LookupDict, CaseInsensitiveDict, OrderedDefaultDict, attrify
class TestAttrDict:
def test_attr_access_with_init(self):
d = AttrDict(key=1)
assert d['key'] == 1
assert d.key == 1
def test_attr_access_without_init(self):
... |
75576 | import operator
from django.db.models import Q as DjangoQ
from django.db.models.lookups import Lookup
from ..ql import Q as SearchQ
def resolve_filter_value(v):
"""Resolve a filter value to one that the search API can handle
We can't pass model instances for example.
"""
return getattr(v, 'pk', v)
... |
75590 | import unittest
import pytest
import paramak
class TestExtrudeHollowRectangle(unittest.TestCase):
def setUp(self):
self.test_shape = paramak.ExtrudeHollowRectangle(
height=10, width=15, casing_thickness=1, distance=2
)
def test_default_parameters(self):
"""Checks that th... |
75602 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from numpy import asarray
from scipy.spatial import Voronoi
from scipy.spatial import Delaunay
__all__ = [
'delaunay_from_points_numpy',
'voronoi_from_points_numpy',
]
def delaunay_from_points_numpy... |
75610 | import sys
from ..api import plot
import fuc
import pysam
description = f"""
Plot allele fraction profile from VcfFrame[Imported].
"""
def create_parser(subparsers):
parser = fuc.api.common._add_parser(
subparsers,
fuc.api.common._script_name(),
description=description,
help='Plo... |
75616 | f = plt.figure(figsize=(6,6))
plt.scatter(pres.swing_full, lp.weights.lag_spatial(w, pres.swing_full))
plt.plot((-.3,.1),(-.3,.1), color='k')
plt.title('$I = {:.3f} \ \ (p < {:.3f})$'.format(moran.I,moran.p_sim)) |
75619 | import sys
import pprint
pp = pprint.PrettyPrinter();
import pymongo
from pymongo import MongoClient
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 12 20:30:54 2016
@author: ryanlim, jpitts
Requirements:
- pymongo needs to be installed
- mongodb needs to be running
- brigade-match... |
75628 | from simple_playgrounds.playground.playgrounds import *
from simple_playgrounds.engine import Engine
from simple_playgrounds.agent.controllers import Keyboard
from simple_playgrounds.agent.agents import HeadAgent
import time
import cv2
my_agent = HeadAgent(controller=Keyboard(), lateral=True, interactive=True)
####... |
75636 | from .nlm3 import nlm3
from .nlm2 import nlm2
from .bilateral2 import bilateral2
from .bilateral3 import bilateral3
|
75737 | import logging
import re
import shlex
import threading
import sshim
logging.basicConfig(level='DEBUG')
logger = logging.getLogger()
class Device(threading.Thread):
def __init__(self, script):
threading.Thread.__init__(self)
self.history = []
self.script = script
self.start()
d... |
75766 | import numpy as np
import nanonet.tb as tb
from test.test_hamiltonian_module import expected_bulk_silicon_band_structure
def test_simple_atomic_chain():
""" """
site_energy = -1.0
coupling = -1.0
l_const = 1.0
a = tb.Orbitals('A')
a.add_orbital(title='s', energy=-1, )
xyz_file = """1
... |
75788 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import json
import os
import re
import mock
import requests_mock
from six.moves.urllib import parse as urlparse
import testtools
# Setup dummy enviro... |
75811 | import functools
import numpy as np
import torch as t
import torch.nn as nn
import torch.distributed as dist
from jukebox.transformer.ops import Conv1D, ACT_FNS, LayerNorm
from jukebox.transformer.factored_attention import FactoredAttention
from jukebox.utils.checkpoint import checkpoint
def _convert_mlp_traced(l):
... |
75831 | from __future__ import absolute_import, division, print_function
from .multi_pose import MultiPoseTrainer
train_factory = {
'multi_pose': MultiPoseTrainer,
}
|
75859 | from dassl.utils import Registry, check_availability
EVALUATOR_REGISTRY = Registry("EVALUATOR")
def build_evaluator(cfg, **kwargs):
avai_evaluators = EVALUATOR_REGISTRY.registered_names()
check_availability(cfg.TEST.EVALUATOR, avai_evaluators)
if cfg.VERBOSE:
print("Loading evaluator: {}".format(... |
75861 | from hybrid_astar_planner.HybridAStar.hybrid_astar_wrapper \
import apply_hybrid_astar
import numpy as np
from pylot.planning.planner import Planner
class HybridAStarPlanner(Planner):
"""Wrapper around the Hybrid A* planner.
Note:
Details can be found at `Hybrid A* Planner`_.
Args:
... |
75899 | import os
import numpy as np
import matplotlib.pyplot as plt
import pyvips as Vips
NP_DTYPE_TO_VIPS_FORMAT = {
np.dtype('int8'): Vips.BandFormat.CHAR,
np.dtype('uint8'): Vips.BandFormat.UCHAR,
np.dtype('int16'): Vips.BandFormat.SHORT,
np.dtype('uint16'): Vips.BandFormat.USHORT,
... |
75908 | from torch import nn
import torch.nn.functional as F
from ssd.modeling import registry
from ssd.modeling.anchors.prior_box import PriorBox
from ssd.modeling.box_head.box_predictor import make_box_predictor
from ssd.utils import box_utils
from .inference import PostProcessor
from .loss import MultiBoxLoss, FocalLoss
... |
75940 | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
from urllib.parse import quote
import requests
from pypuppetdb.errors import (APIError, EmptyResponseError)
log = logging.getLogger(__name__)
ENDPOINTS = {
'facts': 'pdb/query/v4/facts',
'fact-names': ... |
75988 | from rllab.misc import logger
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import os.path as osp
import numpy as np
import math
import random
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
this returns the intersect... |
76008 | import json
import sys
import csv
import argparse
import time
import subprocess
import pingparsing
# defined in parameters.py
from parameters import (
filters,
number_rules,
iterations,
iface,
bandwidth,
seed,
ipnets,
ping_interval,
ping_count,
)
from k8s import benchmark_pod_tmp... |
76069 | import os
from unittest import TestCase
# most of the features of this script are already tested indirectly when
# running vensim and xmile integration tests
_root = os.path.dirname(__file__)
class TestErrors(TestCase):
def test_canonical_file_not_found(self):
from pysd.tools.benchmarking import runner... |
76090 | from abc import abstractmethod, abstractproperty
import os
from pathlib import Path
import collections.abc
import logging
import pkg_resources
import uuid
from urllib.parse import urlparse
from typing import Set, List
import threading
import numpy as np
from frozendict import frozendict
import pyarrow as pa
import v... |
76142 | import os
import argparse
import pyautogui
import time
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')
parser.add_argument("-f... |
76165 | import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from core.bounds import WSR_mu_plus
from core.concentration import get_tlambda, get_lhat_from_table, get_lhat_from_table_binarysearch
import numpy as np
from scipy.optimize import brentq
from tqdm import tqdm
import pdb
def get_coco_example_l... |
76216 | import FWCore.ParameterSet.Config as cms
process = cms.Process("WRITE")
process.source = cms.Source("EmptySource", numberEventsInLuminosityBlock = cms.untracked.uint32(4))
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20))
process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untra... |
76222 | import copy
from django.http import HttpResponseBadRequest
from django.contrib.sitemaps import views as django_sitemaps_views
def custom_sitemap_index(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml'):
platform = request.GET.get('platform', None)
platform_in = reque... |
76226 | from jmetal.algorithm.singleobjective.simulated_annealing import SimulatedAnnealing
from jmetal.operator import BitFlipMutation
from jmetal.problem import OneMax
from jmetal.util.solution import print_function_values_to_file, print_variables_to_file
from jmetal.util.termination_criterion import StoppingByEvaluations
i... |
76255 | import ledshim
class Leds(object):
def __init__(self):
self.count = 24
def set_one(self, led_number, color):
ledshim.set_pixel(led_number, *color)
def set_range(self, a_range, color):
ledshim.set_multiple_pixels(a_range, color)
def set_all(self, color):
l... |
76367 | import pytest
from yamlpath.merger.enums.anchorconflictresolutions import (
AnchorConflictResolutions)
class Test_merger_enum_anchorconflictresolutions():
"""Tests for the AnchorConflictResolutions enumeration."""
def test_get_names(self):
assert AnchorConflictResolutions.get_names() == [
"STOP",
"LEFT",... |
76386 | import numpy as np
import pandas as pd
from statsmodels.sandbox.stats.multicomp import multipletests
import regreg.api as rr
from ...api import (randomization,
glm_group_lasso,
multiple_queries)
from ...tests.instance import (gaussian_instance,
lo... |
76391 | from django import template
register = template.Library()
@register.simple_tag(name='render_field')
def render_field(field, **kwargs):
field.field.widget.attrs.update(kwargs)
return field
|
76429 | import json
data = '''
[
{
"name":"Sister",
"count":95
},
{
"name":"Sidharth",
"count":94
},
{
"name":"Ilona",
"count":93
},
{
"name":"Ruairidh",
"count":93
},
{
"name":"Virginie",
"count":92
},
{
"name":"Alan... |
76434 | from tethys_sdk.testing import TethysTestCase
import tethys_services.models as service_model
from unittest import mock
class SpatialDatasetServiceTests(TethysTestCase):
def set_up(self):
pass
def tear_down(self):
pass
def test__str__(self):
sds = service_model.SpatialDatasetServi... |
76462 | from django.utils.functional import cached_property
from redis.exceptions import ConnectionError, ResponseError
from experiments.redis_client import get_redis_client
COUNTER_CACHE_KEY = 'experiments:participants:%s'
COUNTER_FREQ_CACHE_KEY = 'experiments:freq:%s'
class Counters(object):
@cached_property
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.