content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_move(main_prefix: str, original_path: str, new_file: str) -> bool:
"""Checks that a given file exists at the location in
the main bucket and no longer exists in the upload bucket.
Returns True if this is the case and False otherwise.
"""
main_path = os.path.join('gs://', main_prefix, 'b... | 5,318,400 |
def incident_created_modal_payload(pd_api_response):
"""Return the Slack Block Kit payload for the "Incident created" modal"""
safe_summary = slack_escape(pd_api_response["summary"])
return {
"response_action": "update",
"view": {
"type": "modal",
"title": {"type": "p... | 5,318,401 |
def test_menu__archive_menu__2(archive_menu):
"""The archive tab is selected on the archive overview."""
assert archive_menu.item_selected(archive_menu.menu_item_URL) | 5,318,402 |
def split_name(package: str):
""" Use regex to properly split the string into name and version spec """
version_tuple = re.search('(-\d{1,10}\.\d{1,10}\.\d{1,10}-?.{0,50})', package)
version_string = version_tuple.groups()[0]
version = version_string.split("-", 1)[1]
name = re.split('(-\d{1,10}\.\d... | 5,318,403 |
def buchdahl_find_alpha(wv, indices, wv_center, n_center, order=3, gtol=1.0e-9):
"""
Find the Buchdahl alpha parameter which gives a refractive index versus omega curve that is closest to a straight line.
Parameters
----------
wv : array of float
Wavelengths at which the refractive index da... | 5,318,404 |
def ddpg_n_step_new(env_name, render_env=False,
actor_hidden_layers=[300, 300], critic_hidden_layers=[300, 300],
seed=0,
steps_per_epoch=5000, epochs=100, replay_size=int(1e6), gamma=0.99,
n_step=1, backup_method='mixed_n_step', exp_batch_s... | 5,318,405 |
def transcode_file(filename):
"""Transfers code file."""
command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename)
subprocess.call(command, shell=True) | 5,318,406 |
def shn_pentity_represent(id, default_label="[No ID Tag]"):
""" Represent a Person Entity in option fields or list views """
pe_str = T("None (no such record)")
pe_table = db.pr_pentity
pe = db(pe_table.pe_id == id).select(pe_table.instance_type,
pe_table.pe_la... | 5,318,407 |
def calculate_mean_SD_CV(df, ranking, mean_col_name):
"""calculate the mean coefficient of variation of the tFs binding to a promoter"""
# group by promoter and calculate mean for each promoter
means = df.groupby("promoter_AGI")[ranking].mean()
# turn into a dataframe
means_df = pd.DataFrame(means)
... | 5,318,408 |
def normalize_trinucleotide(trinucleotide):
"""Return the normalized representation of the input trinucleotide sequence
Notes
-----
Each trinucleotide sequence has two possible representations (the sequence
and its reverse complement). For example, 5'-ACG-3' and 5'-CGT-3' are two
representation... | 5,318,409 |
def extract_file_by_file(location, target_dir, arch_type='*', skip_symlinks=True):
"""
Extract all files using a one-by-one process from a 7zip-supported archive
file at location in the `target_dir` directory.
Return a list of warning messages if any or an empty list.
Raise exception on errors.
... | 5,318,410 |
def resize_tiles(size):
"""Resize tiles and apply changes to map and character"""
global current_map
global tile_size
if size == tile_size:
return
tile_size = size
if current_map:
current_map.cell_size = size
screen_size = (current_map.get_size()[
... | 5,318,411 |
def r2z(data):
"""
Fischer's r-to-z transform on a matrix (elementwise).
"""
return(0.5 * np.log((1+data) / (1-data))) | 5,318,412 |
def loader_shift(loader, frame, relative=True):
"""Shift global in time by i preserving duration
This moves the loader by i frames preserving global duration. When relative
is False it will shift the global in to the start frame.
Args:
loader (tool): The fusion loader tool.
frame (int)... | 5,318,413 |
def get_current_timestamp(): # pylint: disable=unused-variable
"""
Retrieves the current local time in a custom timestamp format
"""
return time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) | 5,318,414 |
def get_fight_updates(game_ids=None, before=None, after=None, order=None, count=None, page_size=1000, lazy=False, cache_time=5):
"""
Return a list of boss fight event updates
Args:
game_ids: list or comma-separated string of fight IDs.
before: return elements before this string or datetime ... | 5,318,415 |
def test_missing_attribute_str(experiment):
"""Test experiment missing attribute str."""
attr = attribute_as_str(str(Path(experiment.path) / REL_IMAGE_PATH), "missing")
assert attr is None | 5,318,416 |
def format_float(number, decimal_places):
"""
Accurately round a floating-point number to the specified decimal
places (useful for formatting results).
"""
divisor = math.pow(10, decimal_places)
value = number * divisor + .5
value = str(int(value) / divisor)
frac = value.split('.')[1]
... | 5,318,417 |
def link_or_copy(src, dst):
"""Create a symlink at *dst* pointing back to *src* on systems that support it. On other systems (i.e. Windows), copy *src* to *dst* (using :py:func:`copy_if_different`)
"""
ensure_dir(dst)
if os.path.lexists(dst):
os.unlink(dst)
if sys.platform == 'win32':
... | 5,318,418 |
def make_mean_edisp(
observations,
position,
e_true,
e_reco,
low_reco_threshold=Energy(0.002, "TeV"),
high_reco_threshold=Energy(150, "TeV"),
):
"""Compute mean energy dispersion.
Compute the mean edisp of a set of observations j at a given position
The stacking is implemented in :... | 5,318,419 |
def test_tuning_curves_lif():
"""This tests that the neuron model on SpiNNaker doesn't diverge too far
from the reference LIF model.
"""
with nengo.Network() as model:
a = nengo.Ensemble(100, 1)
a.bias = np.linspace(0.0, 40.0, a.n_neurons)
a.gain = np.ones(a.n_neurons)
p ... | 5,318,420 |
def formatTime ( sec, nsec, fmt ):
""" Convert given time to a string presentation according to
a given control sequence """
# replace %f (and its variations) with fractional seconds
match = _ffmtre.search ( fmt, 0 )
while match :
# make replacement string
subsec = ".%09d" ... | 5,318,421 |
def CalculateChi6ch(mol):
"""
#################################################################
Calculation of molecular connectivity chi index for cycles of 6
---->Chi6ch
Usage:
result=CalculateChi6ch(mol)
Input: mol is a molecule object.
... | 5,318,422 |
def decode_transaction_filter(metadata_bytes):
"""Decodes transaction filter from metadata bytes
Args:
metadata_bytes (str): Encoded list of transaction filters
Returns: decoded transaction_filter list
"""
transaction_filter = []
if not metadata_bytes:
return None
for i in... | 5,318,423 |
def init_log(): # real signature unknown; restored from __doc__
"""
init_log() -> None :
C++ signature :
void init_log()
init_log( (int)arg1) -> None :
C++ signature :
void init_log(int)
init_log( (int)arg1, (bool)arg2) -> None :
C... | 5,318,424 |
def get_signin_box(burl):
""" xxx """
box_content = ''
if user_is_login() == 0:
l_app_header_title = 'Create unlimited optimized trading strategies'
l_app_header_desc = 'Chart patterns, price movements, '+\
'and news analysed using quantitative methods '+\
'with the power of... | 5,318,425 |
def jsonify(*args, **kwargs):
""" jsonify with support for MongoDB ObjectId
"""
return Response(
json.dumps(
dict(
*args,
**kwargs),
cls=MongoJSONEncoder),
mimetype='application/json') | 5,318,426 |
def test_celltype_update():
"""
Warning: changes files in package if ontology mismatches are found!
"""
dssg = DatasetSuperGroupLoaders(data_path=DIR_DATA_LOADERS_CACHE, meta_path=DIR_DATA_LOADERS_CACHE,
cache_path=DIR_DATA_LOADERS_CACHE)
for dsg in dssg.dataset_g... | 5,318,427 |
def parse_variable(srcline, funcname=None):
"""Return a Variable for the variable declared on the line (or None)."""
line = srcline.strip()
# XXX Handle more than just static variables.
if line.startswith('static '):
if '(' in line and '[' not in line:
# a function
retur... | 5,318,428 |
def _assert_df_is_valid_cforest(candidate_model):
"""Assert *df* represents valid causal forest.
A valid causal forest model is given by a pd.DataFrame which fulfills the
following criteria: 1 (MultiIndex). The data frame *df* must have a
MultiIndex with the first layer 'tree_id' and the second layer '... | 5,318,429 |
def get_folder_output(folder_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetFolderResult]:
"""
Retrieves a folder identified by the supplied resource name. Valid folder resource names have the format `folders/{folder_id}` (for examp... | 5,318,430 |
async def test_process_check_device_request(
tcp_connection: TcpConnection, bypass_asyncio_connection
) -> None:
"""Test processing of check device frame."""
# Setup test data for network information.
eth_data: Dict[str, Any] = {
"ip": "1.1.1.2",
"netmask": "255.255.255.255",
"ga... | 5,318,431 |
def delete_sample_template(job):
"""Deletes a sample template
Parameters
----------
job : qiita_db.processing_job.ProcessingJob
The processing job performing the task
"""
with qdb.sql_connection.TRN:
qdb.metadata_template.sample_template.SampleTemplate.delete(
job.pa... | 5,318,432 |
def is_ip(str_value: str) -> bool:
"""Returns True if string represents and IP address (either IPv4 or IPv6), else False.
:param str str_value: String to evaluate.
"""
return is_ipv4(str_value) or is_ipv6(str_value) | 5,318,433 |
def initialize_from_ckpt(init_ckpt, name_replacement_dict={},
non_trainable_names=[],
list_vars=None, assignment_map=None):
""" name_replacement_dict = { old_name_str_chunk: new_name_str_chunk }
non_trainable_names = ["bert", "word_embeddings"] # for ex... | 5,318,434 |
def parse_ply(fin):
"""Parse vertex data from a PLY format
Retuns a dictionary of keys to numpy arrays
"""
num_pts, attr_key, attr_type = parse_ply_header(fin)
data = [[] for k in attr_key]
for i in range(num_pts):
line = next(fin)
tokens = line.split()
for j, t in enum... | 5,318,435 |
def energy_change_charge_qa_atom(
df_qc, df_qats, target_label, delta_charge, target_initial_charge=0,
change_signs=False, basis_set='aug-cc-pV5Z', use_ts=True,
ignore_one_row=True, considered_lambdas=None, return_qats_vs_qa=False):
"""Calculate the energy difference to change the charge of a target ato... | 5,318,436 |
def initiate_XY_data(config):
"""Initiates an empty dictionary to contain the XY-data for each polygon, ie. both sample data and target data.
This is needed for the reference run.
By default, the first column is for the polygon ID, the second for polygon geometry.
The antepenultimate column is for bool... | 5,318,437 |
def test_save_from_dict():
"""
Test the not supported of save_from_dict.
"""
with pytest.raises(NotImplementedError):
conf = suapp.configuration.ConfigurationParser("here")
conf.save_from_dict(conf) | 5,318,438 |
def startup_framework(conn: Optional["projectconfig.ProjectConfig"] = None) -> None:
"""Start Pineboo project like framework."""
if conn is None:
raise Exception("conn is empty!")
import pyfiglet # type: ignore
qapp = call_qapplication(sys.argv + ["-platform", "offscreen"])
init_logging(T... | 5,318,439 |
def test_gge_cost_dictionary():
"""
Should not raise an error if gge_cost_dictionary is correctly formatted.
"""
test = gge_cost_dictionary()
assert test == {
'Gasoline': 2.23,
'Diesel': 2.0865800865800868,
'E85': 2.329700272479564,
'Hydrogen': 13.729146221786067,... | 5,318,440 |
def load_key_string_pubkey(string, callback=util.passphrase_callback):
# type: (str, Callable) -> PKey
"""
Load an M2Crypto.EC.PKey from a public key as a string.
:param string: String containing the key in PEM format.
:param callback: A Python callable object that is invoked
... | 5,318,441 |
def lookuptemplate(ui, topic, tmpl):
"""Find the template matching the given -T/--template spec 'tmpl'
'tmpl' can be any of the following:
- a literal template (e.g. '{rev}')
- a map-file name or path (e.g. 'changelog')
- a reference to [templates] in config file
- a path to raw template f... | 5,318,442 |
def PrintCI(fp, cm, ps):
"""Writes a line in the LaTeX table.
fp: file pointer
cm: diameter in cm
ts: tuples of percentiles
"""
fp.write('%0.1f' % round(cm, 1))
for p in reversed(ps):
fp.write(' & %0.1f ' % round(p, 1))
fp.write(r'\\' '\n') | 5,318,443 |
def handle_enumeration(tag, target, name, parent):
"""
Handle a 'type enumeration' tag
tag: pyang object for type enumeration
target: xml tag to place resulting node
parent: parent YangCSDLConversionObj for document access
"""
prop_node = SubElement(target, 'EnumType', {
'N... | 5,318,444 |
def _save_checkpoint(checkpoint_dir, model, optimizer, iterations):
"""SAVE CHECKPOINT
Args:
checkpoint_dir (str): directory to save checkpoint
model (torch.nn.Module): pytorch model instance
optimizer (Optimizer): pytorch optimizer instance
iterations (int): number of current it... | 5,318,445 |
def test_output_shape():
"""The output size (h, w) must be the same as the input"""
input_shapes = [(20, 20, 1), (20, 20, 3)]
nb_labels = 10
for input_shape in input_shapes:
x, y = generate_data(input_shape, nb_labels, 10)
model = generate_model(input_shape, nb_labels)
... | 5,318,446 |
def merge(left, right, path=None):
"""Merge dicts"""
if path is None:
path = []
for key in right:
if key in left:
if isinstance(left[key], dict) and isinstance(right[key], dict):
merge(left[key], right[key], path + [str(key)])
elif left[key] == right[... | 5,318,447 |
def update_copernicus_location(l1file):
"""This routine updates the latitude, longitude and altitude for the Copernicus radar
:param l1file: Full path of NetCDF Level 1 file, `<path-to-file>/ncas-radar-camra-1_cao_20201210-212823_fix-ts_l1_v1.0.nc`
:type infile: str
"""
# ------------------------... | 5,318,448 |
def resize_min_side(pil_img, min_len):
"""
Resize image such that the shortest side length = mins_len pixels
:param pil_img:
:param mins_len:
:return:
"""
# What's the min side?
w, h = pil_img.size
if w < h:
new_w = min_len
new_h = int(np.round(h * (new_w / float(w)))... | 5,318,449 |
def get_numeric_boundaries(df: DataFrame, column_name: str) -> (float, float):
"""
get the min and max values in a numric column. forces a cast to float.
If the column can't be casted as such then this wil throw an error which is currently not trapped
:param df:
:param column_name:
:return: (min... | 5,318,450 |
def test_delete_crontab_deletes_single_tab(setup):
"""Test get_crontab with env set to TAB_FILE"""
create_crontab("Test", "Test text", "@10m")
cron = get_crontab()
cron_tab_id = cron.crons[0].comment.replace("mac-os-notifier-id: ", "")
delete_crontab(cron_tab_id)
cron = get_crontab()
ass... | 5,318,451 |
def periodic_plot(
df,
attribute="atomic_weight",
title="Periodic Table",
width=1000,
height=800,
missing="#ffffff",
decimals=3,
colorby=None,
output=None,
cmap="RdBu_r",
showfblock=True,
long_version=False,
):
"""
Use Bokeh to plot the periodic table data contain... | 5,318,452 |
def concatenate(data: tvm.te.Tensor, axis: Optional[int] = 0):
"""Join a sequence of arrays along an existing axis. Optimized for CPU exeution.
Parameters
----------
data : tuple of tvm.te.Tensor
The arrays to concatenate
axis : int, optional
The axis along which the arrays will be... | 5,318,453 |
def defgrad_from_strain(E, kappa, flatten=1):
"""Compute the deformation gradient from the strain measure
Parameters
----------
E : ndarray (6,)
Strain measure
kappa : int or float
Seth-Hill strain parameter
flatten : bool, optional
If True (default), return a flattened ... | 5,318,454 |
def delete_bucket_content(resource_properties, request_type):
""" Deletes the content of an S3 Bucket.
Args:
resource_properties (dictionary): The Resource Properties
request_type (string): The Request Type
"""
bucket = resource_properties['BucketName']
logger.debug("bucket: %s, req... | 5,318,455 |
def get_url_gravatar(email):
"""
Obtenemos una url de gravatar
"""
m = hashlib.md5()
m.update(email.encode('utf-8'))
url = "http://www.gravatar.com/avatar/{0}.jpg?s=300".format(m.hexdigest())
return url | 5,318,456 |
def main():
"""
#---------------------------------------------------------------------------#
#--- main ---#
#---------------------------------------------------------------------------#
Description:
Main Function
Inputs:
See... | 5,318,457 |
def volume_type_qos_disassociate_all(context, qos_specs_id):
"""Disassociate all volume types from specific qos specs."""
return IMPL.volume_type_qos_disassociate_all(context,
qos_specs_id) | 5,318,458 |
def add_cached_properties(new_model: Type["Model"]) -> None:
"""
Sets cached properties for both pydantic and ormar models.
Quick access fields are fields grabbed in getattribute to skip all checks.
Related fields and names are populated to None as they can change later.
When children models are c... | 5,318,459 |
def create_command_at_set(command_set, command):
""" create a command on set """
command_entry = CommandEntry.objects.create(
command_set=command_set,
command=command
)
return command_entry | 5,318,460 |
def get_index_image():
"""Formats html.
Returns:
Modified index.html content
"""
return """<!DOCTYPE HTML><html lang="en-us">
<head>
</head>
<body style='margin:0'>
<img src='image.[[image_ext]]'>
</body>
</html>""" | 5,318,461 |
def merge_schema(original: dict, other: dict) -> dict:
"""Merge two schema dictionaries into single dict
Args:
original (dict): Source schema dictionary
other (dict): Schema dictionary to append to the source
Returns:
dict: Dictionary value of new merged schema
"""
source =... | 5,318,462 |
def noise_eq_bandwidth(window, axis=-1):
"""
Calculate the noise equivalent bandwidth (NEB) of a windowing function
as
sqrt(window.size * window.max ** 2 / sum(window ** 2))
See https://analog.intgckts.com/equivalent-noise-bandwidth/
Args:
window : float ndarray
axis : int,... | 5,318,463 |
def hash160(s: bytes) -> bytes:
"""
sha256 followed by ripemd160
:param s: data
:return: hashed data
"""
return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest() | 5,318,464 |
def trim_frame(fr: NDFrame, freq: str) -> NDFrame:
"""Trim index of frame to only keep full periods of certain frequency.
Parameters
----------
fr : NDFrame
The (untrimmed) pandas series or dataframe.
freq : str
Frequency to trim to. E.g. 'MS' to only keep full months.
Returns
... | 5,318,465 |
def settings_alert_rules(request):
"""
To allow users to manage alert
rules for given sites
"""
context_dict = {}
sites = _get_user_sites(request)
user_sites = _get_user_sites(request)
context_dict['permitted'] = get_org_edit_permissions(request.user)
context_dict['sites_stats'] = g... | 5,318,466 |
def test_keras_loss_func():
""" Keras loss set as standard function """
grapher = Grapher()
model = keras.models.Sequential()
model.compile(loss=keras.losses.hinge)
btf.keras_set_model_properties(grapher, model)
assert grapher.training_props['loss'] == 'Hinge' | 5,318,467 |
def generate_states_1qubit(c_sys: CompositeSystem, names: List[str]) -> List[State]:
"""returns a list of states on a common 1-qubit system.
Parameters
----------
c_sys: CompositeSystem
1-qubit system
names: List[str]
list of 1-qubit state names
Returns
-------
List[St... | 5,318,468 |
def fix_columns(data, text_1_name=None, text_2_name=None, label_name=None):
"""
Rename columns in an input data frame to the ones bisemantic expects. Drop unused columns. If an argument is not
None the corresponding column must already be in the raw data.
:param data: raw data
:type data: pandas.Da... | 5,318,469 |
def substitute_placeholders_from_file_to_memory(filename, verb, data):
"""replace all variables placeholders in filename and return the result"""
if os.path.exists(filename):
with open(filename, "r") as in_file:
buffer = substitute_placeholders_from_memory_to_memory(
in_file.... | 5,318,470 |
def unpack_kgrid(n, vals, log=null_log):
"""
Unpack the 'pyramid' of values u>=v>=w into the (n,n,n) k-grid.
n - the size of the grid
vals - m(m+1)(m+2)/6 values in the pyramid
returns out - (n,n,n) float64 array.
"""
lib = _initlib(log)
v = require(vals, dtype=float64, require... | 5,318,471 |
def valid_email(email):
"""Check for a valid email address.
Args:
email (str): Email.
Returns:
bool: Return True if in valid email format and False if not.
"""
return bool(re.match('^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', email)) | 5,318,472 |
def db_remove(key):
""" Endpoint Function to interact with PupDB's remove() method. """
try:
if not key:
return {'error': 'Missing parameter \'key\''}, 400
try:
result = DB.remove(key)
except KeyError as key_err:
return {'error': str(key_err)[1:-1]},... | 5,318,473 |
def slug(value):
"""
Validate whether or not the given string is a valid slug.
Args:
value (str): the value to validate.
Raises:
`~serde.exceptions.ValidationError`: when the value is not a valid slug.
"""
if not validators.slug(value):
raise ValidationError('{!r} is no... | 5,318,474 |
def n_plus_one_thresholds(count=None, duration=None):
"""
Reduce the thresholds on NPlusOneTracker to force capture without having to
run a lot of slow queries
"""
if count is None:
mock_count = nullcontext
else:
mock_count = mock.patch.object(NPlusOneTracker, "COUNT_THRESHOLD", ... | 5,318,475 |
def loading_items(data):
"""
Loads the items of the game. All the items are created along with their
names, properties, and descriptions.
Parameters:
data(dict): Nested dictionaries containing
all information of the game in regard to items.
"""
names = game_data.load_items(d... | 5,318,476 |
def raise_if_file_changed(path_to_file: str):
"""
Context manager that raises if a file is modified.
On Windows, the OS modification time resolution is 100 ns
"""
pre_operation_time = getmtime(path_to_file)
# we don't want to catch and re-raise anything, since there is no clean-up
# that we ... | 5,318,477 |
def rgb2gray(img):
""" Given an RGB image return the gray scale image.
Based on http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
img = 0.299 R + 0.587 G + 0.114 B
"""
print('Converting RGB image to gray scale.')
return np.uint8(np.dot(img[...,:3], [0.299, 0.587, 0.114])) | 5,318,478 |
def example1():
"""
Example 1: Read/Write - Level 2
"""
# this example will demonstate:
# - reading the BDF
# - getting some basic information
# - writing the BDF
# our model
import pyNastran
pkg_path = pyNastran.__path__[0]
test_path = os.path.join(pkg_path, '..', 'model... | 5,318,479 |
def Constrains(params):
"""" This function takes a set of parameters.
Applies some constrains to the parameters and check if constrains are fulfilled.
If yes, returns the passed parameters
If no, returns a set of modified parameters that fulfill the constrains
This function has to be executed a... | 5,318,480 |
def search():
"""获取随机推荐"""
html = '<form action="/blog/search/" method="get" name="form" ><div class="my-search" >' \
'<input type="text" name="q" autocomplete="off" placeholder="请输入搜索内容" class="search-input">' \
'<i class="layui-icon layui-icon-search search-btn" onclick="javascript:form.... | 5,318,481 |
def find_number(text, ignore_spaces=False, make_int=True,
ignore_chars=None):
"""
Find the number in the `text`.
:param text: unicode or byte-string text
:param ignore_spaces: if True then groups of digits delimited
by spaces are considered as one number
:raises: :class:`Dat... | 5,318,482 |
def PeerDownHasBgpNotification(reason):
"""Determine whether or not a BMP Peer Down message as a BGP notification.
Args:
reason: the Peer Down reason code (from the draft)
Returns:
True if there will be a BGP Notification, False if not
"""
return reason == 1 or reason == 3 | 5,318,483 |
def create_transition_model_corrected_arrays(star_dir, function='quadratic',
n_sigma=2.5):
"""
Create the transition model-corrected arrays for a Star from a given
directory.
Parameters
----------
star_dir : `pathlib.Path`
The directory in w... | 5,318,484 |
def productos_pos():
"""
Muestra las configuraciones para productos pos
"""
productos = db(db.maestro_pos).select()
return dict(productos=productos) | 5,318,485 |
def _build_measurement_vectors(ppci):
"""
Building measurement vector z, pandapower to ppci measurement mapping and covariance matrix R
:param ppci: generated ppci which contains the measurement columns
:param branch_cols: number of columns in original ppci["branch"] without measurements
:param bus_... | 5,318,486 |
def load(path):
"""Load data and reconstruct model."""
with zipfile.ZipFile(path,'r') as zf:
buf = StringIO.StringIO(zf.read('weights.npy'))
weights = numpy.load(buf)
config = json.loads(zf.read('config.json'))
data = pickle.loads(zf.read('data.pkl'))
task = pickle.load... | 5,318,487 |
def test_diffmodel_surfflux(diffmodel_surfflux):
"""Check that we can integrate the model with diffusion."""
diffmodel_surfflux.step_forward()
diffmodel_surfflux.integrate_days(2) | 5,318,488 |
def env(
a,
import_models=False,
c=None,
f=None,
dir='',
):
"""
Return web2py execution environment for application (a), controller (c),
function (f).
If import_models is True the exec all application models into the
environment.
"""
request = Request()
response ... | 5,318,489 |
def get_payload_hash(payload):
"""Return unique hash of HySDS job JSON payload."""
clean_payload = copy.deepcopy(payload)
for k in ('_disk_usage', '_sciflo_job_num', '_sciflo_wuid'):
if k in clean_payload:
del clean_payload[k]
return hashlib.md5(json.dumps(clean_payload, sort_keys=2... | 5,318,490 |
def binStack(array, bins, id0=1):
"""
Bin a hyperstack according to a known list of frames per bin
@param array: input array to be binned, hyperstack or otherwise.
Binning occurs along the first axis
@type array: numpy.ndarray
@param bins: list of frames in each bin. Each index in bins is a... | 5,318,491 |
def knn(A, B, k, distFcn):
"""
Returns the indices of the k-nearest neighbors of A in B
Parameters
----------
A : Tensor
a (N,F,) tensor
B : Tensor
a (M,F,) tensor
k : int
the number of neighbors to find
distFcn : callable
the distance function to use
... | 5,318,492 |
def parallel(func, items):
"""
Run the given function in parallel.
Use multithreading to run the given function and arguments in parallel.
"""
# Setup the work and results queues and the finish event.
item_queue = queue.Queue()
fin = threading.Event()
# Load the ports into the queue
... | 5,318,493 |
def set_purpose(slack_client, channel, purpose):
"""
Set the purpose of a given channel.
"""
response = slack_client.api_call("channels.setPurpose",
purpose=purpose, channel=channel)
return response | 5,318,494 |
def generate_aes_key(size=256):
"""
Generates aes key with specified size
:param size: aes bits, default 256
:return: generated key bytes
"""
return os.urandom(int(size / 8)) | 5,318,495 |
def masked_minimum(data, mask, dim=1):
"""Computes the axis wise minimum over chosen elements.
Args:
data: 2-D float `Tensor` of size [n, m].
mask: 2-D boolean `Tensor` of size [n, m].
dim: The dimension over which to compute the minimum.
Returns:
masked_minimum: N-D `Tensor`.
The minimize... | 5,318,496 |
def predict(ifile, modification):
"""
Predicts and prints the predicted class for the input file.
Parameters
----------
ifile:
Filename of the input file.
modification:
Dictionary that contains all config parameters for reproducibility
+ a Classifier key that contains t... | 5,318,497 |
def spawn_node_process(output_dir: PathLike) -> Tuple[subprocess.Popen, str]:
"""
Spawn an rfbrowser node process, that can be shared between library instances.
Usage example:
rc = 1
background_process, port = spawn_node_process(ATEST_OUTPUT / "playwright-log.txt")
try:
os.environ["ROB... | 5,318,498 |
def decode_stderr_json(stderr):
""" return a list of decoded json messages in stderr """
# - check for blank input
if not stderr:
# - nothing to do
return list()
# - split the input (based on newlines) into list of json strings
output = list()
for line in stderr.split('\n'):
... | 5,318,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.