id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4829983 | x = 10
if x == 10:
print 'The variable x is equal to 10.'
if x > 20:
print 'The variable x is greater than 20.'
else:
print 'The variable x is not greater than 20.'
if x > 10:
print 'The variable x is greater than 10.'
elif x > 5:
print 'The variable x is not greater than 10, but greater than 5.'
... |
4830012 | import argparse
import os
import utils
def test_tokenlevel_confliction(text_e, text_d):
tokens_e = text_e.split()
tokens_d = text_d.split()
if len(tokens_e) != len(tokens_d):
return False
for i in range(len(tokens_e)):
if tokens_e[i] != tokens_d[i]:
return False
return ... |
4830015 | from .base_sampler import BaseSampler
from .combined_sampler import CombinedSampler
from .instance_balanced_pos_sampler import InstanceBalancedPosSampler
from .foreground_balanced_pos_sampler import ForegroundBalancedPosSampler
from .iou_balanced_neg_sampler import IoUBalancedNegSampler
from .ohem_sampler import OHEMSa... |
4830064 | import mock
import pexpect
import pytest
from ocflib.account.utils import dn_for_username
from ocflib.account.utils import extract_username_from_principal
from ocflib.account.utils import home_dir
from ocflib.account.utils import is_in_group
from ocflib.account.utils import list_group
from ocflib.account.utils import ... |
4830068 | import unittest
from seaworthy.stream.matchers import (
EqualsMatcher, OrderedMatcher, RegexMatcher, UnorderedMatcher)
class TestEqualsMatcher(unittest.TestCase):
def test_matching(self):
""" Matches exactly equal strings and nothing else. """
matcher = EqualsMatcher('foo')
self.asser... |
4830071 | description = 'XCCM'
group = 'basic'
includes = [
'source',
'table',
'detector',
'sample_motors',
'detector_motors',
'optic_motors',
'IOcard'
]
|
4830084 | import numpy as np
import matplotlib.pyplot as plt
from skimage import data, filters, color, morphology
from skimage.segmentation import flood, flood_fill
import cv2 as cv
def flood_fill_white(img):
I = np.array(cv.cvtColor(img, cv.COLOR_BGR2RGB))
rgb = np.transpose(I, (2,0,1))
RGB = rgb
R, G, B = RGB[... |
4830088 | from dbus_next._private.address import parse_address
def test_valid_addresses():
valid_addresses = {
'unix:path=/run/user/1000/bus': [('unix', {
'path': '/run/user/1000/bus'
})],
'unix:abstract=/tmp/dbus-ft9sODWpZk,guid=a7b1d5912379c2d471165e9b5cb74a03': [('unix', {
... |
4830106 | from __future__ import print_function
import sys
import Pyro4
from listener import Listener
if len(sys.argv) != 2:
print("Give topic as argument.")
else:
topic = sys.argv[1].strip()
if not topic:
raise ValueError("Must give topic name.")
listener = Listener(topic)
daemon = Pyro4.Daemon()
... |
4830160 | import pyblish.api
from avalon import photoshop
class CollectInstances(pyblish.api.ContextPlugin):
"""Gather instances by LayerSet and file metadata
This collector takes into account assets that are associated with
an LayerSet and marked with a unique identifier;
Identifier:
id (str): "pybl... |
4830168 | from django.contrib import admin
from .models import Notes
# Register your models here.
admin.site.register(Notes) |
4830177 | from yaps.lib import int, real, uniform, bernoulli
import yaps as yaps
import numpy as np
@yaps.model
def coin(x: int(lower=0, upper=1)[10]):
theta: real(lower=0, upper=1) is uniform(0, 1)
for i in range(1, 11):
x[i] is bernoulli(theta)
coin.graph
print(coin)
flips = np.array([0, 1, 0, 0, 0, 0, 0, ... |
4830200 | from __future__ import unicode_literals
from django.apps import AppConfig
class NearBeachConfig(AppConfig):
name = 'NearBeach'
|
4830201 | from collections import Counter
class Solution:
def findRepeatedDnaSequences(self, s):
c = Counter(s[i : i + 10] for i in range(0, len(s) - 9))
return [k for k, v in c.items() if v > 1]
|
4830204 | import unittest
from etk.extractors.regex_extractor import RegexExtractor, MatchMode
class TestRegexExtractor(unittest.TestCase):
def test_match_mode_with_group(self) -> None:
regexp = RegexExtractor('(.)@(.)', 'test_extractor')
test_str = 'a@1, b@2, c@3, d@4'
extractions_with_flag_0 = re... |
4830225 | import torch
from torchvision import datasets, transforms
MNIST_PATH = '/home/dingxiaohan/datasets/torch_mnist/'
CIFAR10_PATH = '/home/dingxiaohan/datasets/cifar-10-batches-py/'
CH_PATH = '/home/dingxiaohan/datasets/torch_ch/'
SVHN_PATH = '/home/dingxiaohan/datasets/torch_svhn/'
class InfiniteDataLoader(torch.utils.... |
4830230 | from django.conf import settings
from django.template.loader import render_to_string
from django.utils import translation
import urllib.request, urllib.parse, urllib.error
import hmac
import hashlib
import re
import bleach
from contextlib import contextmanager
def signed_querystring(params):
key = bytes(settings... |
4830254 | import torch
from torch import nn
import numpy as np
import copy
from pcfg import PCFG
from pcfg_logprob import LogProbPCFG
from program import Function, Variable, BasicPrimitive, New
device = 'cpu'
def guess_output_size(latent_encoder, H):
test_input = torch.zeros(H)
with torch.no_grad():
output =... |
4830268 | import logging
from asyncio.events import get_event_loop
from asyncio.tasks import sleep
from typing import Optional
from aiohttp import ClientSession
try:
from dico import Client # type: ignore
except ImportError:
pass
from koreanbots.client import Koreanbots
log = logging.getLogger(__name__)
class Dico... |
4830352 | from lib import api
import numpy.testing as npt
# Note that shared_datadir is set up by pytest-datadir
def test_load_bgen(shared_datadir):
path = (shared_datadir / "example.bgen")
ds = api.read_bgen(path, backend='pybgen', chunks=(100, 500, 3))
assert "sample" in ds.dims
assert "variant" in ds.dims
... |
4830439 | from __future__ import division
import argparse
import os
import torch
from mmcv import Config
from mmdet import __version__
from mmdet.apis import (get_root_logger, init_dist, set_random_seed,
train_detector_normal, train_detector_calibration)
from mmdet.datasets import build_dataset
from mmd... |
4830472 | import json
from datetime import datetime
from tempfile import NamedTemporaryFile
from airflow.hooks.S3_hook import S3Hook
from airflow.models import BaseOperator
from google_analytics_plugin.hooks.google_analytics_hook import GoogleAnalyticsHook
class GoogleAnalyticsReportingToS3Operator(BaseOperator):
"""
... |
4830485 | from pymtl import *
from lizard.util.rtl.interface import Interface, UseInterface
from lizard.util.rtl.method import MethodSpec
from lizard.util.rtl.register import Register, RegisterInterface
from lizard.util.rtl.onehot import OneHotEncoder
from lizard.util.rtl.async_ram import AsynchronousRAM, AsynchronousRAMInterfa... |
4830551 | from dataclasses import dataclass
from typing import Any, Mapping, Optional, Sequence
from .util import path_default, try_get
__all__ = ('CommunityHistoryEntry', 'DEFAULT_DELETE_ACTION_PATH',
'make_community_history_entry')
DEFAULT_DELETE_ACTION_PATH = (
'actionMenu.menuRenderer.items.1.menuNavigationI... |
4830557 | from functools import lru_cache
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from events.models import Event, Keyword, KeywordSet, DataSource
HELSINKI_KEYWORD_SET_DATA = {
'id': 'helsinki:audiences',
'name_en': '<NAME>',
'name_fi': '<NAME>',
'nam... |
4830586 | import re
from PyQt5 import QtCore
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from DyCommon.DyCommon import *
from DyCommon.Ui.DyTableWidget import *
from DyCommon.Ui.DyDataFrameWindow import *
class DyStatsTableWidget(DyTableWidget):
def __init__(self, paren... |
4830589 | import os
import sys
import numpy as np
import multiprocessing
# Import flags specifying dataset parameters
from flags import getFlags
# Import sampling and conversion functions
from sample_gaussian import fast_convert_samples, sample_gaussian
if __name__ == '__main__':
FLAGS = getFlags()
def sample(d):
... |
4830596 | import itertools
num_het = {1:0, 2:1, 3:2, 4:4, 5:6, 6:10} #full model
t = 0 #topology = 0 (full model)
genome_filename = "random_genome.fa"
k = 21
coverage = 15
read_length = 100
br = 0
err = 0.01
model = "Partition"
COMMANDS_file = open("HETEROZYGOSITY_COMMANDS", 'w')
for i in range(1,8):
for p in [2,3,4,5,6]:
... |
4830599 | import logging
from gehomesdk.erd.converters.abstract import ErdReadOnlyConverter
from gehomesdk.erd.converters.primitives import *
from gehomesdk.erd.values.laundry import ErdRinseOption
_LOGGER = logging.getLogger(__name__)
class RinseOptionConverter(ErdReadOnlyConverter[ErdRinseOption]):
def erd_decode(self, ... |
4830613 | import re
from datetime import datetime
from city_scrapers_core.constants import COMMISSION
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
class CleLandmarksSpider(CityScrapersSpider):
name = "cle_landmarks"
agency = "Cleveland Landmarks Commission"
... |
4830619 | import unittest
from copy import deepcopy
from hummingbot.client.settings import AllConnectorSettings
from hummingbot.strategy.arbitrage.arbitrage_config_map import (
arbitrage_config_map,
primary_trading_pair_prompt,
secondary_trading_pair_prompt
)
class ArbitrageConfigMapTest(unittest.TestCase):
@... |
4830647 | from guillotina.utils import get_jwk_key
from jwcrypto import jwe
import base64
import json
import logging
import time
logger = logging.getLogger("guillotina")
class BasePolicy:
name = "<FILL IN>"
def __init__(self, request):
self.request = request
async def extract_token(self):
"""
... |
4830666 | class Queue:
def __init__(self):
self.main_stack = list()
self.aux_stack = list()
def __repr__(self):
return str(self.main_stack)
def enqueue(self, val):
self.main_stack.append(val)
def dequeue(self):
if not self.main_stack:
return None
whi... |
4830691 | def golden_section(f, a, b, tol=1e-5, **kwargs):
"""
Golden section search.
Stolen from https://en.wikipedia.org/wiki/Golden-section_search
Given a function f with a single local minimum in
the interval [a,b], gss returns a subset interval
[c,d] that contains the minimum with d-c <= tol.
... |
4830728 | from unittest import TestCase
from k8s_handle.k8s.mocks import ResourcesAPIMock
from .resource_getters import CoreResourceGetter, RegularResourceGetter
from .mocks import MockResource
class TestCoreResourceGetter(TestCase):
def setUp(self):
self.getter = CoreResourceGetter(
ResourcesAPIMock... |
4830733 | from sklearn.metrics import roc_auc_score, make_scorer
def get_scorer():
scorer = make_scorer(roc_auc_score)
return scorer |
4830734 | import re
import subprocess
import sys
import typing
possible_types = [
"build",
"chore",
"ci",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test",
]
types = "|".join(possible_types)
re_conventional_commit_header = re.compile(fr"^({types})(?:\(([^\)]+)\))... |
4830772 | from os.path import dirname, join, realpath, expanduser, isdir
from os import chmod
import platform
import sys
import shutil
from app.util import autoversioning, fs
from app.util.conf.configuration import Configuration
from app.util.conf.config_file import ConfigFile
BASE_CONFIG_FILE_SECTION = 'general'
class Base... |
4830801 | import unittest
from mpi4py import MPI
from util import run_unittest_script
# The packages we import will import MPI, causing an MPI init, but we don't actually
# want to use MPI under this script. We have to finalize so mpirun will work on
# the test scripts we call that *do* need MPI.
MPI.Finalize()
class UsingMP... |
4830805 | import unittest
from numpy.testing import assert_almost_equal
from openmdao.utils.general_utils import set_pyoptsparse_opt, printoptions
from openmdao.utils.testing_utils import use_tempdirs
import dymos.examples.brachistochrone.test.ex_brachistochrone_vector_states as ex_brachistochrone_vs
from dymos.utils.testing_u... |
4830860 | from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yacs.settings')
app = Celery('yacs')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object(... |
4830875 | from typing import List
import numpy as np
from ..tokenize import Sentences
from ._base import ExtractiveSummarizer
from ..config import load_config
class TFIDFSummarizer(ExtractiveSummarizer):
tags = ExtractiveSummarizer.tags + ['ml', 'tfidf', 'ir']
def __init__(self, tf_method=None, idf_method=None, drop... |
4830877 | import matplotlib.pyplot as plt
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.optimize import minimize
from pymoo.problems.multi import ZDT1
from pymoo.util.nds.non_dominated_sorting import NonDominatedSorting
from pymoo.visualization.pcp import PCP
from pymoo.visualization.scatter import Scatter
from pyrecorder... |
4830917 | import logging
import os
import zlib
from mmap import ACCESS_READ, mmap
from typing import Any, List, Optional, Tuple
from .chunks import ChunkRaw, create_chunk
from .chunktypes import (CHUNK_CRC_SIZE, CHUNK_LENGTH_SIZE, CHUNK_TYPE_SIZE,
TYPE_IDAT, TYPE_IHDR, TYPE_PLTE, is_text_chunk)
from .im... |
4830946 | from pdb import set_trace as T
class Material:
harvestable = False
capacity = 1
def __init__(self, config):
pass
def __eq__(self, mtl):
return self.index == mtl.index
def __equals__(self, mtl):
return self == mtl
class Lava(Material):
tex = 'lava'
index = 0
class Water(M... |
4830947 | import pytest
from common.filters import type_choices
from common.tests.factories import TestModel2Factory
from common.tests.models import TestModel2
pytestmark = pytest.mark.django_db
@pytest.fixture(params=(0, 1, 10))
def choice_inputs(request):
return [TestModel2Factory() for _ in range(request.param)]
def... |
4830952 | from pkg_resources import DistributionNotFound, get_distribution
from . import fit, load, plot, preprocess, setup # noqa
try:
version = get_distribution(__name__).version
except DistributionNotFound: # pragma: no cover
version = '0.0.0' # pragma: no cover
__version__ = version
|
4830990 | import pandapower as pp
import pytest
from numpy import array, isclose
@pytest.fixture()
def base_net():
net = pp.create_empty_network()
pp.create_bus(net, vn_kv=10)
pp.create_bus(net, vn_kv=10)
pp.create_ext_grid(net, 0)
pp.create_load(net, 1, p_mw=0.2, controllable=False)
pp.create_line_from_... |
4831028 | import requests
R = '\033[31m' # red
G = '\033[32m' # green
C = '\033[36m' # cyan
W = '\033[0m' # white
def ns_lookup(host, port):
print('[+]Fetching Details...\n')
result = requests.get(
'http://api.hackertarget.com/dnslookup/',
params={"q": host}
).text
print(result)
|
4831074 | import cv2
import pandas as pd
def extract_SURF_data(inputpath, outputpath):
img = cv2.imread(inputpath)
surf = cv2.xfeatures2d.SURF_create(4000)
kps, features = surf.detectAndCompute(img, None)
kps_data = []
for kp in kps:
# 关键点X,Y,从左到右0~255,从上到下0~255。关键点角度。关键点直径大小
# print(kp.pt[0... |
4831079 | config = {
"name": "Ijwu's Header Reader", # plugin name
"type": "receiver", #plugin type
"description": ["Prints the World Header into console."] #description
}
class Receiver(): # required class to be called by plugin manager
def __init__(self): #do any initialization stuff
pass # we d... |
4831094 | try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # type: ignore
import os
import re
import sys
import traceback
from appdirs import user_config_dir
from pygments import highlight
from pygments.formatters import Terminal256Formatter as TerminalFormatter
from... |
4831097 | from unittest import TestCase
import numpy as np
import pytest
import scipy.stats as sp
import torch
import pyro.distributions as dist
from tests.common import assert_equal
class TestCategorical(TestCase):
"""
Tests methods specific to the Categorical distribution
"""
def setUp(self):
n = 1... |
4831169 | import uroboros
def print_version():
print("multiple modules example v{version}"
.format(version=uroboros.version))
class RootCommand(uroboros.Command):
name = 'multi_module'
long_description = 'Sample of uroboros. ' \
'Use multiple modules to make this app'
def bu... |
4831170 | try:
import redis
except ImportError:
redis = None
from django.conf import settings
from django.dispatch import Signal
customer_recognized = Signal(providing_args=['customer', 'request'])
if redis and hasattr(settings, 'SESSION_REDIS'):
redis_con = dict((key, settings.SESSION_REDIS[key]) for key in ['hos... |
4831175 | from hashlib import md5
from typing import Optional
from urllib.parse import urlencode
import aiohttp
import attr
from ...box import box
from ...command import argument
from ...event import Message
from ...utils import json
from ...utils.datetime import fromtimestamp
from ...utils.http import USER_AGENT
box.assert... |
4831233 | from dal.test.utils import Fixtures, fixtures
from django.apps import AppConfig
from django.db.models.signals import post_migrate
class TestApp(AppConfig):
name = 'select2_generic_foreign_key'
def ready(self):
post_migrate.connect(fixtures, sender=self)
post_migrate.connect(Fixtures('auth.gr... |
4831254 | from unittest import TestCase
import os.path as osp
import numpy as np
from datumaro.components.annotation import AnnotationType, Bbox
from datumaro.components.dataset import Dataset
from datumaro.components.extractor import DatasetItem
from datumaro.util.test_utils import TestDir, compare_datasets
from datumaro.util... |
4831278 | import numpy as np
from scipy import sparse
class Reservoir(object):
"""
Build a reservoir and evaluate internal states
Parameters:
n_internal_units = processing units in the reservoir
spectral_radius = largest eigenvalue of the reservoir matrix of connection weights
leak = amo... |
4831343 | import functools
import gzip
import io
import os
import zipfile
def open_filepath(filepath_or_buffer, compression):
# Determine the compression from the file extension if "infer" has been specified
if compression == 'infer':
_, ext = os.path.splitext(filepath_or_buffer)
compression = {'.gz': ... |
4831360 | from django.utils.translation import LANGUAGE_SESSION_KEY, ugettext_lazy as _
from django.utils.six import iteritems
from django.db import models
from django.conf import settings
from timezone_field import TimeZoneField
# noinspection PyProtectedMember
from phonenumbers.data import _COUNTRY_CODE_TO_REGION_CODE
import ... |
4831369 | import pytest
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance("node", main_configs=["configs/config_information.xml"])
@pytest.fixture(scope="module")
def start_cluster():
try:
cluster.start()
yield cluster
finally:
clus... |
4831377 | import pytest
import mock
from django_alexa.internal import validation
from imp import reload
from datetime import datetime, timedelta
import pytz
import os
class TestValidation:
def test_validate_response_limit(self):
valid_value = 'x' * 1000 * 1000 * 24
validation.validate_response_limit(valid_v... |
4831386 | from datetime import datetime
from time import time
import pytest
from tests.sdk.queries.conftest import EXISTS
from tests.sdk.queries.conftest import format_datetime
from tests.sdk.queries.conftest import format_timestamp
from tests.sdk.queries.conftest import IN_RANGE
from tests.sdk.queries.conftest import IS
from t... |
4831396 | from unittest import mock
import pytest
from django.core import management
class TestAnonymizeDB():
@pytest.mark.parametrize(
'''action, check_only, anonymize_called, clean_called''', [
(None, None, True, True),
('anonymize', False, True, False),
('clean', False, False... |
4831424 | from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import time
import sys
cascade_path = "HS.xml"
image_path = sys.argv[1]
# image = cv2.imread(image_path)
cascade = cv2.CascadeClassifier(c... |
4831427 | start_molecule = None
epsilon_start = 1.0
epsilon_end = 0.01
epsilon_decay = 2000
optimizer = "Adam"
polyak = 0.995
atom_types = ["C", "O", "N"]
max_steps_per_episode = 40
allow_removal = True
allow_no_modification = True
allow_bonds_between_rings = False
allowed_ring_sizes = [3, 4, 5, 6]
replay_buffer_size = 1000000
l... |
4831509 | from rpython.jit.metainterp.history import AbstractDescr, getkind
from rpython.jit.codewriter.flatten import Register, Label, TLabel, KINDS
from rpython.jit.codewriter.flatten import ListOfKind, IndirectCallTargets
from rpython.jit.codewriter.format import format_assembler
from rpython.jit.codewriter.jitcode import Swi... |
4831538 | from math import *
from fractions import *
def solve():
n, k, b = [int(x) for x in raw_input().split()]
v = (b*(b+1))/2
if n < v:
print -1
return
if n == v:
for i in xrange(1, b): print i,
print b
return
tmp = (k*(k+1))/2
tmp -= ((k-b)*(k-b+1))/2;
if tmp < n:
print -1
return
# x = b+1
# ... |
4831548 | from testmodule import *
import time
class TestWrites(TestRunner):
def __init__(self):
super().__init__()
def mthd(self):
import pysharkbite
tableOperations = super().getTableOperations()
if not tableOperations.exists(False):
print ("Creating table")
if not tableOperations.create(False):
... |
4831558 | import sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
# Print the table contents
f... |
4831564 | from django import template
register = template.Library()
##
## Allows you to set variables in a template.
## Used when deciding what class to use based on an object value.
##
## Usage:
##
## {% define "Edit" as action %}
##
## {{ action }}
##
@register.simple_tag
def define(val=None):
return val |
4831565 | import urllib
import os
import shlex
import sys
from subprocess import run as subprocess_run, PIPE
from .changelog import update_release_notes
# Modified from doctr.travis.run_command_hiding_token
def run(args, shell=False, check=True):
token = os.environ.get("GH_AUTH").encode('utf-8')
if not shell:
... |
4831577 | import collections
from supriya.enums import CalculationRate
from supriya.synthdefs import UGen
class ScopeOut2(UGen):
"""
::
>>> scope_out_2 = supriya.ugens.ScopeOut2.ar(
... input_array=input_array,
... max_frames=4096,
... scope_frames=scope_frames,
...... |
4831589 | import numpy as np
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
import time
import utils
class Base(nn.Module):
""" This class is the base structure for all of classification/regression DNN models.
Mainly, it provides the general methods for training, evaluati... |
4831595 | from pathlib import Path
import appdirs
def normalize_dirname(string: str) -> str:
return string.replace("/", "_").lower()
def get_dir() -> Path:
fontman_dir = Path(appdirs.user_data_dir()) / "fonts" / "fontman"
fontman_dir.mkdir(parents=True, exist_ok=True)
return fontman_dir
|
4831605 | class LocalFTP(object):
"""
Class adding recursive nlst() behavior to ftplib.FTP instance. The
ftplib.FTP instance is available through the connection attribute, and
is exposed through __getattr__.
The behavior added by this class (recursive directory listing) is most
appropriate for ftp connec... |
4831635 | def main():
info('Pump after analysis')
gosub('felix:PumpBone')
if get_resource_value(name='FelixMiniboneFlag'):
gosub('felix:PumpMinibone') |
4831636 | onUserCreates={}
onCreates={}
onScriptLoads={}
onScriptSaves={}
onScriptCloses={}
onDestroys={}
knobChangeds={}
updateUIs={}
autolabels={}
beforeRenders={}
beforeFrameRenders={}
afterFrameRenders={}
afterRenders={}
renderProgresses={}
beforeBackgroundRenders=[]
afterBackgroundFrameRenders=[]
afterBackgroundRenders=[]
f... |
4831638 | import os
from typing import List, Optional, Tuple, Union
import vapoursynth as vs
from bvsfunc.util import ap_video_source
from lvsfunc.misc import source
from lvsfunc.types import Range
from vardautomation import (JAPANESE, AudioStream, FileInfo, Mux, Patch,
PresetAAC, PresetWEB, RunnerCo... |
4831664 | from bokeh.io import show
from bokeh.models import TickFormatter
from bokeh.plotting import figure
from bokeh.util.compiler import TypeScript
JS_CODE = """
import {TickFormatter} from "models/formatters/tick_formatter"
export class MyFormatter extends TickFormatter {
// TickFormatters should implement this method,... |
4831686 | import hashlib
import json
import os
import signal
import subprocess
import time
from contextlib import contextmanager
from typing import List, Set
import requests
def getDefaultExpectedHash() -> bytes:
# "uniquestring" is stored in /etc/unique of the SSH server. We then run
# the command `sha1sum /etc/uniqu... |
4831743 | import pytest
from traitlets import CInt, Int, HasTraits, List, default
from traitlets.config import Config, Configurable
from jupyter_project.autoinstance import AutoInstance
class C(Configurable):
i = CInt(config=True)
class A(Configurable):
a = List(AutoInstance(C), config=True)
def test_smoke():
... |
4831789 | from __future__ import print_function, division
from math import sqrt, atan2, degrees
polyhedra = {}
# Tetrahedron
polyhedra[4] = [(+1., +1., +1.),
(-1., -1., +1.),
(-1., +1., -1.),
(+1., -1., -1.)]
# Octahedron
polyhedra[6] = [(+1., +0., +0.),
(-1., +... |
4831792 | from collections import namedtuple, defaultdict
import numpy as np
from polara.recommender.data import RecommenderData
from polara.lib.similarity import build_indicator_matrix
from polara.recommender.hybrid.data import (IdentityDiagonalMixin,
SideRelationsMixin)
class Item... |
4831856 | import re
import os
import sys
import time
import socket
import imp
import ssl
import paho.mqtt.client as mqtt
g_recv_data=""
g_recv_topic=""
g_broker_connected=0
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
global g_broker_connected
... |
4831925 | import socket
import struct
q = lambda x: struct.pack("Q", x)
s = socket.create_connection(("127.0.0.1", 4000))
def malloc(sz):
s.send("1\n%d\n" % sz)
dat = s.recv(8192)
print dat
if "OK" in dat:
return int(dat.split("\n")[0])
else:
return None
def free(idx):
s.send("3\n%d\n" % idx)
print s.recv... |
4831937 | import json
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from skimage.exposure import equalize_hist
from skimage.metrics import structural_similarity as ssim
class bcolors:
"""
printing helper class
"""
HEADER = '\03... |
4831943 | from collections import defaultdict
from gym import Wrapper
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sb
sb.set_style("darkgrid")
current_palette = list(sb.color_palette())
class PerformanceTrackingWrapper(Wrapper):
"""
Wrapper to track episode performance.
Includes interval m... |
4831951 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gym
import numpy as np
import tensorflow.compat.v2 as tf
from gym import spaces
from gym.utils import seeding
import dice_rl.utils.common as common_utils
class PointMaze(gym.Env):
def __init__(sel... |
4831954 | import os
import numpy as np
import cv2
import pandas as pd
import torch
from torch.utils.data.dataset import Dataset
from torchvision import transforms
from PIL import Image, ImageFilter
import utils
def get_list_from_filenames(file_path):
# input: relative path to .txt file with file names
# output: ... |
4831957 | import os
import time
import base64
import redis
import config
import plivo
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and "0" ) or (baseN(num // b, b).lstrip("0") + numerals[num % b])
def tinyid(size=6):
id = '%s%s' % (
baseN(abs(hash(time.time())), 36)... |
4832012 | import os.path as osp
import random
from collections import defaultdict
from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase
from dassl.utils import mkdir_if_missing, read_json, write_json
@DATASET_REGISTRY.register()
class SSDGPACS(DatasetBase):
"""PACS.
Statistics:
- 4 domains: Pho... |
4832025 | from coreapi import Document
from coreapi_cli.history import History, dump_history, load_history
import pytest
def test_empty_history():
history = History()
assert history.is_at_most_recent
assert history.is_at_oldest
assert history.current is None
assert list(history.get_items()) == []
assert... |
4832041 | from datetime import timedelta
from typing import Optional
class Rule(object):
def __init__(
self,
# gen_second param
second: int = 0,
minute: int = 0,
hour: int = 0,
day: int = 0,
week: int = 0,
# token config
max_token_num: int = 100, # Ma... |
4832056 | from butterphy import read_ti_adc, read_rx_input
from dragonphy import *
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
class AdcModel:
def __init__(self, N_bit =8, full_scale_range=1, signed=False):
self.signed = signed
self.N_bit = N_bit
self.f... |
4832075 | import nqs
import numpy as np
import sampler
import heisenberg1d
import time
from scipy.linalg import hankel
n1 = nqs.Nqs(40,1)
n1 = n1.load_parameters("./Outputs/evolution_ti_0.npz") # a full, normal nqs without translation invariance
n2 = nqs.NqsTI(n1.nv, 1) # A translation invariant NQS instance with alpha = 2
#... |
4832103 | import logging,json
import os
import time
from typing import Dict
import requests
import azure.functions as func
from azureml.core.authentication import ServicePrincipalAuthentication
from ..shared.auth_helper import get_access_token
def trigger_aml_endpoint(pipeline_endpoint, experiment_name, parameter_b... |
4832105 | from unittest.mock import call, patch, Mock
import asyncio
import pytest
from . import FakeSleeper
from . import deadman_app
from . import mock_plugin
def fake_best_replicas(replicas):
l = sorted(replicas, key=lambda x: x[1]['willing'])
if l:
winner = l[0][1]['willing']
l = [i for i in l if ... |
4832126 | import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot import backends
@entrypoint
def show():
im = []
blist = []
for x in backends():
try:
print("--> grabbing by " + x)
im.append(pyscreenshot.grab(bbox=(500, 400, 800, 600), backend=x))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.