id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
411345 | import pytest
from kedro_mlflow.framework.cli.cli_utils import (
render_jinja_template,
write_jinja_template,
)
@pytest.fixture
def template_path(tmp_path):
return tmp_path / "template.py"
@pytest.fixture
def jinja_template(template_path):
with open(template_path, "w") as file_handler:
file... |
411421 | import pytest
from oval_graph.command_line_client.client import Client
from .constants_for_tests import PATH_TO_ARF_REPORT
def get_client(rule, optional_args=None):
path = str(PATH_TO_ARF_REPORT)
args = [path, rule]
if optional_args is not None:
args.extend(optional_args)
return Client(args)... |
411443 | class SVG_map:
"""
This class generates the svg for the API response
This class initializes itself with title, total range and progress.
It calculates the necessary measurements from these info to generate
the SVG.
Attributes
----------
__title__ : str
title of the progress-bar... |
411452 | from typing import Union, Optional, List
from django.utils.translation import gettext
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from polaris.models import OffChainAsset, Asset, ExchangePair, DeliveryMethod
def asset_id_to_kwargs(asset_id: str) -> dict:
if asset_id.star... |
411548 | import brownie
import pytest
from brownie import chain
from eth_account import Account
from eth_account.messages import encode_structured_data
amount = 100
owner = Account.create()
spender = Account.create()
def generate_permit(vault, owner: Account, spender: Account, value, nonce, deadline):
data = {
"t... |
411554 | import json
from fastapi import FastAPI, status, Body
from fastapi.responses import PlainTextResponse
from yes_predictor import PythonPredictor
my_app = FastAPI()
my_app.ready = False
my_app.predictor = None
@my_app.on_event("startup")
def startup():
with open("predictor_config.json", "r") as f:
config ... |
411576 | import numpy as np
from utils import *
from exponential_families import load_nodes
import csv
import scipy.sparse as sps
def get_node_map(nodes):
'''Calculate the mapping from data column to node.'''
cols = []
for i,node in enumerate(nodes):
cols.extend([i]*node.num_params)
return np.array(cols... |
411645 | r = input()
s = input()
a = r.split(",")
b = s.split(",")
count = 0
k = 0
for i in range(len(b)):
count = count + int(b[k])
k += 1
for j in a:
n = j.split(":")
if count == int(n[0]):
count = int(n[1])
if count>= 100:
print("Yes"... |
411669 | import argparse
import json
from collections import Counter
from datetime import datetime
import pendulum
import requests
from github import Github
from .config import (
FOREST_CLAENDAR_URL,
FOREST_ISSUE_NUMBER,
FOREST_LOGIN_URL,
FOREST_SUMMARY_HEAD,
FOREST_SUMMARY_STAT_TEMPLATE,
FOREST_TAG_UR... |
411698 | from pyui.geom import Size
from .base import View
class Rectangle(View):
def content_size(self, available: Size):
return available
|
411704 | from typing import Iterable
import math
import numpy as np
from torch.utils.data import Sampler, BatchSampler
class SortishSampler(Sampler):
"""Returns indices such that inputs with similar lengths are close together."""
def __init__(self, sequence_lengths: Iterable, bucket_size: int, num_replicas: int = 1,... |
411708 | import time
import pyaudio
import numpy as np
from threading import Thread, Lock
class SoundStream(object):
def __init__(self, src=0):
self.started = False
self.read_lock = Lock()
self.sound = 0
self.chunk = np.zeros(1024, dtype=np.int16)
self.p = pyaudio.PyAudio()
... |
411709 | import runpy
from setuptools import setup, find_packages
__version__ = runpy.run_path("torch_em/__version__.py")["__version__"]
# NOTE requirements are not all available via pip, you need to use conda,
# see 'environment_gpu.yaml' / 'environment_cpu.yaml'
requires = [
"torch",
"h5py"
]
setup(
name="tor... |
411763 | import json
import logging
import numpy as np
import os
from scipy.special import logsumexp
from time import time
from __init__ import project_root
from data_handlers.data_providers import load_data_providers, DataProvider
from utils.plot_utils import disp_imdata
from utils.project_constants import IMG_DATASETS
def... |
411804 | import os
import torch
from torchvision.utils import save_image
from config import *
from selfie2anime import get_selfie2anime_loader
from models import Generator
from utils import denorm, make_dirs, make_gifs_test
# Device Configuration #
device = 'cuda' if torch.cuda.is_available() else 'cpu'
def inference():
... |
411877 | import json
import os
import random
import zipfile
from convlab2.util.file_util import cached_path
def auto_download():
model_path = os.path.join(os.path.dirname(__file__), os.pardir, 'model')
data_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data')
db_path = os.path.join(os.path.dirname(__... |
411929 | import torch
import os
os.environ['TORCH_HOME'] = './'
import torch.nn as nn
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data.dataset import Dataset # For custom datasets
from torch.utils.data import DataLoader
from model import UNet, UNet_2
from dorn import DORN
from data... |
411970 | import torch
import torch.nn as nn
from torch import optim
from sampler import PKSampler, PKSampler2
def get_Sampler(sampler,dataset,p=15,k=20):
if sampler == 'all':
return PKSampler2(dataset, p=p, k=k)
else:
return PKSampler(dataset, p=p, k=k)
def get_Optimizer(model, optimizer_type=None, lr=... |
411994 | from __future__ import annotations
import datetime
import warnings
from pathlib import Path
from typing import List, Literal, Union
import numpy as np
import open3d
import pandas
import plotly
import plotly.express as px
import pyntcloud
from pointcloudset.diff import ALL_DIFFS
from pointcloudset.filter import ALL_F... |
412008 | import asyncio
import uvloop
def get_new_uvloop_queue():
loop = uvloop.new_event_loop()
return asyncio.Queue(loop=loop)
new_messages = get_new_uvloop_queue()
users_changed = get_new_uvloop_queue()
online = get_new_uvloop_queue()
offline = get_new_uvloop_queue()
check_online = get_new_uvloop_queue()
is_typin... |
412017 | import numpy as np, tensorflow as tf, aolib.util as ut, aolib.img as ig, os, sys, sklearn.svm, press, copy, sklearn.pipeline
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
import vgg, h5py
import sklearn.metrics
pj = ut.pjoin
full_dim = 256
crop_dim = 224
#gpu = '/gpu:0'
init_path ... |
412025 | import pandas as pd
from selenium import webdriver
import csv
CHROME_DRIVER_PATH = '/Users/jiwoo/Documents/chromedriver'
FILE_PATH = 'products.csv'
def crawler(keyword):
url = 'http://www.lottemart.com/search/search.do?searchTerm='
url = url + keyword
driver = webdriver.Chrome(CHROME_DRIVER_PATH)
driv... |
412035 | import ctypes
import networkx as nx
import numpy as np
import os
import sys
class LearningLib(object):
def __init__(self, args):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/build/dll/learning_lib.so' % dir_path)
self.lib.Fit.restype = ctypes.c_double
... |
412058 | from . import BaseCommand
from flask import send_from_directory
import os
class ResourceRequestCommand(BaseCommand):
def process(self, request, filename, db_session):
return send_from_directory(
os.path.abspath(
os.path.join(os.path.dirname(__file__), "..")
) + '/s... |
412088 | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from echomesh.base import Settings
from echomesh.base import GetPrefix
from echomesh.expression import Expression
from echomesh.util.thread import Lock
class _Client(object):
def __init__(self):
self.clients = {... |
412107 | from tkinter import *
info = [
("Name (TEXT):",1),
("e-mail (TEXT):",2),
("Flat no. (TEXT):",3),
("Tower no. (TEXT):",4),
("Area (NUMBER):",5),
("Parking (TEXT):",6),
("Recpt. Fess (NUMBER):",7),
("Address (TEXT):",8),
("Contact number (TEXT):",9)
]
e=["","","","","","","","","",""] # entries
cla... |
412114 | import os
from pathlib import Path
from xml.etree import ElementTree
from unittest import TestCase
import utilities.file_utilities as file_utilities
from mhs_common.messages.soap_fault_envelope import SOAPFault
class TestSOAPFault(TestCase):
message_dir = Path(os.path.dirname(os.path.abspath(__file__))) / 'test... |
412137 | import sys
import time
import struct
import socket
import pprint
import optparse
# in the github repo, cbapi is not in the example directory
sys.path.append('../src/cbapi')
import cbapi
def build_cli_parser():
parser = optparse.OptionParser(usage="%prog [options]", description="Display information about a part... |
412143 | import FWCore.ParameterSet.Config as cms
from Alignment.APEEstimation.ApeEstimator_cfi import *
from Alignment.APEEstimation.SectorBuilder_cff import *
ApeEstimator = ApeEstimatorTemplate.clone(
maxTracksPerEvent = 0,
#applyTrackCuts = False,
minGoodHitsPerTrack = 1,
residualErrorBinning = [0.0005,0.0010,0.... |
412150 | from cogitare.data.dataholder import AbsDataHolder
from six import add_metaclass
from six.moves import zip_longest
from abc import ABCMeta
import torch
import numpy
@add_metaclass(ABCMeta)
class SequentialAbsDataHolder(AbsDataHolder):
"""
This class is an extension of :class:`~cogitare.data.AbsDataHolder` to ... |
412173 | import unittest
import copy
import gc
from rpy2 import rinterface
rinterface.initr()
class SexpTestCase(unittest.TestCase):
def testNew_invalid(self):
x = "a"
self.assertRaises(ValueError, rinterface.Sexp, x)
def testNew(self):
sexp = rinterface.baseenv.get("letters")
sexp_n... |
412185 | import logging
import pprint
import copy
import types
import six
from mixbox.entities import EntityList
from cybox.core import Object
from cybox.common import ObjectProperties
from stix.core import STIXPackage
import certau.util.stix.helpers as stix_helpers
class StixTransform(object):
"""Base cl... |
412197 | from WorkSpace import *
import matplotlib.pyplot as plt
import statistics
import pickle
import pandas as pd
import numpy as np
class Results:
def __init__(self,lr_method,evaluation_config,meta_methods=None,
architecture='FCRN'):
self.architecture = architecture
self.lr_method = lr_... |
412217 | import pygame
from networktables import NetworkTables
import math
print("Starting fieldsim")
# Init pygame
pygame.init()
gameDisplay = pygame.display.set_mode((1228,635))
pygame.display.set_caption('5024 Fieldsim')
clock = pygame.time.Clock()
# Init NT
NetworkTables.initialize(server='localhost')
sd = NetworkTables.... |
412233 | import mxnet as mx
from symbol_basic import *
# - - - - - - - - - - - - - - - - - - - - - - -
# Standard Dual Path Unit
def DualPathFactory(data, num_1x1_a, num_3x3_b, num_1x1_c, name, inc, G, _type='normal'):
kw = 3
kh = 3
pw = (kw-1)/2
ph = (kh-1)/2
# type
if _type is 'proj':
key_str... |
412242 | class TextFeaturizer(object):
"""文本特征器,用于处理或从文本中提取特征。支持字符级的令牌化和转换为令牌索引列表
:param vocab_filepath: 令牌索引转换词汇表的文件路径
:type vocab_filepath: str
"""
def __init__(self, vocab_filepath):
self._vocab_dict, self._vocab_list = self._load_vocabulary_from_file(
vocab_filepath)
def featur... |
412468 | class Solution:
def newInteger(self, n):
base9 = ""
while n:
base9 += str(n % 9)
n //= 9
return int(base9[::-1]) |
412474 | import os
import torch
import numpy as np
from torch.distributions.normal import Normal
from torch.nn.functional import mse_loss
from copy import deepcopy
from rlil.environments import State, action_decorator, Action
from rlil.initializer import get_writer, get_device, get_replay_buffer
from rlil import nn
from .base i... |
412524 | import argparse
import subprocess
import glob
import re
import os
parser = argparse.ArgumentParser(description='Installing ThirdParty')
parser.add_argument('--all', help='install all dependencies', default=True)
parser.add_argument('--reinstall_all',
help='re-install all dependencies', default=Fal... |
412559 | import struct
import unittest
from collections import OrderedDict
from oppy.cell.fixedlen import (
FixedLenCell,
Create2Cell,
Created2Cell,
CreatedFastCell,
CreatedCell,
CreateFastCell,
CreateCell,
DestroyCell,
EncryptedCell,
NetInfoCell,
PaddingCell,
)
from oppy.cell.util ... |
412598 | from globals import *
import life as lfe
import alife
import logging
import os
def add_goal(life, goal_name, desire, require, tier, loop_until, set_flags):
if tier == 'relaxed':
_tier = TIER_RELAXED
elif tier == 'survival':
_tier = TIER_SURVIVAL
elif tier == 'urgent':
_tier = TIER_URGENT
elif tier == 'comb... |
412599 | from .extract_patches import extract_tensor_patches, ExtractTensorPatches
from .max_blur_pool import max_blur_pool2d, MaxBlurPool2d
__all__ = ["extract_tensor_patches", "max_blur_pool2d", "ExtractTensorPatches", "MaxBlurPool2d"]
|
412613 | from dataclasses import dataclass, replace
from hypothesis.strategies import builds, composite, integers, sampled_from
from raiden.messages.decode import lockedtransfersigned_from_message
from raiden.messages.encode import message_from_sendevent
from raiden.messages.transfers import LockedTransfer
from raiden.tests.u... |
412663 | import pytest
from cocopot.routing import Router
from cocopot.exceptions import BadRequest, NotFound, MethodNotAllowed
def test_basic_routing():
r = Router()
r.add('/', endpoint='index')
r.add('/foo', endpoint='foo')
r.add('/bar/', endpoint='bar')
assert r.match('/') == ('index', {})
assert r.... |
412665 | from ..adapters.mssql import MSSQL
from .base import SQLRepresenter, JSONRepresenter
from . import representers, before_type, for_type
@representers.register_for(MSSQL)
class MSSQLRepresenter(SQLRepresenter, JSONRepresenter):
def _make_geoextra(self, field_type, srid):
geotype, params = field_type[:-1].sp... |
412690 | import logging
import tqdm
import numpy as np
def evaluate(model, tasks, iterator, cuda_device, split="val"):
'''Evaluate on a dataset'''
model.eval()
all_preds = {}
n_overall_examples = 0
for task in tasks:
n_examples = 0
task_preds, task_idxs, task_labels = [], [], []
if ... |
412720 | import numpy as np
from analysis.analysis_utils import corr_frame_stim
from unittest import TestCase
class TestAnalysisUtils(TestCase):
def test_corr_frame_stim(self):
f = np.array([[0., 1], # Time, frame
[1., 2],
[2., 3],
[3., 5],
... |
412748 | def extractUntunedTranslation(item):
"""
"""
title = item['title'].replace(' III(', ' vol 3 (').replace(' III:', ' vol 3:').replace(' II:', ' vol 2:').replace(' I:', ' vol 1:').replace(' IV:', ' vol 4:').replace(
' V:', ' vol 5:')
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(title)
if not (chp ... |
412767 | from distutils.core import Extension
def get_extension():
return Extension(
'japronto.router.cmatcher',
sources=['cmatcher.c', 'match_dict.c', '../capsule.c'],
include_dirs=['.', '../request', '..', '../response'])
|
412796 | import torch
import nestedtensor
import utils
import torch.nn.functional as F
import sys
import random
import argparse
import itertools
import re
import csv
Benchmarks = {}
def register_benchmark(fn):
Benchmarks[fn.__name__] = fn
#
# relu
#
@register_benchmark
def relu__tensor_iter(self):
def _relu_tensor_i... |
412812 | from typing import Optional
import numpy as np
import torch
def torch_one_hot(target: torch.Tensor, num_classes: Optional[int] = None) -> torch.Tensor:
"""
Compute one hot encoding of input tensor
Args:
target: tensor to be converted
num_classes: number of classes. If :attr:`num_classes`... |
412845 | import unittest
import numpy as np
import pandas as pd
import networkx as nx
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import TreeSearch
from pgmpy.factors.discrete import TabularCPD
from pgmpy.sampling import BayesianModelSampling
class TestTreeSearch(unittest.TestCase):
def setUp(self):
... |
412878 | import base64
import json
from datetime import datetime
from bs4 import Tag
from pymonad.maybe import Maybe
from dataclasses import is_dataclass
from .log import get_logger
from .types import House
json_d = json.JSONEncoder.default
log = get_logger(__file__)
class AusBillsJsonEncoder(json.JSONEncoder):
def def... |
412884 | from utils.population import Population
from utils.customer import Customer
from utils.depot import Depot
from utils.chromosome import Chromosome
import math
import random
from copy import deepcopy
import numpy as np
from typing import List
def euclidean_distance(source: Customer, target) -> float:
"""
Comp... |
412904 | import requests
from . import FeedSource, _request_headers
class Coindesk(FeedSource):
def _fetch(self):
feed = {}
url = "https://api.coindesk.com/v1/bpi/currentprice/{base}.json"
for base in self.bases:
for quote in self.quotes:
if quote != 'BTC':
... |
412952 | import sys, time, librosa, os, argparse, pickle, numpy as np
sys.path.append('../')
sys.path.append('../utils/')
import dataset_utils, audio_utils, data_loaders
sys.path.append('./Evaluation')
from eval_utils import *
warnings.simplefilter("ignore")
from tqdm import tqdm
import pandas as pd
from tqdm import tqdm
from... |
412999 | from tastypie.api import Api
from django.conf.urls import patterns, include, url
from bikecompetition.bc import api, actions
bc_api = Api(api_name='bc')
bc_api.register(api.CompetitionResource())
bc_api.register(api.CompetitorResource())
urlpatterns = patterns('',
url(r'^api/', include(bc_api.u... |
413057 | def convert_sample_to_shot_coQA(sample, with_knowledge=None):
prefix = f"{sample['meta']}\n"
for turn in sample["dialogue"]:
prefix += f"Q: {turn[0]}" +"\n"
if turn[1] == "":
prefix += f"A:"
return prefix
else:
prefix += f"A: {turn[1]}" +"\n"
re... |
413067 | import unittest
from binstar_client.tests.fixture import CLITestCase
from binstar_client.tests.urlmock import urlpatch
from binstar_client.scripts.cli import main
from binstar_client import errors
class Test(CLITestCase):
@urlpatch
def test_show(self, urls):
urls.register(
method='GET',
... |
413087 | def ensureUtf(s, encoding='utf8'):
"""Converts input to unicode if necessary.
If `s` is bytes, it will be decoded using the `encoding` parameters.
This function is used for preprocessing /source/ and /filename/ arguments
to the builtin function `compile`.
"""
# In Python2, str == bytes.
# In... |
413105 | import time
from pyrunner import Worker
class SayHello(Worker):
def run(self):
self.logger.info('Hello World!')
return
class FailMe(Worker):
def run(self):
return 1 |
413144 | import gobject
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)
def update():
line.set_ydata(np.random.rand(10))
fig.canvas.draw_idle()
return True # return False to terminate the ... |
413165 | import argparse
from common import run, topics
from collections import defaultdict
import os
import csv
import pprint
from common import CommitDataCache
import re
"""
Example Usages
Create a new commitlist for consumption by categorize.py.
Said commitlist contains commits between v1.5.0 and f5bc91f851.
python c... |
413167 | import torch
import deepspeed
from deepspeed.runtime.utils import partition_uniform as partition
def split_tensor_along_last_dim(tensor, partitions, contiguous_split_chunks=False):
"""Split a tensor along its last dimension. Adapted from Megatron-LM.
Arguments:
tensor: input tensor.
partition... |
413192 | import sublime
import sublime_plugin
from .. import utils
class CfmlNavigateToMethodCommand(sublime_plugin.WindowCommand):
def run(self, file_path, href):
if len(file_path) > 0:
index_locations = self.window.lookup_symbol_in_index(href)
for full_path, project_path, rowcol in ind... |
413200 | class NullLogger:
level_name = None
def remove(self, handler_id=None): # pragma: no cover
pass
def add(self, sink, **kwargs): # pragma: no cover
pass
def disable(self, name): # pragma: no cover
pass
def enable(self, name): # pragma: no cover
pass
def crit... |
413205 | import csv, json
def jsonFromCsv(csvFilePath, jsonFilePath):
# JSON objects
jsonData = {}
trialNums = {}
aimingLandmarks = {}
onlineFB = {}
endpointFB = {}
rotation = {}
clampedFB = {}
tgtDistance = {}
anglesDict = {}
betweenBlocks = {}
targetJump = {}
file... |
413215 | from django.core.management.base import BaseCommand
from django.db.models import Q
from clubs.models import Club
class Command(BaseCommand):
help = (
"Set emails for all active clubs that do not have an email set. "
"Mark newly set emails as private. "
"Use the officer email if it exists.... |
413225 | import cv2
import numpy as np
from IPython.core.debugger import Tracer; keyboard = Tracer()
from scipy.interpolate import UnivariateSpline
def create_LUT_8UC1(x, y):
spl = UnivariateSpline(x, y,k=2)
return spl(xrange(256))
def _get_images_from_batches(batch):
batch_size = batch.shape[0]
img_width = b... |
413231 | import typer
from .. import settings
from typing import Optional
# Program
program = typer.Typer()
# Helpers
def version(value: bool):
if value:
typer.echo(settings.VERSION)
raise typer.Exit()
# Command
@program.callback()
def program_main(
version: Optional[bool] = typer.Option(None,... |
413232 | import os
import pytest
import numpy as np
import trackintel as ti
from trackintel.visualization.util import a4_figsize
class TestA4_figsize:
"""Tests for a4_figsize() method."""
def test_parameter(self, caplog):
"""Test different parameter configurations."""
fig_width, fig_height = a4_figsi... |
413265 | import image, network, rpc, sensor, struct
import time
import micropython
from pyb import Pin
from pyb import LED
# variables that can be changed
save_to_SD = False
# leds are used as an easy way to know if the remote camera has started fine
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)... |
413294 | import numpy as np
import pandas as pd
from ..preprocessing.norm import Normalizer
from ..modeling.model import GruMultiStep
class EthGasPriceOracle:
def __init__(self,
model: GruMultiStep,
training_normalized_dataframe: pd.DataFrame,
scaler: Normalizer,
... |
413341 | import tensorflow as tf
import numpy as np
import math
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
sys.path.append(os.path.join(BASE_DIR, '../../utils'))
sys.path.append(os.p... |
413345 | from alvi.client.containers import Array
from alvi.client.scenes.base import Scene
class ArrayCreateNode(Scene):
def run(self, **kwargs):
data_generator = kwargs['data_generator']
array = kwargs['container']
array.init(data_generator.quantity())
for i, value in enumerate(data_gener... |
413357 | def get_cityscapes_palette(num_cls=19):
""" Returns the color map for visualizing the segmentation mask.
Args:
num_cls: Number of classes
Returns:
The color map
"""
palette = [0] * (num_cls * 3)
palette[0:3] = (128, 64, 128) # 0: 'road'
palette[3:6] = (244, 35,232) ... |
413411 | import os
import sys
import os.path as path
from tinydb import TinyDB
sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..')))
from models import RoadMap
DB_PATH = path.join(path.dirname(__file__), "../../data/data.json")
if __name__ == "__main__":
db = TinyDB(DB_PATH)
entries = db.all()
... |
413462 | import sys
# attempt to import zabbix runtime if running embedded
try:
import zabbix_runtime
except ImportError:
zabbix_runtime = None
__version__ = "1.0.0"
__python_version_string = "Python %i.%i.%i-%s" % sys.version_info[:4]
__modules = []
__items = []
__routes ... |
413486 | import logging
import re
import sys
class Cap:
def __init__(self):
self.flags = {}
self.cmds = {}
self.control_data_start_state = ControlDataState()
def parse_cap(cap_str):
cap = Cap()
for field in cap_str.split(':'):
if len(field) == 0:
continue
if f... |
413491 | import collections
import numpy as np
from glob import glob
from collections import defaultdict
def _split_tags(tag):
res = []
# t1|t2|t3-t4|t5|t6
# to t1-t4, t1-t5, t1-t6, t2-t4, t2-t5, t2-t6, t3-t4, t3-t5, t3-t6
tags = tag.split('-')
assert(len(tags) <= 2), tag + ' has more than 2 parts'
if ... |
413512 | import os, sys, threading, time
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURRENT_DIR, "..", ".."))
import constants
import psutil
import atexit
class Monitor:
def __init__(self):
pass
def warn(self):
pass
def monitor(self):
pass
cl... |
413529 | import pandas as pd
import numpy as np
def Bootstrap(x1,x2,lag,bslength,verbose=True):
'''
Generate bootstrapped data
Input
-----
x1: array-like, serie-1,
x2: array-like, serie-2,
lag: integer, x2's lag,
bslength: integer, output length,
verbose: boolean,
... |
413599 | from .base import WordSubstitute
from ....data_manager import DataManager
from ....exceptions import WordNotInDictionaryException
from ....tags import TAG_English
import pickle
class HowNetSubstitute(WordSubstitute):
TAGS = { TAG_English }
def __init__(self, k = None):
"""
English Sememe-bas... |
413602 | import numpy as np
from .Transform import *
class TransformObject:
def __init__(self, local=None):
self.local = local if local is not None else Matrix4()
self.updated = True
self.left = WORLD_LEFT.copy()
self.up = WORLD_UP.copy()
self.front = WORLD_FRONT.copy()
... |
413643 | from winton_kafka_streams.state.factory.store_factory import StoreFactory
def create(name: str) -> StoreFactory:
# TODO replace this Java-esque factory with a Pythonic DSL as part of the other work on a Streams DSL
return StoreFactory(name)
|
413683 | from arg_parser import lago_args
lago_args()
from arg_parser import UserArgs
from attribute_expert.model import AttributeExpert
from dataset_handler.data_loader import DataLoader
from utils import ml_utils
def main():
print("###################################")
print("#####Main Of Attributes Expert#####")
... |
413693 | import os
import sys
sys.path.append(os.path.split(os.path.realpath(__file__))[0])
from lightnlp.sp import TDP
tdp_model = TDP()
train_path = '../data/tdp/train.sample.txt'
dev_path = '../data/tdp/dev.txt'
vec_path = 'D:/Data/NLP/embedding/english/glove.6B.100d.txt'
tdp_model.train(train_path, dev_path=dev_path, ve... |
413701 | set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
set3 = set1.union(set2)
print(set3)
# set3 = {70, 40, 10, 50, 20, 60, 30}
# set1 y set2 se mantienen igual |
413714 | import requests
import pandas as pd
from gamestonk_terminal import config_terminal as cfg
def get_ipo_calendar(from_date: str, to_date: str) -> pd.DataFrame:
"""Get IPO calendar
Parameters
----------
from_date : str
from date (%Y-%m-%d) to get IPO calendar
to_date : str
to date (%... |
413731 | import socket, random, time, sys
class DeadlyBooring():
def __init__(self, ip, port=80, socketsCount = 200):
self._ip = ip
self._port = port
self._headers = [
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.3072... |
413771 | import logging
from aiohttp.test_utils import AioHTTPTestCase
from saq.job import Status
from saq.worker import Worker
from saq.web import create_app
from tests.helpers import create_queue, cleanup_queue
logging.getLogger().setLevel(logging.CRITICAL)
async def echo(_ctx, *, a):
return a
functions = [echo]
... |
413804 | from hippy import rpath
from hippy.objects.resources.file_resource import W_FileResource
from hippy.objects.base import W_Root
from hippy.builtin import (
wrap, Optional, FileResourceArg, StreamContextArg)
from hippy.objects.resources.socket_resource import W_SocketResource
from hippy.module.url import urlsplit
d... |
413823 | import torch
from fast_transformers.builders import TransformerEncoderBuilder, RecurrentEncoderBuilder
from fast_transformers.masking import TriangularCausalMask
from fit.transformers.PositionalEncoding2D import PositionalEncoding2D
class SResTransformerTrain(torch.nn.Module):
def __init__(self,
... |
413831 | import argparse
import math
import threading
import time
import torch
import hivemind
from hivemind.proto import runtime_pb2
from hivemind.utils.limits import increase_file_limit
from hivemind.utils.logging import get_logger, use_hivemind_log_handler
from hivemind.utils.networking import LOCALHOST
use_hivemind_log_h... |
413855 | import torch
import numpy as np
import pickle
from configs.data_config import number_pnts_on_template
#initialize the weighs of the network for Convolutional layers and batchnorm layers
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.... |
413857 | import re
class MessageTranslator:
messages = {}
def __init__(self):
self.compiled_messages = {m: re.compile(m) for m in self.messages}
def translate_messages(self, messages):
return [self.translate_message(m) for m in messages]
def translate_message(self, message):
for tar... |
413863 | import unittest
from uuid import (
uuid4,
)
from minos.aggregate import (
Action,
Event,
FieldDiff,
FieldDiffContainer,
)
from minos.common import (
current_datetime,
)
from tests.utils import (
AggregateTestCase,
Car,
)
class TestRootEntityDifferences(AggregateTestCase):
async de... |
413920 | import os
import cv2
import imutils
import numpy as np
import matplotlib.pyplot as plt
import tesserocr as tr
from PIL import Image
class ImgProcess:
def __init__(self, filepath):
self.filepath = filepath
self.filename = os.path.basename(filepath)
self.filename_without_ext = os.path.splite... |
413965 | import os
try:
from munkicon import plist
from munkicon import worker
except ImportError:
from .munkicon import plist
from .munkicon import worker
# Keys: 'tcc_accessibility'
# 'tcc_address_book'
# 'tcc_apple_events'
# 'tcc_calendar'
# 'tcc_camera'
# 'tcc_file_provider_pr... |
413981 | from collections import namedtuple
import camus
from unittest import mock
from pytest import raises
IdRecord = namedtuple("IdRecord", "id")
def check_id(i, row):
assert row.id == i
class MockAurora:
def begin_transaction(self, secretArn, resourceArn, database):
return {"transactionId": "transact... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.