id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9913223 | from dataclasses import dataclass, field
from typing import Optional
from transformers.training_args import TrainingArguments as _TrainingArguments
from transformers.utils import logging
from trapper.common import Registrable
from trapper.common.utils import append_parent_docstr
logger = logging.get_logger(__name__)... |
9913241 | import torch
import numpy as np
def embed_data_mask(x_categ, x_cont, cat_mask, con_mask,model,vision_dset=False):
device = x_cont.device
x_categ = x_categ + model.categories_offset.type_as(x_categ)
x_categ_enc = model.embeds(x_categ)
n1,n2 = x_cont.shape
_, n3 = x_categ.shape
if model.cont_emb... |
9913242 | import mxnet as mx
import os
import pytest
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from rl_coach.base_parameters import MiddlewareScheme
from rl_coach.architectures.middleware_parameters import LSTMMiddlewareParameters
from rl_coach.architectures.mxnet_components.middle... |
9913251 | import mock
import sys
REG_INPUT = 0x00
REG_OUTPUT = 0x01
REG_POLARITY = 0x02
REG_CONFIG = 0x03
regs = [0 for x in range(4)]
class SMBus:
def __init__(self, bus_id):
global regs
regs[REG_INPUT] = 0 # 0x00: REG_INPUT
regs[REG_OUTPUT] = 0 # 0x01: REG_OUTPUT
regs[REG_POLARITY] = 0 #... |
9913259 | from __future__ import print_function
import os
import torch
import torch.nn.functional as F
import numpy as np
import math
#for single depth [stable version]
def depthToNormal(depthmap,
device,
K,
thres,
img_size
):
# defau... |
9913313 | import os
import argparse
import numpy as np
import argoverse
from argoverse.data_loading.argoverse_tracking_loader import ArgoverseTrackingLoader
from argoverse.utils.calibration import Calibration
from argoverse.visualization.mayavi_utils import draw_lidar, mayavi_compare_point_clouds
from argoverse.utils.ply_loader... |
9913314 | import subprocess
from pathlib import Path
import ffmpeg
from logging import getLogger
logger = getLogger(__name__)
class MovieConverter(object):
# /path/to/project_root/bin/ffmpeg/bin/ffmpeg.exe
FFMPEG_PATH = Path(__file__+'/../../bin/ffmpeg/bin/ffmpeg.exe').resolve().as_posix()
@staticmethod
def pr... |
9913360 | class PinterestException(Exception):
""""""
class PinterestHttpException(PinterestException):
def __init__(self, code, url, message: str = None):
super().__init__()
self.code = code
self.url = url
self.message = message or ' '
def __str__(self):
return "PinterestH... |
9913364 | import base64
import binascii
import functools
import re
import sys
import textwrap
from ...vendor import click
COMMAND_NAME = 'base64'
# Because every 3 bytes map to 4 base64 bytes, the buffer should be
# a multiple of 3. Conveniently, this is also a multiple of 4 for decoding
BUFSIZE = 3 * 1024
@click.command(... |
9913383 | import numpy as np
from scipy.integrate import quad
from scipy.special import legendre as P
def b(r, K=1000, s=0.0033 * 180 / np.pi, **kwargs):
"""
The sigmoid spot profile.
"""
theta = np.linspace(0, np.pi, K)
return 1 / (1 + np.exp((r - theta) / s)) - 1
def get_Bp(K=1000, lmax=5, eps=1e-9, si... |
9913466 | import random
for _ in range(0, 100):
date = '2012-01-{:0>2} {:0>2}:00:00{:0=+3}:00'.format(random.randint(
1, 31), random.randint(0, 23), random.randint(-11, 12))
with open(date.replace(' ', '-').replace(':', '') + '.md', 'w') as file:
print("""\
Title: {date}
Date: {date}
This is a test for ... |
9913515 | import os
import time
from tapsdk import TapSDK, TapInputMode
from tapsdk.models import AirGestures
import asyncio
import logging
from bleak import _logger as logger
def notification_handler(sender, data):
"""Simple notification handler which prints the data received."""
print("{0}: {1}".format(sender, data... |
9913518 | try:
import cechomesh
cechomesh.LOADED = True
except ImportError:
class _NoEntry(object):
LOADED = False
def __getattr__(self, name):
raise AttributeError(
'Not able to import cechomesh dynamic library.')
cechomesh = _NoEntry()
|
9913556 | from rlberry.network.client import BerryClient
from rlberry.network import interface
from rlberry.network.interface import Message, ResourceRequest
port = int(input("Select server port: "))
client = BerryClient(port=port)
# Send params for AgentManager
client.send(
Message.create(
command=interface.Comman... |
9913570 | import logging
import os
import subprocess
import sys
import virtualenv
from .activate_this import write_activate_this
LOGGER = logging.getLogger(__name__)
PREFIX = getattr(sys, "prefix", None)
REAL_PREFIX = getattr(sys, "real_prefix", None)
def install_virtualenv(install_dir):
if is_virtualenv(install_dir):
... |
9913578 | import asyncio
import collections
import io
import struct
from ..tl import TLRequest
from ..tl.core.messagecontainer import MessageContainer
from ..tl.core.tlmessage import TLMessage
class MessagePacker:
"""
This class packs `RequestState` as outgoing `TLMessages`.
The purpose of this class is to suppor... |
9913630 | from django.contrib.contenttypes.models import ContentType
from django.db import models
from comment.conf import settings
from comment.utils import id_generator
class CommentManager(models.Manager):
def all_exclude_flagged(self):
"""Filter out comments that have been flagged"""
allowed_flags = g... |
9913639 | from hachoir.stream import InputSubStream
from hachoir.core.tools import humanFilesize, humanDuration
from hachoir.core.memory import limitedMemory
from hachoir.subfile.data_rate import DataRate
from hachoir.subfile.output import Output
from hachoir.subfile.pattern import HachoirPatternMatching as PatternMatching
from ... |
9913657 | import rx
import rx.operators as ops
from rx.scheduler import ThreadPoolScheduler
import threading
import time
threadpool_scheduler = ThreadPoolScheduler()
numbers = rx.from_([1, 2, 3, 4], scheduler=threadpool_scheduler)
subscription = numbers.pipe(
ops.map(lambda i: i*2),
ops.map(lambda i: "number is: {}".for... |
9913660 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import torch
from torch import nn
from torchocr.networks.CommonModules import ConvBNACT, SEBlock
class ResidualUnit(nn.Module):
def __init__(self, num_in_filter, num_mid_filter, nu... |
9913663 | from json import loads
from requests import get, exceptions
try:
response = get(url='https://api.github.com/repos/DCSFlightpanels/dcs-bios/releases/latest', timeout=1)
if response.status_code == 200:
dcsbios_ver = response.json()['tag_name']
except exceptions.ConnectTimeout:
dcsbios_ver = '0.7.42'... |
9913671 | from __future__ import unicode_literals
from django.apps import AppConfig
class LoginConfig(AppConfig):
name = 'login'
|
9913674 | from typing import Tuple
import numpy as np
import gdsfactory as gf
from gdsfactory import LAYER, Port
from gdsfactory.component import Component
@gf.cell
def big_device(
size: Tuple[float, float] = (400.0, 400.0),
nports: int = 16,
spacing: float = 15.0,
layer: Tuple[int, int] = LAYER.WG,
wg_wi... |
9913683 | from scenarios import *
scenario = (
send_stanza("<iq type='set' id='hello-command1' from='{jid_one}/{resource_one}' to='{biboumi_host}'><command xmlns='http://jabber.org/protocol/commands' node='hello' action='execute' /></iq>"),
expect_stanza("/iq[@type='result']/commands:command[@node='hello'][@sessionid][@... |
9913684 | from .threshold_reducer import ThresholdReducer
class AvgNonZeroReducer(ThresholdReducer):
def __init__(self, **kwargs):
super().__init__(low=0, **kwargs)
|
9913718 | from copy import deepcopy
from typing import List, Dict
from overrides import overrides
import numpy
from allennlp.common.util import JsonDict
from allennlp.data import Instance
from allennlp.predictors.predictor import Predictor
from allennlp.data.fields import LabelField
@Predictor.register('xstance_predictor')
c... |
9913733 | from typing import List, Set
from pydantic import BaseModel
from figcli.ui.models.config_tree_data import ConfigTreeData
class ConfigOrchard(BaseModel):
trees: List[ConfigTreeData] = []
def add_tree(self, tree: ConfigTreeData):
self.trees.append(tree)
@staticmethod
def build_orchard(config... |
9913738 | import argparse
import pathlib
import pickle
import yaml
import numpy as np
import pycocotools.mask as mask_util
from PIL import Image
from scipy.optimize import linear_sum_assignment
import utils.vis as vis
def get_unique_objects(groundtruth):
"""Get unique object ids from segmentation mask
Adapted from D... |
9913830 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class BiLSTM(nn.Module):
def __init__(self, in_channel=1, out_channel=10):
super(BiLSTM, self).__init__()
self.hidden_dim = 64
self.kernel_num = 16
self.num_layers = 2
... |
9913875 | import json
class TestStackiAttribute:
def test_add_global_attribute(self, host, run_ansible_module):
# Add the attribute
result = run_ansible_module("stacki_attribute", attr="test", value="foo")
assert result.status == "CHANGED"
assert result.data["changed"] == True
# Check that it is there now
result ... |
9913897 | from webex_skills.api import SimpleAPI
from webex_skills.dialogue import responses
from webex_skills.models.mindmeld import DialogueState
api = SimpleAPI()
@api.handle(default=True)
async def greet(current_state: DialogueState) -> DialogueState:
text = 'Hello I am a super simple skill'
new_state = current_st... |
9913906 | from make_tree_from_parent_vec import make_tree_from_parent_vec
from collections import OrderedDict
from auxilliary import Aux
import numpy as np
import cell
from file_io import *
from get_parent_from_neuron import get_parent_from_neuron
import scipy.io as sio
from io import StringIO
import csv
import math
# input_dic... |
9913928 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from Revi... |
9913958 | import json
import requests
from .helpers import Nested, add_json_headers
from .admin import Admin
from .projects import Projects
from .ssh import Keys
from .compat import basestring
from .allrepos import Repos
from .builds import Build
class Stash(object):
_url = "/"
def __init__(self, base_url, username=No... |
9913970 | import os
from typing import Any, List
import attr
from hydra.utils import instantiate
from omegaconf import OmegaConf
from ray import tune
from ray.tune.integration.mlflow import MLflowLoggerCallback
from ray.tune.trial import Trial
class CustomMLflowLoggerCallback(MLflowLoggerCallback):
def __init__(self, *arg... |
9914012 | from pwn import *
#io = process("./pwn")
io = remote("172.16.17.32",8081)
context.log_level = 'debug'
libc = ELF("./bc.so.6")
def add(idx, size):
io.sendlineafter(">>",str(1))
io.sendlineafter("index",str(idx))
io.sendlineafter("size",str(size))
def show(idx):
io.sendlineafter(">>",str(4))
io.sendl... |
9914075 | DYNAMO_MAX_RANGE_KEY_LEN = 1024
# bytes in UTF-8 encoding.
# https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-partition-sort-keys
DEFAULT_ITEM_NAME = "Item"
# used throughout xoto3
|
9914104 | import uuid
from collections import defaultdict
from typing import Any, Dict, Text
from rasa.shared.nlu.constants import (
INTENT_NAME_KEY,
ENTITIES,
ENTITY_ATTRIBUTE_TYPE,
ENTITY_ATTRIBUTE_VALUE,
INTENT,
TEXT,
PREDICTED_CONFIDENCE_KEY,
)
from rasa.nlu.emulators.emulator import Emulator
c... |
9914110 | from math import pi
try:
import torch
except ImportError:
torch = None
try:
import numpy
except ImportError:
numpy = None
if numpy is None and torch is None:
raise ImportError("Must have either Numpy or PyTorch but both not found")
def set_framework_dependencies(x):
if type(x) is numpy.ndar... |
9914194 | from django.core.management.base import BaseCommand
from pdoc import cli as pdoc_cli
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("--http", default="0.0.0.0:8080", metavar="HOST:PORT")
def handle(self, *args, **options):
args = pdoc_cli.parser.parse_args()... |
9914200 | import tensorrt as trt
import torch
from torch2trt_dynamic.module_test import add_module_test
from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter,
torch_dim_to_trt_axes, trt_)
@tensorrt_converter('torch.nn.functional.normalize')
def convert_nor... |
9914217 | from ctypes import cdll, CFUNCTYPE, c_char_p, c_void_p, c_bool, POINTER, c_int, c_uint, c_uint64
from wtpy.WtCoreDefs import WTSTickStruct, WTSBarStruct, BarList, TickList
from wtpy.SessionMgr import SessionInfo
from wtpy.wrapper.PlatformHelper import PlatformHelper as ph
from wtpy.WtUtilDefs import singleton
impo... |
9914232 | from .nn_utils import *
from .odst import *
from .utils import *
from .data import *
from .arch import *
from .trainer import *
|
9914266 | import argparse
from datetime import timedelta
from time import time
import requests
from sqlalchemy import or_
from app import db, logger
from journal import Journal
from util import elapsed, safe_commit
def run(retry_apis):
start = time()
journal_ids = db.session.query(Journal.issn_l).filter(
or_... |
9914275 | import collections
import json
import sys
import warnings
import pandas as pd
from TM1py.Objects.Process import Process
from TM1py.Objects.Server import Server
if sys.version[0] == '2':
import httplib as http_client
else:
import http.client as http_client
def get_all_servers_from_adminhost(adminhost='local... |
9914284 | from numpy import *
NTRAIN=1000000
NTEST=10000
def narma(tmax, k):
v = random.randn(tmax)
x = zeros(tmax)
for i in range(1,tmax):
for k in range(max(0,i-k), i):
x[i] += 0.004*x[i-1]*x[k]
x[i] += 0.2*x[i-1] + 0.01
if i>=k:
x[i] += 1.5*v[i]*v[i-k]
return... |
9914288 | from .mvSet import MvSetTest
from .mvSetFull import MvSetTestFull
from .mvSetInc import MvSetTestInc
import pandas as pd
def fit_iSet(Y=None, Xr=None, F=None, Rr=None, factr=1e7, Rg=None, Ug=None, Sg=None, Ie=None, n_nulls=10):
# data
noneNone = Sg is not None and Ug is not None
bgRE = Rg is not None or no... |
9914368 | import json
import boto3
def handler(event, context):
client = boto3.client('ses')
field = event['body']
#reading json from frontend
data = json.loads(field)
SUBJECT = data["subject"]
BODY_TEXT = data["text"]
TO = data["to"]
FROM = data["from"]
print(TO)
message = {"Subject": ... |
9914413 | import torch
import torch.nn as nn
from torch.nn import init
import functools
# import numpy as np
import gc
###############################################################################
# Helper Functions
###############################################################################
def get_norm_layer(norm_type='... |
9914429 | class _SERVICE_STATUS_PROCESS(_SERVICE_STATUS_PROCESS):
SERVICE_STATE = FlagMapper(SERVICE_STOPPED,
SERVICE_START_PENDING,
SERVICE_STOP_PENDING,
SERVICE_RUNNING,
SERVICE_CONTINUE_PENDING,
SERVICE_PAUSE_PENDING,
SERVICE_PAUSED)
SERVICE_TYPE = FlagMapper(SERVICE_K... |
9914484 | import base64
import dataclasses
import html
import os
import re
import sys
import urllib
import uuid
from enum import Enum
from shutil import copyfile
from typing import Dict, Tuple
import requests
from bs4 import BeautifulSoup
from dataclasses_json import dataclass_json
from kobodl.globals import Globals
from kobod... |
9914497 | import argparse
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='View the ANNI vector file (for debug purposes)')
parser.add_argument('--anniVectors',type=str,required=True,help='File containing the raw ANNI vector data')
parser.add_argument('--anniVectorsIndex',type=str,r... |
9914498 | from flask import Flask, jsonify, request
from sklearn.externals import joblib
import numpy as np
import os
MODELPATH = '../models/model.pkl'
TRAINPATH = '../bin/train.py'
def json_to_model_input(request_body):
json_ = request_body.json
input = json_['input']
query = np.array(input)
if len(query.shape... |
9914510 | import asyncio
import json
from bot import get
from message import Message
icons = {'01d': '🌞',
'01n': '🌚',
'02d': '⛅️',
'02n': '⛅️',
'03d': '☁️',
'03n': '☁️',
'04d': '☁️',
'04n': '☁️',
'09d': '🌧',
'09n': '🌧',
'10d': '🌦',
... |
9914545 | import functools
import numpy as np
from mpi4py import MPI
from mpi4py_fft import PFFT, newDistArray
from mpi4py_fft.fftw import dctn, idctn
# Set global size of the computational box
N = np.array([18, 18, 18], dtype=int)
dct = functools.partial(dctn, type=3)
idct = functools.partial(idctn, type=3)
transforms = {(1,... |
9914560 | import itertools
import re
from abc import ABCMeta, abstractmethod, abstractproperty
from enum import Enum
class CONSTRAINTS(Enum):
NULL = 'null'
AND = 'and'
OR = 'or'
IN = 'in'
EQUALITY = 'eq'
INEQUALITY_GT = 'ineq_gt'
INEQUALITY_GTE = 'ineq_gte'
INEQUALITY_LT = 'ineq_lt'
INEQUALI... |
9914570 | import sys
from ldaptor.protocols.ldap import ldif
from ldaptor import usage, inmemory
from twisted.internet import reactor
exitStatus = 0
def error(fail):
print("fail:", fail.getErrorMessage(), file=sys.stderr)
global exitStatus
exitStatus = 1
def output(result, outputFile):
outputFile.write(ldif.... |
9914596 | class Solution:
def numPrimeArrangements(self, n: int) -> int:
if n == 1:
return 1
prime = [True] * (1 + n)
count = 1
for i in range(3, n + 1, 2):
if prime[i]:
count += 1
for j in range(i * i, n + 1, i):
prim... |
9914623 | import copy
import pathlib
import shutil
from textwrap import dedent
from typing import Optional
import pytest
from django.conf import settings
pytest_plugins = "pytester"
REPOSITORY_ROOT = pathlib.Path(__file__).parent
def pytest_configure(config) -> None:
config.addinivalue_line(
"markers", "django_... |
9914694 | from django.contrib.admin import ModelAdmin
from django.contrib.admin.exceptions import DisallowedModelAdminToField
from django.contrib.admin.options import TO_FIELD_VAR
from django.contrib.admin.utils import unquote
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translat... |
9914757 | import numpy as np
import pandas as pd
from scipy.stats import binom_test
def simulation_binomial_test(observed_successes, n, p, alternative_hypothesis):
#initialize null_outcomes
null_outcomes = []
#generate the simulated null distribution
for i in range(10000):
simulated_monthly_visitors = np.random.c... |
9914767 | import pygame
# use font_enhanced.formatted_text_gen if you want colors
class Tooltip:
"""
Tooltips will pop up after <rect_reference> has been hovered for <visible_delay> seconds and will show <text>.
They are bound by the display size and will adjust their placement automatically.
<rect_reference>... |
9914819 | import itertools
import sys
from math import radians, sqrt
from typing import Any, Callable, Dict, List, Sequence, Set, Tuple
import bpy
from mathutils import Matrix, Vector
from ..common import human_bone
from .abstract_base_vrm_importer import AbstractBaseVrmImporter
from .vrm_parser import PyMesh
class LegacyVrm... |
9914824 | from PIL import Image
import math
import sys
import xy
COLORS = {
'.': (255, 255, 255),
'X': (0, 0, 0),
}
def get_points(im, color=(0, 0, 0)):
result = []
w, h = im.size
for y in range(h):
for x in range(w):
if im.getpixel((x, y)) == color:
result.append((x, y))... |
9914868 | import os
target_suffix = (".rs", ".sh", ".md", ".proto",
".yml", ".bat", ".yml", "Dockerfile")
# remove \r by suffix and overwrite file
def dir2unix(path):
for line in os.walk(path):
for name in line[2]:
if name.endswith(target_suffix):
file_path = line[0]+... |
9914877 | import os
import sys
import unittest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),'../../../src')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'../../../src/common/python')))
import custom_exceptions
from mock import patch
from snapshot import snapshot_function
... |
9914993 | HANDLE = []
# ENV is a dict holding plugins objects, like functions, classes etc.
# Plugins should install their handles in ENV.
ENV = {}
def autoload(plugin, *args, **kwargs):
HANDLE.append((plugin.install, args, kwargs))
def autocall(handle, *args, **kwargs):
HANDLE.append((handle, args, kwargs))
... |
9915040 | import capstone
import struct
class BinaryDisassembler(object):
def set_org(self, org):
pass
def disassemble_unknown_region(self, region, data):
pass
def disassemble_code_region(self, region, data):
pass
def disassemble_data_region(self, region, data):
pass
def disas... |
9915084 | import logging
from typing import Dict
from typing import List
import neo4j
from azure.core.exceptions import HttpResponseError
from azure.mgmt.compute import ComputeManagementClient
from .util.credentials import Credentials
from cartography.util import run_cleanup_job
from cartography.util import timeit
logger = lo... |
9915113 | import FWCore.ParameterSet.Config as cms
process = cms.Process('jerdb')
process.load('CondCore.DBCommon.CondDBCommon_cfi')
process.CondDBCommon.connect = 'sqlite_file:Summer15_V0_MC_JER.db'
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(1))
process.source = cms.Source('EmptySource')
process.PoolDB... |
9915121 | from setuptools import setup
setup(name='simple_trpo',
version='0.0.1',
install_requires=[
'gym[mujoco]',
'mujoco-py',
'tensorflow',
'cloudpickle'
]
)
|
9915122 | import numpy as np
import pandas as pd
import riptable as rt
import pytest
from numpy.testing import assert_array_almost_equal
def count(df, data=None):
return df.count() if data is None else df.count() ##this is different
def sum(df, data=None):
return df.sum() if data is None else df.sum(da... |
9915132 | from abc import ABCMeta, abstractproperty
from twitter.common.lang import Compatibility
class NamedValue(object):
__metaclass__ = ABCMeta
def __init__(self, value):
if isinstance(value, int):
self._value = value if value in self.map else 0
elif isinstance(value, Compatibility.string):
self._v... |
9915138 | import os
import sys
from misc.new_directory import new_directory
def out_validation(out_path_parameter, global_variables):
# required inputs
out_path = None
# gets the sub-parameters
sub_params_list = out_path_parameter.split(",")
# checks the sub params
for sub_param in sub_params_list:
... |
9915162 | from subprocess import check_output, STDOUT, CalledProcessError
# ffmpeg command:
# ffmpeg -decryption_key 5df1b4e0d7ca82a62177e3518fe2f35a -i "./video_encripted.mp4" -vcodec copy "./video_decripted.mp4"
key_encript = "5df1b4e0d7ca82a62177e3518fe2f35a"
path_input_video = "./video_encripted.mp4"
path_output_vid... |
9915170 | import pytest
from hypothesis import example, given, settings
from hypothesis import strategies as st
from vyper import ast as vy_ast
from vyper.exceptions import ZeroDivisionException
st_int32 = st.integers(min_value=-(2 ** 32), max_value=2 ** 32)
@pytest.mark.fuzzing
@settings(max_examples=50, deadline=1000)
@giv... |
9915183 | from abc import abstractmethod, ABCMeta
from prudentia.simple import SimpleCli, SimpleProvider
class FactoryCli(SimpleCli):
@staticmethod
def help_create():
print ("Creates the box.\n")
def complete_create(self, text, line, begidx, endidx):
return self.complete_box_names(text, line, begi... |
9915185 | import argparse
import json
import re
import requests
import subprocess
import os
import pathlib
import toml
# See https://pkg.go.dev/gitlab.com/ignitionrobotics/web/cloudsim/simulations for original names
WORLDS = dict(
tq = "Tunnel Qualification",
ts1 = "Simple Tunnel 1", # Yes, tunnel has swapped word "s... |
9915192 | import torch
import torch.nn as nn
import torch.nn.functional as F
from classifier.base import BASE
class ROUTING(BASE):
'''
Induction and Relation module of
"Induction Networks for Few-Shot Text Classification"
'''
def __init__(self, ebd_dim, args):
super(ROUTING, self).__init__(a... |
9915212 | import string
NORMAL_CHAT = 1
WHISPER_CHAT = 2
GUILD_CHAT = 3
CREW_CHAT = 4
SHIPPVP_CHAT = 5
ERROR_NONE = None
ERROR_NO_OPEN_CHAT = 1
ERROR_NOT_FRIENDS = 2
ERROR_NO_RECEIVER = 3
ERROR_NO_GUILD_CHAT = 4
ERROR_NO_CREW_CHAT = 5
ERROR_NO_SHIPPVP_CHAT = 6
TYPEDCHAT = 0
SPEEDCHAT_NORMAL = 1
SPEEDCHAT_EMOTE = 2
SPEEDCHAT_CUST... |
9915234 | import sys
from pypy.interpreter.baseobjspace import W_Root, SpaceCache
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (
cpython_api, bootstrap_function, PyObject, PyObjectP, ADDR,
CANNOT_FAIL, Py_TPFLAGS_HEAPTYPE, PyTypeObjectPtr)
from pypy.module.cpyext.state import S... |
9915244 | from typing import Dict, Text
from pathlib import Path
import pytest
from _pytest.tmpdir import TempPathFactory
from rasa.core import training
from rasa.core.policies.ted_policy import TEDPolicy
from rasa.engine.graph import ExecutionContext, GraphSchema
from rasa.engine.storage.local_model_storage import LocalModel... |
9915283 | from marshmallow.exceptions import ValidationError
from baselayer.app.access import permissions, auth_or_token
from ..base import BaseHandler
from ...models import DBSession, Group, Classification, Taxonomy
class ClassificationHandler(BaseHandler):
@auth_or_token
def get(self, classification_id):
"""
... |
9915303 | import threading
import time
from coinbasepro.token_bucket import TokenBucket
class RateLimiter:
"""Simple thread-safe rate limiter.
Can be configured with a burst size and long term rate limit.
"""
def __init__(self, burst_size: int, rate_limit: int):
self.lock = threading.Lock()
s... |
9915308 | import sys
def detect_test_env():
i = 0
while True:
i += 1
try:
frame_module = sys._getframe(i).f_globals.get('__name__')
except ValueError:
return False
if frame_module == '__main__' or frame_module == '__console__':
return False
eli... |
9915311 | import numpy as np
import modeling.geometric_model as gm
import visualization.panda.world as wd
import basis.robot_math as rm
import math
# import vision.depth_camera.surface.gaussian_surface as gs
# import vision.depth_camera.surface.quadrantic_surface as qs
import vision.depth_camera.surface.bibspline_surface as bs
i... |
9915312 | import numpy as np
import torch
import lifelong_rl.torch.pytorch_util as ptu
def calculate_contrastive_empowerment(
discriminator,
obs,
next_obs,
latents,
num_prior_samples=512,
distribution_type='uniform',
split_group=4096*32,
obs_mean=None,
ob... |
9915337 | import re
import json
import requests
from bs4 import BeautifulSoup
import TweetPoster
class ImageHost(object):
url_re = None
def extract(self, url):
"""
Takes a URL, rehosts an image and returns a new URL.
"""
raise NotImplementedError
@classmethod
def rehost(self... |
9915390 | import inspect
def is_cython(obj):
"""Check if an object is a Cython function or method"""
# TODO(suo): We could split these into two functions, one for Cython
# functions and another for Cython methods.
# TODO(suo): There doesn't appear to be a Cython function 'type' we can
# check against via i... |
9915460 | import logging
from unittest.mock import MagicMock
import pytest
from mock import MagicMock, call
from user_sync.config.sign_sync import SignConfigLoader
from user_sync.engine.sign import SignSyncEngine
from user_sync.engine.umapi import AdobeGroup
@pytest.fixture
def example_engine(default_sign_args):
config =... |
9915517 | from ntpath import realpath
from wtpy.apps import WtBtAnalyst
from glob import glob
from tqdm.auto import tqdm
from os.path import dirname, basename
from click import command, option
# for i in tqdm(glob('./outputs_bt/*/funds.csv')):
# folder = dirname(i)
# name = folder[13:]
# analyst = WtBtAnalyst()
# ... |
9915520 | from . import *
from bfg9000 import file_types
from bfg9000.build_inputs import BuildInputs, Edge
from bfg9000.iterutils import default_sentinel, listify
from bfg9000.path import Path, Root
class TestEdge(TestCase):
def setUp(self):
self.env = make_env()
self.build = BuildInputs(self.env, Path('b... |
9915574 | import logging
import re
from ... import constants
def read(filepath):
with open(filepath, 'r') as f:
return f.read()
def write(filepath, contents):
with open(filepath, 'w') as f:
f.write(contents)
def remove_current_dusty_config(config):
"""Given a string representing the contents of a... |
9915637 | from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class transformVolumeData(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageR... |
9915644 | import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_PATH = os.path.join(ROOT_DIR, os.pardir, "datasets")
|
9915700 | import StringIO
from twisted.trial import unittest
from twisted.trial import reporter, runner
class TrialTest(unittest.TestCase):
def setUp(self):
self.output = StringIO.StringIO()
self.reporter = reporter.TestResult()
self.loader = runner.TestLoader()
class TestInterruptInTest(TrialTest... |
9915712 | import matplotlib.pyplot as plt
import numpy as np
from thermo import *
from fluids.numerics import logspace
ethanol_psat = VaporPressure(Tb=351.39, Tc=514.0, Pc=6137000.0, omega=0.635, CASRN='64-17-5')
methods = ['VDI_TABULAR', 'DIPPR_PERRY_8E', 'COOLPROP'] if coolprop.has_CoolProp() else ['VDI_TABULAR', 'DIPPR_PERR... |
9915736 | from pydantic import BaseModel, validator
class Base(BaseModel):
class Config:
extra = "ignore"
@validator('rating', check_fields=False, pre=True)
def preprocess_rating(cls, val: float) -> float:
return val / 100 if val > 100 else val
|
9915800 | import time
class ProgressBar(object):
'''
custom progress bar
Example:
>>> pbar = ProgressBar(n_total=30,desc='training')
>>> step = 2
>>> pbar(step=step)
'''
def __init__(self, n_total,width=30,desc = 'Training'):
self.width = width
self.n_total = n_total
... |
9915814 | import time
import sys
import datetime
import os
import csv
import json
# Directory where the original .csv files were downloaded to, using downloadTaxisCSVs.py:
CSV_DIR = '/lucenedata/nyc-taxi-data'
normalize = {
'vendorid': 'vendor_id',
'vendor_id': 'vendor_id',
'vendor_name': 'vendor_name',
'pickup_datetim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.