id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1771679 | import os, random
from collections import OrderedDict
import numpy as np
import tensorflow as tf
from gcg.policies.gcg_policy import GCGPolicy
from gcg.data.file_manager import FileManager
from gcg.data.logger import logger
from gcg.tf import tf_utils
class GCGPolicyTfrecord(GCGPolicy):
tfrecord_feature_names =... |
1771696 | import collections
from distutils.dir_util import copy_tree
import functools
import logging
import inspect
import os
import random
import socket
import string
import sys
import tempfile
import time
from gym.utils import seeding
import hermes.backend.dict
import hermes.backend.redis
import numpy as np
import ray
import... |
1771731 | import json
from unittest import skipUnless
from twisted.python.procutils import which
from flocker.node.diagnostics import list_hardware
from flocker.testtools import TestCase
class ListHardwareTests(TestCase):
@skipUnless(which('lshw'), 'Tests require the ``lshw`` command.')
def test_list_hardware(self):... |
1771756 | from azureml.core import Workspace, Environment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.runconfig import RunConfiguration
from azureml.pipeline.core import Pipeline, PipelineEndpoint
from azureml.pipeline.core._restclients.aeva.models.error_response import ErrorResponseException
... |
1771794 | import asyncio
import apigpio
import functools
# This sample demonstrates both writing to gpio and listening to gpio changes.
# It also shows the Debounce decorator, which might be useful when registering
# a callback for a gpio connected to a button, for example.
BT_GPIO = 18
LED_GPIO = 21
class Blinker(object):
... |
1771805 | pkgname = "itstool"
pkgver = "2.0.7"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["python", "libxml2-python"]
makedepends = list(hostmakedepends)
depends = list(makedepends)
pkgdesc = "ITS Tool"
maintainer = "q66 <<EMAIL>>"
license = "GPL-3.0-or-later"
url = "http://itstool.org"
source = f"http://files.i... |
1771840 | from .endpoint import Endpoint, api
from .exceptions import JobCancelledException, JobFailedException
from .. import JobItem, BackgroundJobItem, PaginationItem
from ..request_options import RequestOptionsBase
from ...exponential_backoff import ExponentialBackoffTimer
import logging
logger = logging.getLogger("tableau... |
1771917 | import numpy as np
from src.utils.core import convert_prob2one_hot
def softmax_accuracy(y_hat: np.array, y: np.array) -> float:
"""
:param y_hat - 2D one-hot prediction tensor with shape (n, k)
:param y - 2D one-hot ground truth labels tensor with shape (n, k)
----------------------------------------... |
1771920 | from .product import Product
from .customer import Customer
from .student_customer import StudentCustomer
from .experiment import Experiment
import numpy as np
class MessyExperiment(Experiment):
"""
This is a messier version of the experiment in which
there are student customers as well and student custom... |
1771948 | import json
from datetime import datetime
class Kestra:
def __init__(self):
pass
@staticmethod
def _send(map):
print("::" + json.dumps(map) + "::")
@staticmethod
def _metrics(name, type, value, tags=None):
Kestra._send({
"metrics": [
{
... |
1772005 | from psana import DataSource
from psana import container
from psana.psexp.utils import DataSourceFromString
import numpy as np
import argparse
def dump(obj, attrlist):
allattrs = dir(obj)
usefulattrs=[attr for attr in allattrs if (not attr.startswith('_') and attr != 'help')]
for attr in usefulattrs:
... |
1772078 | import torch
import torch.nn as nn
def infoLOOB_loss(x, y, i, inv_tau):
tau = 1 / inv_tau
k = x @ y.T / tau
positives = -torch.mean(torch.sum(k * i, dim=1))
# For logsumexp the zero entries must be equal to a very large negative number
large_neg = -1000.0
arg_lse = k * torch.logical_not(i) + ... |
1772157 | from urllib.parse import urlparse
from aiodogstatsd import Client
def get_statsd_client(address="udp://127.0.0.1:8125", **kw):
res = urlparse(address)
return Client(host=res.hostname, port=res.port, **kw)
|
1772167 | from typing import List
from unittest import TestCase
from oci.core import ComputeClient, ComputeClientCompositeOperations
from oci.core.models.instance import Instance
from oci.response import Response
from oci.exceptions import ServiceError
from oci_emulator import app
from app.enums.compute.instance_action import ... |
1772199 | from .Solver import *
class SGD(Solver):
def __init__(self, *args, **kwargs):
Solver.__init__(self, *args, **kwargs)
def update(self, l):
params = l.params
grads = l.grads
mlr = self.lr * l.lr
for i in range(len(grads)):
params[i] -= grads[i] * mlr
|
1772212 | import FreeCAD, FreeCADGui
class ArchTextureWorkbench (FreeCADGui.Workbench):
"Texture Architectural objects in FreeCAD"
MenuText = "Arch Texture"
ToolTip = "Texture architectural objects"
def __init__(self):
from arch_texture_utils.resource_utils import iconPath
self.__class__.Icon =... |
1772244 | import torch
import torch.nn as nn
import torch.nn.functional as func
def _compute_indices(data, indices, counts, max_count):
offset = max_count - counts
offset = offset.roll(1, 0)
offset[0] = 0
offset = torch.repeat_interleave(offset.cumsum(dim=0), counts, dim=0)
offset = offset.to(data.device)
index = o... |
1772254 | import alog
import pytest
from mock import PropertyMock, MagicMock, mock
from bitmex_websocket import Instrument
from bitmex_websocket._instrument import SubscribeToAtLeastOneChannelException, \
SubscribeToSecureChannelException
from bitmex_websocket.constants import Channels, SecureChannels, \
SecureInstrumen... |
1772263 | import os
import pickle
import numpy as np
from categorical.models import sample_joint
def intervention_distances(k, n, concentration, intervention, dense_init=True):
"""Sample n mechanisms of order k and for each of them sample an intervention on the desired
mechanism. Return the distance between the origi... |
1772324 | import sys
import toolshed as ts
from sklearn import preprocessing
import numpy as np
regions, weighted = [], []
totlen=0.0
for d in ts.reader(sys.argv[1]):
totlen+=int(d['end'])-int(d['start'])
regions.append(d)
header = ts.header(sys.argv[1])
print "\t".join(header) + "\t" + "weighted_pct"
pct=100.0; regio... |
1772334 | from .common_utils import create_tsv
from .feature_utils import dump_features
from .kmeans import learn_kmeans, get_km_label
__all__ = [
"create_tsv",
"dump_features",
"learn_kmeans",
"get_km_label",
]
|
1772344 | from icevision.backbones.vgg import *
from icevision.backbones.resnet import *
from icevision.backbones.mobilenet import *
import icevision.backbones.resnet_fpn
import icevision.backbones.resnest_fpn
|
1772375 | import tensorflow as tf
_CSV_COLUMNS = [
'age', 'workclass', 'fnlwgt', 'education', 'education_num',
'marital_status', 'occupation', 'relationship', 'race', 'gender',
'capital_gain', 'capital_loss', 'hours_per_week', 'native_country',
'income_bracket'
]
_CSV_COLUMN_DEFAULTS = [[0], [''], [0], [''], [0... |
1772508 | import pkg_resources
__product__ = 'aws-emr-launch'
__version__ = pkg_resources.get_distribution(__product__).version
__package__ = f'{__product__}-{__version__}'
|
1772512 | from brownie import *
from .contract_addresses import *
import time
# Custom parameters
TENPOW18 = 10 ** 18
# Number of tokens you wish to auction, you must be able to transfer these
AUCTION_TOKENS = 1000 * TENPOW18
AUCTION_DAYS = 20
# Dutch auctions start at a high price per token
AUCTION_START_PRICE = 100 * TENPOW1... |
1772525 | import django
import sys,os
rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\","/")
rootpath = rootpath.split("/apps")[0]
# print(rootpath)
syspath=sys.path
sys.path=[]
sys.path.append(rootpath) #指定搜索路径绝对目录
sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路... |
1772541 | import os
import sys
import traceback
def find_class(class_str):
mod_str, _sep, class_str = class_str.rpartition('.')
__import__(mod_str)
try:
return getattr(sys.modules[mod_str], class_str)
except AttributeError:
raise ImportError('Class %s cannot be found (%s)' %
(clas... |
1772588 | from .experiment import Experiment
from .task_runner import TaskRunner
__all__ = [ "Experiment", "TaskRunner" ] |
1772634 | import numpy as np
import keras.backend as K
from keras.layers import Layer, merge, RepeatVector
class InteractionRNN(Layer):
""" output response of two input tensors """
def __init__(self, RNN, num_steps, DNN=None, **kwargs):
self.RNN = RNN
self.num_steps = num_steps
self.DNN = DNN
... |
1772644 | from aiocqhttp import Error as CQHttpError
__all__ = [
'CQHttpError',
]
__autodoc__ = {
"CQHttpError": "等价于 `aiocqhttp.Error`。"
}
|
1772647 | from trame.app import get_server
from trame.widgets import trame, vuetify, html, client
from trame.ui.vuetify import SinglePageLayout
from trame.ui.html import DivLayout
# -----------------------------------------------------------------------------
# Trame setup
# -----------------------------------------------------... |
1772687 | from math import ceil, floor
import numpy as np
import math
import plotly.express as px
import plotly.graph_objects as go
from my_project.global_scheme import template, mapping_dictionary, month_lst
def custom_heatmap(df, global_local, var, time_filter_info, data_filter_info):
"""Return the customizable heatmap.... |
1772696 | from collections import abc, OrderedDict
from .line import Unknown, Dialogue, Movie, Command, Sound, Picture, Comment, Style
from .data import _Field
__all__ = (
'LineSection',
'FieldSection',
'EventsSection',
'StylesSection',
'ScriptInfoSection',
)
class LineSection(abc.MutableSequence):
FO... |
1772711 | import numpy as np
from convolve_nd import convolvend as convolve
def correlate2d(im1,im2, boundary='wrap', **kwargs):
"""
Cross-correlation of two images of arbitrary size. Returns an image
cropped to the largest of each dimension of the input images
Options
-------
return_fft - if true, ret... |
1772714 | data = (
'bols', # 0x00
'bolt', # 0x01
'bolp', # 0x02
'bolh', # 0x03
'bom', # 0x04
'bob', # 0x05
'bobs', # 0x06
'bos', # 0x07
'boss', # 0x08
'bong', # 0x09
'boj', # 0x0a
'boc', # 0x0b
'bok', # 0x0c
'bot', # 0x0d
'bop', # 0x0e
'boh', # 0x0f
'bwa', # 0x10
'bwag', # 0x... |
1772746 | import json
import logging as log
import base64
def lambda_handler(event, context):
print("Target Lambda function invoked")
print(event)
if 'rmqMessagesByQueue' not in event:
print("Invalid event data")
return {
'statusCode': 404
}
print(f'Div Data received from even... |
1772752 | import tempfile
from io import BytesIO
from os import path
from pathlib import Path
from unittest import mock
import apsw
import pytest
from common.tests import factories
from exporter.sqlite import plan
from exporter.sqlite import tasks
from exporter.sqlite.runner import Runner
from workbaskets.validators import Wor... |
1772768 | from .util import (
old_new_new,
DEFAULT_PIN,
DEFAULT_MANAGEMENT_KEY,
NON_DEFAULT_MANAGEMENT_KEY,
)
import re
import pytest
class TestManagementKey:
def test_change_management_key_force_fails_without_generate(self, ykman_cli):
with pytest.raises(SystemExit):
ykman_cli(
... |
1772818 | from setuptools.extension import Extension
from setuptools import setup, find_packages
extensions = [Extension("quicksect", ["src/quicksect.pyx"])]
setup(version='0.2.2',
name='quicksect',
description="fast, simple interval intersection",
long_description=open('README.rst').read(),
author="<NAME>... |
1772828 | from django.views.generic import RedirectView
from rest_framework import viewsets
from sample.models import Product
from sample.serializers import ProductSerializer
class HomepageView(RedirectView):
url = '/api/'
class AbstractHowItWorksViewSet(viewsets.ModelViewSet):
called_counter = 0
def get_que... |
1772831 | from pathlib import Path
from typing import Literal, Optional, Tuple
import healpy
import numpy as np
from caput import config, pipeline
from cora.core import skysim
from cora.util import hputil, units
from cora.util.cosmology import Cosmology
from cora.util.pmesh import (
_bin_delta,
_pixel_weights,
_rad... |
1772867 | import k3d
import numpy as np
import pytest
from .plot_compare import *
import vtk
from vtk.util import numpy_support
def test_volume():
prepare()
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName('./test/assets/volume.vti')
reader.Update()
vti = reader.GetOutput()
x, y, z = vti.GetDim... |
1772894 | from django.contrib import admin
from .models import FirewallConfig
@admin.register(FirewallConfig)
class FirewallConfigAdmin(admin.ModelAdmin):
list_display = ("hostname", "api_key", "panorama")
|
1772923 | import numpy as np
import random
def classification1(y):
if (y[0] >= 0.2) and (y[1] < 0.1):
return 0
elif (y[0] >= -0.5) and (y[0] < -0.25):
return 1
elif (y[0] > 0.4) and (y[1] >= 0.15):
return 2
elif y[1] < 0:
return 3
else:
return 4
def split_data(y)... |
1772931 | import pickle
import random
import torch
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import Sampler
from wavernn_vocoder.utils.dsp import *
from wavernn_vocoder.utils import hparams as hp
from wavernn_vocoder.utils.text import text_to_sequence
from wavernn_vocoder.utils.paths import P... |
1772973 | import numpy as np
import metriks
def test_label_mrr_with_errors():
y_true = np.array([[0, 1, 1, 0],
[1, 1, 1, 0],
[0, 1, 1, 1]])
y_prob = np.array([[0.2, 0.9, 0.8, 0.4],
[0.9, 0.2, 0.8, 0.4],
[0.2, 0.8, 0.9, 0.4]])
... |
1772981 | import requests
from plugins.oob import verify_request, gen_oob_domain
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Seagate BlackArmor NAS - Command Injection''',
"description": '''Seagate BlackArmor NAS allows remote attackers to execute arbitrary code via the... |
1773026 | import scipy.sparse as sp
from scipy.sparse import linalg
import numpy as np
import torch
import torch.nn as nn
from logging import getLogger
from libcity.model.abstract_traffic_state_model import AbstractTrafficStateModel
from libcity.model import loss
def calculate_normalized_laplacian(adj):
"""
L = D^-1/2 ... |
1773041 | import gym
import sonnet as snt
import tensorflow as tf
import numpy as np
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
def build_logits(action_space, latent_vec):
if isinstance(action_space, gym.spaces.Discrete):
return snt.Linear(output_size=action_space.n,
initializers... |
1773066 | from django.utils.decorators import method_decorator
from django.views.generic import View
from django.views.generic.base import ContextMixin
from jsonview.decorators import json_view
class JsonView(ContextMixin, View):
def get_context_data(self, **kwargs):
return {}
def get(self, request, *args, *... |
1773107 | import json
import os
import urllib.parse
import uvicorn
from fastapi import FastAPI, HTTPException, Request, BackgroundTasks, Depends, Body, Response
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from fastapi.exception_handlers import (
http_exception_handler,
reques... |
1773120 | import math
import numpy as np
import pandas as pd
import hashlib
import sys
import os
import shutil
import cv2
import tempfile
from google.cloud import storage
from tqdm import tqdm
import statistics
import torch
import PIL
from PIL import Image, ImageDraw
vis_tmp_path = "/tmp/detect/" #!!!don't spe... |
1773125 | from cryptokit.base58 import get_bcaddress_version
from gevent import spawn
from .lib import loop
import socket
import datetime
import re
class GenericClient(object):
def convert_username(self, username):
# if the address they passed is a valid address,
# use it. Otherwise use the pool address
... |
1773155 | def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
i = i + 1
arr[i], arr[high] = arr[high], arr[i]
return i
def do_quicksort(arr, left, right):
if left < right:... |
1773184 | from random import randint
from gmpy2 import gcd, invert
from pwn import *
from base64 import b64encode
def ext_gcd(a, b):
c0, c1 = a, b
a0, a1 = 1, 0
b0, b1 = 0, 1
while c1 != 0:
q, m = divmod(c0, c1)
c0, c1 = c1, m
a0, a1 = a1, (a0 - q*a1)
b0, b1 = b1, (b0 - q*b1)
... |
1773187 | import argparse
import sqlite3
from flask import Flask, jsonify, send_from_directory
from flask_cors import CORS
# http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
from werkzeug.utils import redirect
app = Flask(__name__)
CORS(app)
def read_calling_points(all_points):
points = [... |
1773196 | import argparse
from collections import defaultdict
import cv2, os
from pytorch_toolbelt.inference.tiles import ImageSlicer
from pytorch_toolbelt.utils import fs
from pytorch_toolbelt.utils.fs import id_from_fname, read_image_as_is
import pandas as pd
from tqdm import tqdm
from inria.dataset import TRAIN_LOCATIONS, r... |
1773226 | import doxygen_parsing
import inspect
import string
import os
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_parsing.someFunction),
"The function comment")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeClass),
"The class comment")
comment_verifier.check(inspect.get... |
1773232 | import win32clipboard
from pytube import YouTube
try:
# get clipboard data
win32clipboard.OpenClipboard()
link = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
except Exception as ex:
print('Error : ',e)
exit()
try:
#where to save
SAVE_PATH = "F:\\Python Program... |
1773242 | from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten, Lambda
from keras.optimizers import Adam, SGD
from keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau
from ke... |
1773253 | from enum import Enum
class ReportKeys(Enum):
Tasks = ['TaskID', 'Context', 'Command', 'Output', 'User', 'SentTime', 'CompletedTime', 'ImplantID']
C2Server = ['ID', 'PayloadCommsHost', 'EncKey', 'DomainFrontHeader', 'DefaultSleep', 'KillDate', 'GET_404_Response', 'PoshProjectDirectory', 'QuickCommand', 'Downlo... |
1773286 | from util.Docker import Docker
class Dredd:
image = 'weaveworksdemos/openapi'
container_name = ''
def test_against_endpoint(self, json_spec, endpoint_container_name, api_endpoint, mongo_endpoint_url,
mongo_container_name):
self.container_name = Docker().random_contai... |
1773327 | import random
import numpy as np
import pandas as pd
def remove_unlinked_triples(triples, linked_ents):
print("before removing unlinked triples:", len(triples))
new_triples = set()
for h, r, t in triples:
if h in linked_ents and t in linked_ents:
new_triples.add((h, r, t))
print("... |
1773395 | import tensorflow as tf
import tensorflow_probability as tfp
import sonnet as snt
class NNNormalDistribution(tf.Module):
"""A Normal distribution with mean and var parametrised by NN"""
def __init__(self,
size,
hidden_layer_sizes,
sigma_min=0.0,
... |
1773415 | import copy
import pandas as pd
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import Legend, Span
# from bokeh.models import HoverTool
from ..utils import in_ipynb
from .plotobj import BasePlot
from .plotutils import get_color
_INITED = False
class BokehPlot(BasePlot):
def __init__(s... |
1773448 | import socket
from nwalign import global_align
import sys
import atexit
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 1233
CHUNK = 32768 * 8
HOST = 'localhost'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(4)
print "\nstarted server on %s:%i\n" % (HOST, PORT)
... |
1773457 | import zipfile
import io
import tempfile
import traceback
from collections import namedtuple
import rx
import rx.operators as ops
import rxsci as rs
from cyclotron.debug import trace_observable
from makinage.util import import_function
from mlflow.pyfunc import load_model
from mlflow.pyfunc.backend import PyFuncBack... |
1773481 | import pytest # noqa
import py_cui
def test_move_right(SCROLLTEXTBLOCK):
text_box = SCROLLTEXTBLOCK('Hello World')
text_box._move_right()
cursor_x, _ = text_box.get_abs_cursor_position()
text_x, _ = text_box.get_cursor_text_pos()
assert text_x == 1
assert cursor_x == 43
def test_move_left_s... |
1773491 | from api import BCFerriesAPI
from terminal import BCFerriesTerminal
from abstract import BCFerriesAbstractObject
from decorators import cacheable, fuzzy
from urlparse import urlparse
from geopy.distance import distance
import functools32, os
class BCFerries(BCFerriesAbstractObject):
DEFAULT_API_ROOT = 'http://mobil... |
1773496 | import gym
import hydra
from omegaconf import DictConfig
from rlcycle.common.abstract.action_selector import ActionSelector
from rlcycle.common.abstract.learner import LearnerBase
from rlcycle.common.abstract.loss import Loss
from rlcycle.common.models.base import BaseModel
from rlcycle.common.utils.env_generator impo... |
1773508 | from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Annalist class for processing a row of field mappings for conversion between
entity values context values and form data.
A FieldRowValueMap is an object that can be inserted into an entity view value
mapping t... |
1773525 | import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from IPython.display import display, Markdown, HTML
def ambiguous_examples_analysis(workspace_pd, lang_util, threshold=0.7):
"""
Analyze the test workspace and find out similar utterances that belongs to differ... |
1773559 | from typing import List
from uuid import UUID, uuid4
import aiounittest
from botframework.streaming import ReceiveRequest
from botframework.streaming.payloads import StreamManager
from botframework.streaming.payloads.assemblers import (
ReceiveRequestAssembler,
PayloadStreamAssembler,
)
from botframework.strea... |
1773564 | from environment import *
from pg import *
import pickle as pl
np.seterr(all='raise')
params = {'lane_width': 4,
'num_scenarios': 1000,
'pos_var': 0.3,
'num_episodes': 6,
'num_trainings_after_simulation': 10,
'num_iterations': 1000,
'num_nds': 10,
... |
1773567 | from archivekit.package import Package
from archivekit.ingest import Ingestor
class Collection(object):
""" The list of all packages with an existing manifest which exist in
the given storage """
def __init__(self, name, store):
self.name = name
self.store = store
def create(self, id... |
1773570 | from pathlib import Path
from python.handwritten_baseline.pipeline.data.base import BaselineDataLoaderStage
class FccLoaderBaseStage(BaselineDataLoaderStage):
def __init__(self, pos, config, config_global, logger):
super(FccLoaderBaseStage, self).__init__(pos, config, config_global, logger)
sel... |
1773591 | import numpy as np
from cardinal.clustering import KCenterGreedy
def test_k_center_greedy():
# Those points are crafted so that they are selected in order by
# k center greedy, no matter batch size
X = np.array([
[ 0, 0],
[64, 1],
[32, 0],
[16, 1],
[ 8, 0],
... |
1773668 | from .crud_user import user
from .crud_hero import hero
from .crud_team import team
from .crud_role import role
from .crud_group import group |
1773742 | from pyrxnlp.api import util
class TextSimilarity:
def __init__(self, apikey, clean=False):
self.apikey = apikey
self.clean = clean
def make_request(self, text1, text2):
if util.check_key(self.apikey):
data = {}
data['text1'] = text1
data['text2'] ... |
1773842 | import os
from subprocess import call
from .HTMLTestRunner import HTMLTestRunner
from .SendEmail import SendMail
__all__ = ["make_report", "make_image", "send_report"]
def make_report(stream, data, theme=None,
stylesheet=None, htmltemplate=None, javascript=None):
test_runner = HTMLTestRunner(str... |
1773851 | import os
import falcon
from falcon import testing
from .dataset_fixtures import *
test_auth = "<KEY>"
def test_git_refs_resource(client):
ds_id = 'ds000001'
response = client.simulate_get(
'/git/0/{}/info/refs?service=git-receive-pack'.format(ds_id), headers={"authorization": test_auth})
asse... |
1773868 | import io
import os
import platform
from unittest import mock
import pytest
from bplustree.node import LeafNode, FreelistNode
from bplustree.memory import (
FileMemory, open_file_in_dir, WAL, ReachedEndOfFile, write_to_file
)
from bplustree.const import TreeConf
from .conftest import filename
from bplustree.seria... |
1773874 | from datetime import datetime
from typing import List
from grapl_common.metrics.metric_reporter import MetricReporter, TagPair
from grapl_common.time_utils import MillisDuration
class TestMetricReporter:
def test__smoke_test(self) -> None:
f = Fixture()
tags = (TagPair("k1", "v1"), TagPair("k2", ... |
1773889 | import math
import numpy as np
from scipy.interpolate import interp1d
import pytransform3d.rotations as pr
import pytransform3d.batch_rotations as pbr
import pytransform3d.transformations as pt
EPSILON = 1e-10
class CouplingTermObstacleAvoidance2D: # for DMP
"""Coupling term for obstacle avoidance in 2D."""
... |
1773911 | import warnings
from typing import Any, Dict, Optional, Union
import numpy as np
import pandas as pd
from scipy import sparse as sps
from sklearn.linear_model import LogisticRegression
from .util import benchmark_convergence_tolerance, runtime
def _build_and_fit(model_args, train_args):
return LogisticRegressio... |
1774006 | import pytest
from zum.requests.errors import (
InvalidBodyParameterTypeError,
MissingEndpointParamsError,
)
from zum.requests.helpers import cast_parameter, cast_value, reduce_arguments
class TestReduceArguments:
def setup_method(self):
self.keys = ["first", "second", "third"]
self.short... |
1774021 | import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
def lag_finder(x1, y1, x2, y2):
n = len(y1)
if len(y1) > len(y2):
i_match = np.argwhere(np.in1d(x1, x2)).flatten()
print(i_match)
y2 = np.append(np.zeros([1, i_match[0]]), y2)
y2 = np.append(y2, np.zeros... |
1774050 | from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import DjangoObjectPermissions
from ..models import Form, FormResponse
from ..serializers import FormSerializer, FormResponseSerializer
class FormViewSet(ModelViewSet):
queryset = Form.objects.all()
serializer_class = FormSerial... |
1774051 | import os
import sys
from jinja2 import Environment, FileSystemLoader
# Set the template environment.
env = Environment(loader=FileSystemLoader(os.path.abspath(os.path.join(
os.path.dirname(__file__), 'templates'))))
# Application wrapped by the debugger.
_debugged_app = None
# werkzeug.debug.utils
def get_tem... |
1774065 | from argparse import ArgumentParser
class ArgParser:
def __init__(self):
description = 'Usage: python proxy_crawler.py -u '
description += '<https://example.com> -k <search keyword>'
self.parser = ArgumentParser(description=description)
self.parser.add_argument(
'-u', '... |
1774088 | import json
import inspect
from functools import wraps
from warnings import warn
from client_encryption.field_level_encryption_config import FieldLevelEncryptionConfig
from client_encryption.session_key_params import SessionKeyParams
from client_encryption.field_level_encryption import encrypt_payload, decrypt_payload
... |
1774112 | from cps_thumb_t2 import CpsThumbT2
from nop_t2 import NopT2
from yield_t2 import YieldT2
from wfe_t2 import WfeT2
from wfi_t2 import WfiT2
from sev_t2 import SevT2
def decode_instruction(instr):
if instr[21:24] != "0b000":
# Change Processor State
return CpsThumbT2
elif instr[21:24] == "0b000... |
1774169 | from __future__ import absolute_import
__all__ = ['Feature', 'OrganizationFeature', 'ProjectFeature',
'ProjectPluginFeature']
class Feature(object):
def __init__(self, name):
self.name = name
def has(self, actor):
"""
A feature may return one of three values:
- Tr... |
1774173 | import pytest
from pysnark import runtime
@pytest.fixture(scope="session")
def disable_output():
"""
Disables all circuit outputs when running tests
"""
yield
runtime.autoprove = False |
1774190 | import base64
import json
import mimetypes
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from itertools import chain
from typing import TYPE_CHECKING, Any, AsyncIterable, Dict, List, Optional, Union
from xml.etree import ElementTree
from httpx import URL, AsyncClient
from pydanti... |
1774207 | import sys
from PyQt5.QtCore import QUrl, QMetaObject, Q_ARG, QVariant, QTimer, \
QDate
from PyQt5.QtQuickWidgets import QQuickWidget
from PyQt5.QtWidgets import QApplication
counter = 0
def onTimeout(obj):
global counter
value = {"lesson": str(counter), "subject": "PE", "day": QDate.longDayName(1 + cou... |
1774226 | import csv
lines = ['LINE_WN', 'LINE_WM', 'LINE_WSEA', 'LINE_WS', 'LINE_P', 'LINE_S',
'LINE_T', 'LINE_N', 'LINE_I', 'LINE_PX', 'LINE_NW', 'LINE_J', 'LINE_SL']
class GlobalVariables:
def __init__(self):
self.LinesStations = {} # 各營運路線車站於運行圖中的位置,用於運行線的繪製
self.LinesStationsFor... |
1774270 | from django.db import models
class FeaturesHelpText(models.Model):
auctions = models.TextField(default="Help text description here!")
wishlist = models.TextField(default="Help text description here!")
mailinglist = models.TextField(default="Help text description here!")
google_analytics = models.TextFi... |
1774272 | import pymssql
def handler(event, context):
conn = pymssql.connect(
host=r'docker.for.mac.host.internal',
user=r'SA',
password=r'<PASSWORD>',
database='TestDB'
)
cursor = conn.cursor()
cursor.execute('SELECT * FROM inventory WHERE quantity > 152')
result = ... |
1774281 | from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, create_achievement, create_variable, create_goals, create_goal_properties, create_goal_evaluation_cache
from gengine.app.model import Achievement, User, Goal, Value
class TestEvaluateGoal(BaseDBTest):
def test_comput... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.