id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
55336 | import pdfcutter
import helper
import json #For writing PDF Link JSON File
import os #To check if PDF Link JSON File exists
#get_session is main method for parsing session to Senats/Bundesrats Texts dict
class MainExtractorMethod:
#In: Can't init TextExtractorHolder before (missing paras in get_beschluesse_text),... |
55340 | class Solution:
# @param A : list of integers
# @return an integer
def solve(self, A):
s = set(A)
if len(s) == len(A):
return -1
for i in A:
if A.count(i) > 1:
return i
else:
return -1
|
55363 | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ChatstateProtocolEntity(ProtocolEntity):
'''
INCOMING
<chatstate from="<EMAIL>">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
OUTGOING
<chatstate to="<EMAIL>">
<{{composing|paused}}></{{composing|paused}}... |
55395 | import unittest
import imp
import sys
import shapy
class TestSettings(unittest.TestCase):
def setUp(self):
self.settings = imp.new_module('test_settings')
sys.modules.update(test_settings=self.settings)
setattr(self.settings, 'UNITS', 'override')
setattr(self.settings, 'NEW_OPTION'... |
55432 | import json
import os
import time
import ray
from ray.train import Trainer
from ray.train.examples.horovod.horovod_example import (
train_func as horovod_torch_train_func,
)
if __name__ == "__main__":
ray.init(address=os.environ.get("RAY_ADDRESS", "auto"))
start_time = time.time()
num_workers = 8
... |
55438 | import numpy as np
from gtsam import SfmTrack
from gtsfm.common.image import Image
import gtsfm.utils.images as image_utils
def test_get_average_point_color():
""" Ensure 3d point color is computed as mean of RGB per 2d measurement."""
# random point; 2d measurements below are dummy locations (not actual pro... |
55456 | r"""
Difference between magnetic dipole and loop sources
===================================================
In this example we look at the differences between an electric loop loop, which
results in a magnetic source, and a magnetic dipole source.
The derivation of the electromagnetic field in Hunziker et al. (2015)... |
55462 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
from sentry.models import UserReport
class ProjectUserReportsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
project = self.create_project()
... |
55466 | import requests
from json import loads
from termcolor import colored
from configparser import RawConfigParser
def init(domain):
PDCH = []
print(colored("[*]-Searching Project Discovery Chaos...", "yellow"))
parser = RawConfigParser()
parser.read("config.ini")
CHAOS_KEY = parser.get("PDChaos", "CHAOS_API_KEY")
... |
55467 | from pathlib import Path
def absolute_path(path):
src_path = str(Path(__file__).parent.resolve())
return src_path + "/" + path
# Paths
DATASET_DIRECTORY = absolute_path("../dataset")
CLEAN_DATA_PATH = absolute_path("clean_data")
TIME_SERIES_PATH = absolute_path("clean_data/series.npy")
TRAINED_MODELS_PATH =... |
55472 | import subprocess
import os
def getBlame(f):
folder = os.path.split(f)[0]
cwd = os.getcwd()
os.chdir(folder)
cmd = "git blame --abbrev=0 -e \"" + f + "\""
try:
sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
response, err = sub.comm... |
55475 | from mycroft.messagebus.message import Message, dig_for_message
from mycroft.skills.core import FallbackSkill, intent_file_handler, intent_handler
from adapt.intent import IntentBuilder
from jarbas_hive_mind_red import get_listener
from jarbas_hive_mind.settings import CERTS_PATH
from jarbas_hive_mind.database import C... |
55484 | import os
import numpy as np
import random
from math import isclose
import torch
import matplotlib.pyplot as plt
from modelZoo.DyanOF import OFModel, fista
from torch.autograd import Variable
import torch.nn
def gridRing(N):
# epsilon_low = 0.25
# epsilon_high = 0.15
# rmin = (1 - epsilon_low)
# rmax ... |
55500 | import csv
import itertools
def _boolean(data):
if data == "False":
result = False
else:
result = True
return result
def row_to_location(row):
if row[4] == "0":
sub = False
nosub = True
else:
sub = True
nosub = False
tss = _boolean(row[6])
... |
55517 | import argparse
import os
class Opts:
def __init__(self):
self.parser = argparse.ArgumentParser()
def init(self):
self.parser.add_argument('-expID', default='default', help='Experiment ID')
self.parser.add_argument('-data', default='default', help='Input data folder')
self.pars... |
55519 | import komand
from .schema import ListAllActivityMonitorMatchesInput, ListAllActivityMonitorMatchesOutput
# Custom imports below
class ListAllActivityMonitorMatches(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="list_all_activity_monitor_matches",
... |
55526 | class n_A(flatdata.archive.Archive):
_SCHEMA = """namespace n {
archive A
{
}
}
"""
_NAME = "A"
_RESOURCES = {
"A.archive" : flatdata.archive.ResourceSignature(
container=flatdata.resources.RawData,
initializer=None,
schema=_SCHEMA,
is_optional=False,... |
55534 | import theano
import numpy
# CRF implementation based on Lample et al.
# "Neural Architectures for Named Entity Recognition"
floatX=theano.config.floatX
def log_sum(x, axis=None):
x_max_value = x.max(axis=axis)
x_max_tensor = x.max(axis=axis, keepdims=True)
return x_max_value + theano.tensor.log(theano.t... |
55613 | from django.conf.urls import url
from ratelimitbackend import admin
from ratelimitbackend.views import login
from .forms import CustomAuthForm, TokenOnlyAuthForm
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'admin/login.html'}, name='login'),
url(r'^custom_login/$', login,
{'tem... |
55683 | from typing import Union
import flask_restx
import flask
from keepachangelog._changelog import to_dict
def add_changelog_endpoint(
namespace: Union[flask_restx.Namespace, flask_restx.Api], changelog_path: str
):
"""
Create /changelog: Changelog endpoint parsing https://keepachangelog.com/en/1.0.0/
... |
55692 | import tensorflow as tf
import numpy as np
import os
import pickle
from utils.symbolic_network import SymbolicNet, MaskedSymbolicNet, SymbolicCell
from utils import functions, regularization, helpers, pretty_print
import argparse
def main(results_dir='results/sho/test', trials=1, learning_rate=1e-2, reg_weight=2e-4, ... |
55697 | from setuptools import setup, find_packages
from os import path
import re
def read_file(file_name: str) -> str:
here = path.abspath(path.dirname(__file__))
with open(path.join(here, file_name), encoding="utf-8") as f:
return f.read()
long_description = read_file("README.md")
version = re.sub("\s+", ... |
55713 | import torch
import torch.utils.data
from torch import nn
from torch.nn import functional as F
from rlkit.pythonplusplus import identity
from rlkit.torch import pytorch_util as ptu
import numpy as np
from rlkit.torch.conv_networks import CNN, DCNN
from rlkit.torch.vae.vae_base import GaussianLatentVAE
imsize48_default... |
55715 | Friend1 = {"First_name": "Anita", "Last_name": "Sanchez", "Age": 21, "City": "Saltillo"}
Friend2 = {"First_name": "Andrea", "Last_name": "<NAME>", "Age": 21, "City": "Monclova"}
Friend3 = {"First_name": "Jorge", "Last_name": "Sanchez", "Age":20, "City": "Saltillo"}
amigos = [Friend1, Friend2, Friend3]
for i in range(... |
55729 | import numpy as np
import torch as th
import torch.nn as nn
from rls.nn.mlps import MLP
from rls.nn.represent_nets import RepresentationNetwork
class QattenMixer(nn.Module):
def __init__(self,
n_agents: int,
state_spec,
rep_net_params,
agent_o... |
55764 | import unittest
from katas.kyu_6.which_are_in import in_array
class InArrayTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(in_array(
['live', 'arp', 'strong'],
['lively', 'alive', 'harp', 'sharp', 'armstrong']),
['arp', 'live', 'strong'])
|
55780 | import numpy as np
import fcl
import torch
# R = np.array([[0.0, -1.0, 0.0],
# [1.0, 0.0, 0.0],
# [0.0, 0.0, 1.0]])
R = np.array([[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]])
T = np.array([1.0, 1.865, 0])
g1 = fcl.Box(1,2,3)
t1 = fcl.Transform()
o1 = ... |
55784 | import torch
import torch.nn as nn
from torch import autograd
from Configs import Global_Config
def calc_Dw_loss(probs: torch.Tensor, label: int):
labels = torch.full((probs.size(0),), label, dtype=torch.float, device=Global_Config.device)
criterion = nn.BCELoss()
adversarial_loss = criterion(probs, labe... |
55786 | from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import pointnet2_utils
class StackSAModuleMSG(nn.Module):
def __init__(self, *, radii: List[float], nsamples: List[int], mlps: List[List[int]],
use_xyz: bool = True, pool_method='max_pool'):
... |
55796 | from . import _compressor
from . import bzip2
from . import gzip
from . import lzma
from . import zlib
|
55809 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.db.models import Count, Sum, F, Func
from datetime import date... |
55826 | import numpy as np
from PIL import Image
from skimage import color
from skimage.feature import hog
from pelops.features.feature_producer import FeatureProducer
class HOGFeatureProducer(FeatureProducer):
def __init__(self, chip_producer, image_size=(224,224), cells=(16, 16), orientations=8, histogram_bins_per_ch... |
55846 | import aiohttp
import discord
from discord.ext import commands
class Silphroad(commands.Cog):
"""
Commands related to Silphroad.
"""
def __init__(self, bot):
self.bot = bot
@commands.command(
aliases=["Silphcard", "Scard", "scard", "s-card", "S-card", "silph", "Silph", "Silphroad... |
55860 | import pytest
@pytest.fixture
def board():
return [
[1, 1, 0],
[0, 1, 0],
[1, 1, 1]
]
@pytest.fixture
def board_mirrored():
return [
[0, 1, 1],
[0, 1, 0],
[1, 1, 1]
]
def complete_column(board, column):
return all(row[column] for row in board)
d... |
55880 | import json
import os
import time
def get_cache_path():
home = os.path.expanduser("~")
return home + '/package_list.cdncache'
def time_has_passed(last_time, time_now):
time_is_blank = time_now is None or last_time is None
if time_is_blank:
return time_is_blank
time_difference = int(time.t... |
55896 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from torch.utils.data.sampler import BatchSampler
from .weight import WeightSampler
def get_batch(dataset, config):
# (sampler, batch_size, drop_last):
return None
def get_weight(dataset,... |
55914 | from Queue import Queue # Threadsafe queue for threads to use
from collections import Counter # To count stuff for us
import datetime # Because datetime printing is hard
from pprint import pprint
import time # Should be obvious
import subprocess # Used to s... |
55916 | from telegram.ext import Updater, CommandHandler, RegexHandler, MessageHandler, Filters, CallbackQueryHandler
from config import settings, command as cmd
from src import bot
import logging
updater = Updater(token=settings.BOT_TOKEN)
dispatcher = updater.dispatcher
bot = bot.ScheduleBot()
# ********* BASE DISPATCH **... |
55918 | import os
import h5py
import numpy as np
import pandas as pd
import multiprocessing as mp
class Scaler:
def __init__(self, mean=None, std=None):
self.mean = mean
self.std = std
def fit(self, data):
self.mean = np.mean(data)
self.std = np.std(data)
def set_mean(self, mean):
self.mean = me... |
55946 | import os
import sys
from keystone import *
sys.path.append("./../../util/script/")
import shellcode
def gen_oepinit_code32():
ks = Ks(KS_ARCH_X86, KS_MODE_32)
code_str = f"""
// for relative address, get the base of addr
push ebx;
call getip;
lea ebx, [eax-6];
// get the ... |
55950 | import pprint
import os
class ServerProps:
def __init__(self, filepath):
self.filepath = filepath
self.props = self._parse()
def _parse(self):
"""Loads and parses the file speified in self.filepath"""
with open(self.filepath) as fp:
line = fp.readline()
... |
55971 | from fairseq.models.transformer_lm import *
from torch.nn import CrossEntropyLoss
from typing import Any, Dict, List, Optional, Tuple
from torch import Tensor
class TransformerLanguageModelWrapper(TransformerLanguageModel):
@classmethod
def build_model(cls, args, task):
"""Build a new model instance.... |
55984 | from __future__ import print_function,absolute_import,division,unicode_literals
_B=False
_A=None
from .compat import no_limit_int
from .anchor import Anchor
if _B:from typing import Text,Any,Dict,List
__all__=['ScalarInt','BinaryInt','OctalInt','HexInt','HexCapsInt','DecimalInt']
class ScalarInt(no_limit_int):
def __n... |
55991 | from __future__ import unicode_literals
from __future__ import print_function
from fnmatch import fnmatch
import sys
from unittest.suite import _call_if_exists, _DebugResult, _isnotsuite, TestSuite
from unittest import util
import unittest
from io import StringIO
from green.config import default_args
from green.outpu... |
55999 | import base_network
import numpy as np
import ou_noise
import signal
import tensorflow as tf
import tensorflow.contrib.slim as slim
import util
def add_opts(parser):
parser.add_argument('--share-conv-net', type=bool, default=True,
help="if set (dft) we have one network for processing input img ... |
56048 | import random
from hathor.crypto.util import decode_address
from hathor.graphviz import GraphvizVisualizer
from hathor.simulator import FakeConnection
from tests import unittest
from tests.utils import add_blocks_unlock_reward
class BaseHathorSyncMempoolTestCase(unittest.TestCase):
__test__ = False
def setU... |
56133 | import os
import socket
import time
from textwrap import dedent
def attack(ip, port):
global sent
global max
sock.sendto(str.encode(bytes), (ip, int(port)))
sent += 1
print(
"\033[36m%s пакетов убила сервер (остановка Ctrl+z) - %s:%s" % (sent, ip, port)
)
if mode == "y":
... |
56146 | import numpy as np
from multiprocessing import Process, Queue
from mxnet.io import DataIter, DataBatch
import mxnet as mx
import numpy as np
from mxnet.io import DataIter
from PIL import Image
import os
import preprocessing
import logging
import sys
#rgb_mean=(140.5192, 59.6655, 63.8419), #mean on tote trainval
cla... |
56169 | import urllib.parse
from wikked.db.base import NoWantedPages
from wikked.page import WantedPage
from wikked.utils import get_absolute_url
from wikked.webimpl import (
get_page_meta, get_page_or_raise, make_page_title,
is_page_readable, get_redirect_target,
get_or_build_pagelist, get_generic_page... |
56173 | import sys
class InvariantParser:
'''
The InvariantParser is used to parse a Daikon-generated invariants file into a
dictionary mapping program points (ppts) to their invariants.
'''
# Path of the invariants file to be parsed.
filepath = ""
# String used to match entry separating lines in the ... |
56234 | from ray.rllib.utils import try_import_tf, try_import_torch
tf = try_import_tf()
torch, nn = try_import_torch()
def explained_variance(y, pred, framework="tf"):
if framework == "tf":
_, y_var = tf.nn.moments(y, axes=[0])
_, diff_var = tf.nn.moments(y - pred, axes=[0])
return tf.maximum(-1... |
56318 | from typing import Union, Callable, Type, Dict, Any
from ray.rllib import MultiAgentEnv, Policy
from ray.rllib.agents import Trainer
from ray.rllib.models import ModelV2
from ray.rllib.utils.typing import ResultDict
from grl.algos.nxdo.nxdo_manager.manager import SolveRestrictedGame
from grl.rl_apps.scenarios.scenari... |
56333 | import pickle
import random
import cv2 as cv
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from config import pickle_file, num_workers
from utils import align_face
# Data augmentation and normalization for training
# Just normalization for validation
data_tra... |
56356 | import FWCore.ParameterSet.Config as cms
# Remove duplicates from the electron list
electronsNoDuplicates = cms.EDFilter("DuplicatedElectronCleaner",
## reco electron input source
electronSource = cms.InputTag("gsfElectrons"),
)
|
56396 | def byte(n):
return bytes([n])
def rlp_encode_bytes(x):
if len(x) == 1 and x < b'\x80':
# For a single byte whose value is in the [0x00, 0x7f] range,
# that byte is its own RLP encoding.
return x
elif len(x) < 56:
# Otherwise, if a string is 0-55 bytes long, the RLP encoding
# consists of a s... |
56413 | pm = sm.getChr().getPotentialMan()
pm.addPotential(pm.generateRandomPotential(1))
sm.completeQuestNoRewards(12394)
sm.dispose()
|
56415 | class UpdateIpExclusionObject:
def __init__(self, filterIp, ipFilterId):
self.filterIp = filterIp
self.ipFilterId = ipFilterId
self.memo = None |
56422 | import pytest
from streaming_form_data.validators import MaxSizeValidator, ValidationError
def test_max_size_validator_empty_input():
validator = MaxSizeValidator(0)
with pytest.raises(ValidationError):
validator('x')
def test_max_size_validator_normal():
validator = MaxSizeValidator(5)
f... |
56424 | import torch
def model_to_vector(model, emb_layer_name='input_emb'):
"""
get the wordvec weight
:param model:
:param emb_layer_name:
:return:
"""
sd = model.state_dict()
return sd[emb_layer_name + '.weight'].cpu().numpy().tolist()
def save_embedding(file_name, embeddings, id2word):
... |
56435 | import sys
import os
import numpy.random
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ext.boss_bodenheimer import bb79_cloud
numpy.random.seed(1234567)
class BossBodenheimerTests(amusetest.TestCase):
def test1(self):
numpy.random.seed(1234)
mc=bb79_cloud... |
56455 | from raytkTools import RaytkTools
# noinspection PyUnreachableCode
if False:
# noinspection PyUnresolvedReferences
from _stubs import *
from ..ropEditor.ropEditor import ROPEditor
iop.ropEditor = ROPEditor(COMP())
class CreateRopDialog:
def __init__(self, ownerComp: 'COMP'):
self.ownerComp = ownerComp
def _s... |
56475 | import logging
import re
import gzip
from pathlib import Path
from argparse import ArgumentParser
from Bio import AlignIO
from make_prg.from_msa import MSA
from make_prg.prg_encoder import PrgEncoder, PRG_Ints
def load_alignment_file(msa_file: str, alignment_format: str) -> MSA:
msa_file = str(msa_file)
log... |
56515 | import argparse
import subprocess
import logging
import time
import re
import os
from datetime import datetime
from contextlib import closing, contextmanager
import pymysql
import pymysql.cursors
import boto3
import botocore.exceptions
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentP... |
56543 | import os
import subprocess
from audio_length import escape_characters
import argparse
filetypes_to_convert=[".mp3",".m4a", ".webm"]
def convert(filename):
filename_extensionless, extension = os.path.splitext(filename)
new_filename = "".join([filename_extensionless, ".wav"])
if not os.path.exists(new_filename):... |
56597 | from stream import CStream
from tokenizer import L2
from data import Expr, Literal, Position
#import space
#table = {
# u'(': u'lp', u')': u'rp',
# u'[': u'lb', u']': u'rb',
# u'{': u'lc', u'}': u'rc',
# u'and': u'and', u'or': u'or', u'not': u'not',
# u'=': u'let', u':=': u'set',
# u'<': u'chain',
# ... |
56647 | import os
import sys
from mininet.node import RemoteController
from mininet.net import Mininet
import dc_gym.utils as dc_utils
import logging
log = logging.getLogger(__name__)
cwd = os.getcwd()
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, FILE_DIR)
def get_congestion_control():
prev_... |
56673 | import unittest
from descriptastorus import MolFileIndex
import os, shutil
import logging
import datahook
TEST_DIR = "test1"
class TestCase(unittest.TestCase):
def setUp(self):
if os.path.exists(TEST_DIR):
shutil.rmtree(TEST_DIR, ignore_errors=True)
index = self.index = MolFileIndex.M... |
56702 | import os
import sys
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument('-gpu', default='0', type=str)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim ... |
56708 | def entry_id(entry):
for field in ['id', 'link']:
ret = getattr(entry, field, None)
if ret:
return ret
raise Exception('no id field found in entry: {}'.format(entry))
|
56710 | import os
from py.path import local
import pypy
from pypy.tool.udir import udir
from pypy.translator.c.test.test_genc import compile
from pypy.rpython import extregistry
import errno
import sys
import py
def getllimpl(fn):
return extregistry.lookup(fn).lltypeimpl
def test_access():
filename = str(udir.join(... |
56722 | class Solution:
def minStartValue(self, nums: List[int]) -> int:
total = minSum = 0
for num in nums:
total += num
minSum = min(minSum, total)
return 1 - minSum
|
56738 | import os
import random
import shutil
# We need to change the dataset so that it is split into train/validation/test
# portions, and labelled with a single attribute (e.g. 'color').
attributes = ('color', 'number', 'shape', 'shading', 'all')
attribute_label_extraction_fns = {
'number': lambda dir: dir.split('-')... |
56787 | import logging
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from core.management.commands import configure_logging
from core.models import Batch, OcrDump
configure_logging("dump_ocr_logging.config", "dump_ocr.log")
_logger = logging.getLogger(__name__)
class Comma... |
56788 | import os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='django-envsettings',
... |
56820 | from definitions import SYSTEM, System, GameStatus
import os
import asyncio
import logging as log
from consts import UBISOFT_REGISTRY_LAUNCHER_INSTALLS
if SYSTEM == System.WINDOWS:
import winreg
def _get_registry_value_from_path(top_key, registry_path, key):
with winreg.OpenKey(top_key, registry... |
56845 | import unittest
from test.test_utils import get_repository
from unittest.mock import Mock
from autopr.database import Database
class DatabaseTest(unittest.TestCase):
def test_needs_pulling_empty(self):
db = Database()
self.assertTrue(db.needs_pulling())
def test_needs_pulling_not_empty(self)... |
56859 | import json
import jieba
import pickle
import csv, h5py
import pandas as pd
import numpy as np
from tqdm import *
import torch
from torch import Tensor
from torch.autograd import Variable
import torch.utils.data as data
from main import Hyperparameters
from collections import Counter
STOP_TAG = "#stop#"
UNK_TAG = "... |
56864 | import librosa
from numba import jit
import numpy as np
@jit(nopython=True, cache=True)
def __C_to_DE(C: np.ndarray = None,
dn: np.ndarray = np.array([1, 1, 0], np.int64),
dm: np.ndarray = np.array([1, 0, 1], np.int64),
dw: np.ndarray = np.array([1.0, 1.0, 1.0], np.float64),
... |
56868 | apiAttachAvailable = u'API Kullanilabilir'
apiAttachNotAvailable = u'Kullanilamiyor'
apiAttachPendingAuthorization = u'Yetkilendirme Bekliyor'
apiAttachRefused = u'Reddedildi'
apiAttachSuccess = u'Basarili oldu'
apiAttachUnknown = u'Bilinmiyor'
budDeletedFriend = u'Arkadas Listesinden Silindi'
budFriend = u'Arkadas'
bu... |
56910 | import random
import string
import unittest
import warnings
from libs import jenkinslib
from libs.JAF.BaseCommandLineParser import BaseCommandLineParser
from libs.JAF.plugin_CreateAPIToken import CreateAPIToken, CreateAPITokenParser
from libs.JAF.plugin_DeleteAPIToken import DeleteAPIToken, DeleteAPITokenParser
from l... |
56912 | import pytest
from ethereum import tester
@pytest.mark.xfail
def test_get_block_by_hash(rpc_server, rpc_client, eth_coinbase):
block_number = rpc_client.get_block_number()
assert block_number == 0
to_addr = "0x" + tester.encode_hex(tester.accounts[1])
txn_hash = rpc_client.send_transaction(_from=eth... |
56936 | from panini import app as panini_app
from panini.middleware.debug_middleware import DebugMiddleware
app = panini_app.App(
service_name="debug_middleware_example",
host="127.0.0.1",
port=4222,
)
message = {
"key1": "value1",
"key2": 2,
"key3": 3.0,
"key4": [1, 2, 3, 4],
"key5": {"1": 1... |
56939 | import os
import pandas as pd
import re
import subprocess
df = pd.read_csv("analysis_output/base_image_version_count.csv")
print(df.head())
df = df[:25].copy()
java_version = []
for i in range(len(df)):
try:
run_cmd = "docker run " + df["base-image:version"][i] + " java -version"
result = subprocess.check_output... |
56957 | import json
import httplib2
from graphipy.graph.graph_base import BaseNode as Node, BaseEdge as Edge
class Pinterest:
def __init__(self, api):
self.access_token = api["access_token"]
# get a single user info in JSON format by username
def get_single_user(self, username):
url = "https://a... |
56960 | import numpy as np
import pandas as pd
from autodcf.models._base import AbstractDCF
from datetime import datetime
class DCF(AbstractDCF):
"""Class for flexible DCF.
Note that all _to_sales args take either an iterable or float. If given a float, the DCF will
use this constant across all time periods (ex... |
56968 | import asyncio
import json
import logging
from typing import List, Set
import websockets
class BrowserWebsocketServer:
"""
The BrowserWebsocketServer manages our connection to our browser extension,
brokering messages between Google Meet and our plugin's EventHandler.
We expect browser tabs (and our ... |
56973 | from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
claimed = dict()
for l in s.splitlines():
a = l.split('@')[1].strip().split(':')
b = a[0].split(',')
c = a[1].split('x')
x = int(b[0])
y ... |
56987 | import pandas as pd
from pandas.testing import assert_frame_equal
import pytest
def assert_dataframes_equals(expected, actual):
assert expected.shape==actual.shape
assert set(expected.columns) == set(actual.columns)
columns_order = list(expected.columns)
a = actual[columns_order].sort_values(by=list(a... |
57038 | import click
from gradient.cli import common
from gradient.cli.clusters import clusters
from gradient.cli.common import api_key_option
from gradient.commands.machine_types import ListMachineTypesCommand
@clusters.group("machineTypes", help="Manage machine types")
def machine_types_group():
pass
@machine_types_... |
57100 | expected_output = {
"interfaces": {
"Port-channel1": {
"name": "Port-channel1",
"protocol": "lacp",
"members": {
"GigabitEthernet0/0/1": {
"activity": "Active",
"age": 18,
"aggregatable": True,
... |
57133 | from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('', views.blog, name='blog'),
path('<int:pk>/', views.post_detail, name='post_detail'),
path('<int:pk>/share/', views.post_share, name='post_share'),
path('manage/', views.ManagePostListView.as_view(), name='manag... |
57181 | from ..model_tests_utils import (
status_codes,
DELETE,
PUT,
POST,
GET,
ERROR,
random_model_dict,
check_status_code,
compare_data
)
from core.models import (
ActionSequenceType,
ExperimentTemplate,
ActionSequence
)
actionsequence_test_data = {}
actionsequence_tests = [
... |
57270 | import torch
import torch.nn as nn
from lightconvpoint.nn.deprecated.module import Module as LCPModule
from lightconvpoint.nn.deprecated.convolutions import FKAConv
from lightconvpoint.nn.deprecated.pooling import max_pool
from lightconvpoint.spatial.deprecated import sampling_quantized, knn, upsample_nearest
from ligh... |
57272 | import requests
import os
url_image = 'https://www.python.org/static/community_logos/python-logo.png'
r_image = requests.get(url_image)
print(r_image.headers['Content-Type'])
# image/png
filename_image = os.path.basename(url_image)
print(filename_image)
# python-logo.png
with open('data/temp/' + filename_image, 'w... |
57297 | import falcon
import six
from monitorrent.settings_manager import SettingsManager
# noinspection PyUnusedLocal
class SettingsNotifyOn(object):
def __init__(self, settings_manager):
"""
:type settings_manager: SettingsManager
"""
self.settings_manager = settings_manager
def on_... |
57322 | import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
def get_mean_stds(data):
return np.mean(data), np.std(data) / np.sqrt(len(data)) * 1.96
if __name__ == '__main__':
labels = ['OpenTAL', 'EDL', 'SoftMax']
result_folders = ['edl_oshead_iou', 'edl_15kc', 'default']
colors = ['k... |
57355 | import random
import _jsonnet, json
import logging
import hashlib
import os
from copy import deepcopy
import pandas as pd
from tqdm import tqdm
import math
from LeapOfThought.resources.teachai_kb import TeachAIKB
from LeapOfThought.common.general import num2words1, bc
from LeapOfThought.common.data_utils import unifor... |
57376 | from chemex.plotters.cest import CestPlotter as CestPlotter
from chemex.plotters.cpmg import CpmgPlotter as CpmgPlotter
from chemex.plotters.plotter import Plotter as Plotter
from chemex.plotters.relaxation import RelaxationPlotter as RelaxationPlotter
from chemex.plotters.shift import ShiftPlotter as ShiftPlotter
|
57379 | from shaape.parser import Parser
import nose
import unittest
from nose.tools import *
class TestParser(unittest.TestCase):
def test_init(self):
parser = Parser()
assert parser != None
assert parser.parsed_data() == []
assert parser.drawable_objects() == []
def test_run(self):
... |
57392 | class IDGroup:
"""
The IDGroup Type
================
This type supports both iteration and the []
operator to get child ID properties.
You can also add new properties using the [] operator.
For example::
group['a float!'] = 0.0
group['an int!'] = 0
group['a string!'] = "hi!"
group['an array!'] = [0, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.