content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def should_build_new_prices() -> bool:
"""
Determine if prices were built recently enough that there
is no reason to build them again
:return: Should prices be rebuilt
"""
cache_file = CACHE_PATH.joinpath("last_price_build_time")
if not cache_file.is_file():
... | 0cc1f673cf39c554aa1ad72ff4c7e0a5f90cc713 | 3,628,600 |
def config_nat_pool_binding(dut, **kwargs):
"""
Config NAT pool bindings
Author:kesava-swamy.karedla@broadcom.com
:param :dut:
:param :config: add/del:
:param :binding_name:
:param :pool_name:
:param :nat_type:
:param :twice_nat_id:
:param :acl_name:
usage:
config_nat_p... | e64204b575684fb57e3ab2a025771edad329d902 | 3,628,601 |
def database_obj_to_py(obj, fingerprints_in_song=False):
"""
Recursively convert Fingerprint and Song sqlalchemy objects to native
Python types (lists and dicts).
Args:
obj (database.schema.Fingerprint|database.schema.Song): ``audio``
module Fingerprint or Song object.
finge... | 49d89c0e93ee492f911e1c42e0bfc6af9232c8ba | 3,628,602 |
import csv
def get_outputs(output_file):
"""
Parse ``output_file`` which is a csv file and defines the semantics of the
output of a neural network.
For example, output neuron 1 means class "0" in the MNIST classification
task.
"""
outputs = []
mode = "rt"
with open(output_file, mo... | b001942bc270952c9bb82537d0b5033c9ee968ff | 3,628,603 |
def auto_adjust(img):
"""Python translation of ImageJ autoadjust function.
Parameters
----------
img : ndarray
Returns
-------
(vmin, vmax) : tuple of numbers
"""
# calc statistics
pixel_count = int(np.array((img.shape)).prod())
# get image statistics
# ImageStatistics ... | 861ff4d7c2eaea9e10341f718fd9cfab33a9eab8 | 3,628,604 |
def ChanPcaKmeansDS(ds, xvec='bias', chan='cf', mod=lambda y: y, comps=6,nclust=4, fig=None):
"""
:param ds: xarray dataset
:param xvec: name of dataset coordinate
:param chan: selected channel
:param mod: if desired, pass the modifier for the plotting of the histogram via lambda functions
:... | 487bd468a77340b13f5e5702e24ed87e092f41f9 | 3,628,605 |
def elements(elements, axis=0):
"""
Calculates an node 2-d-array from an element 2-d-array,
uses the [:, 1], [:, -2] entries of the calculated node 2-d-array
to fill the first als last row of the node 2-d-array.
"""
nodes = np.asarray((elements[:, :-1] + elements[:, 1:])) * .5
return np.hsta... | 6be65159469972db6d69ce1b4975e84ef1aef4d4 | 3,628,606 |
def convert_date_to_unix(date_string):
"""Convert date input to unix timestamp.
Args:
date_string: the date input string.
Returns:
(int) converted timestamp.
"""
if not date_string:
return None
return int(dateparser.parse(date_string).timestamp() * 1000) | a3cc4e363d7940df904e02b4e5d5d34a3a58a322 | 3,628,607 |
def decoder(decoder_inputs, initial_state,
cell, output_size, loop_function=None, dtype=None,
scope=None):
"""
The Decoder Function which returns the decoder hidden states after decoding the whole output
args:
decoder_inputs: The inputs to the decoder, either the targets during training or t... | ea8272815be6a0cb206505a811b522ec36f9e7df | 3,628,608 |
from typing import Sequence
def kron(nodes: Sequence[BaseNode]) -> BaseNode:
"""Kronecker product of the given nodes.
Kronecker products of nodes is the same as the outer product, but the order
of the axes is different. The first half of edges of all of the nodes will
appear first half of edges in the result... | d52f6fe4c5a3c5980f6bf8b94543dc9201c3ac7d | 3,628,609 |
def diskmounter() -> Mounter:
"""Fixture with an unversioned disk filesystem mounter."""
return unversioned_mounter(DiskFilesystem) | d3c67839dc7c0d3cb452235c8d4aa29b9a829ee7 | 3,628,610 |
def stations():
"""Return a JSON list of stations from the dataset."""
# most_active_stations = session.query(measurement.station, func.count(measurement.station)).\
# group_by(measurement.station).\
# order_by(func.count(measurement.station).desc()).all()
stationr... | b70109e02d15177343c4d2f8cf8fce078f5c2bf6 | 3,628,611 |
def search_sorted_matrix(matrix, target):
# Write your code here.
"""
1 4 7 12 15 1000
2 50 500 1001
3 1002
4
"""
result = [-1, -1]
row = 0
if len(matrix) == 0:
return result
col = len(matrix[0]) - 1
while col >= 0 and row < len(matrix):
... | 26a2dd0d714b0cdf88822dc2f956fc9d7f9cd02f | 3,628,612 |
def get_io_functions_from_lib(lib, load_func_name='load', dump_func_name='dump', load_kwargs={}, dump_kwargs={}):
"""Helper to create loader and dumper functions for libraries"""
def loader(input_stream, args):
return getattr(lib, load_func_name)(input_stream, **load_kwargs)
def dumper(output, outpu... | 1d81031c7e5421f190f8c8936d92f2a5a2d999bf | 3,628,613 |
def get_pane_id(session: str, window: int, pane: int):
"""
Get a given pane ID
Parameters
----------
session : str
Name of the session
window : int
Window number of pane
pane : int
Pane index in the window
"""
injected = get_injected_pane_data(session, window... | f795859c6a8b5546e220e6d715ca3e3eec984b0f | 3,628,614 |
def normalize_signs(arr1, arr2):
"""Change column signs so that "column" and "-column" compare equal.
This is needed because results of eigenproblmes can have signs
flipped, but they're still right.
Notes
=====
This function tries hard to make sure that, if you find "column"
and "-column"... | 8f44bafdbacc5dcbbc339985092bb459ce7294b1 | 3,628,615 |
def draw_lines(img, lines, scale):
"""
this function draw lines on a picture, according to scale
first point from the left is added in case of absence
last point from the right is added in case of absence
returns updated image
"""
if lines is not None and len(lines) > 0:
# calculate... | 4da51115d3037b9b938fdafef65bb5a6f22176f3 | 3,628,616 |
def tokenize_de(text):
"""
将德语文本从字符串标记为字符串列表
"""
return [tok.text for tok in spacy_de.tokenizer(text)] | 9d5cf22d2356202b8818348edb3c36b6562106b4 | 3,628,617 |
import socket
def port_in_use(port, host=LOCALHOST):
"""Returns True when a port is in use at the given host.
Must actually "bind" the address. Just checking if we can create
a socket is insufficient as it's possible to run into permission
errors like:
- An attempt was made to access a socket i... | 7249e6fe405d4577301c78eaa576c181b99816b1 | 3,628,618 |
def construct_model(lbann):
"""Construct LBANN model.
Args:
lbann (module): Module for LBANN Python frontend
"""
# TODO (tym): Figure out how to switch between LBANN builds. See
# GitHub Issue #1289.
# Layer graph
input_ = lbann.Input()
images = lbann.Identity(input_)
lab... | f5ff4254ceaaa06dbe19364f6493cc67f6643fab | 3,628,619 |
async def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return StreamingResponse(gen(Camera()),
media_type='multipart/x-mixed-replace; boundary=frame') | 27051c6d2adb1dd30a477055b175d8a85103bd46 | 3,628,620 |
def logout():
"""
Log out the user
"""
session.clear()
return json_response(status=200, response_data={"success": True}) | 01a6a15f1ec4c654ff8b0b0c79254bc4962fce95 | 3,628,621 |
import base64
import json
def get_secrets(secret_name):
"""
Get secrets from AWS Secrets Manager
"""
session = boto3.session.Session(profile_name="platform-dev")
client = session.client(
service_name="secretsmanager", region_name="eu-west-1"
)
try:
response = client.get_se... | 8c7d19b34c27f706ec4e6b6e214fa2f42a8e2ec8 | 3,628,622 |
import numpy as np
from stentseg.motion.displacement import _calculateAmplitude, _calculateSumMotion
from stentseg.motion.dynamic import get_mesh_deforms
from visvis.processing import lineToMesh
from visvis import Pointset # lineToMesh does not like the new PointSet class
def make_mesh_dynamic_with_abs_displacement(... | 634687df1c3166c8381f509cedf2fca29711a684 | 3,628,623 |
import sys
def is_piped_output():
"""
Checks the piped output.
This function checks if this script
is being executed with a piped output.
E.g.: python dnsrato.py -d domain.com --format json > outfile.json
Returns
-------
bool
True if the is a piped output, False otherwise.
... | 4f59a6abc6bfaac47340434afd07c62aaf8a5ddc | 3,628,624 |
def load(savime_element: LoadableSavimeElement) -> str:
"""
Get the load query string for a loadable element.
:param savime_element: A loadable savime element.
:return: The load query for the savime element.
"""
return savime_element.load_query_str() | 650387cbde39fd82dcd5484542bd210b3a7ced56 | 3,628,625 |
def topo_flat(x,y):
"""
flat
"""
z = where(x < 204.91213, 30., -30.)
return z | b7d55b2eaff9ebc78645ccf0b2c2f13210eaef3f | 3,628,626 |
def softmax_xent(*, logits, labels, reduction=True, kl=False):
"""Computes a softmax cross-entropy (Categorical NLL) loss over examples."""
log_p = jax.nn.log_softmax(logits)
nll = -jnp.sum(labels * log_p, axis=-1)
if kl:
nll += jnp.sum(labels * jnp.log(jnp.clip(labels, 1e-8)), axis=-1)
return jnp.mean(nl... | 9c59907d365088c6bf54be861db0a67631dbf8cf | 3,628,627 |
def activate_WS_VCC(activation,
Q_cooling_unmet_W,
Qc_water_body_remaining_W,
Qc_DailyStorage_to_storage_W,
Qc_DailyStorage_from_storage_W,
T_district_cooling_supply_K,
T_district_cooling_return_K,
... | 8ba04627c9e1f10f0ce5cb53f1e92a913031bc1e | 3,628,628 |
from typing import Dict
from typing import Any
def sign_block_data(
data: Dict[str, Any], private_key: str, hash_alg: str = 'keccak256'
) -> Dict[str, str]:
"""sign block data
:param data: dict
:param private_key: hex str (private key)
:param hash_alg: `keccak256` or `sha256`, the default val... | 26da624c26885fc3c9b20a0e1229c398f627d63a | 3,628,629 |
def convert_label(label_img):
""" covert label """
label_processed = np.zeros(label_img.shape[0:]).astype(np.uint8)
for index in range(label_img.shape[2]):
label_slice = label_img[:, :, index]
label_slice[label_slice == 10] = 1
label_slice[label_slice == 150] = 2
label_slice... | d76e9b2557048f0bee1d657fb5d50283819e7d4e | 3,628,630 |
def update_hand(hand, word):
"""
Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; ins... | 2f87fe20335d2080b51b2fd40c55a226e1c79b8a | 3,628,631 |
def list_zeroes(line):
"""
Takes a list of integers and removes all non-zero elements.
"""
zeroes = []
for item in line:
if item == 0:
zeroes.append(item)
return zeroes | f10d6a59f8a6f00cb22d5f6ee6ce2087a4969b8e | 3,628,632 |
def ecef_to_lla2(x_m, y_m, z_m):
"""Convert ECEF cartesian coordinates to WGS84 spherical coordinates.
This converts an earth-centered, earth-fixed (ECEF) cartesian position to a
position on the Earth specified in geodetic latitude, longitude and altitude.
This code assumes the WGS84 earth model.
... | 63495e6b1407cc3714b5ee44b115bc47725b0a19 | 3,628,633 |
def ObjectToDict(obj):
"""Converts an object into a dict."""
keys = [ k for k in dir(obj) if not k.startswith("__") ]
return { k : getattr(obj, k) for k in keys } | f2679daab84d5cee2c7f319d1d34f3c669971cd6 | 3,628,634 |
def writeCmd(cmd):
"""Take in a single integer value (command), try sending it to the arduino
command is wrapped in '<>'. Then wait for confirmation from the uC
"""
# Needed? TODO
while ser.in_waiting > 0:
readLine()
print("Write command: " + str(cmd))
cmd = '<' + str(cmd) + '>'
... | 94a4c24a29de5c48d1f116aee93ff0bc6d60a672 | 3,628,635 |
def ortho(subj_coord, obj_coord, subj_dim, obj_dim):
""" It returns a tuple of 3 values: new dim for combined array,
component of subj_origin in it, component of obj_origin in it. """
if subj_coord > obj_coord:
return (subj_coord + (obj_dim - obj_coord), 0,
subj_coord - obj_coord)
... | 36a3127b0721ac87e81259432823eab26fc015e9 | 3,628,636 |
def _unravel(nodes,tets,index):
"""Returns a list containing the node coordinates of the tet
stored in the 'index' position in the 'tets' list."""
return [nodes[tets[index][0]],nodes[tets[index][1]],nodes[tets[index][2]],nodes[tets[index][3]]] | e8428de351db2a84a4875a81b47d07b03a67efd9 | 3,628,637 |
def pairwise(accuracy_balanced, method_names, out_results_dir, num_repetitions):
"""
Produces a matrix of pair-wise significance tests,
where each cell [i, j] answers the question:
is method i significantly better than method j?
The result would be based on a test of choice.
The... | 06618051f2aad89c8eb75877a37f18ba243b4150 | 3,628,638 |
def visdom_image(vis, image,win_name):
"""
eg :
visdom_image(vis=vis, image=drawn_image, win_name='image')
:param vis: 由 setup_visdom 函数创建
:param image: 单幅图片张量,shape:[n,w,h]
:param win_name: 绘图窗口名称,必须指定,不然会一直创建窗口
:return:
"""
vis.image(img=image, win=win_name)
... | 145ad236c0e07a79195a573b562ffd9a8654be96 | 3,628,639 |
def generate_splits_type3(in_data,
slot_data,
intent_data,
instance_types_per_client=3,
clients_per_instance_type=3):
"""Creates non-IID splits of the dataset. Each client is given only a fixed number
of inte... | ae2c2472ba32f737160e69fbe7a77fded9407b07 | 3,628,640 |
import os
import inspect
import tempfile
import subprocess
import re
def is_module_installed(module_name, version=None, installed_version=None,
interpreter=None):
"""Return True if module *module_name* is installed
If version is not None, checking module version
(module must ... | 08482d5a996a47da0fe2f02acdabf07c6463822c | 3,628,641 |
def file_num2size(num_size, h=True):
"""文件大小数值变为 MB 的显示
:param num_size: 文件大小
:param h: 是否 human 显示
:return: {'value': 数值,'measure': 单位,'str': 字串, 'org_size': 原始大小}
"""
measure_list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
fsize = num_size
i = 0
while (fsize >= 1) and (i < len(measure... | f3cf060b4015831381ab5d5b3ed236d8519746cc | 3,628,642 |
def cartopy_ylim(var=None, geobounds=None, wrfin=None, varname=None, timeidx=0,
method="cat", squeeze=True, cache=None):
"""Return the y-axis limits in the projected coordinates.
For some map projections, like :class`wrf.RotatedLatLon`, the
:meth:`cartopy.GeoAxes.set_extent` method d... | ea0b9f40730c19f9cc52e55e6f124a54df07b9f4 | 3,628,643 |
def get_user_csc_name():
"""Get user csc name from saml userdata.
Returns:
[string] -- The users CSC username.
"""
if not is_authenticated() or not is_authenticated_CSC_user() or 'samlUserdata' not in session:
return None
csc_name = session.get('samlUserdata', {}).get(SAML_ATTRIBU... | 17bcbc3b4ca2bfbb0a9de19b77f47aac94f2d089 | 3,628,644 |
import os
import tarfile
def get_ip_representations_info(_, identifier):
"""
get:
Get data set structure
"""
try:
dpts = DirectoryPairtreeStorage(config_path_storage)
object_path = dpts.get_object_path(identifier)
package_path = os.path.join(object_path, representations... | 11109d590c2ec94f2a594b38926ddd4cd5d26ae3 | 3,628,645 |
def precision_Approximation(*args):
"""
* Returns the precision value in real space, frequently used by approximation algorithms. This function provides an acceptable level of precision for an approximation process to define adjustment limits. The tolerance of approximation is designed to ensure an acceptable com... | 01dd6286509b69a875807bdaf4db59a34d7d5aad | 3,628,646 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
help='Input file',
metavar... | 78c1baed2d059c106c16446f47b2f1e16b571c61 | 3,628,647 |
import os
def get_population_data(read_data=dd.defaultDict['read_data'],
file_format=dd.defaultDict['file_format'],
out_folder=dd.defaultDict['out_folder'],
no_raw=dd.defaultDict['no_raw'],
split_gender=False,
... | 4fd20f945d6303ae34da71f7021174f2a3df655e | 3,628,648 |
import time
def getEpoch( ):
"""
Return the Unix epoch divided by a constant as string.
This function returns a coarse-grained version of the Unix epoch. The
seconds passed since the epoch are divided by the constant
`EPOCH_GRANULARITY'.
"""
return str(int(time.time()) / const.EPOCH_GRA... | 649fb0dc8bb8a2bbd8294449ef1c3ffb64ca5aa1 | 3,628,649 |
def build_py_idiv(builder, a, b, name):
"""Build expression for floor integer division.
As seen in Cython:
long q = a / b;
long r = a - q*b;
q -= ((r != 0) & ((r ^ b) < 0));
return q;
"""
q = BuildSDiv(builder, a, b, name + "_q")
r = BuildSub(builder, a, BuildMul(... | 5cdf5281d7bb1272e4bb2468f3d044d16970e444 | 3,628,650 |
def moveeffect_02C(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int:
"""
Move Effect Name: Increases user's special attack and special defense (Calm Mind)
"""
if user.first_turn:
score += 40
if user.boosts.get("spa", 0) == 6 and user.boosts.get("spd", ... | 6bff14b50029af1a60c47c7e478766edbf033c9a | 3,628,651 |
import json
def all_players_are_ready(game_id):
"""Returns true if the game exists and all players are ready."""
# TODO: acquire lock for game_id
game_json_string = redis.get(game_id)
if game_json_string is None:
# TODO: release lock for game_id
return
game_json = json.loads(game... | f592d1d761a4fb0eb3691fa7dd449b08b6850448 | 3,628,652 |
from pathlib import Path
import os
import shutil
def copy_file(src, dst):
"""
Copy the file (or folder) to the specified directory.
You can copy multiple files to the specified directory by listing.
"""
src_type = typeof(src)
dst_type = typeof(dst)
if not src_type == 'str' or 'list':
... | e28200e73ec015a87930a5aea003f1b3df1accc0 | 3,628,653 |
from typing import Optional
from typing import Tuple
from typing import Dict
from typing import Hashable
def get_dataset_subsampling_slices(
dataset: xr.Dataset,
step: int,
xy_dim_names: Optional[Tuple[str, str]] = None
) -> Dict[Hashable, Optional[Tuple[slice, ...]]]:
"""
Compute subs... | 0cef7a329bc33f124e3c5f7263a08cc9df8e9c37 | 3,628,654 |
import types
import asyncio
def loop_apply_coroutine(loop, func: types.FunctionType, *args, **kwargs) -> object:
"""
Call a function with the supplied arguments.
If the result is a coroutine, use the supplied loop to run it.
"""
if asyncio.iscoroutinefunction(func):
future = asyncio.ensure... | d77a70540237f690e712e30b93b53b363907b678 | 3,628,655 |
def zipmap(keys, vals):
"""
Return a ``dict`` with the keys mapped to the corresponding ``vals``.
"""
return dict(zip(keys, vals)) | a058e5a4e462416f48d83b3c288a0cd8d6b000ef | 3,628,656 |
def _create_thingy(sql_entity, session):
"""Internal call that holds the boilerplate for putting a new SQLAlchemy object
into the database. BC suggested this should be a decorator but I don't think
that aids legibility. Maybe should rename this though.
"""
session.add(sql_entity)
#Note t... | 4d50da3a15606c7adf61e2c9c09a4a3a9898edf9 | 3,628,657 |
import torch
def mix_estimator(states, actions, disc_rewards, mask, policy, result='mean'):
"""
states: NxHxm
actions: NxHx1
disc_rewards, mask: NxH
"""
upsilon_scores = policy.loc_score(states, actions) #NxHxm
G = torch.cumsum(upsilon_scores, 1) #NxHxm
sigma_scores = policy.scale_scor... | 510e88bbd9b36e89853341951d67cfc254e68d61 | 3,628,658 |
def weighted_loss(func):
"""
A syntactic sugar for loss functions with dynamic weights and average
factors. This method is expected to be used as a decorator.
"""
@wraps(func)
def _wrapper(pred,
target,
weight=None,
reduction='mean',
... | 078ddd743e5f1e3b835ac86ea25966a3813001ce | 3,628,659 |
def similarity(s, theta, axis, tx, ty, tz):
"""
Create a 4x4 similarity transformation matrix.
Parameters:
-----------
s: isotropic scaling ratio.
theta: angle of rotation about `thetaaxis`.
axis: a vector (not necessarily a unit vector along the axis of rotation.
tx: translation in... | 8303d2b2c988aae8e6217807a35afef1058c42dc | 3,628,660 |
def compute_sequences_weight(alignment_data=None, seqid=None):
"""Computes weight of sequences. The weights are calculated by lumping
together sequences whose identity is greater that a particular threshold.
For example, if there are m similar sequences, each of them will be assigned
a weight of 1/m. No... | b0da45ffb48526cbaaa2d976405323a6c41b6072 | 3,628,661 |
def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT):
""" Determine the bank names to use for a device """
if device != None:
if device.class_name in bank_name_dict.keys():
return bank_name_dict[device.class_name]
else:
banks = number_of_parameter_banks(device)... | 3dbb95d35a7bb837208d812ba377bc546c986993 | 3,628,662 |
def maxsubarray(list):
"""
Naive approach to calculating max subarray
Iterating all possible subarrays
Complexity (n = list size)
Time complexity: O(n^2)
Space complexity: O(1)
"""
maxStart = 0
maxEnd = 0
maxSum = list[0]
for i in range (len(list)):
currentSum = 0
... | 71b4a12d02fab45fc14890ae4a34a0dc50d6a7b4 | 3,628,663 |
def deserialize_transaction_data(f):
"""
Deserialize transaction data
More info: https://learnmeabitcoin.com/technical/transaction-data
:param f: buffer, required
:return: dict
"""
transaction = Transaction()
start_transaction_data = f.tell()
transaction.version = f.read(4)[::-1].he... | 8231bca1dbf7dfb86f16dbd4a5ac30d1c80579e7 | 3,628,664 |
def parse_string(string: str) -> list:
"""Parsing specified string
:param string: File content for parsing
:type string: str
:rtype: list
:raises: ParseException
"""
parsed = create_grammar().parseString(string, parseAll=True)
return parse_tokens(parsed) | 0b94d3917cfb37b28d22c90a877cbe4df32b1d67 | 3,628,665 |
def reset_config():
"""Reset the configuration.
An endpoint that accepts a POST method. The json request object
must contain the key ``reset`` (with any value).
The method will reset the configuration to the original configuration files that were
used, skipping the local (and saved file).
.. ... | f4c8c7aeea43a7c2c8bc196855ce4fb8081ac31c | 3,628,666 |
from typing import Sequence
def is_sequence(obj):
"""Is the object a *non-str* sequence?
Checking whether an object is a *non-string* sequence is a bit
unwieldy. This makes it simple.
"""
return isinstance(obj, Sequence) and not isinstance(obj, str) | 06129c6122fec0290edb34cadc75b68199738435 | 3,628,667 |
import numbers
import numpy
import collections
def sample_points(rng, N=None, conc=None, lower=None, upper=None, start=0, ndim=3):
"""Generate points distributed uniformly.
Args:
rng (numpy.RandomState, optional): A random number generator.
N (int or list, optional): The number of points to b... | acadabe2076ad0fed412fec5ba26ef44c0025117 | 3,628,668 |
def make_exponential_statistics(state):
"""Make ExponentialMovingStatistics object from state."""
return ExponentialMovingStatistics.fromstate(state) | bf9df2841707e2c12d91e23f17bc6de52728e66d | 3,628,669 |
import time
import socket
def DetectAio(timeout=1.1):
"""Detect AIO nodes on the network, present all options if none detected."""
sources = aio.aio_node_helper.Names()
types = aio.message_type_helper.Names()
client = aio.AioClient(types, timeout=0.1, allowed_sources=sources)
ip_list = []
version_list = [... | 805dc33200a6e774fc2d55032242ea79aa97c28f | 3,628,670 |
def getAxisList(var):
"""
Returns a list of coordinates from: var
"""
return [var.coords[key] for key in var.dims] | eae9b971bcbf021ef2203dd6cb21df6343d0f19a | 3,628,671 |
import functools
def listify(fn=None, wrapper=list):
"""
From https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the functi... | d9fe22ffdda41938aa6029bbb3ac54aeda4b818b | 3,628,672 |
def skip_nothing(name, dirpath):
"""Always returns :obj:`False`.
"""
return False | 9e846b7060af43b2c4165e6530fcabc66415615b | 3,628,673 |
import json
def _load(fpath):
"""Get content of json file at <fpath>."""
if not pth.__is_file(fpath):
log.critical("\"{0}\" doesn\'t exist, can\'t load data from it".format(fpath))
log.debug("Loading data from \"{0}\"".format(fpath))
fjson = pth.__open_file(fpath)
ret = json.load(fjson)
... | 8eb8d1bf98eaccdda38a31f9b050db1b89eccf1b | 3,628,674 |
import os
import subprocess
import re
def get_version_number(klocwork_path):
"""This function determines the Klocwork version number.
Inputs:
- klocwork_path: Absolute path to the bin directory of the Klocwork installation [string]
Ouputs:
- version_number: The version number of the Kloc... | 08f919420a1f2465895b3cab26d062fc78b58b95 | 3,628,675 |
def titlecase(string):
"""Titlecase all words in the string.
Words with quote (') titlecased only in the beginning, as opposed to
built-in ``str.title()``. Roman numerals are uppercased.
"""
def f(mo):
roman_mo = ROMAN_PATTERN.match(mo.group())
if roman_mo:
return mo.gro... | 88140ff62db5601573227654f876b0310a343709 | 3,628,676 |
def register(key=None):
"""Returns a decorator registering a widget class in the widget registry.
If no key is provided, the class name is used as a key.
A key is provided for each core Jupyter widget so that the frontend can use
this key regardless of the language of the kernel.
"""
def wrap(w... | c21246a30926f3e78c3e85c487de76affe776b72 | 3,628,677 |
import os
def load_data_dict(project_dir_string):
"""Load data from a colab_zirc_dims project folder into a dictionary.
Parameters
----------
project_dir_string : str
Path to a colab_zirc_dims project folder.
Returns
-------
Dict
A dict of dicts containing data from proje... | e09839bb26f00a9494926ad23b3a9ed2298c3ef7 | 3,628,678 |
import re
def find(pattern):
"""
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' nxos.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output.... | b60aa06d973ec7725351276aa3898be45e73757e | 3,628,679 |
import torch
def get_center(arcs):
"""Centre of the arc
Args:
arcs: tensor [batch_size, num_arcs, 7]
arcs[b, i] = [x_start, y_start, dx, dy, theta, sharpness, width]
Returns: tensor [batch_size, num_arcs, 2]
"""
x_start = arcs[..., 0]
y_start = arcs[..., 1]
dx = arcs[... | 665685e4cc17ab34732ad0928363c2f882bdc03e | 3,628,680 |
import urllib
from bs4 import BeautifulSoup
def get_urls_towns(url_index_by_letter):
"""Provides from the page corresponding to a city index the pages corresponding to the cities of the index.
Args:
url_index_by_letter (string): Url corresponding to a city index
e.g. : "https://elections.int... | 3282a27a4ded8d80f020b2306ab5e62c56c07be9 | 3,628,681 |
def simple_app(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
with Configurator(settings=settings) as config:
config.set_security_policy(TestingSecurityPolicy())
apps = global_config.get('apps', '')
if not isinstance(apps, (list, tuple)):
... | 7aa1edead8a557f6b08cb9323440633684cea6ab | 3,628,682 |
import sys
def _sized_dataframes(dataframe: pd.DataFrame) -> tuple:
""" Determines optimal chunks to publish the dataframe in. In smaller dataframes
this may be the whole dataframe.
This is determined by the hard values of 60MB being ideal for Spectrum, and
assumed compression ratio for dataframes to... | 953f491df83d1c7bb169c353fa22abb6aa52c914 | 3,628,683 |
from typing import Optional
import glob
import tqdm
import re
from pathlib import Path
import PIL
def imgs_preds(model_config: tuple[Model, tuple[int, int]], path: str, slc: Optional[slice] = None) -> list[
list[str, str]]:
"""
Get the predicted class for each image
:param model_config: model object ... | e81c0eaeaba9597656ba2e7459e4c5a316237540 | 3,628,684 |
def vertical_cross(in_field, lon, lat, line_points, npts=100):
"""
Interpolate 2D or multiple dimensional grid data to vertical cross section.
:param in_field: 2D or multiple dimensional grid data,
the rightest dimension [..., lat, lon].
:param lon: grid data longitude.
:param ... | 873985f361883992e23a8bc5142c5d0e469ca6c3 | 3,628,685 |
import csv
def write_wordlist(wordlist):
"""
Write a wordlist to a temporary file.
"""
handler = NamedTemporaryFile("w", encoding="utf-8", delete=False)
writer = csv.DictWriter(
handler, delimiter="\t", fieldnames=list(wordlist[0].keys())
)
writer.writeheader()
writer.writerow... | 377bb1871afaed6109e24e502752f7223238dec6 | 3,628,686 |
def hasfield(model_cls, field_name):
"""
Like `hasattr()`, but for model fields.
>>> from django.contrib.auth.models import User
>>> hasfield(User, 'password')
True
>>> hasfield(User, 'foobarbaz')
False
"""
try:
model_cls._meta.get_field(field_name)
return True
e... | 186b0754b3c87b5fb4c2b9a003221b57887160d1 | 3,628,687 |
def get_distance(point_a, point_b):
"""Receives two coordinates by parameter, and returns the geodesic distance between them (in km).
Params:
- point_a: tuple or list expected, first coordinate
- point_b: tuple or list expected, second coordinate
Returns:
- Formatted string indicati... | 5a897797d5b89448f0af1c7d09b1d7dc9fbd4942 | 3,628,688 |
def __substitute_controller_variables(config):
"""Substitute variables and set defaults for config
Arguments:
config {dict}
Raises:
Exception: [description]
Returns:
[dict]
"""
global_variables = config.get("variables", {})
set_master_password = global_variables.ge... | 29f55775284a5d1f8bd2bbc6ba2dcb18a4b838ec | 3,628,689 |
import os
import sys
def credentials():
"""Retrieves credentials"""
username = os.environ.get('OS_USERNAME')
password = os.environ.get('OS_PASSWORD')
tenant_name = os.environ.get('OS_TENANT_NAME')
auth_url = os.environ.get('OS_AUTH_URL')
if not all((username, password, tenant_name, auth_url)... | 6ac966762db6bb8c9079502d4adcfbf94ec753e8 | 3,628,690 |
def CNOT_like_PTM(idx):
"""
Returns the pauli transfer matrix for gates of the cnot like class
(q0) --C1--•--S1-- --C1--•--S1------
| -> |
(q1) --C1--⊕--S1-- --C1--•--S1^Y90--
"""
assert(idx < 5184)
idx_0 = idx % 24
idx_1 = (idx // 24... | ff861d8490742a9982fbfdb68e89d487e881bf1c | 3,628,691 |
def _random_binary_string_matrix(rows, cols, max_length):
"""Returns a list of lists of random strings"""
return [[_random_binary_string_gen(max_length) for _ in range(cols)] for _ in range(rows)] | 841ea51e2ae54da8d2381bcdc95c696f67ede17e | 3,628,692 |
import time
import json
import hashlib
def emit_webhook(client, url, job_id="test", worker_id=None, signal="new_judgments", unit_state="finalized", treatment="t10", by_get=True):
"""
:param client:
:param url: (str) relative path to target api
:param job_id: (str)
:param worker_id: (str)
:para... | 860a63da9b45991d24f447257ec4a475def2dee8 | 3,628,693 |
def comment_list_view(request, slug):
"""
Get post comments from a server
Selects the post instance matching the comment slug and then
gets all displayed comments that match that post instance.
Then we pass the objects we want to use into the serializer.
The serializer will take that informati... | f8c344d8c8e3fc1d7ca0f1c9db95adb7f0a8d174 | 3,628,694 |
def cos(x):
"""
Takes the cosine of a DualNumber object and returns a DualNumber object with updated value and derivatives.
"""
x = DualNumber.promote(x)
output = x.promote(np.cos(x.value))
# real part of the first parent distributes
for k1 in x.derivatives:
output.derivativ... | 4f20588ae91891287f334243d1db4be5cc29bc9d | 3,628,695 |
def get_defense_strategy(arg_dict, dataset_name, strategy_name, strategy_gpu_id,
defense_desc, metric_bundle, field):
"""Take the strategy name and construct a strategy object."""
return built_in_defense_strategies[strategy_name](
arg_dict, dataset_name, strategy_gpu_id, defense... | 1b0e4701ad1e85fd6fddf2ca174d30e2904b1c7b | 3,628,696 |
def get_role_description(role: str) -> str:
"""Gets the description for a role.
Args:
role (str): The programmatic role name.
Returns:
str: The corresponding role description from the game-info json.
"""
return game_info_json['roles'][role.lower()]['description'] | d6500f2b716938211aebbe11da10bcb6b93c6ce8 | 3,628,697 |
def pairwise_phase_pattern(module, window_type='voronoi', from_absolute=True,
project_phases=False, full_window=False,
sign='regular', length_unit='cm',
palette=None):
"""
Convenience function to plot nice pairwise phase patterns
... | 7262b594974214fb8b43be79ff837ae419591149 | 3,628,698 |
def centtoinch(cents):
"""Cents to inch."""
return .3937*cents | 517142a29242246721abd05638c8ecbefcd888cb | 3,628,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.