id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11595294 | from mako.template import Template
import os
from importlib import import_module
import pathlib
import zipfile
# TODO: Replace with Python 3.9's importlib.resources.files() when it becomes min version
def files(package):
spec = import_module(package).__spec__
if spec.submodule_search_locations is None:
... |
11595301 | from pathlib import Path
from typing import Iterator
def get_paths(path: Path) -> Iterator[Path]:
"""Recursively yields python files.
"""
if not path.exists():
raise FileNotFoundError(str(path))
if path.is_file():
if path.suffix == '.py':
yield path
return
for s... |
11595340 | from briefmetrics import api
from briefmetrics import test
from briefmetrics import model
from briefmetrics.lib.service import registry as service_registry
from briefmetrics.lib.payment import registry as payment_registry
from dateutil.relativedelta import relativedelta
import mock
import json
import logging
import da... |
11595353 | from pprint import pprint
from visdom import Visdom
import pathlib
import json
import sys
import matplotlib.pyplot as plt
def download_env(env):
vis = Visdom('http://logserver.duckdns.org', port=5010)
data = vis.get_window_data(env=env)
d = json.loads(data)
n_deleted = []
test_acc_avg = []
... |
11595383 | from pyamf.remoting.gateway.wsgi import WSGIGateway
def echo(data):
return data
services = {
'echo': echo,
# Add other exposed functions here
}
gateway = WSGIGateway(services)
|
11595414 | import numpy as np
import cv2
import matplotlib.image as mpimg
class CameraCalibration(object):
"""
Prepares camera calibration pipeline based on a set of calibration images.
"""
def __init__(self, calibration_images, pattern_size=(9, 6), retain_calibration_images=False):
"""
Initiali... |
11595432 | import sys
sys.path.append("../../")
from appJar import gui
def change(): print("changed")
def press(btn):
if btn == "clear": app.clearListBox("list", callFunction=app.check("call"))
elif btn == "select":
app.selectListItemAtPos("list", -5, callFunction=app.check("call"))
app.selectListItemAtP... |
11595454 | import json
import os
import sys
import logging
import time
from azure.mgmt.rdbms.mysql import MySQLManagementClient
from azure.identity import ClientSecretCredential
from azure.mgmt.rdbms.mysql.models import ServerUpdateParameters
logging.basicConfig(level=logging.INFO)
class EnableSslEnforcement(object):
def ... |
11595460 | import time
from contextlib import contextmanager
from datetime import datetime
from typing import Dict
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Union
from urllib.parse import urljoin
import lib.core as constance
import requests.packages.urllib3
from lib.core.exce... |
11595465 | import os
import sys
import logging
import time
from azure.eventhub import EventHubClient, Receiver, Offset
logger = logging.getLogger("azure")
# Address can be in either of these formats:
# "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<mynamespace>.servicebus.windows.net/myeventhub"
# "amqps://<namespace>... |
11595499 | from __future__ import absolute_import, print_function, unicode_literals
from wolframclient.language import wl
from wolframclient.serializers import export, wolfram_encoder
# define a new class.
class Animal(object):
pass
# register a new encoder for instances of the Animal class.
@wolfram_encoder.dispatch(Anima... |
11595573 | import numpy.testing
from refnx._lib.util import (
TemporaryDirectory,
preserve_cwd,
possibly_open_file,
MapWrapper,
)
from refnx._lib._numdiff import approx_hess2
from refnx._lib._testutils import PytestTester
try:
from refnx._lib._cutil import c_unique as unique
from refnx._lib._cutil impor... |
11595615 | from django.urls import path
from .views import (
IdeaList,
IdeaDetail,
add_or_change_idea,
delete_idea,
download_idea_picture,
)
urlpatterns = [
path("", IdeaList.as_view(), name="idea_list"),
path("add/", add_or_change_idea, name="add_idea"),
path("<uuid:pk>/", IdeaDetail.as_view(), ... |
11595617 | import FWCore.ParameterSet.Config as cms
from RecoBTag.Skimming.btagMuonInJet_EventContent_cff import *
btagMuonInJetOutputModuleAODSIM = cms.OutputModule("PoolOutputModule",
btagMuonInJetEventSelection,
AODSIMbtagMuonInJetEventContent,
dataset = cms.untracked.PSet(
filterName = cms.untracked.strin... |
11595618 | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from past.builtins import basestring
import os
import os.path
import stat
import logging
import hashlib
from io import BytesIO as StringIO
f... |
11595621 | import sys,os
sys.path.append("..")
import numpy as np
import tensorflow as tf
from bunch import Bunch
from data_generator import tokenization
from data_generator import tf_data_utils
from model_io import model_io
import json
import requests
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_st... |
11595622 | import numpy as np
import pytest
from kiez import Kiez
from kiez.hubness_reduction import MutualProximity
from numpy.testing import assert_array_equal
rng = np.random.RandomState(2)
def test_wrong_input():
with pytest.raises(ValueError) as exc_info:
MutualProximity(method="wrong")
assert "not recogni... |
11595680 | from datetime import datetime, timezone
from enum import Enum
from flask import (
current_app,
url_for
)
class EnumStrAutoName(Enum):
"""
For `Enum`, `auto()` will return strings, not int's.
"""
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return str(c... |
11595709 | import shutil
import tempfile
from unittest import TestCase, mock
import pytest
from lineflow import download
from lineflow.datasets.penn_treebank import PennTreebank, get_penn_treebank
class PennTreebankTestCase(TestCase):
@classmethod
def setUpClass(cls):
cls.default_cache_root = download.get_cac... |
11595742 | from django.db.backends.postgresql.features import (
DatabaseFeatures as PostgresDatabaseFeatures,
)
from django.utils.functional import cached_property
class DatabaseFeatures(PostgresDatabaseFeatures):
# Cloning databases doesn't speed up tests.
# https://github.com/cockroachdb/django-cockroachdb/issues/... |
11595748 | from pycdft.common.atom import Atom
from pycdft.common.sample import Sample
class Fragment(object):
"""
A part of the system to which constraints may apply.
Attributes:
sample (Sample): sample.
atoms (list of Atom): list of atoms belonging to the fragment.
natoms (int): number of... |
11595761 | description = 'CCR with LakeShore LS336 controller'
group = 'optional'
includes = ['alias_T']
tango_base = 'tango://resedahw2.reseda.frm2:10000/reseda'
devices = dict(
# T_ccr = device('nicos_mlz.devices.ccr.CCRControl',
# description = 'The main temperature control device of the CCR',
# stick =... |
11595795 | import logging
import uuid
import eventlet
from errors import ExpectedException
import rtjp_eventlet
class HookboxConn(object):
logger = logging.getLogger('HookboxConn')
def __init__(self, server, rtjp_conn, config, remote_addr):
self._rtjp_conn = rtjp_conn
self.server = server
sel... |
11595797 | from joblib import load
from pyprojroot import here
python_model = load(here("./python_model.joblib"))
test_data = load(here("./test_data.joblib"))
|
11595830 | from netmiko import ConnectHandler
def takebackup(cmd,rname):
uname="cisco"
passwd="<PASSWORD>"
device = ConnectHandler(device_type='cisco_ios', ip=rname, username=uname, password=passwd)
output=device.send_command(cmd)
fname=rname+".txt"
file=open(fname,"w")
file.write(output)
file.clo... |
11595842 | import os
import argparse
import torch
import logging
import json
import pytorch_lightning as pl
from transformers import BartTokenizer, BartConfig
from transformers import AdamW, get_linear_schedule_with_warmup
from .network import BartGen
from .constrained_gen import BartConstrainedGen
logger = logging.getL... |
11595870 | from monosat import *
bv1 = BitVector(4)
bv2 = BitVector(4)
assert(Solve())
Assert(bv1==15)
assert(Solve())
Assert(bv2>bv1)
assert(not Solve())
|
11595900 | import telebot_login
from tg_bot import bot
# Other message
@bot.message_handler(
func=lambda mess: True, content_types=["text"]
)
@telebot_login.login_required_message
def other_text_handler(message):
bot.reply_to(message, "Не понимаю")
|
11595982 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_directories(host):
present = [
"/etc/td-agent"
]
if present:
for directory in present:
d = host.... |
11595983 | import uuid
from unittest import mock
import pytest
from botocore import exceptions
from dagster import DagsterResourceFunctionError, In, Out, build_op_context, configured, job, op
from dagster_aws.s3 import S3FileHandle, S3FileManager, s3_file_manager, s3_resource
def test_s3_file_manager_write(mock_s3_resource, mo... |
11596005 | import torch.nn.functional as F
from torch import nn, tensor
from configuration import config
class PadUp(nn.Module):
def __init__(self, window_size):
super().__init__()
self.window_size = window_size
# TODO this is inefficient, size check should only be done once, not every forward call
... |
11596008 | import sys
from unittest.mock import call
import pytest
import ahkpy as ahk
import _ahk
def noop():
pass
@pytest.fixture
def call_spy(mocker):
return mocker.spy(_ahk, "call")
@pytest.fixture
def menu(request):
menu = ahk.Menu()
yield menu
menu.delete_menu()
def test_get_handle(menu):
m... |
11596030 | import re
import lib.core.common
__product__ = "4D"
__description__ = (
"4D web application deployment server"
)
def search(html, **kwargs):
headers = kwargs.get("headers", None)
plugin_detection_schema = (
re.compile(r"/^4D_v[\d]{1,2}(_SQL)?\/([\d\.]+)$/", re.I),
)
for plugin in plugin... |
11596084 | from .helpers import ResourceBase, IterableResource, Nested
from .errors import ok_or_error, response_or_error
from .compat import update_doc
from enum import Enum
API_NAME = 'branch-permissions'
API_VERSION = '2.0'
API_OVERRIDE_PATH = '{0}/{1}'.format(API_NAME, API_VERSION)
class Matcher(Enum):
"""Valid values... |
11596135 | from ..configuration.configuration import Configuration
from ..interfaces.plugin import Plugin
from ..interfaces.state import State
from ..utilities.attributedict import AttributeDict
import aiotelegraf
from datetime import datetime
import logging
import platform
logger = logging.getLogger("cobald.runtime.tardis.plug... |
11596142 | from __future__ import unicode_literals
import re
PROTOCOL = r'[a-zA-Z]{0,64}:?//'
WEB_PROTOCOL = r'(?:(?:(?:https?|ftp|wss?):)?//)'
HTTP_PROTOCOL = r'https?://'
PROTOCOL_RE = re.compile(r'^%s' % PROTOCOL)
WEB_PROTOCOL_RE = re.compile(r'^%s' % WEB_PROTOCOL)
HTTP_PROTOCOL_RE = re.compile(r'^%s' % HTTP_PROTOCOL)
# Ada... |
11596178 | import operator_benchmark as op_bench
import torch
"""Microbenchmarks for diag operator"""
# Configs for PT diag operator
diag_configs_short = op_bench.config_list(
attr_names=['dim', 'M', 'N', 'diagonal', 'out'],
attrs=[
[1, 64, 64, 0, True],
[2, 128, 128, -10, False],
[1, 256, 256,... |
11596180 | from __future__ import print_function
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='Example_ExtFlash')
def test_examples_storage_ext_flash_fatfs(env, extra_data):
dut = env.get_dut('ext_flash_fatfs', 'examples/storage/ext_flash_fatfs', dut_class=ttfw_idf.ESP32DUT)
dut.start_app()
dut.expect('Initi... |
11596208 | from avatar2.targets import QemuTarget
from avatar2.targets import TargetStates
from avatar2.targets import action_valid_decorator_factory
class PandaTarget(QemuTarget):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
executable = kwargs.get('executable')... |
11596220 | import math
from easydict import EasyDict as edict
import torch
import torch.nn as nn
from common.utility.image_processing_cv import flip
from common_pytorch.common_loss.heatmap_label import generate_gaussian_heatmap_label
from common_pytorch.common_loss.weighted_mse import weighted_mse_loss, weighted_l1_loss, weighte... |
11596250 | import json
import random
import numpy as np
from copy import deepcopy
class dataloader():
def __init__(self, data_file, wordvec_file, max_len=120):
self.max_len = max_len
# Load and Pre-process word vec
print('Wordvec Loading!-----')
with open(wordvec_file,'r') as r:
o... |
11596254 | import os as os
import subprocess as _subprocess
from .utils import netcdf2dict, psp_name
# from .input import AbinitInput
class AbiFiles:
"""
Read an 'abinit.files' file and extract the
names of input, output filenames and put them
into dictionary called 'files'.
"""
basedir = "."
filen... |
11596256 | from django.core.management.base import NoArgsCommand
from time import sleep, time
from django_bitcoin.utils import bitcoind
from django_bitcoin.models import BitcoinAddress
from django_bitcoin.models import Wallet
from django.conf import settings
from decimal import Decimal
class Command(NoArgsCommand):
help = "... |
11596267 | import os
import torch
import torch.nn as nn
import numpy as np
from tqdm import tqdm
class sequential_ablation(object):
def __init__(self, G : nn.Module, device, args):
self.G = G
self.device = device
G.to(self.device)
self.model = args.model
self.sample_size = args.sample_size
# random sampling late... |
11596288 | import alpenglow.Getter as rs
import alpenglow as prs
class AsymmetricFactorExperiment(prs.OnlineExperiment):
"""AsymmetricFactorExperiment(dimension=10,begin_min=-0.01,begin_max=0.01,learning_rate=0.05,regularization_rate=0.0,negative_rate=20,cumulative_item_updates=True,norm_type="exponential",gamma=0.8)
... |
11596334 | import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
from sklearn.feature_extraction.text import TfidfTransformer
import pickle
import chardet
max_features = 50000
webshell_di... |
11596360 | class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
sLen, tLen = len(s), len(t)
if sLen > tLen:
return self.isOneEditDistance(t, s)
if tLen - sLen > 1:
return False
for i in range(sLen):
if s[i] != t[i]:
if sLen == ... |
11596398 | import json
from django.core.management.base import BaseCommand
from uniauth_saml2_idp.utils import get_idp_config
from uniauth_saml2_idp.models import MetadataStore
class Command(BaseCommand):
help = 'Metadata Query protocol'
def add_arguments(self, parser):
parser.epilog = 'Example: ./manage.py m... |
11596485 | import random
import numpy as np
import torch
from torch.utils.data import Dataset
class DummyData(Dataset):
def __init__(
self,
max_val: int,
sample_count: int,
sample_length: int,
sparsity_percentage: int
):
r"""
A data class that generates random d... |
11596492 | from __future__ import division
import datetime
import os
import numpy as np
from scipy import linalg
import matplotlib
if os.environ.get('DISPLAY') is None:
matplotlib.use('Agg')
else:
matplotlib.use('Qt5Agg')
from matplotlib import rcParams
import matplotlib.pyplot as plt
# import bokeh.plotting as b_plt
# fr... |
11596494 | import keras
import numpy as np
from keras.datasets import mnist
from keras.layers import Dropout, BatchNormalization, LeakyReLU, Dense, Input, Activation
from keras.models import Model
from keras.utils.np_utils import to_categorical
def build_model():
x = Input((28 * 28,), name="x")
hidden_dim = 512
h = ... |
11596500 | from Display import Display
from StringDisplayImpl import StringDisplayImpl
from CountDisplay import CountDisplay
if __name__ == '__main__':
d1 = Display(StringDisplayImpl("Hello, China."))
d2 = CountDisplay(StringDisplayImpl("Hello, World."))
d3 = CountDisplay(StringDisplayImpl("Hello, Universe."))
d... |
11596519 | from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from faker import Faker
from hsv_dot_beer.users.test.factories import UserFactory
from venues.test.factories import VenueFactory
from .factories import TapFactory
fake = Faker()
class TestTapDetailTestCase(... |
11596526 | import hyperopt
# from . import register_hpo
from .advisorbase import AdvisorBaseHPOptimizer
from .suggestion.algorithm.chocolate_grid_search import ChocolateGridSearchAlgorithm
# @register_hpo("randadvisor")
class GridAdvisorChoco(AdvisorBaseHPOptimizer):
def __init__(self, args):
super().__init__(args... |
11596540 | import pytest
from asynctest import mock
from asyncpraw.exceptions import ClientException
from asyncpraw.models import RemovalReason
from ... import IntegrationTest
class TestRemovalReason(IntegrationTest):
@mock.patch("asyncio.sleep", return_value=None)
async def test__fetch(self, _):
self.reddit.r... |
11596541 | import tensorflow as tf
from model.common import shape_list, dense_bn_relu, dense, dense_relu, dense_tanh, split_heads, combine_last_two_dimensions, prelu
import sys
VAR2STD_EPSILON = 1e-12
def statistics_pooling(features, aux_features, endpoints, params, is_training):
"""Statistics pooling
Note that we nee... |
11596543 | import logging
from ...splunktalib.common import log as stclog
import six
def set_log_level(log_level):
"""
Set log level.
"""
if isinstance(log_level, six.string_types):
if log_level.upper() == "DEBUG":
stclog.Logs().set_level(logging.DEBUG)
elif log_level.upper() == "INF... |
11596551 | import pycxsimulator
from pylab import *
width = 100
height = 100
initProb = 0.1
maxState = 6
def initialize():
global time, config, nextConfig
time = 0
config = zeros([height, width])
for x in range(width):
for y in range(height):
if random() < initProb:
... |
11596560 | import torch
from nff.utils.scatter import compute_grad
import numpy as np
import math
from ase import units
from torchmd.sovlers import odeint_adjoint, odeint
from ase.geometry import wrap_positions
'''
Here contains object for simulation and computing the equation of state
'''
class Simulations():
"""Si... |
11596641 | from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5
def pad(data):
length = 16 - (len(data) % 16)
return data + (chr(length) * length).encode()
def unpad(data):
return data[:-(data[-1] if isinstance(data[-1], int) else ord(data[-1]))]
def bytes_to_key(data, sa... |
11596644 | udon_types_rel = {
'AINavMeshAgentRef': 'UnityEngineAINavMeshAgentRef',
'AINavMeshDataRef': 'UnityEngineAINavMeshDataRef',
'AINavMeshHitRef': 'UnityEngineAINavMeshHitRef',
'AINavMeshObstacleRef': 'UnityEngineAINavMeshObstacleRef',
'AINavMeshPathRef': 'UnityEngineAINavMeshPathRef',
'AIOffMeshLinkRef': ... |
11596701 | import glob
import logging
import os
import queue
import tempfile
import threading
import typing
import zipfile
from enum import Enum
from multiprocessing.pool import ThreadPool
import pandas as pd
import quandl
def get_time_series(filters: typing.List[dict], threads=1, async=False, processor: typing.Callable = None... |
11596705 | import os
import sys
import sphinx_rtd_theme
sys.path.insert(0,(os.path.abspath(os.path.join('..','snowshu'))))
sys.path.insert(0,(os.path.abspath('..')))
master_doc = 'index'
extensions = [
"sphinx_rtd_theme",
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
# "sphinx_autodoc_typehints",
]
html_theme ... |
11596727 | from __future__ import division, print_function
import sys
import numpy as np
class PeriodicOptimizer(object):
def find_best_periods(self, model, n_periods=5, return_scores=False):
raise NotImplementedError()
def best_period(self, model):
periods = self.find_best_periods(model, n_periods=1,... |
11596733 | import torch
import torch.nn as nn
from model.base_model import BaseModel
import network.hand_depth_net as depth_net
from network.projection import create_projection_net
import util.image as image
from util.joint import JointConverter
class Pix2DepthModel(BaseModel):
def setup(self, make_optimizer = Tru... |
11596759 | from sofi.ui import FormGroup
def test_basic():
assert(str(FormGroup()) == "<div class=\"form-group\"></div>")
def test_text():
assert(str(FormGroup("text")) == "<div class=\"form-group\">text</div>")
def test_custom_class_ident_style_and_attrs():
assert(str(FormGroup("text", cl='abclass', ident='123', s... |
11596760 | from pymatgen.symmetry.analyzer import SpacegroupAnalyzer, SpacegroupOperations, PointGroupAnalyzer
from pymatgen.util.coord import coord_list_mapping_pbc, coord_list_mapping
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Molecule, Structure
from bsym import SpaceGroup, SymmetryOperation... |
11596806 | from dataset.FlowInfer import FlowInfer
from models import LiteFlowNet
import math
from tqdm import tqdm
from torch.utils.data import DataLoader
import cvbase as cvb
import torch
import numpy as np
import sys
import os
import argparse
sys.path.append(os.path.abspath(os.path.join(__file__, '..', '..')))
def parse_args... |
11596817 | from subprocess import check_call
import os
import os.path as op
import shutil as sh
import yaml
from nbclean import NotebookCleaner
import nbformat as nbf
from tqdm import tqdm
import numpy as np
from glob import glob
import argparse
DESCRIPTION = ("Convert a collection of Jupyter Notebooks into Jekyll "
... |
11596838 | import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
import math
from sklearn.cluster import KMeans
from .base_predictor import BasePredictor
"""
Bayesian Learning optimizer
- We will use the Gaussian Prior by default with the Matern Kern... |
11596839 | from hippy.builtin import wrap, Optional
from rpython.rlib import rzlib
import sys
ZLIB_ENCODING_RAW = -15
ZLIB_ENCODING_GZIP = 31
ZLIB_ENCODING_DEFLATE = 15
ZLIB_ENCODING_ANY = 99
def _encode(data, level, encoding):
stream = rzlib.deflateInit(level=level, wbits=encoding)
bytes = rzlib.compress(stream, data... |
11596860 | import io
class StringBuffer(object):
def __init__(self):
self.empty = True;
self._stringio = io.StringIO()
def __str__(self):
val = self._stringio.getvalue()
self._stringio.close()
return val
def append(self, obj):
data = unicode(obj)
if self.empty and len(data) > 0:
sel... |
11596870 | from copy import deepcopy
class MatchData:
"""Contains and collects metadata about a matching document.
A single instance of lunr.MatchData is returned as part of every
lunr.Index.Result.
"""
def __init__(self, term=None, field=None, metadata=None):
self.metadata = {}
if term is ... |
11596872 | import wrapt
import sqlite3
from aws_xray_sdk.ext.dbapi2 import XRayTracedConn
def patch():
wrapt.wrap_function_wrapper(
'sqlite3',
'connect',
_xray_traced_connect
)
def _xray_traced_connect(wrapped, instance, args, kwargs):
conn = wrapped(*args, **kwargs)
meta = {}
m... |
11596900 | expected_output = {
"TenGigabitEthernet0/0/0.101": {
"service_policy": {
"input": {
"policy_name": {
"L3VPNin": {
"class_map": {
"IPP11111": {
"match_evaluation": "match-all",
... |
11596968 | from DeepSparseCoding.tf1x.params.base_params import BaseParams
TRAIN_ON_RECON = False
class params(BaseParams):
def __init__(self):
"""
Additional modifiable parameters:
rectify_a [bool] If set, rectify layer 1 activity
norm_weights [bool] If set, l2 normalize weights after updates
bat... |
11597017 | import symjax
import symjax.tensor as T
# scope/graph naming and accessing
value1 = T.Variable(T.ones((1,)))
value2 = T.Variable(T.zeros((1,)))
g = symjax.Graph("special")
with g:
value3 = T.Variable(T.zeros((1,)))
value4 = T.Variable(T.zeros((1,)))
result = value3 + value4
h = symjax.Graph("inversi... |
11597043 | import json
from flask import g, request, render_template
import requests
from agaveflask.logs import get_logger
logger = get_logger(__name__)
from models import dict_to_camel, display_time
def dashboard():
# default to using the local instance
try:
jwt = g.jwt
except AttributeError:
er... |
11597109 | import os
import autopep8
class Dumper:
DEFAULT_IMPORTS = 'from auror_core.v2.job import Command\n\n\n'
def __init__(self, path):
if not os.path.exists(path):
raise ValueError('Directory, {}, does not exist'.format(path))
self.path = path
def dump_jobs(self, *jobs):
... |
11597115 | from rest_framework import serializers
from ..models import Form
class FormSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='form-detail', lookup_field='slug')
class Meta:
fields = (
'url',
'slug',
'title',
... |
11597117 | import unittest
from cert_core import Chain
from pycoin.serialize import b2h
from cert_issuer.merkle_tree_generator import MerkleTreeGenerator
from cert_issuer import helpers
from lds_merkle_proof_2019.merkle_proof_2019 import MerkleProof2019
def get_test_data_generator():
"""
Returns a generator (1-time it... |
11597123 | from typing import Callable
import flax
import jax.numpy as jnp
def mse_loss(params: flax.core.frozen_dict.FrozenDict, apply_fn: Callable,
X: jnp.ndarray, y: jnp.ndarray):
y_hat = apply_fn(params, X)
predictor_loss = jnp.sum((y - y_hat)**2, 1).mean()
return predictor_loss, (y - y_hat)**2
|
11597209 | import argparse
import os
from pystdlib.uishim import get_selection_rofi
from pystdlib.passutils import collect_entries, read_entry_raw, annotate_entry
from pystdlib import shell_cmd
parser = argparse.ArgumentParser(description="Some pass automation")
parser.add_argument('--store', dest="store_path",
... |
11597283 | import sys
sys.path.append('../')
import numpy as np
#################################### args
import argparse
parser = argparse.ArgumentParser()
# model
parser.add_argument("--configuration", default='L1', nargs='?', type=str)
parser.add_argument("--mode", default='IWAE', nargs='?', type=str)
parser.add_argument(... |
11597286 | from django.conf.urls import patterns, url
from kitsune.customercare import api
# API urls
urlpatterns = patterns(
'',
url(r'^banned$', api.BannedList.as_view(), name='customercare.api.banned'),
url(r'^ban$', api.ban, name='customercare.api.ban'),
url(r'^unban$', api.unban, name='customercare.api.unb... |
11597291 | from ceph_medic.checks import common
from ceph_medic import metadata
class TestGetFsid(object):
def setup(self):
metadata['cluster_name'] = 'ceph'
def make_metadata(self, contents=None):
contents = contents or ''
data = {'paths': {'/etc/ceph':{'files':{'/etc/ceph/ceph.conf':{'content... |
11597292 | from ewah.operators.base import EWAHBaseOperator
from ewah.constants import EWAHConstants as EC
from ewah.hooks.base import EWAHBaseHook as BaseHook
from sshtunnel import SSHTunnelForwarder
from tempfile import NamedTemporaryFile
from datetime import timedelta
from pytz import timezone
import os
from typing import ... |
11597303 | import pandas as pd
import numpy as np
from pyids import IDS
from pyids.algorithms import mine_CARs
from pyids.data_structures import IDSRuleSet
from pyarc.qcba.data_structures import QuantitativeDataFrame
import random
import logging
import time
logging.basicConfig(level=logging.INFO)
df = pd.read_csv("../../../da... |
11597305 | import tensorflow as tf
__all__ = ["gan_discriminator_loss", "gan_generator_loss"]
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
def gan_discriminator_loss(real_output, fake_output):
r"""
Args:
real_output (tensor): A tensor representing the real logits of discriminator
... |
11597340 | from tkinter import *
root=Tk()
s=StringVar()
def disp(x):
global text
text+=x
s.set(text)
def equal():
global text
text=''
try:
text=eval(s.get())
except Exception as e:
s.set(e)
text=''
else:
s.set(text)
text=''
text=''
# root.geometry("300x300")... |
11597361 | from joblib import dump, load
from datetime import date
import mlflow.pyfunc
from mlflow import pyfunc
from util import load_yaml, load_json
class Wrapper(mlflow.pyfunc.PythonModel):
def __init__(self, model=None, preprocessing=None, metrics=None, columns=None):
"""
Constructor
Paramet... |
11597362 | import os
import unittest
from django.test import SimpleTestCase, override_settings, tag
from anymail.exceptions import AnymailAPIError
from anymail.message import AnymailMessage
from .utils import AnymailTestMixin, sample_image_path
# For most integration tests, Postmark's sandboxed "POSTMARK_API_TEST" token is u... |
11597385 | import numpy as np
import code
import theano
from theano import config
import theano.tensor as T
from theano.ifelse import ifelse
from theano.tensor.extra_ops import fill_diagonal
from collections import OrderedDict
import time
from imagernn.utils import *
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomS... |
11597391 | import pytest
from mitmproxy.net import http
from mitmproxy.net import websockets
class TestUtils:
def test_client_handshake_headers(self):
h = websockets.client_handshake_headers(version='42')
assert h['sec-websocket-version'] == '42'
h = websockets.client_handshake_headers(key='some-k... |
11597414 | from .testing import GraphQLTestCase
from .utils import (
DJANGO_FILTER_INSTALLED,
camelize,
get_model_fields,
get_reverse_fields,
is_valid_django_model,
maybe_queryset,
)
__all__ = [
"DJANGO_FILTER_INSTALLED",
"get_reverse_fields",
"maybe_queryset",
"get_model_fields",
"cam... |
11597434 | import lyrebird
import os
import json
import codecs
storage = lyrebird.get_plugin_storage()
CONFIG_FILE = os.path.abspath(os.path.join(storage, 'conf.json'))
DEFAULT_CONF_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', './default_conf/conf.json'))
class Config:
def __init__(self):
s... |
11597493 | import os
import subprocess
import time
def parallel_submitter(cmd_list, log_dir='./logs', logfilename_list=None, num_workers=None):
"""
Run subprocesses in parallel
Import (after installing PMP):
>> from pcmdi_metrics.misc.scripts import parallel_submitter
Inputs:
- cmd_list: python list o... |
11597508 | import numpy as np
import pyflux as pf
noise = np.random.normal(0,1,40)
data = np.zeros(40)
for i in range(1,len(data)):
data[i] = 0.9*data[i-1] + noise[i]
def test_couple_terms():
"""
Tests an GPNARX model with 1 AR term and that
the latent variable list length is correct, and that the estimated
latent variabl... |
11597526 | from typing import Sequence
from pydantic import conint
from rastervision.pipeline.config import (Config, register_config, Field,
ConfigError, validator)
from rastervision.core.data.raster_source import (RasterSourceConfig,
Mul... |
11597550 | from decimal import Decimal
from django.db import models
import directory.models as directory
class PriceName(models.Model):
title = models.CharField(max_length=511, unique=True, help_text='Наименование Прайса', db_index=True)
active_status = models.BooleanField(default=True, help_text='Статус активности', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.