content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def saveCameraTXT( path, camera ):
"""
Saves a Camera view to a simple text format.
*Arguments*:
- path = the path to save the file.
- camera = a camera object containing the data to save.
"""
# make directories if need be
makeDirs( path )
with open(path,'w') as f:
f.wri... | 31,800 |
def save_graphlet_document(gexf_fh, gidx, num_graphlets, samplesize, cooccurence_corpus):
"""Saves the induced graphlet patterns into dataset folder, it is only used in conjunction
with graphlet_corpus()
Parameters
----------
gexf_fh : str
path to gexf file of graph
gidx : int
i... | 31,801 |
def frechet_distance(real, fake):
"""Frechet distance.
Lower score is better.
"""
n = real.shape[0]
mu1, sigma1 = np.mean(real, axis=0), np.cov(real.reshape(n, -1), rowvar=False)
mu2, sigma2 = np.mean(fake, axis=0), np.cov(fake.reshape(n, -1), rowvar=False)
diff = mu1 - mu2
covmean, _ =... | 31,802 |
def get_tenants(zuul_url):
""" Fetch list of tenant names """
is_witelabel = requests.get(
"%s/info" % zuul_url).json().get('tenant', None) is not None
if is_witelabel:
raise RuntimeError("Need multitenant api")
return [
tenant["name"]
for tenant in requests.get("%s/tenan... | 31,803 |
def ant():
"""Configuration for MuJoCo's ant task."""
locals().update(default())
# Environment
env = 'Ant-v2'
max_length = 1000
steps = 2e7 # 20M
return locals() | 31,804 |
def docker_run(task, image, pull_image=True, entrypoint=None, container_args=None,
volumes=None, remove_container=True, **kwargs):
"""
This task runs a docker container. For details on how to use this task, see the
:ref:`docker-run` guide.
:param task: The bound task reference.
:type... | 31,805 |
def test_constants_are_floats():
"""Check that known color constants dont have integers in them"""
from distinctipy import colorsets
def _assert_colors_are_floats(colors):
for color in colors:
r, g, b = color
assert isinstance(r, float)
assert isinstance(g, float... | 31,806 |
def get_accuracy(pred, target):
"""gets accuracy either by single prediction
against target or comparing their codes """
if len(pred.size()) > 1:
pred = pred.max(1)[1]
#pred, target = pred.flatten(), target.flatten()
accuracy = round(float((pred == target).sum())/float(pred.numel()) * 100, 3... | 31,807 |
def ifourier_transform(F,dt,n):
"""
See Also
-------
fourier_transform
"""
irfft = numpy.fft.irfft
shift = numpy.fft.fftshift
return (1.0/dt)*shift(irfft(F,n=n)) | 31,808 |
def preprocess_labels(labels, encoder=None, categorical=True):
"""Encode labels with values among 0 and `n-classes-1`"""
if not encoder:
encoder = LabelEncoder()
encoder.fit(labels)
y = encoder.transform(labels).astype(np.int32)
if categorical:
y = np_utils.to_categorical(y)
... | 31,809 |
async def test_spot_user_info():
"""
POST 获取用户信息 访问频率 6次/2秒
api_key String 是 用户申请的apiKey
sign String 是 请求参数的签名
:return: is_ok:True/False
status_code:200
response:
result:{'info': {'funds': {'free': {'1st': '0.9985', 账户余额
... | 31,810 |
async def test_detect_up(session, mocker):
"""Test the detection logic, still up"""
session.required_min_rx_interval = 4000
session.remote_detect_mult = 3
session.remote_min_tx_interval = 2000
session.last_rx_packet_time = time.time()
session.state = aiobfd.session.STATE_UP
await asyncio.sle... | 31,811 |
def import_minimal_log(path, parameters=None, variant=DEFAULT_VARIANT_LOG):
"""
Import a Parquet file (as a minimal log with only the essential columns)
Parameters
-------------
path
Path of the file to import
parameters
Parameters of the algorithm, possible values:
... | 31,812 |
async def test_app(test_client, loop):
"""Check availability of the feature flags collection endpoint."""
app = await build_application()
client = await test_client(app)
resp = await client.get('/api/v1/features/')
assert resp.status == 200
text = await resp.text()
assert '{"content": "featu... | 31,813 |
def get_input_assign(input_signal, input_value):
""" Get input assignation statement """
input_assign = ReferenceAssign(
input_signal,
Constant(input_value, precision=input_signal.get_precision())
)
return input_assign | 31,814 |
def remove_client_id_from_open_id_connect_provider(OpenIDConnectProviderArn=None, ClientID=None):
"""
Removes the specified client ID (also known as audience) from the list of client IDs registered for the specified IAM OpenID Connect (OIDC) provider resource object.
This action is idempotent; it does not f... | 31,815 |
def prune_repos(region: str=None, registry_prefix: str=None, repo: str=None, current_tag: str=None, all_tags: str=None):
"""
Pull the image from the registry if it doesn't exist locally
:param region:
:param registry_prefix:
:param repo:
:param current_tag:
:param all_tags:
:return:
... | 31,816 |
def convert_size_bytes_to_gb(size_in_bytes):
""":rtype: float"""
return float(size_in_bytes) / GB | 31,817 |
def merge_swab(survey_df, swab_df):
"""
Process for matching and merging survey and swab result data.
Should be executed after merge with blood test result data.
"""
survey_antibody_swab_df, none_record_df = execute_merge_specific_swabs(
survey_df=survey_df,
labs_df=swab_df,
... | 31,818 |
def confirm_space(environ, start_response):
"""
Confirm a spaces exists. If it does, raise 204. If
not, raise 404.
"""
store = environ['tiddlyweb.store']
space_name = environ['wsgiorg.routing_args'][1]['space_name']
try:
space = Space(space_name)
store.get(Recipe(space.public... | 31,819 |
def find_ppp_device_status(address=None, username=None):
"""Find device status node based on address and/or username.
This is currently only used by the web UI. For the web UI this is the best
guess for identifying the device related to a forced web forward; which
allows the web UI to default username... | 31,820 |
def smibbler(search, plot):
""" Print info fetched from omdbapi.com """
# generate search string and fetch data
query = search.replace(' ', '+')
request = 'http://www.omdbapi.com/?t={0}&y=&plot=short&r=json'.format(query)
res = urllib2.urlopen(request)
data = json.load(res)
movie = Movie.L... | 31,821 |
def get_L_dash_prm_bath_OS_90(house_insulation_type, floor_bath_insulation):
"""主開口方向から時計回りに90°の方向の外気に面した浴室の土間床等の外周部の長さ (m)
Args:
house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸'
floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない'
Returns:
float: 主開口方向から時計回りに90°の方向の外気に面した浴... | 31,822 |
def init():
"""Authorize twitter app using tweepy library"""
# ensure environment variables are set
if not os.environ.get("consumer_key"):
raise RuntimeError("consumer_key not set")
if not os.environ.get("consumer_secret"):
raise RuntimeError("consumer_secret not set")
auth... | 31,823 |
def generate_books(request, form):
"""
Returns a list of books.
"""
list_of_books = Book.generate_existing_books(form.cleaned_data['part'])
return HttpResponse(json.dumps(list_of_books), content_type='application/json') | 31,824 |
def window_reverse_4d(windows, window_size, H_q, W_q, H_s, W_s):
"""
Args:
windows: (num_windows*B, window_size, window_size, window_size, window_size, C)
window_size (int): size of window
H_q (int): Height of query image
W_q (int): Width of query image
H_s (int): Height ... | 31,825 |
def parse_arguments():
"""
Function to parse command line arguements
from the user
Returns
-------
opts : dict
command line arguements from the user
"""
info = 'Divides pdb info files for parallelization'
parser = argparse.ArgumentParser(description=info)
# program arg... | 31,826 |
def numeric(symbols, negative, value):
"""Implement the algorithm for `type: numeric`."""
if value == 0:
return symbols[0]
is_negative = value < 0
if is_negative:
value = abs(value)
prefix, suffix = negative
reversed_parts = [suffix]
else:
reversed_parts = []
... | 31,827 |
def register_extension(id, extension):
"""
Registers an image extension. This function should not be
used in application code.
:param id: An image format identifier.
:param extension: An extension used for this format.
"""
EXTENSION[extension.lower()] = id.upper() | 31,828 |
def test__get():
""" test automol.par.typ
test automol.par.spin
test automol.par.radrad
"""
assert automol.par.typ(RCLASS1) == (
ReactionClass.Typ.HYDROGEN_ABSTRACTION)
assert automol.par.spin(RCLASS1) == (
ReactionClass.HIGHSPIN)
assert not automol.par.radra... | 31,829 |
def my_function_lower(sdk):
"""
Example of a custom function. Gets sites object jdout to str, call .lower(), and print.
:param sdk: Authenticated CloudGenix SDK Constructor.
:return: No Return
"""
print(jdout(sdk.get.sites()).lower())
return | 31,830 |
def fetch_MNI6():
"""
Expected templates:
tpl-MNI152NLin6Asym/tpl-MNI152NLin6Asym_res-01_T1w.nii.gz
tpl-MNI152NLin6Asym/tpl-MNI152NLin6Asym_res-02_T1w.nii.gz
tpl-MNI152NLin6Asym/tpl-MNI152NLin6Asym_res-01_desc-brain_mask.nii.gz
tpl-MNI152NLin6Asym/tpl-MNI152NLin6Asym_res-02_desc-brain_mask.nii.... | 31,831 |
def test_ct_d018_ct_d018_v(mode, save_output, output_format):
"""
TEST :Syntax Checking for top level complexType Declaration :
simpleContent, content of restriction and content of maxInclusive
"""
assert_bindings(
schema="msData/complexType/ctD018.xsd",
instance="msData/complexType/... | 31,832 |
def scale_value_dict(dct: Dict[str, float], problem: InnerProblem):
"""Scale a value dictionary."""
scaled_dct = {}
for key, val in dct.items():
x = problem.get_for_id(key)
scaled_dct[key] = scale_value(val, x.scale)
return scaled_dct | 31,833 |
def get_and_log_environment():
"""Grab and log environment to use when executing command lines.
The shell environment is saved into a file at an appropriate place in the Dockerfile.
Returns: environ (dict) the shell environment variables
"""
environment_file = FWV0 / "gear_environ.json"
log.d... | 31,834 |
def green(string: str) -> str:
"""Add green colour codes to string
Args:
string (str): Input string
Returns:
str: Green string
"""
return "\033[92m" + string + "\033[0m" | 31,835 |
def test_cuboid_object_vs_lib():
"""
includes a test of the input copy problem
"""
a = 1
mag = np.array([(10, 20, 30)])
dim = np.array([(a, a, a)])
pos = np.array([(2 * a, 2 * a, 2 * a)])
B0 = magpy.core.magnet_cuboid_field("B", pos, mag, dim)
H0 = magpy.core.magnet_cuboid_field("H"... | 31,836 |
def from_6x6_to_21x1(T):
"""Convert symmetric second order tensor to first order tensor."""
C2 = np.sqrt(2)
V = np.array([[T[0, 0], T[1, 1], T[2, 2],
C2 * T[1, 2], C2 * T[0, 2], C2 * T[0, 1],
C2 * T[0, 3], C2 * T[0, 4], C2 * T[0, 5],
C2 * T[1, 3], C2 ... | 31,837 |
def test_missing_manifest_package_fields(demo_manifest, key):
"""Test that exceptions are raised when a manifest is missing required
fields in the 'packages.packages.afw' object.
"""
yaml = ruamel.yaml.YAML()
manifest = yaml.load(demo_manifest)
del manifest['packages']['afw'][key]
with pytes... | 31,838 |
def test_observations_query_raw(patch_get):
""" test querying raw """
result = gemini.Observations.query_raw('GMOS-N', 'BIAS', progid='GN-CAL20191122')
assert isinstance(result, Table)
assert len(result) > 0 | 31,839 |
def main():
""" main function """
global START_TIME, MINER_URL, MINER_TOKEN, DAEMON_URL, DAEMON_TOKEN
# Start execution time mesurement
START_TIME = time.time()
# SET API IP PORT AND AUTH
if MINER_URL == '':
miner_config = toml.load(str(Path.home()) + "/.lotusminer/config.toml")
... | 31,840 |
def post_add_skit_reply():
""" removes a skit if authored by the current user """
email = is_authed(request)
if email and csrf_check(request):
# same as args, form data is also immutable
request.form = dict(request.form)
request.form['email'] = email
p_resp = proxy(RUBY, requ... | 31,841 |
def register(request):
"""Register new account."""
token_int = int(datetime.datetime.strftime(
datetime.datetime.now(), '%Y%m%d%H%M%S%f'))
token = short_url.encode_url(token_int)
if (not request.playstore_url and not request.appstore_url
and not request.winstore_url and not request.d... | 31,842 |
def predictRegions(regionName,
regionType='country',
target='confirmed',
predictionsPercentiles=PREDICTIONS_PERCENTILES,
siteData=SITE_DATA,
priorLogCarryingCapacity=PRIOR_LOG_CARRYING_CAPACITY,
priorMidPoi... | 31,843 |
def stringify_parsed_email(parsed):
"""
Convert a parsed email tuple into a single email string
"""
if len(parsed) == 2:
return f"{parsed[0]} <{parsed[1]}>"
return parsed[0] | 31,844 |
def standard_simplex_vol(sz: int):
"""Returns the volume of the sz-dimensional standard simplex"""
result = cm_matrix_det_ns(np.identity(sz, dtype=DTYPE))
if result == math.inf:
raise ValueError(f'Cannot compute volume of standard {sz}-simplex')
return result | 31,845 |
def all_saveable_objects(scope=None):
""" Copied private function in TF source. This is what tf.train.Saver saves if var_list=None is passed. """
return (tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope) +
tf.get_collection(tf.GraphKeys.SAVEABLE_OBJECTS, scope)) | 31,846 |
def base_to_str( base ):
"""Converts 0,1,2,3 to A,C,G,T"""
if 0 == base: return 'A'
if 1 == base: return 'C'
if 2 == base: return 'G'
if 3 == base: return 'T'
raise RuntimeError( 'Bad base: %d' % base ) | 31,847 |
def parse_args(args):
"""
function parse_args takes arguments from CLI and return them parsed for later use.
:param list args : pass arguments from sys cmd line or directly
:return dict: parsed arguments
"""
parser = argparse.ArgumentParser()
required = parser.add_argument_group()
requi... | 31,848 |
def attr(accessing_obj, accessed_obj, *args, **kwargs):
"""
Usage:
attr(attrname)
attr(attrname, value)
attr(attrname, value, compare=type)
where compare's type is one of (eq,gt,lt,ge,le,ne) and signifies
how the value should be compared with one on accessing_obj (so
compare=gt me... | 31,849 |
def group_connected(polygon_map, mask=None):
"""Group all connected nodes."""
# Wrap :c:`group_connected()` from ``polygon_map.c``.
polygon_map = mask_polygon_map(polygon_map, mask)
queue = Queue(len(polygon_map) + 1)
group_ids = np.full(len(polygon_map), -1, np.intp, order="C")
groups_count:... | 31,850 |
def pause_refreshing() -> None:
"""
Pauses refreshing to speed up drawing.
:rtype: None
"""
turtle.tracer(0, 0) | 31,851 |
def test_hash_fuction_returns_additative_value_lowercase(ht_fixture):
"""Test the hash function returns and additive value."""
word = 'word'
word_value = 0
for letter in word:
word_value += ord(letter)
assert ht_fixture._hash('word') == word_value | 31,852 |
def dictmask(data, mask, missing_keep=False):
"""dictmask masks dictionary data based on mask"""
if not isinstance(data, dict):
raise ValueError("First argument with data should be dictionary")
if not isinstance(mask, dict):
raise ValueError("Second argument with mask should be dictionary")... | 31,853 |
def connect(file=None, port=8100, counter_max=5000):
"""Open libreoffice and enable conection with Calc.
Args:
file (str or pathlib.Path, optional): Filepath. If None, a
new Calc instance will be opened.
port (int, optional): port for connection.
counter_max (int, optional):... | 31,854 |
def stub_config():
"""Builds a standardized Configuration object and returns it, but does
not load it as the active configuration returned by
dallinger.config.get_config()
"""
defaults = {
u'ad_group': u'Test ad group',
u'approve_requirement': 95,
u'assign_qualifications': Tr... | 31,855 |
def clean_local_folder():
"""Cleans the livestock/local folder on the C drive."""
if os.path.isdir(local_path):
for file in os.listdir(local_path):
os.remove(local_path + '/' + file)
else:
os.mkdir(local_path) | 31,856 |
def example_empty_filter():
""" 演示邮箱验证
"""
resp = client.get("/empty", data={
"params": "wudong@eastwu.cn",
"must": "must"
})
print(resp.data)
# params参数不传时,会默认填充default值
resp = client.get("/empty", data={
"must": "must",
})
print(resp.data)
# 不允许为空的值如果不... | 31,857 |
def terminate_execution(execution: Execution, reason: Union[None, str] = None) -> None:
"""Terminate an execution."""
for service in execution.services: # type: Service
terminate_service(service)
execution.set_terminated(reason) | 31,858 |
def _prepare_policy_input(
observations, vocab_size, observation_space, action_space
):
"""Prepares policy input based on a sequence of observations."""
if vocab_size is not None:
(batch_size, n_timesteps) = observations.shape[:2]
serialization_kwargs = init_serialization(
vocab_size, observatio... | 31,859 |
def RGB2raw(R, G, B):
"""Convert RGB channels to Raw image."""
h, w = R.shape
raw = np.empty(shape=(2*h, 2*w), dtype=R.dtype)
raw[::2, ::2] = R
raw[1::2, 1::2] = B
raw[1::2, 0::2] = G
raw[0::2, 1::2] = G
return raw | 31,860 |
def get_algs_from_ciphersuite_name(ciphersuite_name):
"""
Return the 3-tuple made of the Key Exchange Algorithm class, the Cipher
class and the HMAC class, through the parsing of the ciphersuite name.
"""
tls1_3 = False
if ciphersuite_name.startswith("TLS"):
s = ciphersuite_name[4:]
... | 31,861 |
def remove_object_entry(vmfObject, key, value):
""" Removes a particular object entry from the given VMF object. """
objectEntry = vmfObject[key]
try:
objectEntry.remove(value)
except AttributeError:
# The entry is the last entry. Remove it.
assert (
isinstance(o... | 31,862 |
def centroid(window):
"""Centroid interpolation for sub pixel shift"""
ip = lambda x : (x[2] - x[0])/(x[0] + x[1] + x[2])
return ip(window[:, 1]), ip(window[1]) | 31,863 |
def eval_fasterrcnn(config, dataset_path, ckpt_path, anno_path, target_device):
"""FasterRcnn evaluation."""
if not os.path.isfile(ckpt_path):
raise RuntimeError(f"CheckPoint file {ckpt_path} is not valid.")
ds = create_fasterrcnn_dataset(config, dataset_path, batch_size=config.test_batch_size, is_t... | 31,864 |
def _format_warning(message, category, filename, lineno, line=None):
"""
Replacement for warnings.formatwarning that disables the echoing of
the 'line' parameter.
"""
return "{}:{}: {}: {}\n".format(filename, lineno, category.__name__, message) | 31,865 |
def precision_at_k(predictions: List[int], targets: List[int], k: int = 10) -> float:
"""Computes `Precision@k` from the given predictions and targets sets."""
predictions_set = set(predictions[:k])
targets_set = set(targets)
result = len(targets_set & predictions_set) / float(len(predictions_set))
... | 31,866 |
def assign_metrics(nb_graph: nx.DiGraph, pipeline_metrics: dict):
"""Assign pipeline metrics to specific pipeline steps.
This assignment follows a similar logic to the detection of `out`
dependencies. Starting from a temporary step - child of all the leaf nodes,
all the nodes in the pipelines are trave... | 31,867 |
def test_film_metadata_added() -> None:
"""Tests film metadata is is still added if one of them is an empty string"""
source_path = "test_abc.tiff"
item = Item(source_path)
item.collection = Collection("Collection")
metadata = {"film": "123", "film_sequence_no": "234", "physical_film_condition": "",... | 31,868 |
def wordify_open(p, word_chars):
"""Prepend the word start markers."""
return r"(?<![{0}]){1}".format(word_chars, p) | 31,869 |
def Mt_times_M(M):
"""Compute M^t @ M
Args:
M : (batched) matrix M
Returns:
tf.Tensor: solution of M^t @ M
"""
if isinstance(M, tf.Tensor):
linop = tf.linalg.LinearOperatorFullMatrix(M)
return linop.matmul(M, adjoint=True)
elif isinstance(M, (tf.linalg.LinearOper... | 31,870 |
def update_external_wires():
"""Remove the wires included into the wrapper from the external wire list""" | 31,871 |
def make_values(ints: typing.Iterable[int]):
"""Make datasets.
"""
return [
('int', ints),
('namedtuple', [IntNamedTuple(i) for i in ints]),
('class', [IntObject(i) for i in ints]),
] | 31,872 |
def attach_trans_dict(model, objs):
"""Put all translations from all non-deferred translated fields from objs
into a translations dict on each instance."""
# Get the ids of all the translations we need to fetch.
try:
deferred_fields = objs[0].get_deferred_fields()
except IndexError:
... | 31,873 |
def test_base_probe_export_no_results(caplog):
"""Should log a warning if the probe has no results."""
probe = BaseProbe()
with caplog.at_level(logging.WARNING):
probe.export()
assert len(caplog.records) == 1
for record in caplog.records:
assert record.levelname == "WARN... | 31,874 |
def list_known_protobufs():
"""
Returns the list of known protobuf model IDs
"""
return [k for k in proto_data_structure] | 31,875 |
def hash_value(*args):
"""
hash_value(NodeConstHandle t) -> std::size_t
hash_value(BufferConstHandle t) -> std::size_t
hash_value(FileConstHandle t) -> std::size_t
"""
return _RMF.hash_value(*args) | 31,876 |
def test_properties(mqtt_client: MockedMQTT):
"""Test properties of 360 Heurist."""
device = Dyson360Heurist(SERIAL, CREDENTIAL)
device.connect(HOST)
assert device.current_power_mode == VacuumHeuristPowerMode.QUIET
assert device.default_power_mode == VacuumHeuristPowerMode.HIGH
assert device.cur... | 31,877 |
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
# with tf.gfile.GFile(input_file, "r") as reader:
with open(input_file, "r") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
... | 31,878 |
def get_finance_sentiment_dataset(split: str='sentences_allagree') -> list:
"""
Load financial dataset from HF: https://huggingface.co/datasets/financial_phrasebank
Note that there's no train/validation/test split: the dataset is available in four possible
configurations depending on the p... | 31,879 |
def process_guam_rasters():
"""Process rasters for Guam to be uploaded to CREST.
Requirements:
- target data type
- target nodata value
- lzw compression
"""
input_raster_dir = "D:/NFWF_PhaseIII/Guam/FOR CREST/raw_rasters_from_mxd"
target_raster_dir = "D:/NFWF_PhaseIII/Guam... | 31,880 |
def list_databases():
"""
List tick databases and associated aggregate databases.
Returns
-------
dict
dict of {tick_db: [agg_dbs]}
"""
response = houston.get("/realtime/databases")
houston.raise_for_status_with_json(response)
return response.json() | 31,881 |
def price2bean(outdir):
"""将价格历史输出为 beancount 格式"""
if not os.path.exists(outdir):
os.makedirs(outdir)
for deal in Deal.select(Deal.asset).distinct():
asset = deal.asset
if asset.category not in ('stock', 'fund', 'bond'):
continue
code, suffix = asset.zs_code.sp... | 31,882 |
def nice_range(bounds):
"""
Given a range, return an enclosing range accurate to two digits.
"""
step = bounds[1] - bounds[0]
if step > 0:
d = 10 ** (floor(log10(step)) - 1)
return floor(bounds[0]/d)*d, ceil(bounds[1]/d)*d
else:
return bounds | 31,883 |
def connect_to_portal(config):
"""
The portal/metadata schema is completely optional.
"""
if config.portal_schema:
return aws.connect_to_db(**config.rds_config, schema=config.portal_schema) | 31,884 |
def get_words_for_source():
""" Gets JSON to populate words for source """
source_label = request.args.get("source")
source = create_self_summary_words(source_label)
return json.dumps(source) | 31,885 |
def raster(event_times_list):
"""
Creates a raster plot
Parameters
----------
event_times_list : iterable
a list of event time iterables
color : string
color of vlines
Returns
-------
ax : an axis containing the raster plot
"""
color='k'
ax = plt.gca... | 31,886 |
def for_v():
""" *'s printed in the shape of v """
for row in range(5):
for col in range(9):
if row==col or row +col ==8:
print('*',end=' ')
else:
print(' ',end=' ')
print() | 31,887 |
def FindOneDocument(queryDocument, database='NLP', collection="Annotations", host='localhost', port='27017'):
"""
This method returns the first document in the backing store that matches the criteria specified in queryDocument.
:param queryDocument: [dict] A pymongo document used to query the MongoDB insta... | 31,888 |
def user_info(context, **kwargs):
"""
Отображает информацию о текущем авторизованом пользователе, либо ссылки на авторизацию и регистрацию
Пример использования::
{% user_info %}
:param context: контекст
:param kwargs: html атрибуты оборачивающего тега
:return:
"""
request = co... | 31,889 |
def test_agent_proxy_wait_running(nsproxy, timeout):
"""
Using `wait_for_running` on a proxy after initialization should block until
the agent is running or time out.
"""
AgentProcess('agent').start()
# Get "offline" proxy
agent = Proxy('agent')
time0 = time.time()
Timer(abs(timeout... | 31,890 |
def transactions(request):
"""Transaction list"""
tt = TimerThing('transactions')
# Get profile
profile = request.user.profile
characters = Character.objects.filter(
apikeys__user=request.user,
apikeys__valid=True,
apikeys__key_type__in=[APIKey.ACCOUNT_TYPE, APIKey.CHARACTE... | 31,891 |
def to_bytes(val):
"""Takes a text message and return a tuple
"""
if val is NoResponse:
return val
val = val.replace('\\r', '\r').replace('\\n', '\n')
return val.encode() | 31,892 |
def trainer(input_hdf5=None,
input_trainset=None,
output_name=None,
input_dimention=(6000, 3),
gmlp_blocks=5,
gmlp_dim=32,
seq_len = 375,
activation = 'relu',
drop_rate=0.1,
s... | 31,893 |
def get_standard_container_list() -> List[str]:
"""get list of standard container names
Returns:
List[str]: names
""" | 31,894 |
def unread_ratio_reload(self):
"""
Updates the available/showable ration.
Rationale: As this purely relies on the
backend data, Metis reload and Secretary
reload must occur before calling this
method.
"""
self.unread = len(set(filter(self.Metis.is_available, self.Metis.... | 31,895 |
def compare_sfs(id,era,xvar='pt',dms=None,gms=None,wps=None,tag="",verb=0):
"""Compare old (ROOT) vs. new (JSON) SFs."""
header(f"Compare {id} SF tools")
if xvar=='eta':
jname = f"data/tau/new/tau_sf_eta_{id}_{era}{tag}.json"
else:
jname = f"data/tau/new/tau_sf_pt-dm_{id}_{era}{tag}.json"
cset ... | 31,896 |
def get_vrfs(table) -> None:
"""Gets VRFs from the device. Databse default is "global"""
vrf = {}
vrfs = cursor.execute(f'SELECT vrf FROM {table}')
for i in vrfs:
vrf[i] = None
print("\nVRFs ---------\n")
if len(vrf) == 0:
print("\nPress enter to use global")
e... | 31,897 |
def test_atomic_integer_min_exclusive_3_nistxml_sv_iv_atomic_integer_min_exclusive_4_2(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet minExclusive with value
470740450062970382.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema... | 31,898 |
def _create_fake_data_fn(train_length=_DATA_LENGTH, valid_length=50000, num_batches=40):
""" Creates fake dataset
Data is returned in NCHW since this tends to be faster on GPUs
"""
logger = _get_logger()
logger.info("Creating fake data")
data_array = _create_data(_BATCHSIZE, num_batches, (_HEI... | 31,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.