id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1776752 | from collections import namedtuple
RobotPacket = namedtuple('RobotPacket', 'robot_id command kick_type kick_force dribbler_state charge_kick')
RobotState = namedtuple('RobotState', 'timestamp is_team_yellow packet')
|
1776773 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
def Remove(char, args, evt_obj):
if evt_obj.is_modifier('Countersong'):
args.condition_remove()
return 0
# built-in hook only checks for Sonic descriptor
def Lang(char, args, evt_obj):
lang = 1 << (D20STD_F_SPELL_DESCRIPTOR_LANGUAGE_DEPEN... |
1776784 | from typing import Optional
from typing import Union
import numpy as np
from scipy.sparse.coo import coo_matrix
from ._typing_utils import Float
from ._typing_utils import Matrix
from ._utils import coo_matrix_builder
def build_frame_cost_matrix(
dist_matrix: coo_matrix_builder,
*,
track_start_cost: Opt... |
1776793 | import os
import io
import json
import hashlib
from PIL import Image
from http import HTTPStatus
from pathlib import Path
from starlette.responses import JSONResponse
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from fastai.vision import load_learner, ... |
1776802 | class Im(object):
'''
IMs represent direct message channels between two users on Slack.
'''
def __init__(self, server, user, im_id):
self.server = server
self.user = user
self.id = im_id
def __eq__(self, compare_str):
if self.id == compare_str or self.user == compare... |
1776827 | import os
from exporting.export_objects import get_objects, \
get_query_rulebase_data, format_and_merge_data, \
clean_objects, singular_to_plural_dictionary, format_and_merge_unexportable_objects, \
replace_rule_field_uids_by_name, cleanse_object_dictionary, export_general_objects
from utils import debug_l... |
1776830 | from __future__ import absolute_import, division, unicode_literals
import random as insecure_random
import yaml
from cStringIO import StringIO
from datetime import datetime
from mock import ANY, Mock, patch
from changes.config import db
from changes.constants import SelectiveTestingPolicy
from changes.models.build i... |
1776883 | class Solution:
def __init__(self): self.dic = collections.defaultdict(int)
def findPaths(self, m, n, N, i, j):
if N >= 0 and (i < 0 or j < 0 or i >= m or j >= n): return 1
elif N < 0: return 0
elif (i, j, N) not in self.dic:
for p in ((1, 0), (-1, 0), (0, 1), (0, -1)): self... |
1776962 | import numpy as np
def hydrogen_mass_repartitioning(molecule, H_mass):
H_mass_o = np.sum([atom.mass() for atom in molecule.atoms \
if atom.type.name=='hydrogen'])
H_mass_f = np.sum([1 for atom in molecule.atoms \
if atom.type.name=='hydrogen'])*H_mass
total_mass_o = np.sum([atom.mass() for atom in molec... |
1776987 | from copy import deepcopy
from functools import partial
from pathlib import Path
from unittest import TestCase
import panflute as pf
from panflute.tools import convert_text
from amsthm.helper import cancel_repeated_type, merge_consecutive_type, to_type
DIR = Path(__file__).parent
class TestEmph(TestCase):
Elem... |
1777010 | r"""
GLUE component modules for single-cell omics data
"""
import collections
from abc import abstractmethod
from typing import Optional, Tuple
import torch
import torch.distributions as D
import torch.nn.functional as F
from ..num import EPS
from . import glue, nn, prob
class GraphEncoder(glue.GraphEncoder):
... |
1777018 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
from model.zm_predict.usersim import UserSimulator
from model.zm_predict.memory import ReplayMemory
from tools.accuracy_init import init_accuracy_function
from model.loss import MultiLabelSo... |
1777030 | import torch.nn as nn
import torch.optim as optim
def get_optimizer(conf, optimizer_name, variables_or_model):
if isinstance(variables_or_model, nn.Module):
variables = variables_or_model.parameters()
if isinstance(variables, dict):
assert conf.has_attr('parameter_key'), \
('Parameter key un... |
1777036 | from decimal import Decimal
import json
import requests
from cypherpunkpay.prices.price_source import PriceSource
class CoingeckoCoinPriceSource(PriceSource):
def get(self, coin: str, fiat: str) -> [Decimal, None]:
if fiat != 'usd':
raise Exception(f'Unsupported fiat {fiat}')
try:
... |
1777049 | import json
import uuid
import pytest
import logging
import collections
import requests_mock
from ucloud.client import Client
from ucloud.core import exc
from ucloud.core.transport import RequestsTransport, http
from ucloud.testing.mock import MockedTransport
from tests.test_unit.test_core import consts
logger = lo... |
1777082 | import torch
from tqdm import tqdm
import time
class Trainer:
def __init__(
self,
model,
dataset,
loss_fn,
accuracy_fn=None,
steps_per_epoch=100,
test_steps_per_epoch=20,
learning_rate=1e-3,
batch_size=2,... |
1777085 | import pickle
import os
import pytest
import numpy as np
from infiniteremixer.search.nnsearch import NNSearch
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture
def nn_selector():
nns = NNSearch()
with open(os.path.join(CURRENT_DIR, "mapping.pkl"), "rb") as f:
mapping = pickl... |
1777127 | class Stack(object):
def __init__(self):
self.lst = []
def is_empty(self):
return self.lst == []
def get_size(self):
return len(self.lst)
def push(self, item):
self.lst.append(item)
def pop(self):
if self.is_empty():
return 'stack underflow'
... |
1777128 | from setuptools import setup, find_packages
INSTALL_REQUIRES = ["numpy", "scipy", "scikit-learn", "pandas", "xarray"]
with open("README.rst") as f:
readme = f.read()
setup(
name="sklearn-xarray",
version="0.4.0",
description="xarray integration with sklearn",
long_description=readme,
author="... |
1777150 | import grpc
from sea.servicer import ServicerMeta
from sea.format import msg2dict, stream2dict
from sea import exceptions
from sea.pb2 import default_pb2
from tests.wd.protos import helloworld_pb2
def test_meta_servicer(app, logstream):
class HelloContext():
def __init__(self):
self.code = ... |
1777180 | import persistent
import BTrees.IOBTree
from dateutil import parser
import datetime
from stf.common.out import *
# Create one of these classes for each new model constructor you want to implement
class Model_Constructor(object):
"""
The First Model constructor. Each of this objects is unique. We are going to... |
1777188 | import pickle
misc = {}
misc["bowl_000"] = "cereal_bowl.n.01"
misc["spatula_001"] = "pancake_turner.n.01"
misc["spatula_002"] = "pancake_turner.n.01"
misc["bowl_003"] = "cereal_bowl.n.01"
misc["spatula_004"] = "pancake_turner.n.01"
misc["spatula_005"] = "pancake_turner.n.01"
misc["bottle_006"] = "bottle.n.01"
misc["bo... |
1777223 | from configparser import ConfigParser
from argparse import ArgumentParser
import torch
import gym
import numpy as np
import os
from agents.ppo import PPO
from agents.sac import SAC
from agents.ddpg import DDPG
from utils.utils import make_transition, Dict, RunningMeanStd
os.makedirs('./model_weights', exist_ok=True)... |
1777242 | import random
from paragen.dataloaders import AbstractDataLoader, register_dataloader
from paragen.datasets.abstract_dataset import AbstractDataset
from paragen.utils.ops import search_key
from paragen.utils.runtime import Environment
@register_dataloader
class StreamingDataLoader(AbstractDataLoader):
"""
St... |
1777307 | from example.settings import *
STORY_SETTINGS.update({
'WIDGET': 'example.simpleapp.widgets.CustomTextarea',
'WIDGET_ATTRS': {'cols': '50'}
})
|
1777311 | import os
import subprocess
import tempfile
from pathlib import Path
from mdecbase import Service
class HexraysService(Service):
"""
Hex-Rays decompiler as a service
"""
def decompile(self, path: str) -> str:
"""
Decompile all the functions in the binary located at `path`.
""... |
1777334 | import logging
import os
import click
from graviteeio_cli.exeptions import GraviteeioError
from graviteeio_cli.commands.auth.logout import logout
from graviteeio_cli.core.config import Auth_Type, GraviteeioConfig_apim
logger = logging.getLogger("command-auth-token")
def get_token(ctx, param, value):
if not val... |
1777345 | import inspect
import json
import time
from pathlib import Path
import pytest
import redis
from confluent_kafka import admin
from factory import Factory
from pytest_factoryboy import register
from django.conf import settings
from common.adapters.fhir_api import fhir_api
from tests.conftest import load_export_data, l... |
1777382 | import json
import pandas as pd
import numpy as np
import cloudpickle
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.multioutput imp... |
1777384 | from typing import Any, Callable, List, Optional
from typing_extensions import Protocol
from procrastinate import jobs, retry
class TaskCreator(Protocol):
def task(
self,
_func: Optional[Callable] = None,
*,
name: Optional[str] = None,
aliases: Optional[List[str]] = None,... |
1777426 | import abc
class Broker(metaclass=abc.ABCMeta):
def __init__(self, key_id, secret_key, endpoint):
self.key_id = key_id
self.secret_key = secret_key
self.endpoint = endpoint
@abc.abstractmethod
def get_account(self):
pass
@abc.abstractmethod
def list_positions(self... |
1777442 | import matplotlib.pyplot as plt
import numpy as np
from units import conv_unit
class VLEBinaryMixturePlot:
def __init__(self, diagtype, var, x, y, varunit, title, plottype="both"):
self.diagtype = diagtype
self.var = var
self.x = x
self.y = y
self.varunit = varunit
... |
1777479 | from responsebot.handlers import BaseTweetHandler, register_handler
@register_handler
class AnotherHandlerClass(BaseTweetHandler):
def on_tweet(self, tweet):
print('AnotherHandlerClass')
|
1777480 | import argparse as argparse
import logging
from tempfile import TemporaryDirectory
from threading import Thread
import msgpack
import zmq
from dpu_utils.utils import RichPath, run_and_debug
from buglab.utils.logging import MetricProvider, configure_logging
from buglab.utils.msgpackutils import load_all_msgpack_l_gz
f... |
1777500 | import torch
from torch import nn
import torch.nn.functional as F
import torchvision
from torch.utils.data import DataLoader
import utils
class VAE(nn.Module):
"""Implementation of VAE(Variational Auto-Encoder)"""
def __init__(self):
super(VAE, self).__init__()
self.fc1 = nn.Linear(784, 200)
... |
1777507 | import math
import random
import torch.nn as nn
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.models.fsmt.modeling_fsmt import (
SinusoidalPositionalEmbedding,
EncoderLayer,
DecoderLayer,
FSMTModel as _FSMTModel,
FSMTForConditionalGeneration as _FSMTForConditio... |
1777510 | from os import path
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from ..errors import (
AttachmentTooLargeError,
AuthenticationError,
)
from... |
1777513 | from django.db import models
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, PageChooserPanel
from base.forms import FormContainerForm
from pages.base_page.models import JanisBasePage
from base.models.widge... |
1777541 | from apps.routes.csv import router as csv_router
from apps.routes.excel import router as excel_router
|
1777559 | import offsetbasedgraph as obg
from collections import defaultdict
from graph_peak_caller.postprocess.reference_based_max_path\
import max_path_func
from offsetbasedgraph.vcfmap import VariantMap, DELMap
from graph_peak_caller.sparsediffs import SparseValues
from graph_peak_caller.peakcollection import Peak
from gr... |
1777585 | from __future__ import print_function
import argparse
import sys
import textwrap
import redlock
def log(*args, **kwargs):
if not log.quiet:
print(*args, file=sys.stderr, **kwargs)
def lock(name, validity, redis, retry_count=3, retry_delay=200, **kwargs):
if retry_count < 0:
retry_count = 0... |
1777592 | from boa.builtins import concat
def Main():
str1 = 'hello'
str2 = 'world'
str3 = concat(str1, str2)
# this ends up being 'worldhello'
# need to reverse the parameters...
return str3
|
1777607 | from dcos_installer import config
from gen.exceptions import ValidationError
def test_normalize_config_validation_exception():
errors = {
'key': {'message': 'test'},
}
validation_error = ValidationError(errors=errors, unset=set(['one', 'two']))
normalized = config.normalize_config_validation_e... |
1777655 | import jinja2
import pytest
class TestJinjaFilters:
config = """
tasks:
stripyear:
mock:
- {"title":"The Matrix (1999)", "url":"mock://local1" }
- {"title":"The Matrix", "url":"mock://local2" }
- {"title":"The Matrix 1999", "url":"mock://loca... |
1777665 | import os, sys, shutil
import tempfile
import unittest
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.file... |
1777685 | from ghc.utils.hom import nx2homg, tree_list, cycle_list,\
path_list, hom_profile
import homlib as hl
import networkx as nx
import numpy as np
def hom_tree(F, G):
"""Specialized tree homomorphism in Python (serializable).
Add `indexed` parameter to count for each index individually.
... |
1777722 | from setuptools import setup
setup(
name = 'presidency',
packages = ['presidency'],
version = '0.14',
description = 'A Python wrapper for data on the American Presidency Project (www.presidency.ucsb.edu)',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/jayrav13/presi... |
1777728 | def count_letters(stri, char):
count = 0
for l in stri:
if l == char:
count += 1
print(count)
count_letters("aabaab", "a")
|
1777794 | import click
from catacomb.common import constants
from catacomb.utils import catacomb_handler, formatter, tomb_handler
@click.command(
constants.CMD_STATUS_NAME, help=constants.CMD_STATUS_DESC,
short_help=constants.CMD_STATUS_DESC)
@click.pass_context
def status(ctx):
"""Displays the status of the curre... |
1777831 | from django.contrib.auth.models import AbstractUser
from django.db.models import CharField, BooleanField
from django.urls import reverse
from django.utils.translation import gettext as _
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = CharField(_... |
1777860 | import PIL
import random
import unittest
import numpy as np
import chainer
from chainer import testing
from chainercv.transforms import flip
from chainercv.transforms import rotate
try:
import cv2 # NOQA
_cv2_available = True
except ImportError:
_cv2_available = False
@testing.parameterize(*testing.pr... |
1777863 | from tensorflow.keras import regularizers
from tensorflow.keras.models import Sequential
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, LSTM, RNN, Bidirectional, Flatten, Activation, \
RepeatVector, Permute, Multiply, Lambda, Concatenate, Batc... |
1777871 | import pickle
import os.path as path
import re
import os
from PIL import Image
def commit(obj, file_name): # Escribe los archivos
if path.exists("./data/"):
file = open(f"./data/{file_name}.bin", "wb+")
file.write(pickle.dumps(obj))
file.close()
else:
os.makedirs('./data/')
... |
1777872 | from colors import colored_print_generator as cpg, prettify as pfy
from colors import *
import requests as r
import time
import os
def get_environ(k):
k = k.upper()
if k in os.environ:
return os.environ[k]
else:
return None
# rs = r.Session()
basic_auth = r.auth.HTTPBasicAuth('root','')
... |
1777887 | import argparse
import functools
import json
import multiprocessing
from typing import Optional, Union
import musdb
import museval
import torch
import tqdm
import random
from xumx_slicq import utils
def separate_and_evaluate(
track: musdb.MultiTrack,
model_str_or_path: str,
niter: int,
output_dir: s... |
1777900 | import unittest
from katas.kyu_7.spoonerize_me import spoonerize
class SpoonerizeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(spoonerize('nit picking'), 'pit nicking')
def test_equals_2(self):
self.assertEqual(spoonerize('wedding bells'), 'bedding wells')
def tes... |
1777905 | import re
import json
import logging
from abc import ABC, abstractmethod
from enum import auto, Enum
from wallabag.config import Options, Sections
import requests
from packaging import version
MINIMUM_API_VERSION = "2.1.1"
class ApiException(Exception):
error_text = None
error_description = None
def... |
1777958 | from services.utils import DBConfiguration
import pytest
def get_test_dbconf():
"""
Returns a DBConfiguration suitable for the test environment, or exits pytest completely upon failure
"""
db_conf = DBConfiguration(timeout=1)
if db_conf.dsn != "dbname=test user=test host=db_test port=5432 passwor... |
1777990 | import uuid
from mixer.backend.django import mixer
mixer.register('users.User', username=lambda: str(uuid.uuid4()))
__all__ = [
'mixer',
]
|
1778007 | import unittest
import os
import lob
class TestUSReverseGeocodeLookupFunctions(unittest.TestCase):
def setUp(self):
lob.api_key = os.environ.get('LOB_API_KEY')
def test_us_zip_lookup(self):
reverse_geocode_lookup = lob.USReverseGeocodeLookup.create(
latitude=37.777456,
... |
1778011 | import numpy as np
from scipy.stats import cauchy
import matplotlib.pyplot as plt
n = 1000
distribution = cauchy()
fig, ax = plt.subplots()
data = distribution.rvs(n)
if 0:
ax.plot(list(range(n)), data, 'bo', alpha=0.5)
ax.vlines(list(range(n)), 0, data, lw=0.2)
ax.set_title("{} observations from the Cau... |
1778063 | from clusterer import BaseServer
c = BaseServer(port=50000,authkey=b'password')
c.configure(['gen2sq_q','sq2sub_q','sub2pr_q'])
c.runserver()
|
1778095 | from os.path import dirname, abspath
import sys
# Get path of parent folder
parentpath = dirname(dirname(abspath(__file__)))
# print(parentpath)
# Add to directory defined by sys
sys.path.append(parentpath)
scriptpath = parentpath + "\\min_interval_fourstocks"
# print(scriptpath)
# Add main script to directory
sys.... |
1778104 | import numpy as np
from nengo.builder.builder import Builder
from nengo.builder.operator import Operator
from nengo.builder.signal import Signal
from nengo.exceptions import BuildError
from nengo.neurons import NeuronType, RatesToSpikesNeuronType
from nengo.utils.numpy import is_array_like
class SimNeurons(Operator)... |
1778131 | import torch
from nnc.controllers.base import ControlledDynamics
from nnc.helpers.torch_utils.numerics import sin_difference, sin_difference_mem
class AdditiveControlKuramotoDynamics(ControlledDynamics):
def __init__(self,
interaction_matrix,
coupling_constant,
n... |
1778141 | from pbu import AbstractMongoStore
class Project:
"""
Object class representing a document in this database collection.
"""
def __init__(self):
self.name = None
self.id = None
self.image_count = 0
self.annotation_count = 0
self.annotation_types = {}
def to... |
1778196 | from roleml.roleml import _fix_frame_keys
def key_equals_participant_id(frame):
return all(k == str(v["participantId"]) for k, v in frame["participantFrames"].items())
def test_fix_frame_unordered(clean_game_na):
for frame in clean_game_na["game"]["timeline"]["frames"]:
assert not key_equals_partici... |
1778215 | import numpy as np
from scipy.fftpack import fft, ifft, fftshift
__all__ = ['cwt', 'ccwt', 'icwt', 'SDG', 'Morlet']
class MotherWavelet(object):
"""Class for MotherWavelets.
Contains methods related to mother wavelets. Also used to ensure that new
mother wavelet objects contain the minimum requirements ... |
1778228 | from datetime import date, datetime
from unittest import TestCase
from django.template import engines
from pytz import timezone
class DatetimesExtensionTests(TestCase):
def setUp(self):
self.engine = engines["wagtail-env"]
def test_date_filter(self):
tmpl = self.engine.from_string("{{ d | d... |
1778332 | from setuptools import setup, find_packages
def get_long_description():
with open("README.md", "r", encoding="utf-8") as f:
desc = f.read()
return desc
setup(
name="jupyterlab-autoplot",
version="0.2.0",
author="<NAME>",
author_email="<EMAIL>",
license="BSD 3-Clause",
descrip... |
1778336 | from setuptools import find_packages, setup
setup(
name='vevestaX',
packages=find_packages(include=['vevestaX']),
version='5.1.0',
description='Stupidly simple library to track machine learning experiments as well as features',
author='<NAME>',
license='Apache 2.0',
install_requires=['pand... |
1778407 | import cv2
import random
import glob
filepath = '/home/stijn/Desktop/uploads/000.mp4'
def select_frames(videopath, target_num_frames=50):
# fourcc = cv2.VideoWriter_fourcc(*'MP4V')
# fourcc = cv2.VideoWriter_fourcc(*'MPEG')
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# fourcc = cv2.VideoWriter_fourcc(*'X... |
1778411 | import os
from functools import partial
from threading import RLock
from types import FunctionType
from typing import Any, Optional, Type
from haps.exceptions import ConfigurationError, UnknownConfigVariable
_NONE = object()
def _env_resolver(var_name: str, env_name: str = None,
default: Any = _NO... |
1778415 | from nitorch import spatial, io
from nitorch.core import py, utils
import os
def pool(inp, window=3, stride=None, method='mean', dim=3, output=None,
device=None):
"""Pool a ND volume, while preserving the orientation matrices.
Parameters
----------
inp : str or (tensor, tensor)
Eithe... |
1778418 | from .utils import *
import math
import os
from .label_config import max_param, max_step
from misc import get_distance_to_center
###################################
# generate tables with "thick" supports
# tabletop can be: circle, square, rectangle
# supports can be: circle, square
# max steps: 2
####################... |
1778432 | from arekit.common.frames.connotations.descriptor import FrameConnotationDescriptor
from arekit.common.frames.connotations.provider import FrameConnotationProvider
from arekit.common.frames.text_variant import TextFrameVariant
from arekit.common.labels.scaler import BaseLabelScaler
from arekit.contrib.networks.features... |
1778437 | from abc import ABC
from tempfile import NamedTemporaryFile
from tempfile import TemporaryDirectory
from typing import Union
from fabric import Connection
from crud.crud_config import crud_ssh_config
from crud.crud_module import crud_redirector
from crud.crud_module import crud_team_server
from db.session import sess... |
1778467 | from collections import deque
from plistlib import *
from operator import itemgetter
import time, datetime, copy
class device:
TIMEOUT = 20 # Number of seconds before command times out
WHITELIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "
def __init__(self, newUDID, tuple):
... |
1778472 | import os
import sys
import imp
import numpy as np
import warnings
warnings.filterwarnings("ignore")
# Test for Torch
def torch(test_models, model_path, img_path):
results_o, results_d, op_sets = dict(), dict(), dict()
from PIL import Image
import torch
import torchvision.models as models
from tor... |
1778474 | from enum import IntFlag
class UserFlags(IntFlag):
none = 0
discord_staff = 1 << 0
partnered_server_owner = 1 << 1
hyper_squad_events = 1 << 2
bug_hunter_level_1 = 1 << 3
house_bravery = 1 << 6
house_brilliance = 1 << 7
house_balance = 1 << 8
early_supporter = 1 << 9
team_user ... |
1778496 | class BaseItem:
def __init_(self, name, item_id, page_url):
self.name = name
self.id = item_id
self.page_url = page_url
class ItemDrop:
def __init__(self, enabled, level, max_level, leagues, areas, text):
self.enabled = enabled
self.level = level
self.max_level ... |
1778516 | import connexion
import six
from openapi_server.com.h21lab.TS29573_N32_Handshake.handler.problem_details import ProblemDetails # noqa: E501
from openapi_server.com.h21lab.TS29573_N32_Handshake.handler.sec_negotiate_req_data import SecNegotiateReqData # noqa: E501
from openapi_server.com.h21lab.TS29573_N32_Handshake.... |
1778541 | from typing import List
import pandas as pd
from numpy import tril
from toolz import curry
from fklearn.types import LogType
@curry
def correlation_feature_selection(train_set: pd.DataFrame,
features: List[str],
threshold: float = 1.0) -> LogType:
... |
1778592 | import argparse
import re
from googletrans import Translator
def rgt(text, langs, times):
translator = Translator()
translation = text
for i in range(times):
for lang in langs:
translation = translator.translate(translation, dest=lang).text
translation = translator.translate(translation, dest='en').text
... |
1778597 | import os
import requests
from io import open
try:
to_unicode = unicode
except NameError:
to_unicode = str
class S3RemoteFileDriver(object):
def __init__(self):
self.type = "remote-datmo"
@staticmethod
def upload(src_filepath, s3_presigned_url):
if not os.path.isfile(src_filepath)... |
1778616 | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1,s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
res = ListNode(0)
sums =0
while s... |
1778665 | from __future__ import print_function
from mnist_sequence_api import MNIST_Sequence_API
api_object = MNIST_Sequence_API()
api_object.save_image(api_object.generate_mnist_sequence(range(8), (0, 10), 224), range(8))
api_object.save_image(api_object.generate_mnist_sequence(range(9), (0, 10), 292), range(9))
api_object.... |
1778693 | import os
import cv2
import argparse
import numpy as np
from glob import glob
import tensorflow as tf
from model import BilinearUpsampling
from tensorflow.keras.models import load_model
tf.keras.backend.set_image_data_format('channels_last')
def args():
parser = argparse.ArgumentParser()
parser.add_argument("... |
1778706 | from functools import wraps
import re
from . import is_mac
def _tag(tag_info='p style="font-size:10px"'):
def wrapper(func):
@wraps(func)
def inner(text):
tag = tag_info.split(' ')[0]
text = f'<{tag_info}>{text}</{tag}>'
return text
return inner
retu... |
1778728 | import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
try:
from utils.priority_queue import PriorityQueue
except:
raise
from math import sqrt, inf
from itertools import product
import matplotlib.pyplot as plt
import heapq
import numpy as np
import random
from pathfinding.heu... |
1778816 | import os
import sys
import time
import traceback
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from ctools.utils import read_file, save_file
from .base_comm_actor import BaseCommActor
class FlaskFileSystemActor(BaseCommActor):
def __init__(self, cfg: dict) -> N... |
1778819 | import angr
######################################
# close
######################################
class close(angr.SimProcedure):
def run(self, fd): # pylint:disable=arguments-differ
if self.state.posix.close(fd):
return 0
else:
return -1
|
1778842 | import pylewm.commands
import pylewm.window
import pylewm.monitors
import pythoncom
import win32gui, win32com.client
import win32api
import traceback
import ctypes
from pylewm.commands import PyleCommand
FocusQueue = pylewm.commands.CommandQueue()
FocusSpace = None
FocusWindow = None
LastFocusWindow = None
WindowFoc... |
1778847 | import subprocess
import time
def get_proxy_ip():
bash_command = "bash ../cluster/get-node-ip.sh proxy"
process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
ip = output.decode('ascii').replace('\n', '')
return ip
def get_topic_owner(topic):... |
1778921 | from enum import Enum
import tkinter as tk
from ..translator import Translator
from ..resources import get_resource_path
from ..updater.SimpleSemVer import SimpleSemVer
class UpdateType(Enum):
App = 0
Skills = 1
AppLanguage = 2
SkillCorrections = 3
class AskUpdate(tk.Toplevel):
def __init__(
... |
1778935 | import FWCore.ParameterSet.Config as cms
process = cms.Process("tester")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cout.enable = cms.untracked.bool(True)
process.MessageLogger.cout.threshold = cms.untracked.string('DEBUG')
process.MessageLogger.debugModules = cms.untracked.vstring('*... |
1778937 | import sublime
class CdnjsLoadingAnimation(object):
"""The dot dot dot animation in the status bar."""
def __init__(self, watch_thread):
"""Initialise."""
self.watch_thread = watch_thread
sublime.set_timeout(lambda: self.run(0), 150)
def run(self, i):
"""Run the animation... |
1778961 | import base64
import copy
import json
import random
import time
from textwrap import dedent
import netaddr
import requests
from jumpscale.clients.explorer.models import DeployedReservation, NextAction
from jumpscale.clients.stellar import TRANSACTION_FEES
from jumpscale.clients.stellar.stellar import Network as Stella... |
1778968 | def get_award_title(award_node):
return award_node.select_one('h3').text[:-4].strip()
def get_award_year(award_node):
return int(award_node.select_one('h3').text[-4:]) |
1779000 | from abc import ABC, abstractmethod
class Shape(ABC):
"""Interface that defines the shape."""
@abstractmethod
def draw(self) -> str:
pass
class ShapeError(Exception):
"""Represent shape error message."""
pass
class Circle(Shape):
"""Concrete shape subclass."""
def draw(self)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.