id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9839786 | from z3 import *
[var_x0, var_x1] = Reals('var_x0, var_x1')
var_constraints = [var_x0 >= Q(-5,1), var_x0 <= Q(5,1), var_x1 >= Q(-5,1), var_x1 <= Q(5,1)]
constraints = []
f = (Q(1, 1) - (var_x0 * var_x1))
opt = Optimize()
opt.add(var_constraints + constraints)
result = opt.maximize(f)
opt.check()
print('max = {0}'.... |
9839884 | import torch
import torch.nn as nn
import torchvision
import numpy as np
from model.pytorch_i3d import Unit3D
from model.timeception.nets import timeception_pytorch
# 2D CNN + Timeception
# Timeception for Complex Action Recognition
# https://arxiv.org/abs/1812.01289
class CnnTc(nn.Module):
def __init__(self, in... |
9839918 | from a10sdk.common.A10BaseClass import A10BaseClass
class HealthPostfile(A10BaseClass):
""" :param remote_file: {"optional": true, "type": "string", "description": "Profile name for remote url", "format": "url"}
:param postfilename: {"description": "Specify the File Name", "format": "string", "minLeng... |
9839942 | from .. import Parser, parser, LegacyItemAccess
from insights.specs import Specs
@parser(Specs.ovirt_engine_confd)
class OvirtEngineConfd(LegacyItemAccess, Parser):
def parse_content(self, content):
self.data = dict((k.strip('" '), v.strip('" '))
for k, _, v in [l.partition("=") ... |
9839952 | import os
datasets = ['cr', 'pc', 'sst1', 'sst2', 'subj', 'trec']
for dataset in datasets:
line = 'cat increment_datasets_f2/' + dataset + '/test.txt > sized_datasets_f1/test/' + dataset + '/test.txt'
os.system(line) |
9839953 | import torch
from torch.nn import CrossEntropyLoss
from exp.loading.load_mnist import MNISTLoader
from exp.models.chen2018 import mnist_model
from exp.third_party.optimizers.ekfac import EKFACOptimizer
from exp.third_party.optimizers.kfac import KFACOptimizer
# global hyperparameters
batch = 500
num_epochs = 20
devic... |
9839982 | from django.urls import re_path, path
from web.views import *
urlpatterns = [
path('posts', posts),
re_path('', index),
]
|
9840027 | import pandas as pd
import os
import pickle
class InitialisationCache:
"""
Class to handle caching of initialisation data, eg. individuals and activity locations dataframes
"""
def __init__(self, cache_dir):
self.cache_dir = cache_dir
self.individuals_filepath = os.path.join(self.cache... |
9840073 | import numpy as np
import jams
from mirdata.datasets import guitarset
from mirdata import annotations
from tests.test_utils import run_track_tests
TEST_DATA_HOME = "tests/resources/mir_datasets/guitarset"
def test_track():
default_trackid = "03_BN3-119-G_solo"
dataset = guitarset.Dataset(TEST_DATA_HOME)
... |
9840088 | from http import HTTPStatus
import pytest
from async_asgi_testclient import TestClient
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
import aiodogs... |
9840096 | from interactor import VERSION
from setuptools import setup, find_packages
# fmt: off
setup(
name = "lifx-photons-interactor"
, version = VERSION
, packages = find_packages(include="interactor.*", exclude=["tests*"])
, include_package_data = True
, python_requires = ">= 3.6"
, install_req... |
9840134 | webgui=Runtime.create("WebGui","WebGui")
webgui.autoStartBrowser(False)
webgui.startService()
#start speech recognition and AI
wksr=Runtime.createAndStart("webkitspeechrecognition","WebkitSpeechRecognition")
pinocchio = Runtime.createAndStart("pinocchio", "ProgramAB")
pinocchio.startSession("default", "pinocchio")
htm... |
9840184 | from typing import Set, List, Tuple
from problog.logic import Constant
from mai_experiments.fold_control import FoldInfoController, FoldInfo
from mai_experiments.run_experiments_refactor.example_preprocessing_refactor import Experiment
from mai_version.representation.example import ClauseDBExampleWrapper, ExampleWrap... |
9840203 | import numpy as np
import torch
import copy
from collections import OrderedDict
from util.util import util
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
from sklearn.decomposition import PCA
class DIFLModel(BaseModel):
def name(self):
return 'DIFLModel'
... |
9840303 | class NumRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __hash__(self):
return hash(self.start, self.end)
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def __repr__(self):
return "[{}, {}]".for... |
9840304 | import pathlib
import unittest
from html2csv import Converter
def get_resource(relative_path):
return pathlib.Path(__file__).parent / relative_path
class ConverterTestCase(unittest.TestCase):
def setUp(self):
self.converter = Converter()
def test_convert(self):
html_doc = get_resource... |
9840308 | import FWCore.ParameterSet.Config as cms
# filter to distinguish between runs not needing or needing tracking
trackingRunTypeFilter = cms.EDFilter("SiStripCommissioningRunTypeFilter",
runTypes = cms.vstring( 'ApvLatency', 'FineDelay' ),
InputModuleLabel = cms.InputTag('FedChannelDigis')
)
|
9840318 | def titulo(msg):
tam = len(msg) + 4
print('=' * tam)
print(f'{msg:^{tam}}')
print('=' * tam)
titulo('TRATAMENTO DE ERROS E EXCESSÕES')
//https://pt.stackoverflow.com/q/431508/101
|
9840345 | import sys
from kivy.base import runTouchApp
from kivy_garden.mapview import MapSource, MapView
kwargs = {}
if len(sys.argv) > 1:
kwargs["map_source"] = MapSource(url=sys.argv[1], attribution="")
runTouchApp(MapView(**kwargs))
|
9840439 | class LearningStrategyEnum:
DAP = "dap"
MAULI = "mauli"
MASCOF = "mascof"
SDAP = "sdap"
# try to find the internal value and return
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
# prohibit any attempt to set any values
def __... |
9840480 | def extractDawningHowls(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Dragon Flies Phoenix Dances' in item['tags']:
return buildReleaseMessageWithType(item, 'Dragon Flies Phoenix Dances', vol,... |
9840555 | from capreolus import Dependency, ModuleBase, get_logger
logger = get_logger(__name__) # pylint: disable=invalid-name
class Index(ModuleBase):
"""Base class for Index modules. The purpose of an Index module is to represent an inverted index that can be queried with a :class:`~capreolus.searcher.Searcher` modul... |
9840560 | from bs4 import BeautifulSoup
import requests
import json
import datetime
import codecs
import time
conHolder = {}
conHolder['name'] = 'Pathfinder 2.0 Consumable Item list'
conHolder['date'] = datetime.date.today().strftime("%B %d, %Y")
def get_consumable_multi(link):
items = []
string = " "
res2 = reque... |
9840601 | import dash
import dash_core_components as dcc
import dash_html_components as html
import flask
import gevent
import os
import pandas as pd
from psycogreen.gevent import patch_psycopg
import sqlalchemy
import sqlalchemy_gevent
import time
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)
server... |
9840706 | import unittest
from flask_ipblock.documents import IPNetwork
from mongoengine.connection import connect
connect('testdb')
class IPBlockTestCase(unittest.TestCase):
def setUp(self):
IPNetwork.drop_collection()
def test_blacklist_specific_ip(self):
IPNetwork.create_from_string('192.168.1.2... |
9840735 | import sys
import math
import os
import shutil
import logging
import tempfile
from .base import *
from .dataset import *
from .stagerunner import *
if sys.version_info.major == 3:
import dampr.settings as settings
else:
import settings
class Source(object):
CNT = 0
def __init__(self, name):
s... |
9840751 | from pwn import *
r=remote('pwn2.jarvisoj.com',9880)
elf=ELF('./level4')
plt_write=elf.plt['write']
plt_read=elf.plt['read']
#true_address?
vuladr=elf.symbols['vulnerable_function']
bssadr=elf.symbols['__bss_start']
#elf.bss() elf.symbols['__data_start'] also can be used
def leak(address):
payload1='A'*(0x88+0x4)+p32... |
9840756 | from .campaign import PyCampaign
from .mform import PyMform
# from .partner import MarketingPartner
# from .lead import MarketingLead
|
9840772 | import os
import json
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--Images_dir', type=str,
help='path of extracted video frames',
required=True)
parser.add_argument('--Video_annotation_dir', type=str,
help='path of gaze... |
9840785 | import interleaving as il
import numpy as np
import pytest
class TestMethods(object):
@pytest.yield_fixture(autouse=True)
def fix_seed(self):
np.random.seed(0)
def assert_almost_equal(self, a, b, error_rate=0.01):
assert abs(a-b) < error_rate
def interleave(self, method, lists, k, id... |
9840818 | import random
from pathlib import Path
from qcore.asserts import AssertRaises, assert_eq
from tabml.utils import utils
class TestRandomString:
def test_length(self):
length = random.randint(1, 100)
str1 = utils.random_string(length)
# sanity check
assert_eq(length, len(str1))
... |
9840877 | import logging, matplotlib, os, sys
import scanpy as sc
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import colors
from glbase3 import *
plt.rcParams['figure.figsize']=(8,8)
sc.settings.verbosity = 3
sc.set_figure_params(dpi=200, dpi_save=200)
matplotlib.rcParams['pdf.fonttype']=42
... |
9840894 | import FWCore.ParameterSet.Config as cms
MC_flag = False
GLOBAL_TAG = 'GR_R_52_V8::All'
if MC_flag:
GLOBAL_TAG = 'START52_V5::All'
process = cms.Process("TEST")
process.load("Configuration.StandardSequences.RawToDigi_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("Configurat... |
9840934 | import os
import mock
from cassette.cassette_library import (CassetteLibrary,
DirectoryCassetteLibrary,
FileCassetteLibrary)
from cassette.tests.base import (TEMPORARY_RESPONSES_FILENAME,
TEMPORARY_RESPONSES... |
9840964 | from django.test import TestCase
from django.core import mail
from utils.email import send_templated_email
class TestSendTemplatedEmail(TestCase):
def test_base_page(self):
self.assertEqual(len(mail.outbox), 0)
send_templated_email(
"My subject",
"<EMAIL>",
["... |
9840982 | def palindrome_checker(string):
counter = {}
for i in range(26):
counter[chr(ord('a') + i)] = 0
for s in string:
counter[s] += 1
odd = 0
for c in counter:
if counter[c] % 2 != 0:
if odd == 0:
odd = 1
else:
retu... |
9840995 | from docassemble.webapp.db_object import db
from docassemble.webapp.core.models import Uploads
def get_new_file_number(user_code, file_name, yaml_file_name=None):
new_upload = Uploads(key=user_code, filename=file_name, yamlfile=yaml_file_name)
db.session.add(new_upload)
db.session.commit()
return new_u... |
9840997 | import numpy as np
import cPickle as pickle
# CIFAR 10: all off-the-shelf questions (not presented in the paper)
def cifar10_questions():
# Q = np.diag(np.ones(10, dtype=np.bool))
Q = np.diag(np.ones(10, dtype=np.int))
return Q
# CIFAR 10: all possible questions (not presented in the paper)
def cifar10_al... |
9841006 | import os.path
from mailchute.model import IncomingEmail, RawMessage
from mailchute import db
FIXTURE_DIR = os.path.join(
os.path.dirname(__file__),
'fixtures')
class _Fixture(object):
def __getattr__(self, attr):
fixture_path = os.path.join(FIXTURE_DIR, attr.lower())
with open(fixture_... |
9841017 | class Solution:
# Shuffle String
def restoreString(self, s: str, indices: List[int]) -> str:
# BF, assign to new array
rtn = [""] * len(s)
for i, ic in enumerate(indices):
rtn[ic] = s[i]
return "".join(rtn) |
9841019 | import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GstNet, GObject
from sys import argv
import time
from see import see
import struct
from socket import *
from threading import Thread
import zmq
import json
next_loop = False
loop_index = 0
context = zmq.Context()
loop_times = []
section_times = ... |
9841121 | from flask_influxdb import InfluxDB
from flask import Flask, render_template
influx = InfluxDB()
def create_app(config: str) -> Flask:
app = Flask(__name__)
app.config.from_pyfile(config)
influx.init_app(app)
@app.route("/newdb/<dbname>")
def newdb(dbname):
influx.database.create(dbname... |
9841126 | from ccn.graph_data import TensorGraph
def test_arithmetic():
adj_list, values_list, value_tokens_list, order_list = \
TensorGraph.random_tree('arithmetic', 3, 3)
tg = TensorGraph.tree_to_instance(adj_list, values_list, value_tokens_list,
order_list, 10, 'arithmetic')
|
9841184 | import rospy
import actionlib
from armer_msgs.msg import GuardedVelocityAction, GuardedVelocityGoal
rospy.init_node('armer_example')
vel_cli = actionlib.SimpleActionClient('/arm/cartesian/guarded_velocity', GuardedVelocityAction)
vel_cli.wait_for_server()
goal = GuardedVelocityGoal()
goal.twist_stamped.twist.linear.... |
9841210 | import numpy as np
import open3d as o3d
from skimage.measure import LineModelND, ransac
from util import showPointCloud
def extract_plane_points(point_cloud):
num_point_threshold = 20
if point_cloud.shape[0] < num_point_threshold:
return np.array([])
o3d_point_cloud = o3d.geometry.PointCloud()
... |
9841245 | from moda.dataprep.utils import raw_to_ts, ts_to_range
from moda.dataprep.create_dataset import get_windowed_ts, split_history_and_current
from moda.dataprep.data_reader import read_data
__all__ = [
"raw_to_ts",
"ts_to_range",
"get_windowed_ts",
"split_history_and_current",
"read_data",
]
|
9841260 | import logging
import math
import pandas as pd
from airflow.models import Variable
from airflow.providers.redis.hooks.redis import RedisHook
from hooks.db.oracle_helper import OracleHelper
class RedisHelper(RedisHook):
__slots__ = 'redis_conn_id' # space savings in memory + faster attribute access
def __in... |
9841331 | import itertools
import operator
import os
import sys
import numpy as np
from collections import OrderedDict
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import poreover
import poreover.decoding as decoding
def remove_gaps(a):
# only needed for greedy decoding
# unlike st... |
9841334 | from curious import deferred_to_real
from django.test import TestCase, override_settings
from django.db import connection
from curious_tests.models import Blog, Entry
class TestDeferredToReal(TestCase):
def setUp(self):
blog = Blog(name='Databases')
blog.save()
self.blogs = [blog]
headlines = ('MyS... |
9841353 | import pytest
import sys
if sys.platform == 'win32':
#This module does not exist in windows
pytest.skip('no curses on windows')
# Check that lib_pypy.cffi finds the correct version of _cffi_backend.
# Otherwise, the test is skipped. It should never be skipped when run
# with "pypy py.test -A" and _curses_buil... |
9841366 | import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
def plot_learning_curve(time_steps_to_failure):
# A log plot may show the convergence better, as the learning curve is
# typically jagged even on convergence.
log_tstf = np.log(time_steps_to_failure)
fig = plt.figure(figsize... |
9841369 | from __future__ import division
from builtins import object
import numpy as np
from sporco.admm import cbpdnin
class TestSet01(object):
def setup_method(self, method):
np.random.seed(12345)
def test_01(self):
D = np.random.randn(4, 4, 32)
s = np.random.randn(8, 8)
# Conv... |
9841379 | import os
import concurrent.futures as cf
import pytest
from parsl.app.errors import AppException
from parsl.executors.flux.executor import (
FluxExecutor,
FluxFutureWrapper,
_complete_future,
)
try:
import flux.job.executor # noqa: F401
except ImportError:
FLUX_AVAIL = False
else:
FLUX_AVAI... |
9841454 | from contextlib import closing
from multiprocessing import Pool
import pandas as pd
import numpy as np
import argparse
import glob
import time
import os
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
# For debugging purposes only:
def print(*args, **kwargs):
__bu... |
9841474 | import struct
import alsaaudio
class ALSASrc(object):
def __init__(self):
card = 'default'
self.pcm = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, card)
nchans = 2
self.pcm.setchannels(nchans)
self.pcm.setrate(44100)
self.pcm.setformat(alsaaudio.PCM... |
9841502 | from ananas import PineappleBot, interval, schedule, ConfigurationError
class AnnounceBot(PineappleBot):
"""Bot that regularly checks approved users' feeds for posts with a
particular hashtag and boosts them when found. Good for automated
announcement bots which draw content from admins' feeds."""
def... |
9841546 | from guillotina import addons
from guillotina import app_settings
from guillotina import configure
from guillotina import error_reasons
from guillotina import task_vars
from guillotina.api import content
from guillotina.api.service import Service
from guillotina.component import get_adapter
from guillotina.component im... |
9841602 | from __future__ import division
import tensorflow as tf
import pprint
import random
import numpy as np
from SfMLearner import SfMLearner
import os
flags = tf.app.flags
flags.DEFINE_string("dataset_dir", "", "Dataset directory")
flags.DEFINE_string("checkpoint_dir", "./checkpoints/", "Directory name to save the checkpo... |
9841675 | from django.test import override_settings, SimpleTestCase, tag
from anymail.backends.base_requests import AnymailRequestsBackend, RequestsPayload
from anymail.message import AnymailMessage, AnymailRecipientStatus
from tests.utils import AnymailTestMixin
from .mock_requests_backend import RequestsBackendMockAPITestCas... |
9841679 | import copy
import os
from math import log
from random import randint, shuffle, choice
from bayesian.bbn import *
from bayesian.utils import make_key
from datasetParser import DatasetParser
from episode import Episode
"""
This class models the Developmental Bayesian Model of Trust in Artificial Cognitive Systems (Pa... |
9841693 | import logging
import time
from constance import config
from roll_engine.utils.log import get_logger
# from rest_client import get_remix_client
from .verify import Verify
from ansible_playbook.runplaybook import RunPlaybook
es_logger = get_logger()
def choose_deploy_agency(group):
return globals().get("{0}Agen... |
9841723 | import pytest
import slash
import time
import logbook
from slash.utils.interactive import notify_if_slow_context
from slash.reporting.console_reporter import ConsoleReporter
from io import StringIO
@pytest.mark.parametrize('show_duration', [True, False])
def test_notify_if_slow_context(show_duration):
output_stre... |
9841812 | from flask import current_app
KNATIVE_ROUTE = {"group": "serving.knative.dev",
"version": "v1",
"kind": "routes"}
KNATIVE_REVISION = {"group": "serving.knative.dev",
"version": "v1",
"kind": "revisions"}
KNATIVE_CONF = {"group": "serving.knative... |
9841852 | from django.conf.urls import include, url
from allauth.utils import import_attribute
def default_urlpatterns(provider):
login_view = import_attribute(
provider.get_package() + '.views.oauth_login')
callback_view = import_attribute(
provider.get_package() + '.views.oauth_callback')
urlpat... |
9841890 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension
setup(
name='gesvd',
version="0.1",
ext_modules=[
CppExtension('gesvd_cpp', ['gesvd.cpp']),
],
scripts=['gesvd.py', '__init__.py'],
cmdclass={
'build_ext': BuildExtension
})
|
9841897 | import torch
import torchvision
model=torchvision.models.resnet18()
s=torch.randn(1,3,224,224)
ts=torch.jit.trace(model,s)
ts.save('test.pt') |
9841899 | import json
from collections import OrderedDict
import pytest
from great_expectations.core import (
ExpectationConfiguration,
expectationSuiteSchema,
expectationSuiteValidationResultSchema,
)
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
Expe... |
9841924 | import sqlite_utils
import datetime
from sqlite_utils.db import NotFoundError
import git
import json
def iterate_file_versions(repo_path, filepath, ref="master"):
repo = git.Repo(repo_path, odbt=git.GitDB)
commits = reversed(list(repo.iter_commits(ref, paths=filepath)))
for commit in commits:
blob... |
9841926 | import numpy as np
from ..crs import CartesianCRS
def coordinate_transformer(crs1, crs2):
if crs1 == crs2:
def transformer(x, y):
return x, y
else:
def transformer(x, y):
return crs1.transform(crs2, x, y)
return transformer
class CoordinateGenerator(object):
"""... |
9841931 | from .version import version as __version__ # noqa
from .data import * # noqa
from .utils import * # noqa
from .api import * # noqa
_ga_id = "UA-156363454-3"
|
9841933 | from mpi4py import MPI
import numpy as np
import time
def sleep(n):
tmp = np.random.rand(n)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
sbuf = np.empty(4)
win = MPI.Win.Create(sbuf, comm=comm)
else:
rbuf = np.empty(4)
win = MPI.Win.Create(None, comm=comm)
# tmp = np.random.rand... |
9841980 | from hatch.files.licenses.apache2 import Apache2License
from hatch.files.licenses.cc0 import CC0License
from hatch.files.licenses.mit import MITLicense
from hatch.files.licenses.mpl import MPLLicense
|
9842088 | from server import *
from mongodb.get_the_last_id import *
db = cluster["Notices"]
collection = db["Notices"]
def add_notice(title, description):
collection.insert_one(
{
"_id": get_custom_last_id(db="Notices", collection="Notices"),
"Title": title,
"Description": descr... |
9842124 | PythonWin 2.1 (#15, Jun 18 2001, 21:42:28) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 <NAME> (<EMAIL>) - see 'Help/About PythonWin' for further copyright information.
>>> import sys
>>> # append the complete name of the folder that contains 'link.py'
>>> # (the demo use of pythoncom.CoCreateInstance wi... |
9842170 | import operator as _operator
import sqlalchemy as sa
import trafaret as t
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql import or_
from trafaret.contrib.rfc_3339 import DateTime
from ..exceptions import JsonValidaitonError
from ..utils import MULTI_FIELD_TEXT_QUERY, as_dict
__all__ = ['table_to_tra... |
9842175 | import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def get_color_map(label_num, cmap_name='terrain', normalzation=False):
cmap = cm.get_cmap(cmap_name, label_num)
cmap_array = np.array([cmap(i)[:3] for i in range(label_num)])
return cmap_array * 25... |
9842190 | import time
from time import sleep
import os
import sys
def limit_fps(fps):
delay = 1/fps
def run_fps_capped(func):
def run(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
elapsed_time = time.time() - start_time
sleep_time = delay-elaps... |
9842222 | from django.core.checks import Warning, register
from mezzanine.conf import settings
TWITTER_DEPRECATED = Warning(
"'mezzanine.twitter' is deprecated and will be removed in a future version",
id="mezzanine.twitter.W001",
)
@register()
def check_twitter(app_configs, **kwargs):
issues = []
if "mezzan... |
9842246 | import numpy as np
import csv
n_filename = "Network_Times.csv"
ng_filename = "Network_Times_NO_GPU.csv"
f_filename = "FEniCS_Times.csv"
fc_filename = "FEniCS_Times_Coarse.csv"
n_times = []
ng_times = []
f_times = []
fc_times = []
with open(n_filename, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=' ... |
9842266 | from __future__ import annotations
from jsonclasses import jsonclass, types
@jsonclass
class RoleUser:
username: str = types.str.required
role: str = types.str.readonly.default('normal').required
|
9842322 | import time
from hashlib import sha256
from typing import Dict, List, Optional
import ujson as json
from policy_sentry.querying.actions import get_actions_with_access_level
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
)
f... |
9842325 | import unittest
import pycstruct
class TestInstance(unittest.TestCase):
def test_instance(self):
# First define a complex definition structure
car_type = pycstruct.EnumDef(size=4)
car_type.add("Sedan", 0)
car_type.add("Station_Wagon", 5)
car_type.add("Bus", 7)
car_... |
9842355 | import codecs
import pytest
from ircproto.events import decode_event
from ircproto.exceptions import ProtocolError, UnknownCommand
def test_decode_event_oversized():
buffer = bytearray(b':foo!bar@blah PRIVMSG hey' + b'y' * 600 + b'\r\n')
exc = pytest.raises(ProtocolError, decode_event, buffer)
assert st... |
9842364 | import datetime
from freezegun import freeze_time
from ecmwf.opendata.date import canonical_time, end_step, full_date
@freeze_time("2022-01-21T13:21:34Z")
def test_date_1():
assert full_date("20010101") == datetime.datetime(2001, 1, 1)
assert full_date(20010101) == datetime.datetime(2001, 1, 1)
assert ... |
9842394 | import sys
import numpy as np
import triplet_loss
from batcher import KerasFormatConverter, TripletBatcherSelectHardNegatives, TripletBatcher
from constants import NUM_FBANKS, NUM_FRAMES, CHECKPOINTS_TRIPLET_DIR, CHECKPOINTS_SOFTMAX_DIR, BATCH_SIZE
from conv_models import DeepSpeakerModel
from triplet_loss import dee... |
9842414 | import os
import peru.compat as compat
import shared
class CompatTest(shared.PeruTest):
def test_makedirs(self):
tmp_dir = shared.tmp_dir()
foo_dir = os.path.join(tmp_dir, "foo")
compat.makedirs(foo_dir)
os.chmod(foo_dir, 0o700)
# Creating the dir again should be a no-op e... |
9842420 | from __future__ import absolute_import, division, print_function
import mmtbx.dynamics
from mmtbx.dynamics import constants
from mmtbx.dynamics import cartesian_dynamics
import mmtbx.restraints
import mmtbx.monomer_library.pdb_interpretation
import mmtbx.monomer_library.server
from cctbx.array_family import flex
from l... |
9842434 | import requests
def test_server(host_ip, http_port):
'''
Test that wordpress was setup on the minion correctly and returns a 200 after being installed
'''
resp = requests.get('http://{}:{}'.format(host_ip, http_port), headers={'Host': 'blog.manfred.io'})
assert resp.status_code == 200
|
9842443 | import click
import src.cli.console as console
from src.context.helper import convert_context_arguments
from src.graphql import GraphQL
from src.storage.user import get_local_storage_user
def show_context(context):
console.info("Context:")
console.echo(f"- organization: {context.organization_id}")
consol... |
9842446 | import numpy as np
from ...core import Tensor
from .base import Classifier
class LSSTM(Classifier):
""" Least Squares Support Tensor Machine (LS-STM) for binary classification.
Parameters
----------
C : float
Penalty parameter of the error term.
tol : float
Tolerance for stopping ... |
9842470 | import json
import os
import re
import sys
import requests
import sublime
import sublime_plugin
try:
import lxml.html
HTML_PRETTIFY = True
except ImportError:
HTML_PRETTIFY = False
abspath = os.path.abspath(os.path.dirname(__file__))
sys.path.append(abspath)
import markdown2
class ConfluenceApi(object... |
9842490 | import os.path as osp
import numpy as np
class ImuCalib:
def __init__(self):
self.accelScaleInv = np.eye(3)
self.gyroScaleInv = np.eye(3)
self.gyroGSense = np.eye(3)
self.accelBias = np.zeros((3, 1))
self.gyroBias = np.zeros((3, 1))
@classmethod
def from_attitude_... |
9842524 | from django.db import models
class A(models.Model):
not_null_field = models.IntegerField(null=True)
|
9842558 | import subprocess
import os
from ssr.config.ssr_config import SSRConfig
class MultiScaleReconstructor:
# https://lmb.informatik.uni-freiburg.de/people/ummenhof/multiscalefusion/
# README:
# < pointfusion_octree>
# This program takes a point cloud with normal and scale information
# a... |
9842572 | import unittest
from trading_api_wrappers import Bitcoinity
CURRENCY = "USD"
EXCHANGE = "bitfinex"
class BitcoinityTest(unittest.TestCase):
def setUp(self):
self.client = Bitcoinity()
def test_instantiate_client(self):
self.assertIsInstance(self.client, Bitcoinity)
def test_ticker_retu... |
9842587 | from django import forms
from django.core.exceptions import ValidationError
from django.forms.widgets import HiddenInput
from django.utils.translation import ugettext
from .models import PlanPricing, BillingInfo
from plans.models import Order
class OrderForm(forms.Form):
plan_pricing = forms.ModelChoiceField(que... |
9842598 | from dash import Dash
from flask import jsonify, make_response, redirect, request
from werkzeug.exceptions import BadRequest
class DashIam(Dash):
def __init__(self, authorizer, *args, **kwargs):
"""Dash wrapper that validates resource access before replying.
In order to see how the data is split... |
9842640 | from django.core.files.storage import FileSystemStorage
class NoLocationMigrationFileSystemStorage(FileSystemStorage):
def deconstruct(obj): # pylint: disable=no-self-argument
path, args, kwargs = FileSystemStorage.deconstruct(obj)
kwargs["location"] = None
return (path, args... |
9842645 | from mypy.plugin import MethodContext
from mypy.types import AnyType, Instance
from mypy.types import Type as MypyType
from mypy.types import TypeOfAny
from mypy_django_plugin.django.context import DjangoContext
from mypy_django_plugin.lib import fullnames, helpers
def typecheck_queryset_filter(ctx: MethodContext, d... |
9842655 | from tests.acceptance import (
run_gitlabform,
)
def single_true(iterable):
i = iter(iterable)
# use the fact that thanks to iter() we will "consume"
# all the elements of iterable up to the one that is True
# so that there should be no other True in the rest
return any(i) and not any(i)
cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.