id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3312287 | class Human:
age = 0
lastname = ''
firstname = ''
height = 0.0
weight = 0.0
sato = Human()
sato.age = 35
sato.lastname = '佐藤'
sato.firstname = '次郎'
sato.height = 174.1
sato.weight = 68.2
if( sato.age >= 35 and sato.lastname == '佐藤'):
print('選ばれた人->' + sato.lastname + ' ' + sato.firstname)
|
3312329 | import torch
from .mixmatch_base import MixMatchBase
# for type hint
from typing import List, Dict
from torch import Tensor
from torch.nn import Module
class SimPLE(MixMatchBase):
def __init__(self,
augmenter: Module,
strong_augmenter: Module,
num_classes: int,... |
3312335 | import multiprocessing
from py_wake.examples.data.hornsrev1 import Hornsrev1Site, wt_x, wt_y
from py_wake import IEA37SimpleBastankhahGaussian
from py_wake.tests.check_speed import timeit
import numpy as np
from py_wake.tests import npt
from py_wake.wind_turbines import WindTurbines
from py_wake.examples.data import wt... |
3312353 | import tensorflow as tf
import configuration
import numpy as np
from LSTM_model import LSTM_model
def main():
config = configuration.ModelConfig(data_filename="input_seqs_eval")
train(config)
def train(config):
with tf.Graph().as_default():
model = LSTM_model(config)
inputs_seqs_batch, outputs_batch = ... |
3312377 | from pyqmc.recipes import OPTIMIZE, VMC, DMC, read_mc_output, read_opt
from pyqmc.supercell import get_supercell
from pyqmc.accumulators import EnergyAccumulator, gradient_generator
from pyqmc.mc import vmc, initial_guess
from pyqmc.dmc import rundmc
from pyqmc.optvariance import optvariance
from pyqmc.linemin import l... |
3312418 | from __future__ import absolute_import
from .pyadexceptions import *
# http://msdn.microsoft.com/en-us/library/aa772263(VS.85).aspx
ADS_GROUP_TYPE = {
'GLOBAL':0x2,
'LOCAL':0x4,
'UNIVERSAL':0x8,
'SECURITY_ENABLED':-0x80000000}
# http://msdn.microsoft.com/en-us/library/aa772300.aspx
ADS_US... |
3312434 | import pytest
from wostools.fields import joined, delimited, integer, parse
def test_joined_joins_sequences():
assert joined(["hello", "world"]) == "hello world"
def test_delimited_split_strings():
assert delimited(["key; word;", "more; words"]) == ["key", "word", "more", "words"]
def test_delimited_spli... |
3312446 | from .utils import encode_attr
from .control import Control
# Point
class Point(Control):
def __init__(self, id=None, x=None, y=None, legend=None, color=None,
x_tooltip=None, y_tooltip=None):
Control.__init__(self, id=id)
self.x = x
self.y = y
self.legend = legend
s... |
3312463 | import FWCore.ParameterSet.Config as cms
fixedGridRhoFastjetAll = cms.EDProducer("FixedGridRhoProducerFastjet",
pfCandidatesTag = cms.InputTag("particleFlow"),
maxRapidity = cms.double(5.0),
gridSpacing = cms.double(0.55)
)
fixedGridRhoFastjetAllCalo = cms.EDProducer("FixedGridRhoProducerFastjet",
p... |
3312465 | import tensorflow as tf
import tensorflow.keras as ks
from kgcnn.ops.partition import change_partition_by_name, partition_row_indexing
from kgcnn.layers.base import GraphBaseLayer
@tf.keras.utils.register_keras_serializable(package='kgcnn',name='PoolingTopK')
class PoolingTopK(GraphBaseLayer):
"""Layer for pooli... |
3312483 | from paste import request
def urlparser_hook(environ):
first, rest = request.path_info_split(environ.get('PATH_INFO', ''))
if not first:
# No username
return
environ['app.user'] = first
environ['SCRIPT_NAME'] += '/' + first
environ['PATH_INFO'] = rest
|
3312490 | import ui
import console
import objc_util
class TransferManagementView (object):
def __init__(self, install_action, refresh_main_view, delete_action, refresh_transfer_action, theme_manager, transfer_manager, tv):
self.data = refresh_transfer_action()
self.delete_action = delete_action
self.install_action = insta... |
3312500 | import boto3
import base64
import logging
import logging.config
from botocore.exceptions import ClientError
from botocore.config import Config
config = Config(
retries = {
'max_attempts': 10,
'mode': 'standard'
}
)
session = boto3.session.Session()
kms = session.client('kms', config=config)
logging.... |
3312501 | import numpy as np
import torch
from utils import *
class MuRP(torch.nn.Module):
def __init__(self, d, dim):
super(MuRP, self).__init__()
self.Eh = torch.nn.Embedding(len(d.entities), dim, padding_idx=0)
self.Eh.weight.data = (1e-3 * torch.randn((len(d.entities), dim), dtype=torch.double, ... |
3312517 | import os
import re
import sys
import unittest
from array import array
from collections import defaultdict, deque
from sys import version_info, version
from unittest import skipIf
from tests.utils import TestCaseWithUtils, temp_attrs, assert_unique, Counter, skipUnless, OldStyleClass
try:
from collections import ... |
3312531 | def make_model_tuple(model):
"""
Take a model or a string of the form "app_label.ModelName" and return a
corresponding ("app_label", "modelname") tuple. If a tuple is passed in,
assume it's a valid model tuple already and return it unchanged.
"""
try:
if isinstance(model, tuple):
... |
3312539 | from __future__ import absolute_import, print_function
import unittest
import sys
class runner(object):
def runTest(self):
from pcpp import CmdPreprocessor
p = CmdPreprocessor(['pcpp'] + self.options + [
'-o', 'tests/issue0063.i',
'tests/iss... |
3312548 | from .config import AsyncConfig, Config
from .auth import Auth, AsyncAuth
from .analytics import Analytics, AsyncAnalytics
from .dir import Dir, AsyncDir
from .pipeline import Pipeline, AsyncPipeline
from .manager import Manager, AsyncManager
from .secrets import Secrets, AsyncSecrets, Secret, SecretKey
from .misc impo... |
3312554 | import time
import os
import sys
from pathlib import Path
import numpy as nump
import pandas as panda
import uuid
import csv
import inspect
import re
import platform
import requests
import json
from datetime import datetime
from tir.technologies.core.config import ConfigLoader
from tir.technologies.core.logging_config ... |
3312556 | import unittest
import numpy as np
from sca.util.data_partitioner import DataPartitioner
class TestDataPartitioner(unittest.TestCase):
def test_basic_run(self):
""" Tests a run with normal amount of traces to select."""
traces = np.array([[1, 2, 3], [4, 5, 6], [7, 0.4, 9], [2, 3, 12]])
... |
3312567 | import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA
sns.set_context('poster')
def view_emb(emb, dir):
'''
Visualize a embedding matrix.
Args:
emb (torch.tensor): Embedding matrix with shape (N, D). D is the
feature dimension.
dir (str): Out... |
3312570 | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, EqualTo
class RegisterClass(FlaskForm):
className = StringField(validators=[DataRequired()])
classToken = StringField(validators=[DataRequired()])
classTeacher = StringField(validators=[D... |
3312598 | from os import fdopen, remove
from shutil import move
import subprocess
import sys
from tempfile import mkstemp
from geomeppy import __version__
def replace(file_path, pattern, subst):
# Create temp file
fh, abs_path = mkstemp()
with fdopen(fh, "w") as new_file:
with open(file_path) as old_file:
... |
3312608 | from tinterface import World
tiles = []
from tlib import *
import sys
import time
z = 0
x = 0
# sys.argv.append("world1.wld")
if len(sys.argv) < 2:
print
"No World supplied, shutting down in 5 seconds"
time.sleep(5)
else:
origin = sys.argv[1]
world = World(origin)
header = world.header
f... |
3312661 | from .bytearray import ByteArray
import base64
import hashlib
salt = "".join(map(chr, [
247, 26, 166, 222, 143, 23, 118, 168,
3, 157, 50, 184, 161, 86, 178, 169,
62, 221, 67, 157, 197, 221, 206, 86,
211, 183, 164, 5, 74, 13, 8, 176
]))
packet_keys = []
identification_keys = []
msg_keys... |
3312667 | from django.utils.deprecation import MiddlewareMixin
class EuBuildMiddleware(MiddlewareMixin):
"""EU Ballot Firefox builds mangle inproduct URLs.
EU Ballot builds of Firefox add a /eu/ component to the incoming URL
from in-product help links. Unfortunately, they add it in the middle:
/1/<product... |
3312676 | import fs
from .setup import *
def test_add_suffix_to_filename():
_filename = 'test.csv'
_expected = 'test_suf.csv'
assert _expected == fs.add_suffix(_filename, "_suf")
def test_add_suffix_to_filename_in_path():
_filename = '/foo/bar/test.csv'
_expected = '/foo/bar/test_suf.csv'
assert ... |
3312679 | from .CU import CU
def CNU(control_qubits, work_qubits, unitary, unitary_block, kernel=None):
'''
The fabled Controlled-N Unitary Operator!
'''
control_qubits = kernel.definitions[control_qubits]
work_qubits = kernel.definitions[work_qubits]
print(control_qubits)
print(work_qubits)
p... |
3312699 | import logging
# noinspection PyPackageRequirements
from telegram.ext import CommandHandler, ConversationHandler
# noinspection PyPackageRequirements
from telegram import ChatAction, Update
from bot import stickersbot
from bot.database.base import session_scope
from bot.database.models.pack import Pack
from bot.strin... |
3312743 | import sys
import random
import copy
import collections
from sim import Ledger
class GlobalConsensus():
# List of frozensets , where a[i] corresponds to the new blocks from a tick stored in a
# frozenset
ledger = Ledger()
@classmethod
def init(cls, txns):
for txn in txns:
cls.ledge... |
3312764 | from causaldag import DAG
import numpy as np
def load_gml(filename):
raise NotImplementedError
pass
|
3312770 | import numpy
import theano
from theano import tensor
from dictlearn.util import vec2str
class WordToIdOp(theano.Op):
"""Replaces words with their ids."""
def __init__(self, vocab):
self._vocab = vocab
def make_node(self, input_):
input_ = tensor.as_tensor_variable(input_)
output_... |
3312905 | from sanic_jwt.validators import validate_single_scope
def test_validate_single_scope():
assert validate_single_scope("user", ["something"]) is False
assert validate_single_scope("user", ["user"])
assert validate_single_scope("user:read", ["user"])
assert validate_single_scope("user:read", ["user:read... |
3312976 | import sys
sys.path.append("../../lambda/")
from constant_variables import *
SESSION_INFO_1={DATASTORE_COLUMN_SESSION_ID : 's-1',
DATASTORE_COLUMN_PATIENT_ID: 'p-1',
DATASTORE_COLUMN_HEALTH_CARE_PROFESSSIONAL_ID: 'h-1',
DATASTORE_COLUMN_SESSION_NAME: 'SessionName',
... |
3313057 | import rdflib as rdf
import os, sys
from Constants import *
from NIDMExperiment import NIDMExperimentCore
class NIDMExperimentStudy(NIDMExperimentCore):
"""Class for NIDM-Experimenent Study-Level Objects.
Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py.
Addition... |
3313099 | import neural_network_lyapunov.slip_hybrid_linear_system as slip_hybrid
import neural_network_lyapunov.utils as utils
import unittest
import numpy as np
class SpringHybridLinearSystemTest(unittest.TestCase):
def setUp(self):
# Use the same setup as Underactuated Robotics.
mass = 80
l0 = 1... |
3313131 | import hashlib
def sample_hashes(x):
"""
Helper function that creates MD5 hashes of samples from a NumPy array.
Parameters
----------
x: a NumPuy array (or compatible, e.g. PyTables array)
The array to draw samples
Returns
-------
list
A list of MD5 hashes of the samp... |
3313141 | import asyncio
import logging
import os
from mqttrpc import MQTTRPC, dispatcher
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('hbmqtt').setLevel(level=logging.INFO)
class TestMQTTRPC(MQTTRPC):
@dispatcher.public
async def test(name=''):
print('Hello')
return 'Hello, {}'.format(na... |
3313192 | import argparse
import cv2
import yaml
from models.deblurring.joint_deblur import JointDeblur
def main():
parser = argparse.ArgumentParser(description="Kernel extractor testing")
parser.add_argument("--image_path", action="store", help="image path", type=str, required=True)
parser.add_argument("--save_p... |
3313199 | from bson import Binary
from mongomock import ObjectId
import sys
from pathlib import Path
import mongordkit
import pymongo
import pymongo.errors
import rdkit
from rdkit import Chem
import mongomock
from rdkit.Chem import AllChem
from mongordkit.Database import write, utils
from mongordkit.Search import similarity
from... |
3313211 | import unittest.mock as mock
import mycity.test.test_constants as test_constants
import mycity.test.integration_tests.intent_base_case as base_case
import mycity.test.integration_tests.intent_test_mixins as mix_ins
import mycity.intents.trash_intent as trash_intent
###################################
# TestCase class... |
3313212 | from libsaas import http, parsers
from libsaas.services import base
from . import ads
class Advertiser(base.HierarchicalResource):
path = 'advertisers'
@base.resource(ads.TextAd)
def textad(self, hash):
"""
Return a resource corresponding to a single text ad.
:var hash: A uniqu... |
3313282 | import importlib
import os
import sys
import ctypes
import io
from vergeml.utils import VergeMLError
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class Library:
@staticmethod
def is_installed():
raise NotImplementedError
@staticmethod
def version():
raise NotImplementedError
@staticme... |
3313315 | from abc import abstractmethod
from genrl.environments.vec_env.vector_envs import VecEnv
class VecEnvWrapper(VecEnv):
def __init__(self, venv):
self.venv = venv
super(VecEnvWrapper, self).__init__(envs=venv.envs, n_envs=venv.n_envs)
def __getattr__(self, name):
return getattr(self.ve... |
3313332 | import pickle
import plotly.graph_objs as go
from plotly.offline import plot
import numpy as np
import os
from Bio import SeqIO
pvogs_groups = [
'Lysis',
'Integration',
'Terminase',
'Replication',
'Coat',
'Baseplate',
'Tail',
'Assembly',
'Portal',
'Other (structural)',
'Othe... |
3313340 | description = 'Small charm detector'
group = 'optional'
tango_host = 'qmesydaq-test.del.frm2.tum.de'
tango_base = 'tango://%s:10000/qm/qmesydaq/' % tango_host
sysconfig = dict(
datasinks = ['ds_histogram',],
)
devices = dict(
ds_mon1 = device('nicos.devices.vendor.qmesydaq.tango.CounterChannel',
de... |
3313362 | import asyncio
import logging
from os import path
from config import Config
from pyrogram import (
Client,
idle
)
class TGclient(Client):
def __init__(self):
super().__init__(
"TGclient",
api_id=Config.API_ID,
api_hash=Config.API_HASH,
bot_token=Config.BOT_TOKEN,
workdir="./",... |
3313381 | import tensorflow as tf
class PiecewiseConstantDecayWithLinearWarmup(
tf.keras.optimizers.schedules.PiecewiseConstantDecay):
def __init__(self, warmup_learning_rate, warmup_steps, boundaries, values,
**kwargs):
super(PiecewiseConstantDecayWithLinearWarmup,
self).__in... |
3313382 | import simulation.speedLimits, random
from functools import reduce
from simulation.car import Car
class Road:
def __init__(self, lanesCount, length, speedLimits):
self.lanes = Road.generateEmptyLanes(lanesCount, length)
self.updatedLanes = Road.generateEmptyLanes(lanesCount, length)
self.sp... |
3313393 | from .eurosat import EuroSAT
from .sat import SAT
from .nwpu_resisc45 import NWPU_RESISC45
from .patternnet import PatternNet
|
3313405 | from office365.runtime.client_value import ClientValue
class PortalHealthStatus(ClientValue):
pass
|
3313427 | import pytest
import sys
import numpy as np
import os
#import os.path as osp
import yaml
import matplotlib.pyplot as plt
from scipy.interpolate import PchipInterpolator
import wisdem.inputs as sch # used for loading turbine YAML and using WISDEM validation process
from wisdem.commonse.utilities import arc_length
# ... |
3313446 | from time import sleep
from multiprocessing.dummy import Pool as ThreadPool, Event
event = Event()
def click():
# event.clear() # 设置标准为假(默认是False)
print("用户在修改网页表单")
sleep(2)
print("点击了修改案例")
event.set() # 设置标准为真
def update():
print(f"事件状态:{event.is_set()}")
event.wait() # 等待到标志为真
... |
3313458 | def contour(left,
right,
max_offset=None,
loffset=0,
roffset=0,
left_outer=None,
right_outer=None):
delta = left.x + loffset - (right.x + roffset)
if not max_offset or delta > max_offset:
max_offset = delta
if not left_outer:
... |
3313465 | from Ifc.ClassRegistry import ifc_definition
@ifc_definition
class Type:
"""
A TYPE definition in an Express schema
NOTE: Parsed only as deep as necessary
"""
def __init__(self, classname, defname, defspec, parser):
self.classname = classname
if not defspec.startswith("="):
... |
3313515 | from functools import update_wrapper
from types import MappingProxyType, SimpleNamespace
from .union import Union
#
# Case dispatch
#
def casedispatch(typ):
"""
Decorator that declares a method that participates in a case dispatch.
Example::
@casedispatch(Maybe.Just)
def incr(x):
... |
3313521 | import math
import time
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import geometry as gm
import rtx
scene = rtx.Scene(ambient_color=(0, 0, 0))
box_width = 6
box_height = 6
# 1
geometry = rtx.PlainGeometry(box_width, box_height)
geometry.set_rotation((0, 0, 0))
geometry.set_position((0... |
3313536 | from shakenfist.image_resolver import cirros
from shakenfist.image_resolver import debian
from shakenfist.image_resolver import ubuntu
resolvers = {
'cirros': cirros,
'debian': debian,
'ubuntu': ubuntu
}
def resolve(url):
for resolver in resolvers:
if url.startswith(resolver):
ret... |
3313571 | import numpy as np
###############################################################################
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.01)
m.bias.data.normal_(0.0, 0.01)
elif classname.find('BatchNor... |
3313605 | staticLoad = 2.352
parameters = {
"results": [
{
"type": "max",
"step": "Load",
"identifier": {
"symbol": "RF3",
"nset": "T_NODE",
"position": "Node 9999998"
},
"referenceValue": staticLoad,
"tolerance"... |
3313635 | from contextlib import contextmanager
import logging
import errno
import os
import tempfile
import pwd
import threading
from boto.sqs.message import RawMessage
from bd2k.util.throttle import LocalThrottle
import time
from cgcloud.lib.context import Context
from cgcloud.lib.message import Message, UnknownVersion
from ... |
3313644 | from common.common import *
class ExploitsBuilder(object):
def __init__(self, test_cases, config):
self.config = config
self.case_id = config['case_id'].decode("utf-8")
self.mode = config['mode']
self.test_cases = self.fixup_test_case_data(test_cases)
def fixup_test_case_data(self, t):
if self.config['m... |
3313662 | import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
import pyaf.Bench.TS_datasets as tsds
import datetime
#get_ipython().magic('matplotlib inline')
trainfile = "data/Hierarchical/hts_dataset.csv"
lDateColumn = 'Date'
df = pd.read_csv(trainfile, sep=r',', engine='python', skiprows=0);
df[lDat... |
3313671 | from sphinx_panels import icons
def test_opticon_simple():
string = icons.get_opticon("report")
assert string == (
'<svg version="1.1" width="16" height="16" class="octicon octicon-report" '
'viewBox="0 0 16 16" aria-hidden="true">'
'<path fill-rule="evenodd" d="M1.75 1.5a.25.25 0 00-.... |
3313687 | import tensorflow as tf
decay = 0.95
TAU = 0.001
class Batch_norm:
def __init__(self, inputs, size, is_training, sess, parForTarget=None, bn_param=None):
self.sess = sess
self.scale = tf.Variable(tf.random_uniform([size], 0.9, 1.1))
self.beta = tf.Variable(tf.random_uniform([size], -0.03,... |
3313696 | import random
import numpy as np
import torch
from torch.utils.data import DataLoader, Subset, ConcatDataset
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision.utils
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from .tinyimagenet import TinyImageNet
from .... |
3313710 | import os
import codecs
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\', '/')
data_path = root_dir + '/python/data'
def dump_ele(tree_f, max_len_dic, ele, nest, processed):
if not ele in max_len_dic.keys():
return len(processed)
if ele in processed:
... |
3313715 | import asyncio
class ResponseStreamManager:
def __init__(self):
self.loop = asyncio.new_event_loop()
class ResponseStream:
def __init__(self):
self.callbacks = []
def onData(self, callback):
self.callbacks.append(callback)
async def send(self, data, last = False):
for... |
3313722 | from nose.tools import eq_
from isovar.cli.rna_args import make_rna_reads_arg_parser
from isovar.cli.reference_context_args import add_reference_context_args
from isovar.cli.protein_sequence_args import add_protein_sequence_args
from isovar.cli.variant_sequences_args import add_variant_sequence_args
def test_extend_p... |
3313758 | from discord import NotFound
from discord.ext import commands
class ServiceError(commands.CommandInvokeError):
"""Raised whenever a request to a service and returns a failure of some sort."""
class NSFWException(commands.CheckFailure):
"""Raised whenever a NSFW command is not executed in a NSFW channel."""
... |
3313824 | import sys
import numpy as np
sys.path.append("..")
import SCNN
import tensorflow as tf
import CFAR10
import os
from keras.utils import to_categorical
TRAINING_BATCH = 128
input_real = tf.placeholder(tf.float32)
output_real = tf.placeholder(tf.float32)
global_step = tf.Variable(1, dtype=tf.int64)
step_inc_op = tf.... |
3313840 | from db import db
class ItemModel(db.Model):
__tablename__ = 'items'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(100))
price = db.Column(db.Float(precision = 2))
def __init__(self, name, price):
self.name = name
self.price = price
def json(self):
return {'name' : self.name, ... |
3313844 | import warnings
warnings.filterwarnings("ignore") # Silence warnings in CLI
import os
import pathlib
import shutil
import subprocess
# Some imports are inline in CLI commands to keep initialization times low
import click
from serpent.utilities import (
clear_terminal,
display_serpent_logo,
is_windows,... |
3313906 | from insights.parsers.blkid import BlockIDInfo
from insights.tests import context_wrap
BLKID_INFO = """
/dev/sda1: UUID="3676157d-f2f5-465c-a4c3-3c2a52c8d3f4" TYPE="xfs"
/dev/sda2: UUID="UVTk76-UWOc-vk7s-galL-dxIP-4UXO-0jG4MH" TYPE="LVM2_member"
/dev/mapper/rhel_hp--dl160g8--3-root: UUID="11124c1d-990b-4277-9f74-c5a34... |
3314004 | import FWCore.ParameterSet.Config as cms
from Validation.MuonGEMHits.MuonGEMHits_cff import *
from Validation.MuonGEMDigis.MuonGEMDigis_cff import *
from Validation.MuonGEMRecHits.MuonGEMRecHits_cff import *
from DQM.GEM.GEMDQM_cff import *
GEMDigiSource.modeRelVal = True
GEMRecHitSource.modeRelVal = True
gemSimVali... |
3314015 | from pathlib import Path
import pandas as pd
import wget
from autofe.tabular_embedding.widedeep_embedding import WideDeepEmbeddingModel, WideDeepEmbeddingModelConfig
from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig
from pytorch_tabular.feature_extractor import DeepFeatureExtractor
from pyt... |
3314090 | import logging
from opcua import ua
from opcua.common.node import Node
logger = logging.getLogger(__name__)
def copy_node(parent, node, nodeid=None, recursive=True):
"""
Copy a node or node tree as child of parent node
"""
rdesc = _rdesc_from_node(parent, node)
if nodeid is None:
nodei... |
3314105 | import sys
# So we can find the bgui module
sys.path.append('../..')
import bgui
import bgui.bge_utils
import bge
class SimpleLayout(bgui.bge_utils.Layout):
"""A layout showcasing various Bgui features"""
def __init__(self, sys, data):
super().__init__(sys, data)
# Use a frame to store all of our widgets
... |
3314106 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import glob
import os.path as osp
from urllib.request import urlretrieve
from .datasetbase import DataSetBase
from lib.utils.util import unpack_file, np_filter, check_path
__all__ = ['VIPe... |
3314149 | import torch
from meta.peer import Peer
from misc.rl_utils import collect_trajectory
from misc.utils import log_performance
from gym_env import make_env
def meta_test(meta_agent, log, tb_writer, args):
# Initialize test_iteration
test_iteration = 0
# Set env
env = make_env(args)
env.seed(args.see... |
3314150 | from __future__ import print_function
import time
import random
import gevent
from devp2p.service import BaseService
from ethereum.slogging import get_logger
from ethereum.utils import privtoaddr, encode_hex, sha3
from ethereum.casper_utils import generate_validation_code, call_casper, check_skips, \
... |
3314223 | import astropy
import pyspeckit
try:
from astropy.io import fits as pyfits
except ImportError:
import pyfits
import numpy as np
# Load the spectrum
sp = pyspeckit.Cube('region5_hcn_crop.fits')
errmap = pyfits.getdata('region5.hcn.errmap.fits')
# Register the fitter
# The N2H+ fitter is 'built-in' but is not r... |
3314225 | import logging
from pybar.run_manager import RunManager
from pybar.scans.tune_gdac import GdacTuning # fast GDAC tuning
# uncomment the following line to use the standard GDAC tuning:
# from pybar.scans.tune_gdac_standard import GdacTuningStandard as GdacTuning # standard GDAC tuning
from pybar.scans.tune_feed... |
3314235 | import gif
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
N = 100
@gif.frame
def plot_spiral(i):
fig = plt.figure(figsize=(5, 3), dpi=100)
ax = fig.gca(projection="3d")
a, b = 0.5, 0.2
th = np.linspace(475, 500, N)
x = a * np.exp(b * th) * np.cos(th)
... |
3314248 | import torch
from torch import nn
from torch.nn.modules.utils import _pair
from neurvps.config import M
from neurvps.models.deformable import DeformConv
class ConicConv(nn.Module):
def __init__(self, c_in, c_out, kernel_size=3, bias=False):
super().__init__()
self.deform_conv = DeformConv(
... |
3314270 | import random
from flask import url_for
from psi.app import const
from psi.app.utils import db_util
from tests.base_test_case import BaseTestCase
from tests.fixture import run_as_admin
from tests.object_faker import object_faker
from tests import fixture
class TestDirectPurchaseOrderPages(BaseTestCase):
def se... |
3314275 | import numpy as np
from config.config import *
from lib.machinelearning import feature_engineering, feature_engineering_raw, get_label_for_directory, get_highest_intensity_of_wav_file, get_recording_power
import pyaudio
import wave
import time
import scipy
import scipy.io.wavfile
import hashlib
import os
import operato... |
3314284 | from .esp_dropout_net import CustomESPDropoutNet, ESPDropoutNet
__all__ = [CustomESPDropoutNet, ESPDropoutNet]
|
3314292 | from hisim import component as cp
#import components as cps
#import components
from hisim.components import advanced_fuel_cell
from hisim import loadtypes as lt
from hisim.simulationparameters import SimulationParameters
from hisim import log
from tests import functions_for_testing as fft
def test_chp_system():
s... |
3314305 | from __future__ import print_function
from matplotlib.collections import PatchCollection,LineCollection
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
import numpy as np
from .. import utils
def plot_linestring(ls,**kwargs):
ax=kwargs.pop('ax',plt.gca())
... |
3314314 | import sys
import h5py
from h5py import File as HDF5File
import numpy as np
import keras.backend as K
from keras.layers import (Input, Dense, Reshape, Flatten, Lambda, merge,
Dropout, BatchNormalization, Activation, Embedding)
from keras.layers.advanced_activations import LeakyReLU
from kera... |
3314323 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQM.EcalMonitorTasks.ClusterTask_cfi import ecalClusterTask
from DQM.EcalMonitorTasks.EnergyTask_cfi import ecalEnergyTask
from DQM.EcalMonitorTasks.IntegrityTask_cfi import ecalIntegrityTask
from DQM.EcalMonitorTa... |
3314345 | class Solution:
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
# m, n = len(s1), len(s2)
# if len(s3) != m+n: return False
# dp = [[False]*(n+1) for _ in range(m+1)]
# dp[0][0] = True
... |
3314346 | from guillotina.interfaces import Allow
from guillotina.interfaces import IPrincipal
from typing import Optional
from zope.interface import implementer
ROOT_USER_ID = "root"
ANONYMOUS_USER_ID = "Anonymous User"
@implementer(IPrincipal)
class BaseUser:
groups: list
id: str
# This is used in IGroups.get_p... |
3314362 | from __future__ import print_function, division
from PyAstronomy import funcFit as fuf
from PyAstronomy import pyasl
from PyAstronomy.pyaC import pyaErrors as PE
import numpy as np
import scipy.interpolate as sci
from PyAstronomy.modelSuite import ic
import six.moves as smo
class LLGauss(fuf.OneDFit):
"""
A spec... |
3314370 | import pytest
import chess
from api.models import Board
def test_board_from_fen():
chess_board = chess.Board()
fen = chess_board.fen()
board = Board.from_fen(fen)
assert board.ep_square is None
assert board.halfmove_clock == 0
assert board.fullmove_number == 1
assert board.castling_xfen ... |
3314422 | import torch
from torch import nn
from torch.nn import functional as F
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1. / self.power)
out = x... |
3314428 | from solutions_automation.vdc.dashboard.common import CommonChatBot
from jumpscale.packages.vdc_dashboard.chats.blog import BlogDeploy
class BlogAutomated(CommonChatBot, BlogDeploy):
URL_MESSAGE = "Repository URL"
BRANCH_MESSAGE = "Branch"
QS = {URL_MESSAGE: "url", BRANCH_MESSAGE: "branch"}
|
3314442 | from jivago.lang.annotations import Inject
from jivago.wsgi.annotations import Resource
from jivago.wsgi.invocation.parameters import OptionalQueryParam
from jivago.wsgi.methods import POST
from jivago.wsgi.request.request import Request
from jivago.wsgi.request.response import Response
from pdfinvert.wsgi.application... |
3314457 | import json
from typing import Callable
from unittest.mock import MagicMock, Mock
import pytest
from cadence.cadence_types import StartTimerDecisionAttributes, TimerFiredEventAttributes, HistoryEvent, \
TimerCanceledEventAttributes, EventType, MarkerRecordedEventAttributes, Header
from cadence.clock_decision_cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.