id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
52915 | import marbles.core
class ComplexTestCase(marbles.core.AnnotatedTestCase):
def test_for_edge_case(self):
self.assertTrue(False)
if __name__ == '__main__':
marbles.core.main()
|
52928 | from secml.ml.features.normalization.tests import CNormalizerTestCases
from sklearn.preprocessing import StandardScaler
from secml.ml.features.normalization import CNormalizerMeanStd
class TestCNormalizerMeanStd(CNormalizerTestCases):
"""Unittests for CNormalizerMeanStd."""
def test_transform(self):
... |
52969 | from flask import Flask, request, jsonify
from sqlalchemy import create_engine
app = Flask(__name__)
engine = create_engine("mysql+pymysql://root:admin@db:3306/mydb")
@app.route("/members", methods=["POST"])
def members():
body = request.json
with engine.connect() as connection:
connection.execute(... |
53003 | import os # system()
def can_build(env, platform):
if platform == "x11":
has_pulse = os.system("pkg-config --exists libpulse-simple") == 0
has_alsa = os.system("pkg-config --exists alsa") == 0
return has_pulse or has_alsa
elif platform in ["windows", "osx", "iphone", "android"]:
... |
53020 | import urllib.request, urllib.parse, urllib.error
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
import ssl
import sqlite3
conn = sqlite3.connect('wiki2.sqlite')
cur = conn.cursor()
cur.executescript(... |
53029 | from . import core
import io
import re
import requests
import pytz
import time
import datetime as dt
import dateutil.parser as du
import numpy as np
import pandas as pd
from typing import Tuple, Dict, List, Union, ClassVar, Any, Optional, Type
import types
class ... |
53079 | from django.conf.urls import url
from . import views
urlpatterns = [
# generic profile endpoint
url(r'^profile/(?P<username>\w+)/', views.profile, name='profile-api'),
# current user profile
url(r'^profile/', views.profile, name='profile-api'),
]
|
53119 | import gym
from gym.spaces.box import Box
class TransposeImagesIfRequired(gym.ObservationWrapper):
"""
When environment observations are images, this wrapper transposes
the axis. It is useful when the images have shape (W,H,C), as they can be
transposed "on the fly" to (C,W,H) for PyTorch convolutions... |
53138 | import os
from bottle import Bottle, static_file, run
HERE = os.path.abspath(os.path.dirname(__file__))
STATIC = os.path.join(HERE, 'static')
app = Bottle()
@app.route('/')
@app.route('/<filename:path>')
def serve(filename='index.html'):
return static_file(filename, root=STATIC)
if __name__ == '__main__':
... |
53155 | from locust import HttpUser, task, between
class LoadTest(HttpUser):
@task
def test(self):
self.client.get('/') |
53168 | from uninas.utils.args import Argument
from uninas.register import Register
from uninas.methods.abstract import AbstractBiOptimizationMethod
from uninas.methods.strategies.manager import StrategyManager
from uninas.methods.strategies.differentiable import DifferentiableStrategy
@Register.method(search=True)
class Asa... |
53177 | import pandas as pd
dataset = pd.read_csv('iris.csv')
dataset.boxplot(column = 'sepal_width',by = 'species')
import matplotlib.pyplot as plt
hours_slices = [8,16]
activities = ['work','sleep']
colors = ['g','r']
plt.pie(hours_slices,labels=activities,colors=colors,startangle=90,autopct='%.1f%%')
plt.show()
... |
53198 | import os, sys
import warnings
__thisdir__ = os.path.dirname(os.path.realpath(__file__))
# Testing the import of the numpy package
def test_import_numpy():
try:
import numpy as np
except ImportError as e:
assert(1 == 0), "Numpy could not be imported:\n %s" %e
sys.path.pop(0)
# Testing the ... |
53226 | from trasto.model.entities import EstadoHumorRepositoryInterface
from trasto.model.value_entities import ResultadoAccion
from trasto.model.events import EventRepositoryInterface
class SensorInterface:
def listen_to_task_result(self, evento_repo: EventRepositoryInterface) -> None:
pass
def update_hu... |
53251 | import pulumi
from pulumi_aws import ec2, get_availability_zones
stack_name = pulumi.get_stack()
project_name = pulumi.get_project()
config = pulumi.Config('vpc')
vpc = ec2.Vpc(resource_name=f"eks-{project_name}-{stack_name}",
cidr_block="10.100.0.0/16",
enable_dns_support=True,
... |
53267 | import json
import os
import re
import sys
import maya.cmds as cmds
import maya.mel as mel
current_user = None
asset_size = 100
child_entries_margin = 5
child_assets_column = 3
asset_store_window = "houdiniEngineAssetStoreWindow"
change_user_menu_item = "houdiniEngineAssetStoreChangeUserMenuItem"
asset_entries_scro... |
53277 | from tests.test_resources.helper import select_random_from_list
def get_muncipalities_with_hits():
with_hits = []
for m in municipalities:
if m['hits'] > 0:
with_hits.append(m)
return with_hits
def get_ten_random_municipalities_with_hits():
return select_random_from_list(full_lis... |
53315 | from tgt_grease.enterprise.Model import Detector
import re
class Regex(Detector):
"""Regular Expression Detector for GREASE Detection
A Typical Regex configuration looks like this::
{
...
'logic': {
'Regex': [
{
'fie... |
53348 | from boa3.builtin.interop.runtime import invocation_counter
def Main(example: int) -> int:
invocation_counter = example
return invocation_counter
|
53352 | import json
import glob
import os
import argparse
import time
_DEFAULT_DATASET_DIR_PATH = "D:\\Documents\\output_vvs_2020\\labeled"
_DEFAULT_METADATA_PATH = "C:\\Users\\Steven\\github\\kvasir-capsule\\metadata.json"
_DEFAULT_WORK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
_ANATOMY_CLASSES =... |
53377 | from collections import defaultdict
from copy import copy, deepcopy
from tqdm import tqdm
from ..eventuality import Eventuality
from ..relation import Relation
def conceptualize_eventualities(aser_conceptualizer, eventualities):
""" Conceptualize eventualities by an ASER conceptualizer
:param aser_conceptual... |
53422 | from shlex import split
import json
class RawCommand:
def __init__(self, command, client="local", posix=True, inline=False):
# TODO: check shlex.quote, raw string, etc..
if inline:
self.command = split(command, posix=posix)
else:
self.command = split(command, posix=... |
53426 | from happytransformer import HappyNextSentence
def test_sp_true():
happy_ns = HappyNextSentence()
result = happy_ns.predict_next_sentence(
"Hi nice to meet you. How old are you?",
"I am 21 years old."
)
assert result > 0.5
def test_sp_false():
happy_ns = HappyNextSentence()
r... |
53463 | import torch
import numpy as np
from torch import nn
from torch.nn import functional as F
# from modeling.dynamic_filters.multiheadatt import TransformerBlock
from modeling.dynamic_filters.build import DynamicFilter,ACRM_query,ACRM_video
from utils import loss as L
from utils.rnns import feed_forward_rnn
import utils.p... |
53482 | import re
from functools import lru_cache
from pathlib import Path
import typing as T
from yaml import dump as yaml_dump
from faker import Faker
from faker.config import AVAILABLE_LOCALES
from tools.faker_docs_utils.format_samples import (
yaml_samples_for_docstring,
snowfakery_output_for,
)
from .summarize_fa... |
53511 | import numpy as np
import torch
from fairseq.data.indexed_dataset import __best_fitting_dtype, MMapIndexedDatasetBuilder, IndexedDatasetBuilder
from fairseq.tokenizer import tokenize_line
# TODO move this file into data folder
def make_builder(out_file, impl, vocab_size=None, dtype=None):
if impl == 'mmap':
... |
53512 | from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
from robot_server.robot.calibration.constants import STATE_WILDCARD
if TYPE_CHECKING:
from typing_extensions import Final
class PipetteOffsetCalibrationState(str, Enum):
sessionStarted = "sessionStarted"
labwareLoa... |
53523 | while(True):
jars = [int(x) for x in input().split()]
if sum(jars) == 0:
break
if sum(jars) == 13:
print("Never speak again.")
elif jars[0] > jars[1]:
print("To the convention.")
elif jars[1] > jars[0]:
print("Left beehind.")
elif jars[1] == jars[0]:
print... |
53618 | import time
import eventlet
import ast
from st2reactor.sensor.base import PollingSensor
__all_ = [
'AutoscaleGovernorSensor'
]
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=True,
time=True)
GROUP_ACTIVE_STATUS = [
'expanding',
'deflating'
]
class AutoscaleGovernor... |
53630 | import nltk
from nltk.corpus import wordnet
from nltk.corpus import wordnet as wn
from nltk.corpus import wordnet_ic
brown_ic = wordnet_ic.ic('ic-brown.dat')
semcor_ic = wordnet_ic.ic('ic-semcor.dat')
from nltk.corpus import genesis
genesis_ic = wn.ic(genesis, False, 0.0)
lion = wn.synset('lion.n.01')
cat = wn.synset('... |
53678 | from .exception import NuRequestException, NuException
from .nubank import Nubank
from .utils.mock_http import MockHttpClient
from .utils.http import HttpClient
from .utils.discovery import DISCOVERY_URL
def is_alive(client: HttpClient = None) -> bool:
if client is None:
client = HttpClient()
respons... |
53681 | import argparse
from FVC_utils import load_from_pickle, save_to_pickle, readData, printx, time, path
from xgboost import XGBClassifier
import warnings
warnings.filterwarnings('ignore')
# from sklearn.preprocessing import StandardScaler
def training_series(X_train, y_train, normalizer=None, xgb_params={}):
printx('... |
53692 | from itsdangerous import TimedJSONWebSignatureSerializer, \
JSONWebSignatureSerializer
from nanohttp import settings, context, HTTPForbidden
class BaseJWTPrincipal:
def __init__(self, payload):
self.payload = payload
@classmethod
def create_serializer(cls, force=False, max_age=None):
... |
53739 | import datetime
import json
import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials
from fastapi import FastAPI
app = FastAPI()
@app.get("/stock/{ticker}")
async def get_stock_data(ticker: str):
ticker_data = yf.Ticker(ticker).info
mktopen = ticker_data["open"]
mkthigh = ti... |
53753 | from typing import Dict, List, Optional, Union
import numpy as np
import torch
MOLECULAR_ATOMS = (
"H,He,Li,Be,B,C,N,O,F,Ne,Na,Mg,Al,Si,P,S,Cl,Ar,K,Ca,Sc,Ti,V,Cr,Mn,Fe,Co,Ni,Cu,Zn,"
"Ga,Ge,As,Se,Br,Kr,Rb,Sr,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,Cd,In,Sn,Sb,Te,I,Xe,Cs,Ba,La,Ce,"
"Pr,Nd,Pm,Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu... |
53767 | import pytest
from ncoreparser.util import Size
class TestSize:
@pytest.mark.parametrize("size1, size2", [("1024 MiB", "1 GiB"),
("10 MiB", "10 MiB"),
("2048 KiB", "2 MiB")])
def test_equal(self, size1, size2):
... |
53769 | from bottle import (
template,
route,
redirect,
request,
)
from models import (
Article,
ArticleLinks,
Wiki,
Author,
Tag,
Metadata,
)
from peewee import SQL
from .decorators import *
from .wiki import wiki_home
from .media import image_search
from utils import Message, Error,... |
53794 | from geosolver.utils.prep import sentence_to_words_statements_values
__author__ = 'minjoon'
def test_prep():
paragraph = r"If \sqrt{x+5}=40.5, what is x+5?"
print(sentence_to_words_statements_values(paragraph))
if __name__ == "__main__":
test_prep()
|
53816 | import argparse
import calendar
from datetime import datetime
import glob
import os
import shutil
import subprocess
import sys
import gzip
import unifyQueryTypes
from utility import utility
import config
os.nice(19)
months = {'january': [1, 31],
'february': [2, 28],
'march': [3, 31],
'ap... |
53845 | import image, network, rpc, sensor, struct
import time
import micropython
from pyb import Pin
from pyb import LED
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)
def led_control(x):
if (x&1)==0: red_led.off()
elif (x&1)==1: red_led.on()
if (x&2)==0: green_led.off()
eli... |
53914 | from unittest.mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
from orchestra.tests.helpers import OrchestraTestCase
class MigrateCertificationsTestCase(OrchestraTestCase):
patch_path = ('orchestra.management.commands.'
'mig... |
53951 | def assert_revision(revision, author=None, message=None):
"""Asserts values of the given fields in the provided revision.
:param revision: The revision to validate
:param author: that must be present in the ``revision``
:param message: message substring that must be present in ``revision``
"""
... |
53963 | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
def add_scatter(ax,x,y,c='b',m='o',lab='',s=80,drawln=False,alpha=1):
ax.scatter(x,y, s=s, lw=2.,facecolors='none',edgecolors=c, marker=m,label=lab,alpha=alpha)
if drawln: ax.plot(x,y, c=c,ls='-'... |
53984 | from ..MetaDataObject.core.Simple import Simple
class Constant(Simple):
ext_code = {
'mgr': '1', # модуль менеджера Константы
'obj': '0', # модуль менеджера значения Константы
}
@classmethod
def get_decode_header(cls, header_data):
return header_data[0][1][1][1][1]
|
54030 | from trajminer import TrajectoryData
from trajminer.preprocessing import TrajectorySegmenter
data = TrajectoryData(attributes=['poi', 'hour', 'rating'],
data=[[['Bakery', 8, 8.6], ['Work', 9, 8.9],
['Restaurant', 12, 7.7], ['Bank', 12, 5.6],
... |
54077 | from django import template
import logging
from django.conf import settings
from django.template.defaultfilters import stringfilter
from django_cradmin import css_icon_map
register = template.Library()
log = logging.getLogger(__name__)
@register.simple_tag
@stringfilter
def cradmin_icon(iconkey):
"""
Retu... |
54079 | from os.path import join, exists
import datatable as dt
from rs_datasets.data_loader import download_dataset
from rs_datasets.generic_dataset import Dataset, safe
class YooChoose(Dataset):
def __init__(self, path: str = None):
"""
:param path: folder which is used to download dataset to
... |
54122 | import types
import threading
import time
__all__ = 'suspend', 'suspending', 'start', 'Continuation',
_CONT_REQUEST = object()
@types.coroutine
def suspend(fn, *args):
"""Suspend the currently running coroutine and invoke FN with the continuation."""
cont = yield _CONT_REQUEST
fn(cont, *args)
cont_re... |
54123 | import sys
from pathlib import Path
import os
import torch
from torch.optim import Adam
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from networks.critic import Critic
from networks.actor import NoisyActor, CategoricalActor, GaussianActor
base_dir = Path(__file__).resolve().parent.parent.... |
54193 | from numpy import ndarray, array
from electripy.physics.charges import PointCharge
class _ChargesSet:
"""
A _ChargesSet instance is a group of charges. The electric
field at a given point can be calculated as the sum of each
electric field at that point for every charge in the charge
set.
"""
... |
54214 | import os
import pathlib
import sys
import subprocess
sys.path.insert(1, str(pathlib.Path(__file__).parent.absolute())+"/../../../../parser")
#sys.path.insert(1, '/usr/workspace/wsa/laguna/fpchecker/FPChecker/parser')
from tokenizer import Tokenizer
source = "compute_inst.cu"
def setup_module(module):
THIS_DIR = o... |
54234 | import multiprocessing as mp
import os
import subprocess
import time
import pytest
from solarforecastarbiter.io import fetch
def badfun():
raise ValueError
def bad_subprocess():
subprocess.run(['cat', '/nowaythisworks'], check=True, capture_output=True)
@pytest.mark.asyncio
@pytest.mark.parametrize('ba... |
54290 | import numpy as np
__copyright__ = 'Copyright (C) 2018 ICTP'
__author__ = '<NAME> <<EMAIL>>'
__credits__ = ["<NAME>", "<NAME>"]
def get_x(lon, clon, cone):
if clon >= 0.0 and lon >= 0.0 or clon < 0.0 and lon < 0.0:
return np.radians(clon - lon) * cone
elif clon >= 0.0:
if abs(clon - lon + 3... |
54293 | import os
import shutil
def move_files(files, src_prefix, dst_prefix, app_name):
for file_name, attributes in files.items():
file_path = os.path.join(src_prefix, file_name)
dest_path = os.path.join(dst_prefix, file_name)
if attributes["static"]:
shutil.copy(file_path, dest_path... |
54294 | from setuptools import setup, find_packages
import os
setup_dir = os.path.dirname(__file__)
readme_path = os.path.join(setup_dir, 'README.rst')
version_path = os.path.join(setup_dir, 'keyfree/version.py')
requirements_path = os.path.join(setup_dir, "requirements.txt")
requirements_dev_path = os.path.join(setup_dir, "... |
54306 | import numpy as np
import random
# Softmax function, optimized such that larger inputs are still feasible
# softmax(x + c) = softmax(x)
def softmax(x):
orig_shape = x.shape
x = x - np.max(x, axis = 1, keepdims = True)
exp_x = np.exp(x)
x = exp_x / np.sum(exp_x, axis = 1, keepdims = True)
assert x.shape == orig_sh... |
54328 | class CheckFileGenerationEnum:
GENERATED_SUCCESS = "generated_success"
GENERATED_EMPTY = "generated_empty"
NOT_GENERATED = "not_generated"
# try to find the internal value and return
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
# p... |
54385 | import numpy as np
import pandas as pd
import unittest
from bdranalytics.sklearn.model_selection import GrowingWindow, IntervalGrowingWindow
def create_time_series_data_set(start_date=pd.datetime(year=2000, month=1, day=1), n_rows=100):
end_date = start_date + pd.Timedelta(days=n_rows-1)
ds = np.random.ran... |
54386 | import base64
class Pdf:
def __init__(self, fname=None, data=None, width='100%',
height='300px', border=False, log=None):
self.fname = fname
self.data = data
self.width = width
self.height = height
self.border = border
self.log = log
def save(s... |
54451 | from common import randstr, AES_CTR, xor_str
from random import randint
oracle_key = randstr(16)
oracle_nonce = randint(0, (1 << 64) - 1)
def encryption_oracle(data):
data = data.replace(';', '').replace('=', '')
data = "comment1=cooking%20MCs;userdata=" + data
data = data + ";comment2=%20like%20a%20poun... |
54454 | def approve_new_user(sender, instance, created, *args, **kwarg):
if created:
instance.is_staff = True
instance.is_superuser = True
instance.save()
|
54458 | import os
import math
import xls_cli.ansi as ansi
from xls_cli.grid import Grid
from getkey import getkey, keys
class Frame:
width, height = 0, 0
printable_window = "\x1B[2J"
title = "unititled"
grid = None
def __init__(self, title):
rows, columns = os.popen('stty size', 'r').read().spl... |
54474 | import os
from utils import load_json
from utils import print_err
from global_settings import SCENE_BUILDER_OUTPUT_DIR
class SceneBuilderConfig(object):
def __init__(
self,
input_scene_dir,
scene_builder_root,
output_dir_name,
rigid_mesh_db,
articulated_mesh_db,
... |
54493 | from django.utils.deprecation import MiddlewareMixin
class MyCors(MiddlewareMixin):
def process_response(self, requesst, response):
response['Access-Control-Allow-Origin'] = '*'
if requesst.method == 'OPTIONS':
response["Access-Control-Allow-Headers"] = "*"
response['Access... |
54514 | import sys
from Quartz import *
import Utilities
import array
def doColorSpaceFillAndStroke(context):
theColorSpace = Utilities.getTheCalibratedRGBColorSpace()
opaqueRed = ( 0.663, 0.0, 0.031, 1.0 ) # red,green,blue,alpha
aBlue = ( 0.482, 0.62, 0.871, 1.0 ) # red,green,blue,alpha
# Set the fill ... |
54544 | import random
import cocotb
from cocotb.decorators import coroutine
from cocotb.result import TestFailure, ReturnValue
from cocotb.triggers import RisingEdge, Edge
from cocotblib.misc import log2Up, BoolRandomizer, assertEquals, waitClockedCond, randSignal
class Apb3:
def __init__(self, dut, name, clk = None):
... |
54547 | import base64
from ...base import BaseParser, datetime_to_string, string_to_datetime
class Image(BaseParser):
def __init__(self, d=None, **kwargs):
BaseParser.__init__(self, d, **kwargs)
self.image_location = None
@property
def product_id(self):
return self._dict.get('product_id... |
54566 | import datetime
import utils
import glob
import os
import numpy as np
import pandas as pd
if __name__ == '__main__':
loaddir = "E:/Data/h5/"
labels = ['https', 'netflix']
max_packet_length = 1514
for label in labels:
print("Starting label: " + label)
savedir = loaddir + label + "/"
... |
54587 | import utils
import vss
from crypto import G1, G2, add, neg, multiply, random_scalar, check_pairing
w3 = utils.connect()
contract = utils.deploy_contract('DKG')
def test_add():
a = multiply(G1, 5)
b = multiply(G1, 10)
s = add(a, b)
assert contract.bn128_add([a[0], a[1], b[0], b[1]]) == list(s)
def... |
54600 | from drf_yasg.utils import (
swagger_auto_schema as schema,
swagger_serializer_method as schema_serializer_method,
)
from .yasg import (
BananasSimpleRouter as BananasRouter,
BananasSwaggerSchema as BananasSchema,
)
__all__ = (
"schema",
"schema_serializer_method",
"BananasRouter",
"Ba... |
54607 | child_network_params = {
"learning_rate": 3e-5,
"max_epochs": 100,
"beta": 1e-3,
"batch_size": 20
}
controller_params = {
"max_layers": 3,
"components_per_layer": 4,
'beta': 1e-4,
'max_episodes': 2000,
"num_children_per_episode": 10
}
|
54617 | import base64
import secrets
import cryptography.hazmat.primitives.ciphers
import cryptography.hazmat.primitives.ciphers.algorithms
import cryptography.hazmat.primitives.ciphers.modes
import cryptography.hazmat.backends
'''
This module provides AES GCM based payload protection.
Flow:
1. aes_gcm_generate_key() to ge... |
54658 | import pytest
from django.contrib.auth import get_user_model
from django.template import Context, Template
from proposals.models import AdditionalSpeaker, TalkProposal
def render_template(template_string, context_data=None):
context_data = context_data or {}
return Template(template_string).render(Context(c... |
54664 | from resotolib.config import Config
from resoto_plugin_example_collector import ExampleCollectorPlugin
def test_config():
config = Config("dummy", "dummy")
ExampleCollectorPlugin.add_config(config)
Config.init_default_config()
# assert Config.example.region is None
|
54714 | def howmanyfingersdoihave():
ear.pauseListening()
sleep(1)
fullspeed()
i01.moveHead(49,74)
i01.moveArm("left",75,83,79,24)
i01.moveArm("right",65,82,71,24)
i01.moveHand("left",74,140,150,157,168,92)
i01.moveHand("right",89,80,98,120,114,0)
sleep(2)
i01.moveHand("right",... |
54734 | import os
import utils
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
import numpy as np
import data
import scipy.io as sio
from options.training_options import TrainOptions
import utils
import time
from models import AutoEncoderCov3D, AutoEncoderCov3DMem
f... |
54747 | from functools import partial
from os import path
from .obj import load_obj, save_obj
from .off import load_off, save_off
def load_mesh(filename):
loaders = {
'obj': load_obj,
'off': partial(load_off, no_colors=True),
}
ext = path.splitext(filename)[1].lower()[1:]
if ext not in loader... |
54777 | expected_output = {
"aal5VccEntry": {"3": {}, "4": {}, "5": {}},
"aarpEntry": {"1": {}, "2": {}, "3": {}},
"adslAtucChanConfFastMaxTxRate": {},
"adslAtucChanConfFastMinTxRate": {},
"adslAtucChanConfInterleaveMaxTxRate": {},
"adslAtucChanConfInterleaveMinTxRate": {},
"adslAtucChanConfMaxInter... |
54805 | import functools
import itertools
import operator
import numpy as np
from qecsim.model import StabilizerCode, cli_description
from qecsim.models.rotatedplanar import RotatedPlanarPauli
@cli_description('Rotated planar (rows INT >= 3, cols INT >= 3)')
class RotatedPlanarCode(StabilizerCode):
r"""
Implements ... |
54817 | import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import lrn
fX = theano.config.floatX
def ground_truth_normalizer(bc01, k, n, alpha, beta):
"""
This code is adapted from pylearn2.
https://github.com/l... |
54832 | from PySide2.QtGui import QValidator
class RegValidator(QValidator):
def __init__(self, max_value):
super().__init__()
self.max_value = max_value
def validate(self, text, pos):
if text == '':
return QValidator.Acceptable
try:
value = int(text, 8)
... |
54846 | import typing
import torch
import torch.nn as nn
import torch.nn.functional as F
from .net_sphere import *
class ResCBAMLayer(nn.Module):
"""
CBAM+Res model
"""
def __init__(self, in_planes, feature_size):
super(ResCBAMLayer, self).__init__()
self.in_planes = in_planes
self.f... |
54861 | import re
import sys
from notebook.notebookapp import main
from qulab.utils import ShutdownBlocker
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
with ShutdownBlocker('jupyter-notebook'):
sys.exit(main())
|
54885 | from copy import deepcopy
import pytest
from catenets.datasets import load
from catenets.experiment_utils.tester import evaluate_treatments_model
from catenets.models.jax import FLEXTE_NAME, OFFSET_NAME, FlexTENet, OffsetNet
LAYERS_OUT = 2
LAYERS_R = 3
PENALTY_L2 = 0.01 / 100
PENALTY_ORTHOGONAL_IHDP = 0
MODEL_PARAM... |
54886 | import os
from functools import partial
# pymel
import pymel.core as pm
# mgear
import mgear
from mgear.maya import shifter, skin, pyqt, utils
GUIDE_UI_WINDOW_NAME = "guide_UI_window"
GUIDE_DOCK_NAME = "Guide_Components"
##############################
# CLASS
##############################
class Guide_UI(object):... |
54897 | from bgheatmaps.heatmaps import heatmap
from bgheatmaps.planner import plan
from bgheatmaps.slicer import get_structures_slice_coords
|
54939 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import h5py
import json
import os
import scipy.misc
import sys
import re
import fnmatch
import datetime
from PIL import Image
import numpy as np
'''
sr... |
54979 | import random
from task_widgets.task_base.intro_hint import IntroHint
from utils import import_kv
from .calculation import ModeOperandsCalculation
import_kv(__file__)
class IntroHintNumbersCalculation(IntroHint):
pass
class NumbersCalculation(ModeOperandsCalculation):
FROM = 101
TO = 899
TASK_KEY ... |
54997 | from pprint import pprint
import asyncio
import netdev
import yaml
r1 = {
"device_type": "cisco_ios",
"host": "192.168.100.1",
"username": "cisco",
"password": "<PASSWORD>",
"secret": "cisco",
}
async def send_show(device, commands):
result = {}
if type(commands) == str:
command... |
55025 | import unittest
from kivy3.loaders import OBJLoader
class OBJLoaderTest(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
|
55048 | from random import choice
TRID_CSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def gen_trid(length=12):
return ''.join(choice(TRID_CSET) for _i in range(length))
|
55077 | from pathlib import Path
from boucanpy.core import logger
from boucanpy.cli.base import BaseCommand
from boucanpy.db.models import models
class DbTruncate(BaseCommand):
name = "db-truncate"
aliases = ["truncate"]
description = "truncate db"
add_log_level = True
add_debug = True
@classmethod
... |
55080 | import os
path = ''
if not path:
eixt(1)
for root, dirs, files in os.walk(path):
for f in files:
if f == 'readme.md':
src = os.path.join(root, f)
# print(src)
dst = os.path.join(root, 'README.md')
os.rename(src, dst)
|
55110 | from vedacore.misc import build_from_cfg, registry
def build_loss(cfg):
return build_from_cfg(cfg, registry, 'loss')
|
55148 | from main.save_and_get import Abrufen
import config
example1 = Abrufen(config.bucket_name, config.subdir4rss, 'example1')
example2 = Abrufen(config.bucket_name, config.subdir4rss, 'example2')
|
55161 | import os
from AppKit import NSApp, NSImage
import vanilla
from mojo.UI import CurrentGlyphWindow, UpdateCurrentGlyphView,\
StatusInteractivePopUpWindow
from fontParts.world import CurrentGlyph
resourcesDirectory = os.path.dirname(__file__)
resourcesDirectory = os.path.dirname(resourcesDirectory)
resourcesDirector... |
55273 | from DaPy.core import Series, SeriesSet
from DaPy.core import is_seq
from copy import copy
def proba2label(seq, labels):
if hasattr(seq, 'shape') is False:
seq = SeriesSet(seq)
if seq.shape[1] > 1:
return clf_multilabel(seq, labels)
return clf_binlabel(seq, labels)
def clf_multilabel(seq,... |
55326 | from django.contrib import admin
from thing.models import APIKey, BlueprintInstance, Campaign, Character, CharacterConfig, Corporation, \
Alliance, APIKeyFailure, Asset, AssetSummary, BlueprintComponent, Blueprint, CorpWallet, \
TaskState, CharacterDetails, Contract, UserProfile, Transaction, JournalEntry, Colo... |
55330 | from domain.exceptions.application_error import ApplicationError
class ContainerNotFound(ApplicationError):
def __init__(self, additional_message: str = '', container_name: str = ''):
super().__init__("Container Name Not Found ", additional_message + '{}'.format(container_name))
class JobNotStarted(Appl... |
55331 | import numpy as np
from numpy.testing import assert_equal
import scipy.sparse as sp
import tensorflow as tf
from .math import (sparse_scalar_multiply, sparse_tensor_diag_matmul,
_diag_matmul_py, _diag_matmul_transpose_py)
from .convert import sparse_to_tensor
class MathTest(tf.test.TestCase):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.