content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def lifetime_init(rule='1/e'):
"""Initialize a lifetime object.
Parameters
----------
rule : str {'1/e', 'trapz', 'simpson'}, optional
Name of the method to integrate the correlation curve. \n
'1/e' uses the 1/e rule and assumes an exponential decay. It linearly
interpolates the... | 246bf31672fcd98a7ccd272ec7967c8a5e51817b | 643,897 |
import operator
def get_key_tag(soup, top_result):
"""Finds the nth most popular tag on a webpage.
Args:
soup: A Beautiful Soup object of the target's EX-21 document
(i.e.: subsidiary information).
top_result: The nth most popular tag to find.
Returns:
Returns the tag... | 8d060a10d97dfef325ce1fec9e843bc6d22019ce | 643,898 |
import string
import random
def random_string(lenght: int = 10) -> str:
"""Generate a random string composed of lower cased ascii characters
Args:
lenght (int, optional): lenght of the string to generate. Defaults to 10.
Returns:
str: random string of lenght `lenght` composed of lower ca... | e44f1f44234f9a47eec854c7c351aa26fd68d0bf | 643,899 |
def generatetfmatrix(matrix, idf):
"""
Generate a new term weight matrix when supplied with the current `matrix` and
the weighing factors `idf`. Returns a new matrix using lists.
"""
docamount = len(matrix[0]) # get the amount of documents
wordcount = len(matrix)
updatedmatrix = list() # c... | b62fdc6ec77a923e74dcaa529124ba19dabe1fd7 | 643,900 |
def encrypt(text, public_key):
"""function used for encryption"""
key, n = public_key
ciphertext = [pow(ord(char), key, n) for char in text]
return ciphertext | 622f5d5bb9c531cde7f97f218b25b332e949f965 | 643,902 |
import os
def file_relative_path(dunderfile, relative_path):
"""
This function is useful when one needs to load a file that is
relative to the position of the current file. (Such as when
you encode a configuration file path in source file and want
in runnable in any current working directory)
... | c5f17880a02910230428f398a110301f9d72bddb | 643,903 |
def dadras(XYZ, t, p=3, s=2.7, r=1.7, c=2, e=9):
"""
The Dadras Attractor.
x0 = (0.1,0.03,0)
"""
x, y, z = XYZ
x_dt = y - p * x + s * y * z
y_dt = r * y - x * z + z
z_dt = c * x * y - e * z
return x_dt, y_dt, z_dt | 7c48f74795f029b4ee583f0b0b863b290a9d454c | 643,904 |
def parse_column_names(df):
"""
Method used to parse the column names
:param df: Original data frame
:type df: pd.DataFrame
:return: pd.DataFrame -- Formatted data frame
"""
cols = set(df.columns.tolist())
if "StreamID" in cols:
df.rename(columns={"StreamID": "stream_id"}, inpl... | 2dba3d0d185a0111e93763f74f303dc4bd46f418 | 643,905 |
def layer_uid(use_spatial_hash, spatial_hash_cell_size):
"""
create a number that will always be unique for a spritelist with
the given properties.
"""
uid = spatial_hash_cell_size << use_spatial_hash
return uid | 0e05c3352f2f9cc9cd710155f75bb8f4e5a5034c | 643,906 |
def find_containerName_by_containerId(containers_list, container_id):
"""
Function to get containername based on container ID.
Parameters
----------
containers_list : list
Containers list extracted from CVP.
container_id : string
ID of the container to search
Returns
--... | c3660ab437765a8681def3c2c2b0f4f974629949 | 643,907 |
def distance_from_speed_and_time(movement_speed, movement_time):
"""Returns distance from speed and time"""
return movement_time * movement_speed * 1000 / 3600 | 8cc1a9745c4f03ffe47e6e872a04435beb82a15f | 643,908 |
from pathlib import Path
def get_image_paths(image_folder: Path) -> list:
"""
Get all images in image folder ending in .jpg or .png
"""
suffix_set = {'.jpg', '.png'}
return [
image for image in image_folder.iterdir() if image.suffix in suffix_set
] | edbeacbe899f2e19a1d8a460d2b30215e28c2a46 | 643,909 |
def personal_top_three(scores):
"""
Return top three score from the list. if there are less than 3
scores then return in a decending order the all elements
"""
# sorted the list in a decending order
sorted_scores = sorted(scores, reverse=True)
# check if there are at least 3 elements... | 7937d881fd370e6a710511c51ae5772441f66825 | 643,910 |
import math
def ceil(num: int) -> float:
""" Ceil a specific number """
return math.ceil(num) | 526199245d8f7ac78cf8a88f56858954e5b4cf89 | 643,911 |
import toml
def _return_toml(toml_path):
"""return config files loaded into dicts with toml library
used to test functions that parse config sections, taking these dicts as inputs"""
with toml_path.open("r") as fp:
config_toml = toml.load(fp)
return config_toml | bb7ff9dfeea64a7994e3bf5ada0bb3b98cf24877 | 643,912 |
def lines(
*,
base_width=0.5,
line_base_ratio=2.0,
tick_major_base_ratio=1.0,
tick_minor_base_ratio=0.5,
tick_size_width_ratio=3.0,
tick_major_size_min=3.0,
tick_minor_size_min=2.0,
axisbelow=True,
):
"""Adjust linewidth(s) according to a base width."""
tick_major_width = ti... | 04cfd88f419165f4601e02533bb2def1154de58b | 643,913 |
def stack_template_key_name(blueprint):
"""Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint.
"""
name = bluep... | d7c52712e8c22ef675380e03ddef60e3557296af | 643,914 |
def _read_titles(fn):
""" Read titles from file """
with open(fn) as f:
return [line.strip().replace(r'\n', '\n') for line in f] | e59c4a939475b2a9450ca1f25322a62006ed9d16 | 643,915 |
def _set_log_format(color: bool, include_caller: bool) -> str:
"""
Set log format
:param color: Log message is colored
:param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123]
:return: string of log format
"""
level_name = "* %(levelname)1s"
time = "%(asctime)s,%... | 48e0da162e1633f61ebd787e569d2435f932aa6a | 643,917 |
import torch
def calc_emd_loss(pred, target):
"""calculate emd loss.
Args:
pred (Tensor): of shape (N, C, H, W). Predicted tensor.
target (Tensor): of shape (N, C, H, W). Ground truth tensor.
"""
b, _, h, w = pred.shape
pred = pred.reshape([b, -1, w * h])
pred_norm = torch.sqrt... | fd3c55e31b7e0e6044c091402dfd0b7b6c1498de | 643,918 |
def format_sort_key(sort_key):
"""
format sort key (list of integers) with | level boundaries
>>> str(format_sort_key([1, 0, 65535]))
'0001 | FFFF'
"""
return " ".join(
("{:04X}".format(x) if x else "|") for x in sort_key
) | b03f09c1a6d35bb97029e873f186498b5deea320 | 643,919 |
def get_lcps(yaml, interfaces=True, loopbacks=True, bridgedomains=True):
"""Returns a list of LCPs configured in the system. Optionally (de)select the different
types of LCP. Return an empty list if there are none of the given type(s)."""
ret = []
if interfaces and "interfaces" in yaml:
for _if... | db8126143d7249e71f4a1367d9ffdf9bbb946569 | 643,920 |
def bitceil(N):
"""
Find the bit (i.e. power of 2) immediately greater than or equal to N
Note: this works for numbers up to 2 ** 64.
Roughly equivalent to int(2 ** np.ceil(np.log2(N)))
"""
# Note: for Python 2.7 and 3.x, this is faster:
# return 1 << int(N - 1).bit_length()
N = int(N) ... | 33bd75c2a129f7797b8efcb50a3be275918dfd16 | 643,921 |
import numpy as np
def sph_dist(a1, d1, a2, d2):
"""Calculate spherical distance between two sky positions. Uses the haversine
formula so accuracy degrades at distances near 180 degrees.
The input coordinates can be either native python types (float, int) or
numpy arrays. The output will matchin th... | ad57cb6a15cb7486668f5ae288cb61d1784f75cd | 643,922 |
def dos_list_request_to_indexd(dos_list):
"""
Takes a DOS ListDataObjects request and converts it into a request against
indexd index.
:param gdc:
:return:
"""
mreq = {}
mreq['limit'] = dos_list.get('page_size', None)
mreq['start'] = dos_list.get('page_token', None)
return mreq | e89c45750e9119c77201692b8777df07175fd7a8 | 643,923 |
def append_descriptor(descriptor, desc_new):
"""
appends a descriptor to an existing one
Args:
descriptor(dict): the descriptor dictionary, with list-like values
desc_new(dict): the descriptor dictionary to append
Returns:
descriptor(dict): the longer descriptor
"""
fo... | de5d9a7a1ec146b535b45e7c3faad503a871675b | 643,924 |
def _loop_action_in_command_line(command_line: str) -> bool:
"""Does the command line contain a loop statement
Args:
command_line (str): The command line to test.
Returns:
bool: True if there's a loop in this command line.
"""
return any(
word in command_line.split() for wo... | 8cf6c17805dc25be41ecbc32664bd396d13e3df1 | 643,925 |
def validate(attrs):
""" No-op function which will validate the client-side data.
Werkzeug will throw an exception if you try to access an
attribute that does not have a key for a MultiDict.
"""
try:
#required_attributes = ('qquuid', 'qqfilename')
#[attrs.get(k) for k,v in attrs.item... | 01449e7e7073df966fed3da6d43487c31c2f7c47 | 643,926 |
from datetime import datetime
def format_date(
date: datetime, base: datetime = datetime.now(), all_day: bool = False
) -> str:
"""Convert dates to a specified format
Arguments:
<date>: The date to format
[base]: When the date or time matches the info from base, it will be skipped.
This helps avoid repeated i... | 5e755097dd858b5f37000be113758611076dc59c | 643,927 |
def private_base_url_and_expected_port(private_base_url, request):
"""
Returns the upstream api url to be used, along with the port that is
expected
"""
url = private_base_url(request.param)
port = url.split(":")[2].replace('/', '')
return url, port if port not in {'80', '443'} else None | f8ce95538fa8a6f070fea2b29b946bcfa2e14251 | 643,929 |
import torch
def compute_accuracy(idxR, idx, k, device="cpu"):
"""
================================= \n
#----- INPUT \n
idxR : (Tensor) real labels \n
idx : (Tensor) estimated labels \n
k : (Scalar) numbe... | 506b179bca88e0d256d865965808c6b635340770 | 643,930 |
def replace(source_files):
"""Utility function to replace empty files list"""
replace_files = list(source_files)
for o in replace_files:
o.name = o.name[:-1] + '0'
o.index = (o.index[0], 0)
o.out_index = None
o.in_index = None
# Set a vacuous data list
replace_data =... | 55cd0fddd26d372691a272bb377f5c97dd829c19 | 643,931 |
def create_switch(cfmclient, data, fabric_type=None):
"""
Create a Composable Fabric switch.
"""
params = {'type': fabric_type} if fabric_type else None
return cfmclient.post('v1/switches', params, data).json().get('result') | 3db8f54afdd5022c36de6b4cd9a14332b409fd0d | 643,932 |
import hmac
import hashlib
import base64
def authenticate(request, channel_secret):
"""Validates the incoming HTTP requests.
Args:
request (flask.Request): HTTP request object.
channel_secret (str): channel secret got from LINE developer console.
Returns:
bool: true when ... | 7908d4d9ee6a4ecd4c6ff2e6eafe5f2903fbfe9c | 643,933 |
import base64
def string_to_base64(string):
"""
Encodes a string in base64 (> str)
"""
string_bytes = string.encode('ascii')
base64_encoded = base64.b64encode(string_bytes)
base64string = base64_encoded.decode('ascii')
return base64string | d918ad8120331aa62efcc548ff6345cd8c67580b | 643,934 |
def resolve_xpath_to_element(*names):
""" Resolves the objects from the context (which are supposed to be XPath
expressions) referenced by ``names`` with the *one* element that the XPaths
yield or
``None``. This is useful when a copied tree is processed and 'XPath pointers'
are passe... | 05a44e9ddd99114d492fc834585b13c0fa2d9efc | 643,935 |
import re
def get_vcpus_per_osd_from_ironic(ironic, tripleo_environment_parameters, num_osds):
"""
Dynamically sets the vCPU to OSD ratio based the OSD type to:
HDD | OSDs per device: 1 | vCPUs per device: 1
SSD | OSDs per device: 1 | vCPUs per device: 4
NVMe | OSDs per device: 4 | vCPUs p... | a0a88b9e3d29342b16792d56198f7ee0ee7cabf7 | 643,936 |
def power(base, exp):
"""Finding the power"""
assert exp >=0 and int(exp) == exp, 'The exponential must be positive integers only'
if exp == 0:
return 1
if exp == 1:
return base
return base * power(base, exp-1) | d44a8df50ed5d2744a4a48a7a5fe2e005a517e17 | 643,937 |
def gimmepi():
"""
returns pi
"""
return 3.141592653589793 | fa544a0246429cdf29f601275616ee6192e17eca | 643,938 |
import os
def out_of_date(extensions):
"""
Check whether any pyx source is newer than the corresponding generated
C source or whether any C source is missing.
"""
for extension in extensions:
for pyx in extension.sources:
path, ext = os.path.splitext(pyx)
if ext not in ('.pyx', '.py'):
continue
cs... | bb8dffbe2a76743eefc2c5128344a6c99ca9ac90 | 643,939 |
def get_uce_num(header):
"""use own function vs. import from match_contigs_to_probes - we don't want lowercase"""
return header.lstrip('>').split(' ')[0].split('_')[1] | 933ecab6f8fb18a59dda74f76f8bcba6f92c4329 | 643,940 |
import os
def project_info(result):
"""Get toplevel dir, project_slug, and project dir from baked cookies"""
project_path = str(result.project)
project_slug = os.path.split(project_path)[-1]
project_dir = os.path.join(project_path, project_slug)
return project_path, project_slug, project_dir | 572afc7542a8cbff309c1617d72a6e1cd4cecb39 | 643,941 |
from typing import Tuple
from typing import List
def sort_read_groups(read_groups_string: str) -> Tuple[List[str], List[str]]:
"""Reorder the argument to the STAR `--outSAMattrRGline` parameter.
The sort line could be substituted by using the `sorted()`
method on both lists, since what's being sorted on ... | 3ad1122b7280167c6f7fbb91f1b36e9770b05102 | 643,942 |
import numpy
def smooth_profile(xh, ak, xa):
"""Calculated smoothed profile.
Calculate a smoothed profile following Rodgers and Connor (2003).
:param xh: High-resolution profile
:param ak: Low-resolution averaging kernel [VMR]
:param xa: Low-resolution a priori profile
"""
OK = (numpy.i... | 1c83da1563514063e423795e11b5bef6e4d95e9b | 643,943 |
import torch
def create_pinhole(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz):
"""Creates pinhole model encoded to a torch.Tensor.
"""
return torch.Tensor([
[fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz]]) | 2ffa87c9c7b243ff9769329d0e705a245cb52bef | 643,944 |
def _universal_binary_test_transition(_settings, attr):
"""Implementation of the universal_binary_test_transition transition."""
return {
"//command_line_option:cpu": attr.cpu,
} | 61b2dafecfb891c20d6472bbd095343a4ed9ac67 | 643,945 |
def need_elem(glyph):
""" Finds RGlyph object that needs elem attribute. """
return not glyph.name.startswith('uni') and glyph.name.endswith('V') | 58925177d41e7d860ad8f74c1746218fa94a99e1 | 643,946 |
import base64
def _posh_encode(command):
"""Encode a powershell command to base64.
This is using utf-16 encoding and disregarding the first two bytes
:param command: command to encode
"""
return base64.b64encode(command.encode('utf-16')[2:]) | e307c56179b6aa1d5cfa76d7568b7c26f8fe5800 | 643,947 |
import six
def _convert_str(data, to_binary=False):
"""Helper to convert str to corresponding string or binary type.
`data` has `str` type (in both Python 2/3), the function converts it
to corresponding string or binary representation depending on Python
version and boolean `to_binary` parameter.
... | 10d16fbe6be8148299969f7f455f3f54089cec45 | 643,949 |
import re
def _is_valid_import(source_module, target_module, disallowed):
""" Return whether an import is allowed.
Parameters
----------
source_module : str
Name of the module where the import statement is.
target_module : str
Name being imported.
disallowed : str
Regu... | e943da982133f168810ce219571e00f94c811937 | 643,950 |
import os
def package_is_installed(name, path):
"""Check if <name>.yaml exist in path.
"""
yaml_fn = os.path.join(path, name + '.yaml')
return os.path.isfile(yaml_fn) | 5c20f0bbdbace4d4a850c322b010c1bbb6b666bd | 643,951 |
import torch
def extract_indices(seq, which_one):
"""
Helper method to extract the indices of elements which have the specified label.
:param labels: (torch.tensor) Labels of the context set.
:param which_class: Label for which indices are extracted.
:return: (torch.tensor) Indices in the form of ... | a9865c58bd05fe2e818091a0c1e7f1dc62962064 | 643,953 |
import random
def decision(probability: float):
"""Function that gives you a decision based on a given probability
:param probability: float between 0 and 1
:type: float
:return: True or False
:rtype: bool
"""
if random.random() < probability:
print("You know what let's do it...")
... | 9a4213f1ac7f6bc95d58e9dcb7223a73cdf10fc7 | 643,954 |
def create_events_blocks(events):
"""
Function to create list of events grouped by time.
:param events: all (or available) elements of `DayStudyEvents`
:type events: list
:return: list of events grouped by time
:rtype: list of list
"""
event_blocks = []
for i, event in enumerate(eve... | 17934584ab04dd01e34b4ff5ee79df792e392df1 | 643,955 |
import random
def _point_in_vertices(pt, vertices):
"""**HELPER METHOD. DO NOT CALL.** Returns whether a point
is contained in a polygon specified by a sequence of vertices.
Parameters
----------
pt : libpysal.cg.Point
A point.
vertices : list
A list of vertices representing a... | ebeaa431f507ebdface4873efa440acbd80668de | 643,956 |
def speed_ms_to_kmh(speed_ms):
"""Converts to m/s to km/h"""
return speed_ms * 3.6 | 25dff568fb0edb5f3d7af73cc45b3dfd5ec24e9b | 643,957 |
import os
def _getbaseDir(ctx, name=None):
"""
Returns an absolute path based on the given folder name:
".": directory that contains the current instance's the ensemble
"src": directory of the source file this expression appears in
"home" The "home" directory for the current instance (committed... | 89669b0bf14cf08ceaf9ca89e3a1088335cdc51a | 643,958 |
from pathlib import Path
def temp_directory(tmpdir):
"""Return path to temporary directory, and cleanup afterwards."""
return Path(tmpdir).resolve() | a0a9ec9282414a0187a1e98ba9a58f6beac9b7ee | 643,960 |
import requests
def get_jupyter_kernels(resource_url, user_token):
"""extracting information for each kernel on a Jupyter server"""
sessions_url = f"{resource_url}api/sessions"
headers = {"Authorization": f"token {user_token}"}
response = requests.get(sessions_url, headers=headers)
result = respon... | 4896ea9a4951c8f4c0a1c018525dda54aa8155ce | 643,961 |
def ipv6_mask_to_long(mask):
"""Convert an IPv6 prefixlen to long
>>> ipv6_mask_to_long(64)
340282366920938463444927863358058659840L
>>> ipv6_mask_to_long(128)
340282366920938463463374607431768211455L
"""
mask_binary = ("1" * mask) + ("0" * (128-mask))
return int(mask_binary, 2) | eda598f07220c69238ba4988cbf37f0b7ba9241a | 643,963 |
def other_citations():
"""
Other citations that should be included. A dict of strings
:return:
:rtype:
"""
return {
'conda-forge': """
conda-forge community. (2015).
The conda-forge Project: Community-based Software Distribution Built on the conda Package Format and Ecosystem.
Zenodo. htt... | be51d7518317926e8874512eecb7c23f4d72caec | 643,964 |
def generateOldLibraryEntry(data):
"""
Return a list of values used to save entries to the old-style RMG
thermo database based on the thermodynamics object `data`.
"""
items = '{0:3d}'.format(data.symmetry)
for lower, upper, degeneracy in data.frequencies:
items += ' {0:3d} {1:9.1f} ... | f6b19d402c3320e505e5be51690adb42c5bf3d47 | 643,965 |
def check_index(active_array, item):
"""Check row and column index of 2d array"""
for c in range(5):
for r in range(5):
if active_array[c][r] == item:
return [c, r] | 65a5486298160aebece6fd5afb901c9201611c68 | 643,967 |
def normalize_volume(audio, dBFS=-15):
"""Normalizes the volume of an audio clip.
Normalizes the amplitude of and audio clip to match a specified value of
decibels relative to full scale.
Args:
audio (pydub AudioSegment): The audio clip to be normalized.
dBFS (int): the desired... | 3dde8c64fc5cb4997c17da1596458788b675a6f5 | 643,968 |
def use_map(letters):
"""
>>> import string
>>> list(use_map(string.ascii_letters)) # doctest: +ELLIPSIS
[97, 98, 99, ..., 88, 89, 90]
"""
return map(ord, letters) | 35965362456be35f78263cff7b765f0a4a0c8d91 | 643,969 |
def findMatching(device, device_arr):
"""
Check the array of devices to see if there is a matching element.
Args:
device (string): The name of the device attempting to be added.
device_arr (array): An array of the devices attached to a profile.
"""
matches = [x for x in device_arr i... | 388e7ee8c66d91f52935dfe61e9b2ce8cb3ac661 | 643,970 |
def R4(fZ, delta_P, delta_S):
"""
R4 Preload changes Fz
(Section 5.4.2)
Fz : Loss of preload due to embedding
"""
#
Fz = fZ / (delta_P + delta_S) # (R4/1)
#
return Fz
# | 264a77a1222f1a02fc008c38de2347948c186e19 | 643,971 |
import csv
def read_random_seeds():
"""Reads in the random seeds from a csv file and sorts them in ascending order."""
random_seeds = []
with open('./final.csv') as data_file:
csvReader = csv.reader(data_file)
for row in csvReader:
random_seeds.append(int(row[0]))
random_s... | b35b89c58a36275d5058027d394c9269852e8753 | 643,972 |
import os
def is_modified(file_path, info):
"""."""
state = False
mtime = os.path.getmtime(file_path)
last_mtime = info.get(file_path)
if mtime and mtime != last_mtime:
state = True
return state | c50b2b2c73cf172c705a7eeee59b35c278365d23 | 643,973 |
import re
def sanitize_host(host):
""" Removes extraneous characters from a hostname, leaves an IP untouched. """
if re.match(r'[a-zA-Z]', host):
return host.split()[0].strip().replace('_', '-').replace('.', '')
else:
return host | fdb33ca216c99ce5de7d33b71bd44cd104ae83c4 | 643,975 |
def convert_bounding_box(bb_from_get):
"""Convert bounding box specified by by {'low': (x_min, y_min, z_min), 'high': (x_max, y_max,
z_max)} to {'xMin': x_min, 'yMin': y_min, ..., 'zMax': z_max}
Input typically comes from Abaqus' function getBoundingBox. Output, bb_to_get_by, can be used in
Abaqu... | 9676826b64c987186c035043c39e838eb8d232ca | 643,976 |
def get_labelled(df, X):
"""Add participant id column and remove special characters."""
X['participant_id'] = df.participant_id.astype(int)
not_null = df.created_account.notnull()
to_replace = ['?', '-', ' ', '(', ')', '&']
X.columns = X.columns.str.replace('?', 'unknown')
for symb in to_replace... | 6c3fe228d95c853adc891463fb61ca04e4162d92 | 643,977 |
def _unwrap_decorator(func):
"""Return (filename, lineno) for the func the given func wraps.
If the wrapped func cannot be identified then return None. Likewise
for the wrapped filename. "lineno" is None if it cannot be found
but the filename could.
"""
try:
func = func.__closure__[0]... | 7845bc2cba484e53b01485c0d7c0ab5ee8cde6c5 | 643,978 |
import re
def cfgString2Dict(cfg_raw):
"""
Converts a string with configuration parameters separated by a space
into a dictionary.
Parameters
----------
cfg_raw : str
Returns
-------
dict
"""
return {key: value for key, _, value, _ in re.findall(
r"(\w+\s?)(=\s?... | 184c27ef3baf2d0addbfca432dff4c4de13d3494 | 643,980 |
def heart_rate_average(hr_list):
"""Averages posted heart rates of a patient
Method curated by Braden Garrison
The accepted heart rate list of a specific patient is iterated
through to produce a total which is then divided by the list
length to produce the heart rate average.
Args:
hr... | 45c4d1fb1f89f451cea07e8afa6ee233465edd10 | 643,981 |
def _insert_token_to_repo_url(url, token):
"""Insert the token to the Git repo url, to make a component of the git
clone command. This method can only be called when repo_url is an https url.
Args:
url (str): Git repo url where the token should be inserted into.
token (str): Token to be ins... | 6cf18aded0cbbbe317b9c94cbcf232932e90d4ec | 643,982 |
def b58decode(string):
"""Takes a base58-encoded number and returns it in base10.
:param string: the number to base58_decode (as str).
:return: the number passed as first parameter, base10 encoded.
"""
alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
# Populating a dicti... | 709e147ec0200c26817fa1e433ad6f530c8b3bb9 | 643,983 |
def parse_inviscid_pressure(lines, line, i):
"""reads inviscid pressure (method=3)"""
ncomponents = int(line[0:2])
# 0 : save component force data; use new Unit 9
# 1 : save component force data; use old Unit 9
# 2 : dont save force data
ifsave = int(line[2:3])
unused_title = line[6:66].stri... | 7d84dbd27986e52edee9a8e2678d75cbfda13b5c | 643,984 |
def controller_delete(id):
"""
Thing Manager Data Handler for DELETE requests
"""
return 'delete' | 5b1fcc31089a47abfe46148e05ea1bd2a7a60b7d | 643,985 |
def indent(input_str, prefix):
"""
Given a multiline string, return it with every line prefixed by "prefix"
"""
return "\n".join([f"{prefix}{x}" for x in input_str.split("\n")]) | e05f4b133b396bfcb9aecd4549b03397ab04fb7d | 643,986 |
import re
from typing import Dict
def _parse_group(pr_txt: str, header_pattern: str,
entry_regex: re.Pattern) -> Dict[str, int]:
"""General function to parse and extract a listing from the press release.
Args:
pr_txt: The text of the press release.
header_pattern: A string rep... | b8c8c95636b331aac2963b1259d67eb55dd4e140 | 643,987 |
import uuid
def create_boundary(prefix, compact=False):
"""Creates a string that can be used as a multipart request boundary.
:param bool compact:
:param str prefix: String to use as the start of the boundary string
"""
if compact:
return prefix + str(uuid.uuid4())[:8]
else:
r... | b80acd4b79886c12d10a323a5b15b9898c7bc7b9 | 643,988 |
def check_lru(sc):
""" Check LRU replacement of sim_cache. """
sc.reset()
# Setup 5 addresses with different tags but in the same set
address = [sc.merge_address(i, 0, 0) for i in range(5)]
# Write different data to each address
for i in range(5):
sc.write(address[i], "1111", i + 1)
... | 85f1f729e396915ea0388fb96eb9c15d94d5ef6b | 643,989 |
def short_id(id64):
"""Given a 64-bit id, make a shorter 16-bit one."""
id16 = 0
for offset in range(0, 64, 16):
id16 ^= id64 >> offset
return id16 & 0xFFFF | d3e8ff6d838d5da4a14276c85d930bac0e502c30 | 643,990 |
import math
def is_prime(n: int) -> bool:
"""
Check wether a certain number is prime or not.
Parameters
----------
n: int
The number to check.
Returns
-------
bool
True if the number is prime, False if it isn't.
"""
if n <= 1:
return False
if n == ... | 6bb394bf24683e4895980ff75a4416fbdb642410 | 643,992 |
import re
def enclose(s):
"""Enclose the string in $...$ if needed"""
if not re.match(r'.*\$.+\$.*', s, re.MULTILINE | re.DOTALL):
s = u"$%s$" % s
return s | cead88fbf821337aa0d08145f5422446cc6b298d | 643,993 |
def dot_notation(dict_like, dot_spec):
"""Return the value corresponding to the dot_spec from a dict_like object
:param dict_like: dictionary, JSON, etc.
:param dot_spec: a dot notation (e.g. a1.b1.c1.d1 => a1["b1"]["c1"]["d1"])
:return: the value referenced by the dot_spec
"""
attrs = dot_spec.... | ea6c71a7f33dac3e7f1690212493ab7fca1c3962 | 643,994 |
def m_hook(self, node):
"""Alias .mm files to be compiled the same as .cpp files, gcc/clang will do the right thing."""
return self.create_compiled_task('cxx', node) | c5a4fb01c76729cbbb5da496f35ea467bede6b7c | 643,995 |
def varint_encode(num):
"""Convert number into varint bytes
:param num: number to encode
"""
buf = b''
while True:
towrite = num & 0x7f
num >>= 7
if num:
buf += bytes(((towrite | 0x80),))
else:
buf += bytes((towrite,))
break
r... | 9188ea7fc7812cacf3e2bb8b3501f42cdc79b074 | 643,997 |
def parse_pattern(pattern):
"""Convert a string of 1s and 0s into a pattern of Trues and Falses.
>>> parse_pattern('1010010')
[True, False, True, False, False, True, False]
"""
return map(lambda x: True if x == '1' else False, pattern) | 58490b1c62e95e25d7bb9b3990c6530ca40b8fd9 | 643,998 |
def _check_installed_pkg(module, package, repository_path):
"""
Check the package on AIX.
It verifies if the package is installed and informations
:param module: Ansible module parameters spec.
:param package: Package/fileset name.
:param repository_path: Repository package path.
:return: B... | 276157ca75ca7397395aa00837dc368d5f2ee0e0 | 643,999 |
def GetIndexFromInputId(input_spec, input_id):
"""Get the 0-based index of the input_id inside input_spec.
Args:
input_spec: Dictionary with the input specification, mapping from input name
to another dictionary with a 'time_limit' key.
input_id: Id whose index must be retrieved.
Returns:
0-... | a897912b19ed3e4c48a333470cedc4b37ce02af2 | 644,000 |
def totalSizeOf(s):
"""
@type s: C{str} or L{StringFragment}
@return An estimate of how much memory (in bytes) string C{s} consumes.
@rtype: C{int}
"""
return 30 + len(s) | be73c97d6df9db97866b78b3894cae0393ba95e0 | 644,001 |
import argparse
def parse_args():
"""Arguments to pass to this Script"""
parser = argparse.ArgumentParser(description="Parse arguments")
##file directories
parser.add_argument('--data_dir', type=str, help='directory that contains train, test and target labels csv files')
parser.add_argument('... | ee5b10fb43310f57d3742cb647acf37f1870d8f1 | 644,002 |
def listify_cleanup(value):
"""Clean up top level splicer_code
Convert newline delimited strings into a list of strings.
Remove trailing newline which will generate a blank line.
Or replace None with "" in a list.
Used with nested dictionaries used to mirror scopes.
CXX_definitions: |
... | 17778462a9af1e6117cf67cc464d5caa2ad4c027 | 644,003 |
def cross3D(v1, v2):
"""Calculates the vector cross product of two 3D vectors, v1 and v2"""
return (v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]) | 888db7be621be85643eb1b6aa5f29cdefd264f03 | 644,004 |
def CombineDicts(a, b):
"""Unions two dictionaries by combining values of keys shared between them.
"""
c = {}
for key in a:
if b.has_key(key):
c[key] = a[key] + b.pop(key)
else:
c[key] = a[key]
for key in b:
c[key] = b[key]
return c | 8b241e666cd14a02c81529072efa28dbbaf38db7 | 644,005 |
def codegen_reload_data():
"""
Parameters required reload codegen for the fn_pa_panorama package
"""
return {
"package": u"fn_pa_panorama",
"message_destinations": [u"palo_alto_panorama"],
"functions": [u"panorama_get_address_groups", u"panorama_get_users_in_a_group", u"panorama_... | a50408c071ff97125e3385cc09284d15aa3f0767 | 644,006 |
def cubrt(x):
"""Returns the cubed root of x"""
return round(x ** (1/3), 12) | 41e500d1ee6ccc61c4442ea618c17daebea76c4e | 644,007 |
import re
def _add_latex_syntax_around_scientfic_number_string(string):
"""Add curly braces around scientific numbers.
Otherwise, siuntix will raise an error.
"""
if "e" not in string:
out = string
else:
prefix, *num_parts, suffix = re.split(r"([+-.\d+])", string)
number ... | 83a3bf0c52118cf48b5aadd8852a08e09a5db923 | 644,008 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.