id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1688770 | from bitmovin.errors import InvalidTypeError
from bitmovin.resources import AbstractNameDescriptionResource
from bitmovin.resources.models import AbstractModel
from bitmovin.utils import Serializable
from .concatenation_input_stream_configuration import ConcatenationInputStreamConfiguration
class ConcatenationInputSt... |
1688790 | data = (
'jeo', # 0x00
'jeog', # 0x01
'jeogg', # 0x02
'jeogs', # 0x03
'jeon', # 0x04
'jeonj', # 0x05
'jeonh', # 0x06
'jeod', # 0x07
'jeol', # 0x08
'jeolg', # 0x09
'jeolm', # 0x0a
'jeolb', # 0x0b
'jeols', # 0x0c
'jeolt', # 0x0d
'jeolp', # 0x0e
'jeolh', # 0x... |
1688798 | from chainercv.datasets.coco.coco_instances_base_dataset import \
COCOInstancesBaseDataset
class COCOBboxDataset(COCOInstancesBaseDataset):
"""Bounding box dataset for `MS COCO`_.
.. _`MS COCO`: http://cocodataset.org/#home
Args:
data_dir (string): Path to the root of the training data. If ... |
1688838 | import os
import numpy as np
import copy
from PIL import Image, ImageDraw
from collections.abc import Sequence
from paddle.io import Dataset
from data.operators import *
from eval_model import get_categories, get_infer_results
class ImageFolder(Dataset):
def __init__(self,
dataset_dir=None,
... |
1688874 | import requests
from requests.auth import HTTPBasicAuth
from optparse import OptionParser
import sys
import time
if ((len(sys.argv) < 9 or len(sys.argv) > 9) and '-h' not in sys.argv):
print("Usage:")
print("python3 %s -p <password> -f <inputfile> -d <domain> -w <wait_time>" % sys.argv[0])
sys.exit(1)
pa... |
1688892 | import torch
from torch.nn import functional as F
from torch.autograd import Variable
import torch.nn as nn
import math
import numpy as np
from ..config import eps
class ConvBlock4(torch.nn.Module):
def __init__(self, inpt_kernel, output_kernel, kernel_size=4, stride=1, padding=0):
super().__init__()
... |
1688893 | import csv
import ipdb
import logging
from operator import itemgetter
from gensim import corpora, models
from gensim.utils import lemmatize
from gensim.parsing.preprocessing import STOPWORDS
from gensim.models.coherencemodel import CoherenceModel
import gensim
logging.basicConfig(format='%(asctime)s : %(levelname)s : ... |
1688917 | from loguetools import xd
def test_translate_step_data():
data = "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 20 30 40".replace(' ', '')
og_step_data = bytes.fromhex(data)
output = xd.fn_translate_step_data(og_step_data)
match = bytes.fromhex(
'00 01 02 03 00 00 00 00 04 05 06 07 00 00 ... |
1688920 | import os
def pre_process(data_path):
file_name = os.path.split(data_path)[1].split('.')[0]
return data_path, file_name
|
1688934 | import json
import asyncio
import pytest
from model_mommy import mommy
from aiohttp import ws_connect, WSServerHandshakeError
from aiohttp.web import Application, MsgType
from rest_framework.authtoken.models import Token
from redis_pubsub.contrib.websockets import websocket, websocket_pubsub
from redis_pubsub.contr... |
1688935 | from typing import Callable
from indexpy.utils.register import RegisterDict
def test_register_dict():
d: RegisterDict[str, Callable] = RegisterDict()
@d.register("foo")
def foo():
pass
assert d["foo"] is foo
|
1688973 | import pytest
import datetime
import shutil
import os
from textwrap import dedent
from os.path import join
from ...api import Gradebook, MissingEntry
from .. import run_nbgrader
from .base import BaseTestApp
class TestNbGraderDb(BaseTestApp):
def test_help(self):
"""Does the help display without error?... |
1689019 | import math, unittest
from collections import namedtuple
from robot import constant
from robot.mech.exceptions import InvalidJointAngleError, InvalidJointDictError
from robot.mech.joint import DenavitHartenberg, JointLimits, Joint
from spatial import Transform, Vector3
def ... |
1689025 | import logging
import string
import numpy as np
from ...tools.constants import DISEASE_PLACEHOLDER
from ...tools.constants import GENE_PLACEHOLDER
module_logger = logging.getLogger(__name__)
def generate_embedding_matrix(sentences_tokenized, word_vectors, word_to_index, max_length, min_words_mapped=0,
... |
1689088 | import itertools
import re
from .common import SearchInfoExtractor
class GoogleSearchIE(SearchInfoExtractor):
IE_DESC = 'Google Video search'
IE_NAME = 'video.google:search'
_SEARCH_KEY = 'gvsearch'
_TESTS = [{
'url': 'gvsearch15:python language',
'info_dict': {
'id': 'pyt... |
1689209 | import sqlalchemy as sa
from karmabot.db.modelbase import SqlAlchemyBase
class KarmaUser(SqlAlchemyBase):
"""Models a slack user with karma in the DB"""
__tablename__ = "karma_user"
user_id = sa.Column(sa.String, primary_key=True)
username = sa.Column(sa.String)
karma_points = sa.Column(sa.Inte... |
1689226 | from sqlalchemy import Column, event, Index, Integer, String
from rdr_service.model.base import Base, model_insert_listener
from rdr_service.model.utils import UTCDateTime
class ApiUser(Base):
__tablename__ = "api_user"
id = Column("id", Integer, primary_key=True, autoincrement=True, nullable=False)
crea... |
1689267 | from unittest import TestCase
from jsonmapping import StatementsVisitor
from .util import resolver, fixture_uri
def load_maker(stmts):
def _load(subject):
for (s, p, o, t) in stmts:
if s == subject:
yield {
'subject': s,
'predicate': p,... |
1689294 | import doctest
from insights.combiners import package_provides_httpd
from insights.parsers.package_provides_httpd import PackageProvidesHttpd
from insights.combiners.package_provides_httpd import PackageProvidesHttpdAll
from insights.tests import context_wrap
PACKAGE_COMMAND_MATCH_1 = """
/opt/rh/httpd24/root/usr/sb... |
1689369 | r"""Functions for nuclear and neutron beta decay effective couplings and $Ft$ values."""
from math import pi, log, sqrt
import flavio
from flavio.config import config
from flavio.physics.betadecays.common import wc_eff
from flavio.physics.ckm import get_ckm
from flavio.physics.taudecays.taulnunu import GFeff
from fla... |
1689388 | import asyncio
from random import choice as randchoice
import aiohttp
import discord
from redbot.core import Config, checks, commands
numbs = {"next": "➡", "back": "⬅", "exit": "❌"}
class Halo(commands.Cog):
"""
Display Halo 5 and Halo Wars 2 stats and information
"""
def __init__(self, bot):
... |
1689395 | self.description = "Sysupgrade with ignored package prevent other upgrade"
lp1 = pmpkg("glibc", "1.0-1")
lp2 = pmpkg("gcc-libs", "1.0-1")
lp2.depends = ["glibc>=1.0-1"]
lp3 = pmpkg("pcre", "1.0-1")
lp3.depends = ["gcc-libs"]
for p in lp1, lp2, lp3:
self.addpkg2db("local", p)
sp1 = pmpkg("glibc", "1.0-2")
sp2 = pmpk... |
1689407 | from types import FunctionType
from lab import B
from matrix import Constant
from mlkernels import (
num_elements,
ZeroKernel,
TensorProductKernel,
)
from plum import Union
from .fdd import FDD
from .gp import GP, assert_same_measure
from .observations import (
AbstractObservations,
Observations,
... |
1689416 | import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import Row
import operator
from pyspark.mllib.clustering import KMeans
spark = SparkSession.builder \
.master("local") \
.appName("Anomalies Detection") \
.con... |
1689440 | import logging
from pyscreenshot.about import __version__
from pyscreenshot.childproc import childprocess_backend_version
from pyscreenshot.loader import FailedBackendError, backend_dict, backend_grab
ADDITIONAL_IMPORTS = [FailedBackendError]
log = logging.getLogger(__name__)
log.debug("version=%s", __version__)
d... |
1689442 | import vcf
import sys
import os
from lib.csq_parser import CsqParser
from Bio.Seq import translate
import lib.run_utils
class ProximalVariant:
#flanking_bases is the number of bases (not amino acids!) to search on each side of a variant position
def __init__(self, proximal_variants_vcf, pass_only, flanking_bas... |
1689461 | import sys
import os
from selexp import *
def fn2type(x):
c1 = 'CLUSTER_1_ITER'
clust = 'CLUSTER'
grdy = 'GREEDY'
if c1 in x:
return c1
elif clust in x:
return clust
elif grdy in x:
if 'OUTLIERS' in x:
return ('OUTLIERS', float(x.split("OUTLIERS_")[1].split... |
1689463 | import unittest
import torch
import torch_testing as tt
from all import nn
from all.core import StateArray
from all.approximation import VNetwork, FeatureNetwork
from all.memory import NStepAdvantageBuffer
class NStepAdvantageBufferTest(unittest.TestCase):
def setUp(self):
torch.manual_seed(1)
sel... |
1689468 | import numpy as np
from context import arkouda as ak
from base_test import ArkoudaTest
SIZE = 10
K = 5
def make_array():
a = ak.randint(0, SIZE, SIZE)
return a
def compare_results(akres, sortedres) -> int:
'''
Compares the numpy and arkouda arrays via the numpy.allclose method with the
default re... |
1689469 | import argparse
from functools import partial
import gzip
from pathlib import Path
import random
from typing import List
from tqdm import tqdm
def get_random_lines_from_file(filepath, title_line: bool = True,
k: int = 1, N: int = 1) -> List[List]:
open_ = partial(gzip.open, mode='rt... |
1689498 | import numpy
import math
from timeit import default_timer as timer
import willump.evaluation.willump_executor
@willump.evaluation.willump_executor.willump_execute()
def process_row(input_numpy_array):
return_numpy_array = numpy.zeros(516)
return_numpy_array[0] = input_numpy_array[68] / math.sqrt(input_numpy_a... |
1689517 | from collections import defaultdict
from past.builtins import basestring
from pyramid.response import Response
from pyramid.view import view_config
from subprocess import Popen, PIPE
from xml.sax.saxutils import quoteattr, escape
from contentbase import TYPES
def includeme(config):
config.add_route('graph_dot', '... |
1689534 | from django.db import connection
from django.db.backends.util import truncate_name
from django.db.models.fields import Field # Django base Field class
from django.contrib.gis.db.backend.util import gqn
from django.contrib.gis.db.backend.oracle.query import TRANSFORM
# Quotename & geographic quotename, respectively.
qn... |
1689609 | import cv2
import numpy as np
cap=cv2.VideoCapture('data/vtest.avi')
ret,frame1=cap.read()
ret,frame2=cap.read()
while cap.isOpened():
diff=cv2.absdiff(frame1,frame2)
gray=cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
blur=cv2.GaussianBlur(gray,(5,5),0)
_,thresh=cv2.threshold(blur,20,255,cv2.THRESH... |
1689623 | from collections import defaultdict
import fcntl
import io
import os
import re
import subprocess
import sys
import tempfile
from django.conf import settings
#from celery.utils import log as logging
import logging
log = logging.getLogger(__name__)
#log = logging.task_logger
__author__ = 'pflarr'
SUDO_CMDS = settin... |
1689646 | import pytest
import pandas as pd
from roughviz.charts.stacked_bar import StackedBar
def test_wrong_type_data():
wrong_data = {"loc": ["North", "South", "East", "West"], "values": [10, 5, 8, 3]}
match = "Only valid type of data is list"
with pytest.raises(TypeError, match=match):
StackedBar(data... |
1689716 | from __future__ import print_function
import time
import epics
import pvnames
print('== Test get/put for synchronous groups')
pvs = pvnames.motor_list
chids = [epics.ca.create_channel(pvname) for pvname in pvs]
for chid in chids:
epics.ca.connect_channel(chid)
epics.ca.put(chid, 0)
print('Now create synch ... |
1689748 | import time,os
import re
from modint import chinese_remainder
def profiler(method):
def wrapper_method(*arg, **kw):
t = time.time()
ret = method(*arg, **kw)
print('Method ' + method.__name__ +' took : ' + "{:2.5f}".format(time.time()-t) + ' sec')
return ret
return wrapper_metho... |
1689807 | import string
from pathlib import Path
class AUDIO_CONFIG:
sampling_rate = 32000
duration = 1
hop_length = 251 # making it 128 in size
fmin = 500
fmax = 15000
n_mels = 128
n_fft = n_mels * 20
samples = sampling_rate * duration
padmode = 'reflect'
def fill_range(letter_start, le... |
1689820 | from unittest.mock import create_autospec, ANY, patch, call
import pytest
from stack.commands import DatabaseConnection
from stack.commands.remove.host.firmware.mapping import Command
from stack.exception import CommandError
from stack.commands.remove.host.firmware.mapping.plugin_basic import Plugin
class TestRemoveHo... |
1689852 | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.join(BASE_DIR, os.pardir)
DATA_DIR = os.path.join(ROOT_DIR,'Data')
mesh_top_dir = os.path.join(DATA_DIR,'GraspNet')
scan_result_dir = os.path.join(DATA_DIR,'BlensorResult')
CommandFile_dir = os.path.join(DATA_DIR,'CommandFiles')
|
1689864 | from __future__ import print_function
import unittest
from unittest import TestCase
import numpy as np
from numpy.testing import assert_, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from hmmlearn.utils import normalize
from autohmm import tm
np.seterr(all='warn')
def tes... |
1689883 | import numpy as np
import scipy.sparse as spa
import cvxpy
class RandomQPExample(object):
'''
Random QP example
'''
def __init__(self, n, seed=1):
'''
Generate problem in QP format and CVXPY format
'''
# Set random seed
np.random.seed(seed)
m = int(n * ... |
1689889 | from kratos import *
class SW_NET(Generator):
'''
The switching network will bring in multiple items per cycle and direct
them to the appropriate aggregation buffer
'''
def __init__(self,
interconnect_in,
offsets, # Offset between the interconnect_in ports
... |
1689894 | from codebase.models.extra_layers import leaky_relu, wndense, noise, wnconv2d, wnconv2d_transpose, scale_gradient
import tensorflow as tf
from tensorflow.contrib.framework import arg_scope
from tensorbayes.layers import dense, conv2d, conv2d_transpose, upsample, avg_pool, max_pool, batch_norm, instance_norm
from codeba... |
1689901 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from fontTools.misc.textTools import safeEval
from . import DefaultTable
import array
import sys
Gloc_header = '''
> # big endian
version: 16.16F # Table version
... |
1689921 | import argparse
import sys
from os.path import abspath
from json import dumps
from charset_normalizer import from_fp
from charset_normalizer.models import CliDetectionResult
from charset_normalizer.version import __version__
from platform import python_version
def query_yes_no(question, default="yes"):
"""Ask a... |
1689942 | from app.thirdparty.oneforall.config import settings
from app.thirdparty.oneforall.common.query import Query
class ChinazAPI(Query):
def __init__(self, domain):
Query.__init__(self)
self.domain = domain
self.module = 'Dataset'
self.source = 'ChinazAPIQuery'
self.addr = 'htt... |
1689959 | import ftplib
import sys
import os
import argparse
def get_arg_parser():
parser = argparse.ArgumentParser(
description="Upload to ftp server",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("file_path", nargs='?', default="/data/test.txt",
help="Path t... |
1690017 | from typing import Any, Dict, Iterable, Tuple, Union
import numpy as np
from cirq import linalg, protocols, value
from cirq._compat import proper_repr
from cirq.ops import raw_types
class MixedUnitaryChannel(raw_types.Gate):
"""A generic mixture that can record the index of its selected operator.
This type ... |
1690056 | def import_class(module_name, class_name):
"""
Import a class given the specified module name and class name.
"""
klass = __import__(module_name)
class_segments = class_name.split(".")
for segment in class_segments:
klass = getattr(klass, segment)
return klass
|
1690095 | from prefix import *
from chaperone.cutil.syslog import _syslog_spec_matcher
SPECS = (
('*.*', '(True)'),
('[crond].*', '((g and "crond" == g.lower()))'),
('.*', 'Invalid log spec syntax: .*'),
('kern.*... |
1690129 | from enum import Enum, auto
from zemberek.core.turkish import PrimaryPos, SecondaryPos, RootAttribute, TurkishAlphabet, Turkish
from zemberek.morphology.analysis.single_analysis import SingleAnalysis
class WordAnalysisSurfaceFormatter:
ALPHABET = TurkishAlphabet.INSTANCE
def format_(self, analysis: SingleAn... |
1690175 | import sublime
import json
import codecs
import os
is_sublime_text_3 = int(sublime.version()) >= 3000
if is_sublime_text_3:
from .settings import Settings
else:
from settings import Settings
class ProcessCache():
_procs = []
last_task_name = None
@classmethod
def get_from_storage(cls):
... |
1690185 | import os
from ._base import DirSyncTestCase
from . import trees
from dirsync import sync
class SimpleTests(DirSyncTestCase):
init_trees = (('src', trees.simple),)
def test_simple_exclude(self):
sync('src', 'dst',
'sync',
create=True,
exclude=... |
1690189 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import numpy as np
from models.losses import FocalLoss, RegL1Loss, RegLoss, RegWeightedL1Loss, BinRotLoss, AutoShape_Position_loss, RegWeightedL1Loss2
from models.utils import _sigmoid
from .base_... |
1690206 | import argparse
def annotate_enhancer_promoter_loops(
left_enhancers, right_enhancers, left_promoters, right_promoters):
"""
Split loops into anchors.
"""
loops = {}
left_coords = {}
right_coords = {}
# Left enhancers
with open(left_enhancers, 'r') as f:
for line in f:... |
1690217 | import numpy as np
# import PIL.Image
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# lowest = -1.0
lowest = 0.0
highest = 1.0
# --------------------------------------
# Color maps ([-1,1] -> [0,1]^3)
# --------------------------------------
def heatmap(x):
x = x[..., np.newaxis]
# positive re... |
1690253 | import opencv
#this is important for capturing/displaying images
from opencv import highgui
import pygame
import sys
camera = highgui.cvCreateCameraCapture(0)
def get_image():
im = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
im = opencv.cvGetMat(im)
#convert Ipl ima... |
1690281 | from __future__ import division
from options import get_parsed_commandline_options
from data_3d import WaveFront
# from data_3d import *
from modes import *
from file_utils import *
from modes.manipulate_results_data import *
import logging
from service import GracefulShutdown
# ===================================... |
1690316 | import os
import logging
import sys
from logging.handlers import RotatingFileHandler
from mlcomp import LOG_FOLDER, LOG_NAME, FILE_LOG_LEVEL, DB_LOG_LEVEL, \
CONSOLE_LOG_LEVEL
from mlcomp.db.core import Session
from mlcomp.db.providers import LogProvider
from mlcomp.db.models import Log
from mlcomp.utils.misc impo... |
1690329 | import multiprocessing
import os
import time
import gym
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from RLToolbox.toolbox.common.utils import *
from RLToolbox.agent.A3C_agent import A3CAgent
from RLToolbox.storage.storage_continous_parallel import ParallelStorage
from RLToolbox.toolbox.baselin... |
1690337 | import sqlite3
import textwrap
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, open_sqlite_db_readonly
def get_smanagerLow(files_found, report_folder, seeker, wrap_text):
file_found = str(files_found[0])
db = open_sqlite_db... |
1690344 | import json
import argparse
import yaml
import copy
from flair.utils import logging
from flair.algorithms import dict_merge
logger = logging.init_logger()
class Params(object):
"""
Parameters
"""
def __init__(self, params):
self.params = params
def __eq__(self, other):
if not i... |
1690359 | STATES = (
('AK', 'Alaska'),
('AL', 'Alabama'),
('AR', 'Arkansas'),
('AZ', 'Arizona'),
('CA', 'California'),
('CO', 'Colorado'),
('CT', 'Connecticut'),
('DC', 'District of Columbia'),
('DE', 'Delaware'),
('FL', 'Florida'),
('GA', 'Georgia'),
('HI', 'Hawaii'),
('IA', '... |
1690424 | from tracking.abstract import AbstractTracker
from jnius import autoclass, JavaException
ScreenViewBuilder = autoclass('com.google.android.gms.analytics.HitBuilders$ScreenViewBuilder')
EventBuilder = autoclass('com.google.android.gms.analytics.HitBuilders$EventBuilder')
GoogleAnalytics = autoclass('com.google.android.... |
1690431 | from __future__ import absolute_import
def test_1d_acoustics():
"""test_1d_acoustics
tests against known classic, sharpclaw, and high-order weno results """
from . import acoustics_1d
def verify_expected(expected):
""" binds the expected value to the acoustics_verify methods """
def... |
1690485 | import pytest
import responses
from django.core.files.uploadedfile import SimpleUploadedFile
from docutils.nodes import document
from inmemorystorage.storage import InMemoryFile
from django_docutils.favicon.prefetch import (
is_favicon_stored,
prefetch_favicon,
yield_page_doctrees,
yield_references,
)... |
1690505 | import py
import sys, os, gc
from rpython.translator.c.test import test_newgc
from rpython.translator.translator import TranslationContext
from rpython.translator.c.genc import CStandaloneBuilder
from rpython.annotator.listdef import s_list_of_strings
from rpython.conftest import option
from rpython.translator.tool.cbu... |
1690546 | import os
import json
import configparser
from ssr.utility.logging_extension import logger
_config = None
class SSRConfig:
default_section = "DEFAULT"
comment_symbol = "#"
@staticmethod
def get_instance():
assert _config is not None
return _config
@staticmethod
def set_ins... |
1690549 | import torch
import MinkowskiEngine as ME
from torch.utils.tensorboard import SummaryWriter
from typing import List
from collections import defaultdict
from models.transition_model import TransitionModel
from utils.pad import unpack, get_gt_values
from utils.util import timeit, downsample
from utils.scheduler import In... |
1690668 | import datetime
import nose
from traces import TimeSeries, Histogram
def test_distribution():
start = datetime.datetime(2015, 3, 1)
# v. simple
a = TimeSeries()
a.set(start, 1)
a.set(datetime.datetime(2015, 3, 2), 0)
a.set(datetime.datetime(2015, 3, 3), 1)
a.set(datetime.datetime(2015, 3... |
1690695 | from .pydbg import DebuggerBase, DbgEng
class CrashDbg(DebuggerBase):
def __init__(self):
super().__init__(client=None, standalone=True)
def load_dump(self, name):
self._client.OpenDumpFile(name)
self.go() |
1690708 | import numpy as np
import matplotlib.pyplot as plt
# ========== HW04 SOLUTION [Python2] ========== #
# ========== 1 ========== #
five_dim_array = np.load('five_dim_array.npy')
array_flat = five_dim_array.flatten()
print array_flat.argmin()
# ========== 2 ========== #
x = np.linspace(-10, 10)
plt.figure()
plt.plo... |
1690721 | import json
from math import exp
from matplotlib import pyplot as plt
if __name__ == "__main__":
with open("primitives.json", "r") as f:
primitives = {x['label']:x for x in json.load(f)}
with open("results.json", "r") as f:
results = json.load(f)["results"]
ys_precip = [r['intervened']['v... |
1690754 | from __future__ import absolute_import
from __future__ import print_function
from .products import load_product_yaml
from .yaml import open_raw
def open_environment(build_config_yaml_path, product_yaml_path):
contents = open_raw(build_config_yaml_path)
contents.update(load_product_yaml(product_yaml_path))
... |
1690832 | import meshcat
import numpy as np
import pinocchio as pin
# Meshcat utils
def meshcat_material(r, g, b, a):
import meshcat
material = meshcat.geometry.MeshPhongMaterial()
material.color = int(r * 255) * 256 ** 2 + int(g * 255) * 256 + int(b * 255)
material.opacity = a
return material
def meshca... |
1690855 | import datetime
import pathlib
import unittest
from freenom_dns_updater import Record, RecordType
from freenom_dns_updater.record_parser import RecordParser
class DomainParserTest(unittest.TestCase):
def test_parse_records(self):
path = pathlib.Path(__file__).parent / "resources" / "record_page.html"
... |
1690869 | import unittest
import orca
import os.path as path
from setup.settings import *
from pandas.util.testing import *
def _create_odf_csv(datal, datar):
dfsDatabase = "dfs://testMergeAsofDB"
s = orca.default_session()
dolphindb_script = """
login('admin', '<PASSWORD>')
... |
1690940 | import argparse
from argparse import Namespace
from datasets import CIFAR10
from datasets import MNIST
from datasets import SHANGHAITECH
from datasets import UCSDPed2
from models import LSACIFAR10
from models import LSAMNIST
from models import LSAShanghaiTech
from models import LSAUCSD
from result_helpers import OneCl... |
1690959 | from bento.compat.api \
import \
defaultdict
class CommandRegistry(object):
def __init__(self):
# command line name -> command class
self._klasses = {}
# command line name -> None for private commands
self._privates = {}
def register(self, name, cmd_klass, public=Tr... |
1690979 | import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import cv2
import numpy as np
from .config import cfg, MEANS, STD
from pycocotools import mask as maskUtils
import contextlib
import io
import logging
import time
def collate_fn_flying_c... |
1691042 | import os
import torch
import torch.nn as nn
from core.model_transform import *
from core.utils import is_main_process
__all__ = ["CheckPoint"]
class CheckPoint(object):
"""
save model state to file
check_point_params: model, optimizer, epoch
"""
def __init__(self, save_path, ... |
1691043 | import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
import argparse
import backtest
import indicators
import strategies
def main():
parser = argparse.ArgumentParser()
parser.add_argument("file")
parser.add_argument("--sma", type=int, nargs='+... |
1691054 | import os
import sys
from pathlib import Path
from helpers.generator import generate_files
from helpers.files import download_file, CompressionResult, discover, FileData
# Add the engine directory to the path of importable directories
engine_path = os.getcwd() + "/engine"
sys.path.append(engine_path)
from engine impo... |
1691141 | import gym
from typing import Dict
from ding.envs import BaseEnv
from ding.envs.common import EnvElement
ALL_ACTION_TYPE = set(['change'])
class SumoAction(EnvElement):
r"""
Overview:
the action element of Sumo enviroment
Interface:
_init, _from_agent_processor
"""
_name = "Sumo... |
1691159 | import json
import csv
import random
import boto3
from botocore.vendored import requests
def lambda_handler(event, context):
try:
# Set user pidx from S3
s3 = boto3.resource('s3')
bucket = s3.Bucket('gamingonaws2018')
obj = bucket.Object(key = 'userList.csv')
respon... |
1691201 | import warnings
from ibllib.misc import logger_config
warnings.filterwarnings('always', category=DeprecationWarning, module='ibllib')
# if this becomes a full-blown library we should let the logging configuration to the discretion of the dev
# who uses the library. However since it can also be provided as an app, th... |
1691217 | import csv
import os
import pickle
from typing import List
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import PandasTools
def save_features(path: str, features: List[np.ndarray]) -> None:
"""
Saves features to a compressed :code:`.npz` file with array name "features".
:p... |
1691250 | from __future__ import unicode_literals
import frappe
def execute():
if not frappe.db.exists("Item Group", {'item_group_name': 'WA State Classifications'}):
from erpnext_biotrack.install.after_install import install_fixtures
install_fixtures()
|
1691264 | import pytest
from pymongo_migrate.generate import slugify
@pytest.mark.parametrize(
"test_input,expected",
[
("My comment", "my_comment"),
("counting: 1, 2, 3", "counting_1_2_3"),
("wat?!", "wat"),
("<NAME>", "may_wik"),
],
)
def test_slugify(test_input, expected):
as... |
1691304 | import numpy as np
import yaml
import os, sys
import copy
from functools import reduce
import random
from timeloop_env import TimeloopEnv
from multiprocessing.pool import Pool
from multiprocessing import cpu_count
import shutil
from functools import cmp_to_key, partial
class GammaTimeloopEnv(object):
def __init__... |
1691317 | import argparse
import codecs
import datetime
import hashlib
import inspect
import logging
import os
import sys
import time
import traceback
import warnings
import dill
import nbformat as nbf
from jupyter_client.kernelspec import KernelSpecManager
from nbconvert import HTMLExporter
from nbconvert.preprocessors import ... |
1691351 | from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Q
from user.permissions import CustomerPremission
from rest_framework.permissions import IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, AllowAny
import time,da... |
1691355 | import logging
from construct import Int64ul
from regipy.exceptions import RegistryKeyNotFoundException
from regipy.hive_types import SYSTEM_HIVE_TYPE
from regipy.plugins.plugin import Plugin
from regipy.utils import convert_wintime
logger = logging.getLogger(__name__)
BAM_PATH = r'Services\bam\UserSettings'
clas... |
1691378 | from datetime import *
import sys
sys.path.append("../../..")
import JeevesLib
from smt.Z3 import *
import macropy.activate
from users import *
from assignment import *
class Submission():
def __init__(self, submissionId, title, assignmentId, submitterId, fileRef):
self.submissionId = submissionId
self.tit... |
1691428 | from pyecharts import options as opts
from pyecharts.charts import EffectScatter
from pyecharts.faker import Faker
c = (
EffectScatter()
.add_xaxis(Faker.choose())
.add_yaxis("", Faker.values())
.set_global_opts(
title_opts=opts.TitleOpts(title="EffectScatter-显示分割线"),
xaxis_opts=opts.Ax... |
1691430 | from .token import coord
from termcolor import colored as X
import os.path
import sys
def show_line(pos, hi=lambda x: X(x, 'red', attrs=['bold'])):
if not pos.file:
return
if not os.path.isfile(pos.file):
return
with open(pos.file) as tmp:
for num, line in enumerate(tmp):
if num + 1 == pos.l... |
1691437 | from tests.utils import W3CTestCase
class TestBidiOverride(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'bidi-override-'))
|
1691475 | from .processors import InputExample, InputFeatures, DataProcessor
from .processors import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features
from .processors import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
from .metrics import is_sklearn_available
if is_sklea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.