id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9847331 | import ctypes
import windows
from windows import winproxy
import windows.generated_def as gdef
from windows.generated_def.winstructs import *
from windows.utils import AutoHandle
import sys
class LogicalDrive(AutoHandle):
DRIVE_TYPE = gdef.FlagMapper(DRIVE_UNKNOWN, DRIVE_NO_ROOT_DIR, DRIVE_REMOVABLE,
... |
9847384 | from helpers.constants import AddressZero, MaxUint256
from helpers.token_utils import (
BalanceSnapshotter,
distribute_from_whales,
distribute_test_ether,
get_token_balances,
)
from ape_safe import ApeSafe
from brownie import *
from gnosis.safe.safe import Safe
from config.badger_config import badger_co... |
9847414 | import numpy as np
import pytest
import pandas as pd
from pandas import PeriodIndex
import pandas._testing as tm
def test_to_native_types():
index = PeriodIndex(["2017-01-01", "2017-01-02", "2017-01-03"], freq="D")
# First, with no arguments.
expected = np.array(["2017-01-01", "2017-01-02", "2017-01-03"... |
9847415 | from . import haven_utils as hu
from . import haven_chk as hc
import os
import time
import copy
import pandas as pd
import numpy as np
import getpass
import pprint
import requests
try:
import borgy_job_service_client
except:
pass
# Api
# ==============
def get_api(**kwargs):
# Get Borgy API
config = b... |
9847508 | import ast
import inspect
import logging
import math
import os
import torch
import numpy as np
import skyline.protocol_gen.innpv_pb2 as pm
from skyline.analysis.static import StaticAnalyzer
from skyline.exceptions import AnalysisError, exceptions_as_analysis_errors
from skyline.profiler.iteration import IterationProf... |
9847540 | import socket
import struct
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 9999
SUBSCRIBE = 0
UNSUBSCRIBE = 1
PUBLISH = 2
class Client(object):
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, host=DEFAULT_HOST, port=DEFAULT_PORT):
self.sock... |
9847556 | import numpy as np
import scipy.sparse as sp
import tensorflow as tf
import yaml
from pymongo import MongoClient
def to_sparse_tensor(M, value=False):
"""Convert a scipy sparse matrix to a tf SparseTensor or SparseTensorValue.
Parameters
----------
M : scipy.sparse.sparse
Matrix in Scipy spar... |
9847558 | import wx
app_name = None
class HeeksConfig(wx.Config):
def __init__(self, disabled = False):
global app_name
if app_name == None:
app_name = wx.GetApp().GetAppConfigName()
wx.Config.__init__(self, app_name)
self.disabled = disabled
def Write(se... |
9847562 | import os.path as osp
import argparse
from scripts.object_ap_eval import kitti_common as kitti
from scripts.object_ap_eval import coco_format as cf
from scripts.object_ap_eval.eval import get_official_eval_result, get_coco_eval_result
"""
python scripts/object_ap_eval/test_det_ap.py data/GTA/anns/tracking_mini.json.se... |
9847601 | import time
class TimeUtils:
@staticmethod
def timestamp() -> int:
"""
now timestamp(ms)
"""
return int(time.time() * 1000)
|
9847608 | from typing import Optional, List
from abc import ABC, abstractmethod
from collections import namedtuple
DEFAULT_WORD_LIMIT = 5
DEFAULT_REACTION_LIMIT = 3
WordCount = namedtuple("WordCount", "word, count")
ReactionCount = namedtuple("ReactionCount", "reaction, count")
UserReactionCount = namedtuple("UserReactionCount... |
9847666 | def predict_top5(images, device, seed):
"""
Args:
images: torch Tensor with dimensionality B x C x H x W
(batch size x number of channels x height x width)
device: STRING
`cuda` if GPU is available, else `cpu`.
Output:
top5_probs: torch Tensor (B, 5) with top 5 class probabilities
... |
9847736 | import paddle
import os
import sys
import argparse
import numpy as np
sys.path.append(
os.path.join(os.path.dirname("__file__"), os.path.pardir, os.path.pardir))
from paddleslim import UnstructuredPruner
from utility import add_arguments, print_arguments
import paddle.vision.transforms as T
import paddle.nn.functio... |
9847816 | import wget
import os
from colorama import Fore
import requests
import services.console as console
from sys import exit
def downloadAndMove(downloadLink: str, destinationDir='.', aLotOfTraffic=False):
import urllib
if destinationDir != '.' and os.path.exists(destinationDir):
print("File {} is exists... |
9847819 | import numpy as np
import sys
sys.path.append('.')
from dataset import *
from scipy.misc import imsave
import matplotlib.pyplot as plt
import os
import pdb
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import unary_from_softmax, create_pairwise_bilateral, create_pairwise_gaussian
from loss import *
from tqd... |
9847862 | import sys
sys.path.append("../../")
from appJar import gui
def to_checkout():
print("check")
with gui() as app:
app.label('hello world')
with app.frameStack("main", start=0):
with app.frame():
# Tabbed page for displaying info for each category
with app.labelFrame("Item Inve... |
9847889 | from PyQt5.QtCore import Qt
from PyQt5.QtGui import QBrush
from PyQt5.QtSql import QSqlQuery, QSqlQueryModel, QSqlDatabase
from PyQt5.QtWidgets import QTableView, QApplication, QMessageBox, qApp
def createConnection():
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('memory')
if not db.open():... |
9847931 | from __future__ import absolute_import, division, print_function, unicode_literals
import platform
PLATFORM = platform.system().lower()
DEBIAN = 'debian'
MAC = 'darwin'
RASPBERRY_PI = 'raspberry-pi'
UBUNTU = 'ubuntu'
WINDOWS = 'windows'
IS_LINUX = (PLATFORM == 'linux')
if IS_LINUX:
PLATFORM = platform.linux_di... |
9847946 | from pandas import concat
from smart_fruit.feature_types.feature_type_base import FeatureType
__all__ = ["Vector"]
class Vector(FeatureType):
def __init__(self, feature_types):
self.feature_types = feature_types
@property
def feature_count(self):
return sum(feature_type.feature_count fo... |
9847964 | from typing import Generator
import pytest
from app.core.scheduler import get_scheduler
@pytest.yield_fixture(scope="session", autouse=True)
def scheduler_lifespan() -> Generator[None, None, None]:
"""
Ensure that the global scheduler singleton is
torn down when tests finish. Otherwise, the test runner w... |
9847988 | import numpy as np
import torch
from mmdet3d.core.points import DepthPoints
from mmdet3d.datasets.pipelines import MultiScaleFlipAug3D
def test_multi_scale_flip_aug_3D():
np.random.seed(0)
transforms = [{
'type': 'GlobalRotScaleTrans',
'rot_range': [-0.1, 0.1],
'scale_ratio_range': [0... |
9848015 | from ..helpers import Config
class Parser(Config):
"""Parser is a component responsible for the parsing.
Router uses a parsers dictionary to handle user placeholders in paths.
Placeholder is a path insertion in following form "<name:parser>".
.. seealso:: Implements:
:class:`.Config`
Pa... |
9848038 | from .function import *
from .hypergraph import Hypergraph
from .hypergraphviews import subhypergraph
from .simplicialcomplex import SimplicialComplex
|
9848055 | import sublime
import os
from .common_path import common_path
from .debug import debug
from .get_source_folders import get_source_folders
from .utils import norm_path
# Returns import root - part of the file path which be cutted as common part.
# Can return None if can't detect.
def get_import_root(project_data=None,... |
9848060 | import asyncio
import string
import random
import time
import asyncio
import math
import copy
import psutil
import os
import logging
from quart import Quart, g, websocket, session, redirect, request, url_for, jsonify, render_template, send_file, abort
from rockutils import rockutils
import ujson as json
config = roc... |
9848115 | import asyncio
import gc
import os
import pytest
import aiomysql
@pytest.fixture()
def fill_my_cnf(mysql_params):
tests_root = os.path.abspath(os.path.dirname(__file__))
path1 = os.path.join(tests_root, 'fixtures/my.cnf.tmpl')
path2 = os.path.join(tests_root, 'fixtures/my.cnf')
with open(path1) as f... |
9848119 | import numpy as np
import matplotlib.pyplot as plt
from sklearn_evaluation.plot.matplotlib.data_grid import DataGrid
from sklearn_evaluation.plot.util import set_default_ax
def plot(values, orientation, labels=None, sort=True, error=None, ax=None):
if orientation == 'horizontal':
return horizontal(values... |
9848127 | from collections import defaultdict
from functools import lru_cache
from typing import Iterable, Dict, List, Set
from toposort import toposort
from checkmate.core.utils.definitions import Vertex, EdgeList, AdjList
from checkmate.core.utils.graph import edge_to_adj_list, adj_to_edge_list, gcd, connected_components
cl... |
9848142 | expected_output = {
"slot": {
"1": {
"rp": {
"card_type": "Catalyst 6000 supervisor 2 (Active)",
"fw_ver": "6.1(3)",
"hw_ver": "3.9",
"mac_address_from": "0001.64ff.1958",
"mac_address_to": "0001.64ff.1959",
... |
9848158 | from . import db
from .models import User
from .models import Workout
from flask import Blueprint, render_template, redirect, url_for, request, flash, abort
from flask_login import current_user, login_required
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('index.html')
... |
9848176 | import os
import pytest
import yaml
from compose.config.types import VolumeSpec
from construi.config import Config, NoSuchTargetException
class TestConfig(object):
@property
def working_dir(self):
return os.path.dirname(os.path.realpath(__file__))
def config(self, yml, target):
return Co... |
9848187 | import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import utils
class SpectralNorm:
def __init__(self, name, bound=False):
self.name = name
self.bound = bound
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
u =... |
9848230 | from __future__ import absolute_import
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import warnings
from itertools import chain
import numpy as np
import nibabel as nib
from .. import image
from ..image import Image, iter_axis, is_image, rollimg
fr... |
9848261 | import random
import numpy as np
import torch
import torch.nn as nn
import scipy.sparse as sparse
from advex_uar.attacks.attacks import AttackWrapper
from advex_uar.attacks.gabor import get_gabor_with_sides, valid_position, gabor_rand_distributed
class GaborAttack(AttackWrapper):
def __init__(self, nb_its, eps_m... |
9848264 | import math
class ResultValue(object):
"""Wrapper class to keep track of valid and final
accs for 1-5 utterances
Args:
valid_acc (list[float]): valid accuracies in order 1-5
final_acc (list[float]): final accuracies in order 1-5
"""
def __init__(self, valid_accs, final_accs):
... |
9848273 | from openapi_core.schema.servers import get_server_url
def get_spec_url(spec, index=0):
servers = spec / "servers"
return get_server_url(servers / 0)
|
9848283 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densesolve import LU_solve, rref_solve, cholesky_solve
from sympy import Dummy
from sympy import QQ
def test_LU_solve():
x, y, z =... |
9848317 | from __future__ import absolute_import, print_function
from flask import request, jsonify, send_file
from app import db
from flask.ext.login import current_user, login_required
from . import posts
from .models import Post, PostSerializer
from datetime import datetime
import json
@posts.route('/api/posts/all')
def all... |
9848356 | import math
from WonderPy.core.wwConstants import WWRobotConstants
from .wwSensorBase import WWSensorBase
from WonderPy.util import wwMath
_rcv = WWRobotConstants.RobotComponentValues
_expected_json_fields = (
_rcv.WW_SENSOR_VALUE_AXIS_X,
_rcv.WW_SENSOR_VALUE_AXIS_Y,
_rcv.WW_SENSOR_VALUE_AXIS_Z,
)
class ... |
9848364 | import collections
import copy
import json
import os
import re
import subprocess
import sys
import threading
import time
import traceback
import pytest
import requests
from pytest_localserver.http import WSGIServer
from werkzeug.serving import WSGIRequestHandler
SYMBOLICATOR_BIN = [os.environ.get("SYMBOLICATOR_BIN") ... |
9848369 | import contextlib
import logging
import flask
from flask import Response
from werkzeug.exceptions import MethodNotAllowed
import os
from core.app_server import ErrorHandler
from core.model import (
Admin,
ConfigurationSetting,
get_one_or_create
)
from api import app
from api import routes as api_routes
fr... |
9848401 | from dns import resolver
def get_nameservers(domain):
records = []
answers = resolver.query(domain, 'NS')
for rdata in answers:
records.append(rdata.to_text())
return records
def get_a_records(host):
records = []
answers = resolver.query(host, 'A')
for rdata in answers:
r... |
9848476 | import polyphony
import sub1
import sub2
from sub1 import func2 as func2_1
from sub2 import func2 as func2_2
def import06_a1(x):
return sub1.func1(x) + sub2.func1(x)
def import06_a2(x):
return func2_1(x) + func2_2(x)
@polyphony.testbench
def test():
assert 31 == import06_a1(10)
assert 42 == import... |
9848490 | from entity.Node import Node
class NetworkStructure:
def create_nodes(dump, num_of_features, hidden_nodes):
nodes = []
#--------------------------------
#input layer
if dump == True:
print("input layer: ", end='')
#-----------------------------... |
9848520 | import math
print ("Enter the a number")
number = int(input())
primes = []
for i in range(2,number+1):
primes.append(i)
i = 2
#from 2 to sqrt(number)
while(i <= int(math.sqrt(number))):
#if i is in list
#then we gotta delete its multiples
if i in primes:
#j will give multiples of i,
#... |
9848584 | from __future__ import absolute_import
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import tempfile
import numpy as np
from nose import SkipTest
from nipy.testing.decorators import skipif
try:
import matplotlib as mp
# Make really sure that ... |
9848587 | from pathlib import Path
from json import loads
from pkg_resources import resource_filename
from typing import List
from tdw.controller import Controller
from tdw.object_init_data import TransformInitData, AudioInitData
class FloorplanController(Controller):
"""
A controller that can create an interior scene ... |
9848601 | import logging.config
import torch
from utils.utils import calculate_accuracy, calculate_topk_accuracy, load_best_model
logging.config.fileConfig(fname='./config/config.logger', disable_existing_loggers=False)
logger = logging.getLogger("Evaluator")
class MultipleModelEvaluator(object):
def __init__(self, devic... |
9848618 | import pytest
import struct, py, sys
from jitlog.objects import (FlatOp, TraceForest, Trace,
MergePoint, iter_ranges, PointInTrace)
from jitlog import constants as const
from vmlog.views import (LogMetaSerializer, TraceSerializer,
VisualTraceTreeSerializer)
PY3 = sys.version_info[0] >= 3
def test_to_j... |
9848670 | from bfxhfindicators.indicator import Indicator
class PC(Indicator):
def __init__(self, period, offset, cache_size=None):
self._p = period
self._offset = offset
self._l = period + offset
self._buffer = []
super().__init__({
'args': [period, offset, cache_size],
'id': 'pc',
'nam... |
9848672 | from .auth import __THMAuth
from .instance import __THMInstance
from .koth import __THMKoth
from .leaderboard import __THMLeaderboard
from .room import __THMRoom
from .stats import __THMStats
from .team import __THMTeam
from .user import __THMUser
import requests
class THM(
__THMAuth,
__THMStats,
__THMLea... |
9848674 | from BlackBoxAuditing.model_factories.AbstractModelFactory import AbstractModelFactory
from BlackBoxAuditing.model_factories.AbstractModelVisitor import AbstractModelVisitor
from sklearn import svm
import numpy as np
import copy
class ModelFactory(AbstractModelFactory):
def __init__(self, *args, **kwargs):
... |
9848684 | import re
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import RedirectView
import localshop.apps.dashboard.urls
import localshop.apps.packages.urls
from localshop import views
from local... |
9848696 | import os
import sys
import argparse
import tensorflow as tf
sys.path.append((os.path.normpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)),
'..'))))
from model import OpenNsfwModel, InputType
"""Exports a tflite version of tensorflow-open_nsfw
Note: The ... |
9848729 | import paramiko
import sys
print("""
######################################
## ##
## PoC for CVE-2019-16864 ##
## Rhino Security Labs ##
## ##
######################################
""")
host = sys.argv[1]
user = sys.argv[2]
pass... |
9848759 | import pytest
from botocore.session import Session
# The list of services which were available when we switched over from using
# endpoint prefix in event to using service id. These should all accept
# either.
SERVICES = {
"acm": {
"endpoint_prefix": "acm",
"service_id": "acm"
},
"acm-pca... |
9848787 | from django.db import migrations
TENANT_TYPE = 'Packages.Template'
STORAGE_MODE_FIXED = 'fixed'
def drop_offering_components(apps, schema_editor):
"""
Drop offering components for volume types if storage mode is fixed.
"""
OfferingComponent = apps.get_model('marketplace', 'OfferingComponent')
Off... |
9848807 | from jobs.other_nodes_jobs import *
from jobs.thorchain_network_jobs import check_network_security_job, check_thorchain_constants_job
from jobs.thorchain_node_jobs import *
def setup_bot_jobs(dispatcher):
dispatcher.job_queue.run_repeating(general_bot_checks,
interval=JOB_IN... |
9848814 | import warnings
import pandas as pd
def load_data(
file_path, input_text_column, target_text_column, label_column, keep_label=1
):
df = pd.read_csv(file_path, sep="\t", error_bad_lines=False)
df = df.loc[df[label_column] == keep_label]
df = df.rename(
columns={input_text_column: "input_text",... |
9848893 | import numpy as np
import pandas as pd
from ruspy.estimation.est_cost_params import derivative_loglike_cost_params
from ruspy.estimation.est_cost_params import derivative_loglike_cost_params_individual
from ruspy.estimation.est_cost_params import loglike_cost_params
from ruspy.estimation.est_cost_params import loglike... |
9849007 | import inspect
from inspect import signature
import mxnet
import json
library = []
def gen_func(obj):
params = inspect.getfullargspec(obj)
print(params)
def gen_class_def(obj):
mlist = inspect.getmembers(obj, predicate=inspect.isfunction)
funclist = []
for name, mobj in mlist:
if inspec... |
9849042 | from .one_hot_decoder import *
from .one_hot_encoder import *
from .alternative_one_hot_decoder import *
from .alternative_one_hot_encoder import *
from .classifier import Classifier
from .encoder import *
from .decoder import *
from .auto_encoder import *
from .decoder_classifier import *
from .selective_decoder impor... |
9849052 | import glob
import numpy as np
import re
from configuration import config
import cPickle as pickle
import utils
from validation_set import get_cross_validation_indices
import random
print "Loading data"
patient_folders = sorted(glob.glob("/data/dsb15_pkl/pkl_train/*/study/"), key=lambda folder: int(re.search(r'/(\d+... |
9849069 | from habitat_extensions import actions, measures, obs_transformers, sensors
from habitat_extensions.config.default import get_extended_config
from habitat_extensions.task import VLNCEDatasetV1
|
9849083 | from __future__ import unicode_literals
import hashlib
import io
import logging
import os
import re
from collections import namedtuple
from random import randint
from django.conf import settings
from django.core import checks
from django.core.cache import cache
from django.core.exceptions import ValidationError
from ... |
9849128 | import cv2
import numpy as np
from skimage.segmentation import watershed
def segment_region_score(watershed_param, region_score, word_image, pseudo_vis_opt):
region_score = np.float32(region_score) / 255
fore = np.uint8(region_score > 0.75)
back = np.uint8(region_score < 0.05)
unknown = 1 - (... |
9849222 | import logging
import os.path
from gaphor.abc import ActionProvider, Service
from gaphor.core import action, gettext
from gaphor.ui.filedialog import open_file_dialog
from gaphor.ui.questiondialog import QuestionDialog
log = logging.getLogger(__name__)
FILTERS = [
(gettext("All Gaphor Models"), "*.gaphor", "app... |
9849230 | from netmiko.rad.rad_etx import RadETXSSH
from netmiko.rad.rad_etx import RadETXTelnet
__all__ = ["RadETXSSH", "RadETXTelnet"]
|
9849251 | from happytransformer import (
HappyGeneration,
ARGS_GEN_TRAIN,
ARGS_GEN_EVAl,
GENSettings,
GENTrainArgs,
GENEvalArgs
)
from tests.shared_tests import run_save_load
def test_default_simple():
happy_gen = HappyGeneration()
args = GENSettings(min_length=5, max_length=5)
output = happ... |
9849254 | import json
from binascii import hexlify
from dataclasses import dataclass
from datetime import datetime
from typing import List
import pytest
from mashumaro import DataClassJSONMixin, MissingField
from .entities import MyEnum
def test_to_json():
@dataclass
class DataClass(DataClassJSONMixin):
x: L... |
9849307 | from Codigo_3D.FuncionesPara3D import FuncionesPara3D
class Codigo3D():
t4 = t1
t6 = t10
t5 = t20
t6 = t9
t9 = res + res
t9 = 0
res = 0
|
9849329 | def onValueChange(channel, sampleIndex, val, prev):
# Output the patterns and capture the first image with pattern 0
op.ProjectorOutputs.op('switch_projection_map').par.index = 0
# Capture first image
op('tex3d_captures').par.resetpulse.pulse()
op('tex3d_captures').par.replaceindex = 0
op('tex3d_captures').par.r... |
9849424 | from unidecode import unidecode
def importDGER(fobj):
DGER = dict()
DGER['info'] = None
for bline in fobj.readlines():
try:
line = bline.decode('utf-8')
except:
line = unidecode(str(bline))
if not DGER['info']:
DGER['info'] = unidecode(str(line)).... |
9849536 | import torch
import numpy as np
from pathlib import Path
from torch.utils.data import Dataset, DataLoader
from matplotlib import colors, pyplot as plt
from numpy.fft import rfft, irfft
from scipy.io import wavfile
import torchaudio
# Set Audio backend as Sounfile for windows and Sox for Linux
torchaudio.set_audio_... |
9849552 | from tests.common.helpers.assertions import pytest_require
from tests.common.broadcom_data import is_broadcom_device
def skip_pfcwd_test(duthost, trigger_pfcwd):
"""
Skip PFC watchdog tests that may cause fake alerts
PFC watchdog on Broadcom devices use some approximation techniques to detect
PFC stor... |
9849574 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScAguasFriasSpider(FecamGazetteSpider):
name = "sc_aguas_frias"
FECAM_QUERY = "cod_entidade:10"
TERRITORY_ID = "4200556"
|
9849604 | import asyncio
import logging
import traceback
from discord.ext import commands
from .bilibili_api import NotBilibiliVideo
from .bilibili_downloader import BilibiliVideo
logger = logging.getLogger(__name__)
class VoiceEntry:
def __init__(self, message, player):
self.requester = message.author
sel... |
9849612 | from __future__ import absolute_import, division
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from sentry.models import Group, GroupMeta
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectV... |
9849648 | class PyrezException(Exception):
"""Base exception for this library, catch-all for most Pyrez issues."""
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args[1]) if self.args else 'An unknown error has occured within Pyrez'
class InvalidTime(PyrezE... |
9849663 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from ...users.models.model_patient import Patient
from django.core.validators import MinValueValidator
class Curves(models.Model):
patient = models.ForeignKey(
Patient,
on_delete=models.CASCADE,
verbose_n... |
9849665 | import pytest
from mock import patch
from m3d.hadoop.algorithm.algorithm_configuration_hadoop import AlgorithmConfigurationHadoop
from m3d.hadoop.algorithm.algorithm_materialization import AlgorithmMaterialization
from m3d.hadoop.emr.emr_system import EMRSystem
from test.core.emr_system_unit_test_base import EMRSystem... |
9849756 | DEFAULT_CELERY_BROKER_LOGIN_METHOD = 'AMQPLAIN'
DEFAULT_CELERY_BROKER_URL = 'memory://'
DEFAULT_CELERY_BROKER_USE_SSL = None
DEFAULT_CELERY_RESULT_BACKEND = None
TEST_CELERY_RESULT_KEY = '__mayan_test_result'
TEST_CELERY_RESULT_VALUE = 'test'
WORKER_DEFAULT_CONCURRENCY = 0
|
9849800 | import logging
from mayan.apps.documents.models.document_models import Document
from mayan.apps.documents.permissions import (
permission_document_create, permission_document_file_new
)
from mayan.apps.documents.tests.base import DocumentTestMixin
from mayan.apps.sources.tests.mixins.base_mixins import (
Docum... |
9849864 | from zope.interface import implementer
from twisted.internet.defer import succeed
from .._interfaces import IProbe, IOperation
@implementer(IProbe)
class NoOpProbe(object):
"""
A probe that performs no operation.
"""
def run(self):
return succeed(None)
def cleanup(self):
return... |
9849868 | import numpy as np
from pandas import DataFrame, Series, date_range
from pandas.core.algorithms import checked_add_with_arr
try:
import pandas.core.computation.expressions as expr
except ImportError:
import pandas.computation.expressions as expr
class Ops(object):
params = [[True, False], ['default', 1]]... |
9849869 | from util.net import UrlQuery
from util.primitives.mapping import odict
from contacts.Group import Group
from facebook.fbacct import pstr_to_list, pstring
from facebook.fbconnectlogin import LOGIN_SUCCESS_PAGE
from facebook.facebookapi import db_rows_to_dict
import traceback
import jabber
from logging import getLogger
... |
9849875 | import numpy as np
import torch
def get_batches(model, sentences, max_batch, training=True):
"""
Partitions a list of sentences (each a list containing [word, label]) into a set of batches
Returns:
-- batched_sents: original tokens in sentences
-- batched_orig_token_lens: length of original tokens in s... |
9849884 | import re
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.generic.base import RedirectView
from .views import (OldIndexView,
UserProfileView,
MergeProjectView,
TestSlackView,
TestWe... |
9849910 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from .chart import Chart
class PieChart(Chart):
TYPE = "pieChart"
|
9849958 | from pypy.conftest import gettestobjspace
import py
import errno
def setup_module(mod):
mod.space = gettestobjspace(usemodules=['errno'])
class AppTestErrno:
def setup_class(cls):
cls.space = space
cls.w_errno = space.appexec([], "(): import errno ; return errno")
cls.w_errorcode = ... |
9849961 | import botocore
import botocore.exceptions
from . import Terminator
class S3Bucket(Terminator):
@staticmethod
def create(credentials):
return Terminator._create(credentials, S3Bucket, 's3', lambda client: client.list_buckets()['Buckets'])
@property
def name(self):
return self.instanc... |
9849982 | import torch
import torch.nn as nn
import torch.nn.functional as F
'''
Adopted from https://github.com/passalis/probabilistic_kt/blob/master/nn/pkt.py
'''
class PKTCosSim(nn.Module):
'''
Learning Deep Representations with Probabilistic Knowledge Transfer
http://openaccess.thecvf.com/content_ECCV_2018/papers/Nikolao... |
9849994 | from odl.ufunc_ops.ufunc_ops import log_op
from dival.evaluation import TaskTable
from dival.measure import PSNR, SSIM
from dival.reconstructors.odl_reconstructors import FBPReconstructor
from dival.datasets.standard import get_standard_dataset
from dival.util.constants import MU_MAX
# %% data
dataset = get_standard_d... |
9850069 | import os.path
from collections import OrderedDict
import execjs.runtime_names as runtime_names
import execjs._external_runtime as external_runtime
import execjs._pyv8runtime as pyv8runtime
import execjs._exceptions as exceptions
def register(name, runtime):
'''Register a JavaScript runtime.'''
_runtimes.app... |
9850077 | import time
import logging
import math
try:
import pygame
from pygame.locals import K_r
from pygame.locals import K_p
from pygame.locals import K_ESCAPE
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportEr... |
9850082 | import math
import time
class Client(object):
queues = {}
task_data = {}
def __init__(self, conn_string):
"""
An in-memory `Client`. Useful for development & testing.
Likely not particularly thread-safe.
Args:
conn_string (str): The DSN. Ignored.
"""
... |
9850088 | import torch
from torch import nn
from torch.nn.init import xavier_uniform
import math
import numpy as np
class Identity(torch.nn.Module):
def forward(self, input):
return input
def parse_stage_config(stage_cfg):
if isinstance(stage_cfg, int):
return (stage_cfg,), stage_cfg
elif isinstan... |
9850147 | from django.core.management.base import BaseCommand
from zentral.contrib.monolith.models import ManifestEnrollmentPackage
from zentral.contrib.monolith.utils import build_manifest_enrollment_package
class Command(BaseCommand):
help = 'Rebuild monolith manifest enrollment packages.'
def handle(self, *args, **... |
9850155 | from __future__ import division
def return_three():
return 3
def return_two():
return 2
def f1():
return 3 / 2
def f2():
return return_three() / return_two()
def f3(x):
if isinstance(x, float):
return x / 2
else:
return (1.0 * x) / 2
def f4():
do_stuff(f3(1))
do_stu... |
9850174 | import argparse
def populate_experiment_params(
arg_parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
arg_parser.add_argument('--root', default='data/signal-game/',
help='data root folder')
# 2-agents specific parameters
arg_parser.add_argument('--tau_s', ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.