id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9828035 | from json import loads, dumps
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import (QiitaDBError, QiitaDBDuplicateError)
from qiita_db.util import convert_to_id
from qiita_db.study import Study
from re import sub
# August 6, 2018
# Create parameters f... |
9828047 | import os
import time
from glob import glob
from pathlib import Path
import pandas as pd
import pytorch_lightning as pl
import sastvd as svd
import sastvd.linevd as lvd
from ray.tune import Analysis
def main(config, df):
"""Get test results."""
main_savedir = svd.get_dir(svd.outputs_dir() / "rq_results_new")... |
9828075 | import logging
import json
import time
from pathlib import Path
from argparse import ArgumentParser
from functools import wraps
from flask import Flask, Response, render_template
from gqlalchemy import Match, Memgraph
from gqlalchemy.models import MemgraphIndex
from enum import Enum
log = logging.getLogger(__name__)
... |
9828174 | from collections import defaultdict
from ast_helpers import get_human_name
from violation import RuleViolation
from scrapers import AnnotationKind
class Rule( object ):
def check( self, call_tree, func_tags, standard_funcs ):
raise NotImplementedError( "Child class should override this" )
class RuleRes... |
9828192 | import json
import gzip
import sys
import pandas as pd
for filename in sys.argv[1:]:
df = pd.read_hdf(filename, "table")
with gzip.open(
filename.replace(".hdf5", "_trees.json.gz"), "wt", encoding="UTF-8"
) as fileobj:
json.dump(df.trees.values.tolist(), fileobj)
|
9828204 | from collections import deque
from hypothesis.strategies import lists, none, one_of
def deques(elements=None, min_size=0, max_size=None,
unique_by=None, unique=False):
return lists(**locals()).map(deque)
def optionals(strategy):
return one_of(strategy, none())
|
9828215 | import abc
from copy import deepcopy
from typing import Callable, Dict, Optional, TypeVar
import numpy as np
from robogym.observation.common import Observation, ObservationProvider, SyncType
from robogym.observation.image import ImageObservationProvider
class GoalObservationProvider(ObservationProvider):
"""
... |
9828224 | from hydra.utils import instantiate
from pytorch_lightning import seed_everything
from autoalbument.faster_autoaugment.datamodule import FasterAutoAugmentDataModule
from autoalbument.faster_autoaugment.models.faa_model import (
FAAClassificationModel,
FAASemanticSegmentationModel,
)
from autoalbument.search_in... |
9828270 | import aiohttp
import asyncio
import json
import opentera.messages.python as messages
from google.protobuf.json_format import ParseDict, ParseError
from google.protobuf.json_format import MessageToJson
login_api_endpoint = '/api/user/login'
async def fetch(client, url, auth=None, params=None):
if params is No... |
9828280 | import os
import torch
import torch.nn.functional as F
from uninas.models.networks.uninas.search import SearchUninasNetwork
from uninas.data.abstract import AbstractBatchAugmentation
from uninas.methods.abstract import AbstractOptimizationMethod
from uninas.methods.strategies.manager import StrategyManager
from uninas.... |
9828293 | from uuid import UUID
import pytest
from django.db import IntegrityError
from myapp.application.adapter.spi.persistence.entity.article_vote_entity import \
ArticleVoteEntity
from myapp.application.adapter.spi.persistence.repository.article_vote_repository import \
ArticleVoteRepository
from myapp.application.... |
9828299 | from functools import lru_cache
from itertools import chain
from pathlib import Path
from time import sleep
from typing import Iterable, Optional, Sequence, Set, Tuple, Union
import numpy as np
import pandas as pd
from tqdm import tqdm
from ._database import Database, require_write_access
from ._dataframe import iter... |
9828329 | from rest_framework.routers import DefaultRouter
from users.urls import user_router
from groups.urls import group_router
from servers.urls import server_router
from images.urls import image_router
route = DefaultRouter()
route.registry.extend(user_router.registry)
route.registry.extend(group_router.registry)
route.reg... |
9828347 | from sklearn.metrics import f1_score
def evaluate(active_learner, train, test):
y_pred = active_learner.classifier.predict(train)
y_pred_test = active_learner.classifier.predict(test)
print('Train accuracy: {:.2f}'.format(
f1_score(y_pred, train.y, average='micro')))
print('Test accuracy: {:.... |
9828396 | import sys
from ..metadata_payload import get_metadata_obj
from calm.dsl.api import get_api_client
from calm.dsl.store import Cache
from calm.dsl.config import get_context
from calm.dsl.log import get_logging_handle
from calm.dsl.constants import CACHE
LOG = get_logging_handle(__name__)
def _walk_to_parent_with_give... |
9828435 | from osim.env import RunEnv
from agent import *
import ConfigParser
from osim.http.client import Client
def str2bool(v):
return v.lower() in ("yes", "true", "1")
remote_base = 'http://grader.crowdai.org:1729'
client = Client(remote_base)
config = ConfigParser.ConfigParser()
config.readfp(open('config.ini'))
learn... |
9828463 | import cv2 as cv
import numpy as np
import os
import time
def get_alpha_W_black():
video = "videos/clipcanvas-black.mp4"
cap = cv.VideoCapture(video)
res, waterpic = cap.read()
print(waterpic.max(),waterpic[:,:,0].mean(),waterpic[:,:,1].mean(),waterpic[:,:,2].mean(),)
# waterpic = cv.cvtColor(waterpic, cv.COLOR_B... |
9828495 | from django import forms
from django.core.validators import URLValidator
from django.utils.translation import gettext_lazy as _
class EmbedForm(forms.Form):
url = forms.CharField(
label=_("URL"), validators=[URLValidator(message=_("Please enter a valid URL"))]
)
|
9828531 | import re
from typing import List, Optional
from datetime import datetime
from pydantic import BaseModel, Field, validator
from project.helpers.pydantic_typo import MongoId
class PhysicalPerson(BaseModel):
id: Optional[MongoId] = Field(default=None, alias='_id')
name: str
last_name: str
status: str
... |
9828553 | import os
import shutil
import unittest
from docopt import DocoptExit
from odml import load as odml_load
from odml.scripts import odml_convert
from . import util
class TestScriptOdmlConvert(unittest.TestCase):
def setUp(self):
self.tmp_dir = util.create_test_dir(__file__)
self.dir_files = os.pa... |
9828598 | import numpy as np
import matplotlib.pyplot as plt
# x co-ordinates
x = np.arange(0, 9)
A = np.array([x, np.ones(9)])
# linearly generated sequence
y = [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24]
# obtaining the parameters of regression line
w = np.linalg.lstsq(A.T, y)[0]
line = w[0]*x + w[1] # regression line
pl... |
9828619 | import pandas as pd
import nltk, json, os
from nltk import word_tokenize
import numpy as np
from textblob import TextBlob
import itertools
def nltk_featurize(transcript):
#alphabetical features
a=transcript.count('a')
b=transcript.count('b')
c=transcript.count('c')
d=transcript.count('d')
e=transcript.count... |
9828645 | import numpy as np
import pandas as pd
import pyarrow as pa
from pyarrow import parquet as pq
from time_series_transform.io.base import io_base
from time_series_transform.io.pandas import (
from_pandas,
to_pandas
)
from time_series_transform.io.arrow import (
to_arrow_table,
from_arrow_table
)
from time... |
9828713 | import pytest
import pathlib
from mktestdocs import check_docstring, grab_code_blocks
from simsity.datasets import fetch_clinc, fetch_voters
@pytest.mark.parametrize("func", [fetch_clinc, fetch_voters], ids=lambda d: d.__name__)
def test_function_docstrings(func):
"""Test the docstring code of some functions."""... |
9828714 | import os
import subprocess
def dd():
print('mdmdmd')
res = subprocess.check_output(dd, stderr=subprocess.STDOUT, shell=True)
print(res) |
9828715 | import sys
with open("word.in","r") as fin:
L = list(fin)
N,W = map(int,L[0].split())
with open("word.out","w") as fout:
w = 0
for c in L[1].split():
if w+len(c) > W:
fout.write("\n"+c)
w = len(c)
else:
if w > 0:
fout.write(" ")
fout.write(c)
w += len(c)
fout.write("\n") |
9828727 | import struct
from pycoin.encoding.hexbytes import bytes_as_revhex
from pycoin.serialize.streamer import Streamer
from .satoshi_int import parse_satoshi_int, stream_satoshi_int
from .satoshi_string import parse_satoshi_string, stream_satoshi_string
STREAMER_FUNCTIONS = {
"I": (parse_satoshi_int, stream_satoshi_... |
9828783 | from ..factory import Type
class inputPersonalDocument(Type):
files = None # type: "vector<InputFile>"
translation = None # type: "vector<InputFile>"
|
9828878 | from datetime import date
from django.contrib import messages
from django.forms import inlineformset_factory
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, reverse
from django.views import View
from common.mixins import AccessModelMixin, NextPageMixin, PermissionsRequi... |
9828906 | import random
from django import template
from django.utils.safestring import mark_safe
from common.data.greetings import DUMB_GREETINGS
from common.markdown.markdown import markdown_email
register = template.Library()
@register.filter(is_safe=True)
def email_markdown(text):
return mark_safe(markdown_email(tex... |
9828936 | from django.forms.widgets import MultiWidget, NumberInput, Select
import re
from .units import ureg
class QuantityWidget(MultiWidget):
def __init__(self, *, attrs=None, base_units=None, allowed_types=None):
self.ureg = ureg
choices = self.get_choices(allowed_types)
self.base_units = base... |
9828958 | from skweak.base import CombinedAnnotator
from .sentiment_lexicons import LexiconAnnotator, NRC_SentAnnotator, VADAnnotator, SocalAnnotator, BUTAnnotator
from .sentiment_models import DocBOWAnnotator, MultilingualAnnotator, MBertAnnotator
import os
from spacy.tokens import Doc #type: ignore
from typing import Sequence,... |
9829008 | import os
import sys
import glob
from download import calc_sha1
file_directory = sys.argv[1]
file_directory = os.path.abspath(file_directory)
paths_to_hash = []
file_list = []
for filename in glob.iglob(file_directory + '**/**', recursive=True):
if os.path.isfile(filename):
file_list.append((calc_sha1(fil... |
9829025 | import numpy as np
import lintel
'''
video decode on the fly based on https://github.com/dukebw/lintel
'''
def _sample_frame_sequence_to_4darray(video, dataset, should_random_seek, fps_cap):
"""Called to extract a frame sequence `dataset.num_frames` long, sampled
uniformly from inside `video`, to a 4D num... |
9829026 | import queue
import threading as th
import multiprocessing as mp
from typing import Any, Iterator
class Yielder:
def __init__(self, result_queue: mp.Queue, task_complete_queue: mp.Queue, all_tasks_done_event: th.Event):
self._result_queue = result_queue
self._tasks_done_event = all_tasks_done_event... |
9829027 | from nautobot.core.apps import HomePageItem, HomePagePanel
from nautobot.tenancy.models import Tenant
layout = (
HomePagePanel(
name="Organization",
weight=100,
items=(
HomePageItem(
name="Tenants",
link="tenancy:tenant_list",
mod... |
9829073 | import torch
from mmdet.models.dense_heads import query_generator
from mmdet.models.roi_heads.bbox_heads.adaptive_mixing_operator import AdaptiveMixing
from mmdet.models.dense_heads.query_generator import InitialQueryGenerator
from mmdet.models.detectors import QueryBased
num_stages = 6
num_proposals = 100
QUERY_DIM ... |
9829097 | class NoSuchTopic(Exception):
pass
class PrivateTopicNoAccess(Exception):
pass
class MemberTopicNotSubscribed(Exception):
pass |
9829108 | import exifread
import python_storage_balancing
import session_vars
#def pep_resource_resolve_hierarchy_pre(rule_args, callback, rei):
# return python_storage_balancing.pep_resource_resolve_hierarchy_pre(rule_args, callback, rei)
def acPostProcForPut(rule_args, callback, rei):
sv = session_vars.get_map(rei)
... |
9829111 | import securitycenter
HOST = 'DNS_NAME_OR_IP'
USER = 'USERNAME'
PASS = 'PASSWORD'
CSV_FILENAME = 'example.csv'
IGNORE = [
# Some Example Ignores:
'Security Update',
# 'Python',
]
sc = securitycenter.SecurityCenter4(HOST)
sc.login(USER, PASS)
software = {}
# Remove the ): and ... |
9829193 | from collections import UserDict
from Skoarcery.SkoarPyon import toke_inspector, skoarmantics
from Skoarcery.SkoarPyon.lex import Toke_Whitespace, Toke_EOF, SkoarToke
class Toker:
def __init__(I, code):
I.skoarse = code
I.am_here = 0
I.saw = None
def see(I, want):
if I.saw:
... |
9829216 | import pycraft_minetest as pcmt
import pycraft_minetest.blocklist as blocklist
import PIL as pl
"""
converte immagini jpg/png/gif in minetest usando blocchi di lana colorata come pixel
crea immagine in verticale a posizione assoluta
"""
# https://stackoverflow.com/questions/1109422/getting-list-of-pixel-value... |
9829237 | import sys
import os
from scipy.signal import firwin, lfilter
import numpy as np
import matplotlib.pyplot as plt
sys.path.append(os.path.abspath("../../IoTPy/agent_types"))
sys.path.append(os.path.abspath("../../IoTPy/core"))
sys.path.append(os.path.abspath("../../IoTPy/helper_functions"))
sys.path.append(os.path.absp... |
9829257 | import abc
import os
import json
import gdown
import lm_dataformat as lmd
from tqdm import tqdm
from .utils import *
class Dataset(abc.ABC):
@abc.abstractmethod
def name(self):
""" Human-readable name of the dataset """
pass
@abc.abstractmethod
def documents(self):
""" A gene... |
9829266 | import tempfile
import math
import numbers
from pathlib import Path
import torch
import torchvision
import numpy as np
import av
def load_video_webdata(data, num_frames, duration=None, skip_shorter_seconds=None):
with tempfile.TemporaryDirectory() as dname:
path = dname + "/sample.mp4"
with open(... |
9829269 | from . import manim_cell
from . import mango
#this enables autocomplete
from manimlib.imports import * |
9829309 | import sqlite3
from sqlite3 import Error
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.patches as mpatches
import plotly.graph_objects as go
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by... |
9829313 | import torch
from argus import Model
from src.stacking.models import FCNet
class StackingModel(Model):
nn_module = {
'FCNet': FCNet
}
prediction_transform = torch.nn.Sigmoid
|
9829384 | import binascii
import json
from base64 import b64decode
from datetime import datetime
from django.utils.timezone import utc
from .base import AnymailBaseWebhookView
from ..exceptions import (
AnymailInvalidAddress,
AnymailWebhookValidationFailure,
AnymailImproperlyInstalled,
_LazyError,
AnymailC... |
9829412 | from django.contrib import admin
from .models import (Ambulance_request, Appointment, Complaint, Counter,
Doctor, Expiry, Hospital, Hospital_admit, Medicine,
Prescribed_medicine, Prescription, Schedule, Stock)
admin.site.register(Doctor)
admin.site.register(Appointment)
admin... |
9829430 | import unittest
import json
import pickle
from moto import mock_s3
import boto3
import pandas as pd
from tagr.tagging.artifacts import Tagr
from tagr.storage.aws import Aws
DATA = [{"a": 1, "b": 2, "c": 3}, {"a": 10, "b": 20, "c": 30}]
DF = pd.DataFrame(DATA)
EXPERIMENT_PARAMS = {
"proj": "unit-test-project",
... |
9829494 | def config_caches(is_docker: bool):
return {
'default': {
'BACKEND': 'django_redis.cache.RedisCache', # 缓存后端 Redis
# 连接Redis数据库(服务器地址)
# 一主带多从(可以配置个Redis,写走第一台,读走其他的机器)
'LOCATION': [
# 'redis://localhost:6379/0',
'redis://redis... |
9829502 | from typing import Sequence, List
import json
class WSDLException(Exception):
pass
class WSDLInvalidArgument(Exception):
def __init__(self, argument: str, element_name: str, *args: object) -> None:
self.arg = argument
self.element = element_name
super().__init__(*args)
def __str... |
9829547 | import pytest
import datetime
from conda_store_server.server.auth import (
AuthenticationBackend,
RBACAuthorizationBackend,
Permissions,
)
from conda_store_server.schema import AuthenticationToken
@pytest.mark.parametrize(
"expression, resource, match",
[
("e*/d*", "example/data", True),
... |
9829552 | try:
from importlib import metadata
except ImportError:
# Running on pre-3.8 Python
import importlib_metadata as metadata # noqa
__version__ = metadata.version('agentpy')
|
9829554 | from models_library.projects_state import RunningState
from simcore_postgres_database.models.comp_pipeline import StateType
DB_TO_RUNNING_STATE = {
StateType.FAILED: RunningState.FAILED,
StateType.PENDING: RunningState.PENDING,
StateType.SUCCESS: RunningState.SUCCESS,
StateType.PUBLISHED: RunningState.... |
9829573 | from adafruit_circuitplayground.express import cpx
import time
while True:
print(cpx.light)
time.sleep(0.1)
|
9829590 | from jmessage import users
from jmessage import common
from conf import *
jmessage=common.JMessage(app_key,master_secret)
users=jmessage.create_users()
user= [users.build_user("user12345678","password")]
response=users.regist_user(user)
print (response.content)
|
9829607 | from setuptools import setup, find_packages
VERSION = '4.0.2'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
... |
9829611 | import pytest
import typing
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
import nonebot_bison
merge_source_9 = [
'https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vib7zooj30dx0dxmz5.jpg',
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vib5oqjj30dw0dxjt2.jpg",
"https:... |
9829629 | import os
import subprocess
from _pytest.monkeypatch import MonkeyPatch
from redash.query_runner.script import query_to_script_path, run_script
from tests import BaseTestCase
class TestQueryToScript(BaseTestCase):
monkeypatch = MonkeyPatch()
def test_unspecified(self):
self.assertEqual(
... |
9829635 | from setuptools import setup, find_packages
setup(
name='GHCNpy',
version='1.0',
author='<NAME>, <NAME>',
author_email='<EMAIL>, <EMAIL>',
packages=find_packages(),
url='https://github.com/jjrennie/GHCNpy/',
description='Package for Analyzing and Displaying Weather Stations from GHCN-Daily'... |
9829666 | import os
import copy
import BeeVeeH
import BeeVeeH.bvh_helper as BVH
import pytest
import numpy as np
BVH_DIR = '%s/bvh_files' % os.path.dirname(__file__)
class TestCase():
def test_bvh_parse(self):
file_path = '%s/0007_Cartwheel001.bvh' % BVH_DIR
self.root, self.frames, self.frame_time = BVH.loa... |
9829674 | from django.core.management import setup_environ
import settings
import itertools
setup_environ(settings)
from gazetteer.models import FeatureCode
from gazetteer.models import AdminBoundary
from gazetteer.place import *
es_settings = settings.ELASTICSEARCH["default"]
conn = ElasticHistory(es_settings["HOST"], timeo... |
9829710 | from gensim.matutils import unitvec as g_unitvec
import numpy as np
def unitvec(arr):
return g_unitvec(np.array(arr))
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def intersect_nonempty_set(base, target):
if isinstance(target, set) and target:
result = base.intersection(target)
else:
... |
9829718 | import boto3
import time
class SpeechService:
def __init__(self, storage_service):
self.client = boto3.client('polly')
self.bucket_name = storage_service.get_storage_location()
self.storage_service = storage_service
def synthesize_speech(self, text, target_language):
POLL_DELA... |
9829745 | import numpy as np
import matplotlib.pyplot as plt
blue = (0, 0, 1.0)
green = (0, 0.8, 0)
red = (1.0, 0, 0)
red_alpha = (1.0, 0, 0, 0.001)
gray = (0.7, 0.7, 0.7)
# Settings
n_repeat = 100 # Number of iterations for computing expectations
n_train = 30 # Size of the training set
n_test = 1000 # Size ... |
9829789 | import argparse
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
def main(arguments):
inputs = np.load(arguments.input)
outputs = []
for _ in range(arguments.replicate):
outputs.append(inputs)
outputs = np.vstack(outputs)
np.save(arguments.output, outp... |
9829827 | import FWCore.ParameterSet.Config as cms
process = cms.Process("Dump")
process.load('Configuration.StandardSequences.Services_cff')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Conf... |
9829839 | from whoosh.index import Index as whooshIndex
from whoosh.reading import IndexReader as whooshIndexReader
from whoosh.matching import Matcher as whooshMatcher
import bisect
from .manager import StaticIndexManager
from .postings import Postings
try:
from .svbcomp import load2, load2_to_np
except ImportError:
fro... |
9829841 | class LASDataError(Exception):
"""Error during reading of numerical data from LAS file."""
pass
class LASHeaderError(Exception):
"""Error during reading of header data from LAS file."""
pass
class LASUnknownUnitError(Exception):
"""Error of unknown unit in LAS file."""
pass
|
9829873 | import json
from flask_restplus import Resource, marshal
from ..models.mine_summary_view import MineSummaryView
from app.api.exports.response_models import MINE_SUMMARY_MODEL
from app.extensions import api, cache
from app.api.utils.access_decorators import requires_role_view_all
from app.api.constants import MINE_DET... |
9829909 | from .pvt import *
from .pvtv2 import *
from .pcpvt import *
from .config import *
from .gvt import *
|
9829911 | from .fameldb import FameLeaderboard
async def setup(bot):
cog = FameLeaderboard(bot)
await cog.crtoken()
bot.add_cog(cog) |
9829923 | class CachedModelException(Exception): pass
# Our invalidation classes
class CacheInvalidationWarning(CachedModelException): pass
class CacheMissingWarning(CacheInvalidationWarning):
"""
CacheMissingWarning is thrown when we're trying to fetch a queryset
and it's missing objects in the database.
"""
... |
9829940 | import uuid
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flump import FlumpView, FlumpBlueprint, OrmIntegration, Fetcher
from marshmallow import fields, Schema
# Create a basic Flask app and set it to use SQLite.
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
# Regi... |
9829953 | import FWCore.ParameterSet.Config as cms
pedTest = cms.EDAnalyzer("EcalPedOffset",
dbUserName = cms.untracked.string('foo'),
xmlFile = cms.string('provaSuperWide'),
EEdigiCollection = cms.InputTag("ecalEBunpacker","eeDigis"),
run = cms.int32(100),
dbHostPort = cms.untracked.int32(0),
EBdigiColl... |
9829954 | import argparse
import json
from nubia_score import Nubia
def main(args):
metric = Nubia()
six_dim = args.six_dim.lower() == "true"
with open(args.output_file, "w") as out:
with open(args.input_file, "r") as f:
for line in f:
data = json.loads(line)
ca... |
9829967 | from .render4cnn import *
from .clickhere_cnn import *
import models.wrapper
# from .vgg_tm import *
|
9829971 | from django.shortcuts import render
def home(request):
request.active_nav_item = "manage"
return render(request, 'django_airavata_dataparsers/parsers-manage.html', {
"bundle_name": "parser-list"
})
def parser_details(request, parser_id):
return render(request, 'django_airavata_dataparsers/p... |
9830038 | import glob
from Bio import PDB
pdb_files = glob.iglob('all_pdbs/*')
file = open('casp11.sec', 'w')
c = 0
for pdb in pdb_files:
c += 1
print(c)
p = PDB.PDBParser()
structure = p.get_structure(pdb[:-4], pdb)
model = structure[0]
dssp = PDB.DSSP(model, pdb)
seq = ''
ss = ''
for ke... |
9830157 | from . import unittest
class TestPackage(unittest.TestCase):
def test_top_level_namespace(self):
import kafka as kafka1
self.assertEqual(kafka1.KafkaClient.__name__, "KafkaClient")
self.assertEqual(kafka1.client.__name__, "kafka.client")
self.assertEqual(kafka1.codec.__name__, "kafk... |
9830168 | import torch
import numpy as np
from src.utils.tensors import lengths_to_mask
def calculate_acceletation(motionloader, device, xyz):
# for now even if it is not xyz, the acceleration is one the euclidian/pose
outfeat = "output_xyz" if xyz else "output"
sum_acc = 0
num_acc = 0
for batch in motion... |
9830176 | from .base import Formatter
from .hex import Hex
from .code import Code
from .binary import Binary
|
9830191 | import torch
def bbox_overlaps_nd_pytorch(anchors: torch.Tensor,
targets: torch.Tensor,
dim=None,
mode='iou',
aligned=False,
eps=1e-6) -> torch.Tensor:
"""
:param an... |
9830241 | input = """
i(0). i(1).
a(X) v -a(X) :- i(X).
ok :- #count{X:a(X)} > 0, not #count{T:a(T)} >= 2.
:- not ok.
"""
output = """
{-a(0), a(1), i(0), i(1), ok}
{-a(1), a(0), i(0), i(1), ok}
"""
|
9830252 | import numpy as np
import tensorflow as tf
import time
def add_read_shot_noise(
imgs, sig_read=None, sig_shot=None,
min_read=-3., max_read=-1.5, min_shot=-2., max_shot=-1.):
bsz = tf.shape(imgs)[0]
if sig_read is None or sig_shot is None:
sig_read = tf.pow(10., tf.random.uniform(
... |
9830258 | import math
from unittest import mock
from unittest.mock import patch, call
import classifier
def levenshtein_distance_side_effect(a, b):
if a == 2 and b == 2:
return 0.3
return 0
def test_levenshtein_distance():
# Arrange
a = 2
b = {
'features': 2
}
# Act
with mock... |
9830259 | import os
import logging
import numpy as np
import torch
from collections import OrderedDict
from contextlib import contextmanager
logger = logging.getLogger(__name__)
def should_stop_early(patience, valid_auprc: float) -> bool:
if valid_auprc is None:
return False
if patience <= 0:
return Fa... |
9830338 | import vanilla
from defconAppKit.windows.baseWindow import BaseWindowController
from defconAppKit.controls.glyphLineView import GlyphLineView
from mojo import events
class MultiFontPreview(BaseWindowController):
def __init__(self):
self.w = vanilla.Window((400, 400), minSize=(100, 100))
self.w.gl... |
9830369 | import windse
import numpy as np
### Initialize WindSE ###
windse.initialize("params.yaml")
### Generate Domain ###
dom = windse.BoxDomain()
### Generate Wind Farm ###
farm = windse.ImportedWindFarm(dom)
farm.Plot()
### Warp the mesh and refine ###
dom.Warp(200,0.75)
region = [[farm.ex_x[0],dom.x_range[1]],farm.ex_... |
9830429 | from pyramid.view import view_config
from pypi.viewmodels.utils.sitemap_viewmodel import SiteMapViewModel
# ################### Sitemap #################################
@view_config(route_name='sitemap.xml', renderer='pypi:templates/utils/sitemap_xml.pt')
def sitemap(request):
vm = SiteMapViewModel(request, 100... |
9830481 | from django.contrib import admin
from zebra.conf import options
if options.ZEBRA_ENABLE_APP:
from vendor.zebra.models import Customer, Plan, Subscription
admin.site.register(Customer)
admin.site.register(Plan)
admin.site.register(Subscription)
|
9830496 | import FWCore.ParameterSet.Config as cms
# Muon Associator
from SimMuon.MCTruth.muonAssociatorByHitsHelper_cfi import *
# Setting for StandAloneMuons
muonAssociatorByHitsHelper.tracksTag = cms.InputTag("standAloneMuons")
muonAssociatorByHitsHelper.UseTracker = cms.bool(False)
muonAssociatorByHitsHelper.UseMuon = cms.... |
9830514 | import matplotlib.pyplot as plt
from skidl.pyspice import *
lib_search_paths[SPICE].append('SpiceLib')
###############################################################################
# Resistor-capacitor driven by pulses.
###############################################################################
reset()
# Cre... |
9830522 | import os
import sys
import re
#Read a counts file(output from $ngram-count -write1 countsfile.lm -text corpus.txt) and only write words to new file with a >= count than MIN_COUNT.
#Currently using this because vocab on 30 js repos is about 75k words, removing words with count of 1 drops to around 25k
#This method rem... |
9830524 | import datetime
import pandas as pd
def log_error(err_file, err_msg):
with open(err_file, "a") as f:
f.write("-" * 15 + "\n")
f.write(str(datetime.datetime.now()) + "\n")
f.write(str(err_msg) + "\n")
def build_row_table(df, config=None, namespace=None):
df_quant = pd.DataFrame(index... |
9830525 | from runners.python import Submission
from collections import defaultdict
def get_paths(graph, path=[(0, 0)]):
last = path[-1][1]
for node in graph[last]:
if (node, last) in path or (last, node) in path:
continue
new_path = path + [(last, node)]
yield new_path
yield... |
9830562 | import sys
sys.path.append("../")
from appJar import gui
def press(btn):
if btn == "CLEAR": app.clearDatePicker("dp1")
elif btn == "CLEAR ALL": app.clearAllDatePickers()
elif btn == "GET": print(app.getDatePicker("dp1"))
elif btn == "SET": app.setDatePicker("dp1")
app=gui()
app.addDatePicker("dp1")
a... |
9830608 | from youtube_livechat_messages.api import API
from youtube_livechat_messages.auth import get_access_token, get_credentials
from youtube_livechat_messages.models import EventType
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.