content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import time
def toc(tic):
"""Returns the time since 'tic' was called."""
return time.perf_counter() - tic | 976cdeb30a723a8667ae2e0d86a4270ad356d634 | 638,715 |
from typing import Optional
import math
def round_for_theta(
v: float,
theta: Optional[float]
) -> float:
"""
Round a value based on the precision of theta.
:param v: Value.
:param theta: Theta.
:return: Rounded value.
"""
if theta is None:
return v
else:
... | ef6d18df588df8a80be9dc6c9b7f9104e3109d69 | 11,514 |
def read_DDTpos(inhdr):
"""
Read reference wavelength and DDT-estimated position from DDTLREF and
DDT[X|Y]P keywords. Will raise KeyError if keywords are not available.
"""
try:
lddt = inhdr['DDTLREF'] # Ref. wavelength [A]
xddt = inhdr['DDTXP'] # Predicted position [spx]
... | 39cce130305440f14db8e5378ae4e66b8e124b20 | 32,979 |
def markdown_list(url: str, title: str) -> str:
"""Return the Markdown list syntax for YouTube video."""
return f'* [{title}]({url})' | d6da7ea5bcef4fd4f6f1b6fe48521e7cf71772c6 | 327,034 |
def traverse_maze(network, part_two=False):
"""Traverse the maze collecting letters and counting the steps taken."""
x = network[0].index('|')
y = 0
direction = 'D'
letters = []
steps = 0
while network[y][x] != ' ':
if direction == 'D':
y += 1
elif direction == 'U... | eceda7d741a37db63784a708effefdf0f2908f05 | 379,708 |
import re
def parse_jobs_list(cli_output):
"""
Parse Databricks CLI output of `databricks jobs list` to return
a list of job ids and their names.
"""
jobs = cli_output.decode('utf-8').replace('\r\n','\n').split('\n')
output = {}
for job in jobs:
matches = re.search('(\d+) +(.+)', j... | ca3970fca80e88bc7b9c376fdae0f8fed10ac9da | 407,061 |
def scapy_layers_dot11_Dot11_find_elt_by_id(self, id):
"""Iterate over elt and return the first with a specific ID"""
for elt in self.elts():
if elt.ID == id:
return elt
return None | a976e4a0487cc9d3e0cef0cf1a5730c710db95ba | 564,923 |
def reduce_id(id_):
"""Reduce the SsODNet ID to a string with fewer free parameters."""
return id_.replace("_(Asteroid)", "").replace("_", "").replace(" ", "").lower() | 8f6d236030bb6304af04808cdabc6a15c06aeb40 | 588,372 |
def reverse(s):
"""Returns the string s, reverse-videoed."""
return '\x16%s\x16' % s | c62fa89f9b50ee401482a2bcb1b4b2e56f792446 | 160,991 |
def Levenshtein_Distance(str1, str2):
"""
cal str1 and str2 edit distance.
Args:
str1: string A
str2: string B
Return:
value of edit distance
"""
matrix = [[ i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1)+1):
... | 89b8c6d761442bb514d798e650c87705e3126397 | 240,572 |
def get_menu_name(name):
"""Make any supplied string suitable/nice for menubar name.
:arg name: Name need to make nice for menubar.
:type name: str
:return: Nice menu name for menubar.
:rtype: str
"""
# get menu name and use it for menu identifier
menu_name = ""
for char in name:
... | 1e53113a99209e81b60e57846a27de1a7ec19959 | 187,457 |
import re
def validate_hair_color(hcl):
"""
Validate Height - a # followed by exactly six characters 0-9 or a-f.
"""
match = re.search("#[0-9a-f]{6}", hcl)
return bool(match) | 96a63139b907861ffd29cff27b02842ba2d43e9b | 492,178 |
def pivotCombinedInventories(combinedinventory_df):
"""Create a pivot table of combined emissions.
:param combinedinventory_df: pandas dataframe returned from a
'combineInventories..' function
:return: pandas pivot_table
"""
# Group the results by facility,flow,and compartment
combinedi... | 71d56bd546b5990c7b2658f0616ebaf8ed6f472f | 628,390 |
def permutation_from_block_permutations(permutations):
"""Reverse operation to :py:func:`permutation_to_block_permutations`
Compute the concatenation of permutations
``(1,2,0) [+] (0,2,1) --> (1,2,0,3,5,4)``
:param permutations: A list of permutation tuples
``[t = ... | 3b6508c103e39051ccfa909b54aa9ec506b35f86 | 64,666 |
def lol_product(head, values):
"""List of list of tuple keys, similar to `itertools.product`.
Parameters
----------
head : tuple
Prefix prepended to all results.
values : sequence
Mix of singletons and lists. Each list is substituted with every
possible value and introduces ... | bc48c9044ba30fd84347430cf42e4d31904a8d74 | 233,272 |
import random
def max_weight_paths(k, weight_paths_dict, paths_to_edges, overlap=True, norev=False, rgen=None):
"""
Returns k largest-weight paths. The function proceeds in order through descending weight values to select paths,
and if an entire weight class of paths is not to be included, applies a pred... | 50264effde7c0f7f97c6e5a4c6c34899ad5462db | 669,326 |
def countit(objs):
"""Return a dict with counts for each item in a list."""
out = {}
for el in objs:
out[el] = 1 + out.get(el, 0)
out = {k: v for k, v in out.items()}
return out | f9909092180ccd1bf12bc96a972701cfbd6ff3c7 | 504,418 |
def dataframeToPaths(df):
"""
returns list of paths for given dataframe
:param df: dataframe/segment of dataframe
:return: gcp urls/paths for this segment/dataframe
"""
return df['gcp_url'].tolist() | c10bb462c350039631f631953da5fca18b82c031 | 143,639 |
def factorial(
*,
number: int,
) -> int:
"""Recursive Factorial Function
Args:
number (int): number
Returns:
int: factorial of the number
"""
if number <= 1:
return 1
return number * factorial(number=number - 1) | 0ab7323ebd6bd9df7a72a3b26abeddc46e8a5a37 | 643,881 |
def type_of_user(datum, city):
"""
Takes as input a dictionary containing info about a single trip (datum) and
its origin city (city) and returns the type of system user that made the
trip.
Remember that Washington has different category names compared to Chicago
and NYC.
"""
user... | 63e21b544dab127043f46bab7956b056a3aa1058 | 407,445 |
import pathlib
def get_message(message):
"""
get message from file or string format and return it.
Args:
message: str or Path.file path to the cleartext or cleartext itself.
Returns:
message: str.cleartext
"""
if not isinstance(message, str) and not isins... | c00dfa1bda60445c605eddaa8a8e7df1a3802be0 | 98,357 |
def GitRemoteUrlFilter(url, patch):
"""Used with FilterFn to isolate a patch based on the url of its remote."""
return patch.git_remote_url == url | eb6e509c1966e5b9b9e6abf00a164b3a3f9cb1f2 | 74,302 |
import torch
def region_mask(n, min_mask_size, max_mask_size, maskable_length, device=None):
"""Create a vector of ``n`` random region masks.
Masks are returned in a vector with shape `(n, maskable_length)`.
The mask vectors are boolean vectors of ``maskable_length`` with a
continuous region of 1s b... | ceedf548f1b9f25f579bff51d69cfb593ab2b7df | 98,420 |
def mass_transfer_coefficient_OILTRANS(wind_speed, length, schmdt_nmbr):
"""
Return the mass transfert coefficien [m/s], formula derived
from (Mackay and Matsugu, 1973)
source : (Berry et al., 2012)
Parameters
----------
wind_speed : Wind speed 10 meters above the surface [m/s]
length :... | 799a491fce669262c939a18da07dbb2a52750c43 | 298,582 |
async def ping():
"""A test ping endpoint."""
return {"ping": "I'm alive!"} | 3e12e2ec3b4d7fd26b64ca9e2269a24c5ab995e6 | 103,307 |
def sanitize_price(price_str):
"""
Normalise a price string and convert to float value.
:param price_str: Price string to normalise.
:return: Float price value.
"""
if price_str is None:
return None
price_str = price_str.strip('$ \t\n\r')
price_str = price_str.replace(',', '')
... | 84af7c25c19bcbef690cc19554f01e6e284446f2 | 26,457 |
def indent(s, indentation=" "):
"""
helper function to indent text
@param s the text (a string)
@param indentation the desired indentation
@return indented text
"""
return [indentation + _ for _ in s] | 59ec5d6751f906b84c2d46a51777f0831116082a | 35,074 |
def calculate_mean(some_list):
"""
Function to calculate the mean of a dataset.
Takes the list as an input and outputs the mean.
"""
return (1.0 * sum(some_list) / len(some_list)) | d0374fc5321f6caa05f546e274490e906bf60106 | 30,681 |
def enf_list(item):
"""
When a list is expected, this function can be used to ensure
non-list data types are placed inside of a single entry list.
:param item: any datatype
:return list: a list type
"""
if not isinstance(item,list) and item:
return [item]
else:
ret... | b27bde2da0855ffa02837dda2f8dfb85f43db30a | 150,151 |
def b_ord(byte):
"""Return the Unicode code point for a byte or iteration product \
of a byte string alike object (e.g. bytearray).
:param byte: The single byte or iteration product of a byte string to \
convert
:type byte: bytes or str or int
:return: Unicode code point
:rtype: int"""
return b... | ba79752c7ee7cadde1e7a7323f88fcb46f2d8511 | 463,835 |
def get(isamAppliance, instance_id, id, check_mode=False, force=False):
"""
Retrieving the contents of a file in the administration pages root
"""
return isamAppliance.invoke_get("Retrieving the contents of a file in the administration pages root",
"/wga/reverseproxy/... | 7ced8fa881e2fe89da5a135f43f883d7e20f8f62 | 286,956 |
from typing import Any
import yaml
def parse_arg_value(val: str) -> Any:
"""Parse a string value into its Python representation."""
return yaml.safe_load(val) | dfa3a916f78360c7b8209abb573c5cdc17ef2d9d | 169,617 |
def _is_sequence(obj):
"""Check if the object is a sequence (list, tuple etc.).
Parameters
-----------
object
an object to be checked
Returns
--------
bool
True if the object is iterable but is not a string, False otherwise
"""
return hasattr(obj, '__iter__') and no... | 8733ec482df1b09e6051537524f9c69d5a4295da | 291,597 |
def get_attribute_from_tag(tag, attribute):
"""Returns a xml attribute from a given tag"""
element = None
try:
element = tag.attrib[attribute]
except KeyError:
pass
# print("Error: attribute {} was not defined in this tag.".format(e))
return element | 914e04f2e6441ffb5f42d71de49bd99fe5e3092b | 27,207 |
import logging
def getLogger(module_name=None):
"""
Returns a logger appropriate for use in the ocp_cd_tools
module. Modules should request a logger using their __name__
"""
logger_name = 'ocp_cd_tools'
if module_name:
logger_name = '{}.{}'.format(logger_name, module_name)
return... | ff1f9e859332c7f0f7d9f734d63eaefdd766b491 | 94,704 |
import math
def deg2rad(ang_deg):
"""
Converts degrees to radians
"""
return math.pi*ang_deg/180.0 | 190dbd8bfccba8ffe206ef5bb089145026bb9f07 | 103,596 |
def Dict(**entries):
"""Create a dct out of the argument=value arguments.
Ex: Dict(a=1, b=2, c=3) ==> {'a':1, 'b':2, 'c':3}"""
return entries | a7575cffcd6345b9402ca8ae21213d72f5e83775 | 237,933 |
def get_job_status(job):
"""Returns the status of the job(celery.result.ResultSet) as a percentage
of completed tasks
"""
total = len(job.results)
return (float(job.completed_count()) / total) * 100 | 5cc2bfd7cce4cd5aa3344bf52a99b6a8f48c8d6a | 214,621 |
import math
def _gain2db(gain):
"""
Convert linear gain in range [0.0, 1.0] to 100ths of dB.
Power gain = P1/P2
dB = 10 log(P1/P2)
dB * 100 = 1000 * log(power gain)
"""
if gain <= 0:
return -10000
return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0)) | 1bd602e0db397b3730c4f2b3439aeb351e6bd854 | 9,041 |
def group_list(actions, agent_states, env_lens):
"""
Unflat the list of items by lens
:param items: list of items
:param lens: list of integers
:return: list of list of items grouped by lengths
"""
grouped_actions = []
grouped_agent_states = []
cur_ofs = 0
for g_len in env_lens:
... | bc6199f5cc0efcdfde7e9c9085c1ccc95c535e30 | 662,003 |
import json
import requests
def check_aws(admin_api_key, env, cc_account_id):
"""
Checks if an account is an AWS Account with get_account API call
"""
api_url = env + "/api/account.json/get_account"
get_account_info = json.dumps({"account_id": cc_account_id})
r7 = requests.post(api_url, hea... | fc69b72870dadb54b796e4206319f2181d252686 | 606,726 |
def is_input_op(node):
"""Return true when the node is the input of the graph."""
return node.WhichOneof("op_type") == "input_conf" | 294f5f1b785bb4ac26be8f7d9cacde2a26e73ce6 | 373,155 |
def is_fq(name):
"""Return True if the supplied 'name' is fully-qualified, False otherwise.
Usage examples:
>>> is_fq('master')
False
>>> is_fq('refs/heads/master')
True
:name: string name of the ref to test
:returns: bool
"""
return name.startswith('refs/') | e603920b192caa4e72d7f265dac72761cf2d6611 | 226,635 |
import time
from datetime import datetime
def format_date(timestamp, precision=0):
"""
Construct an ISO 8601 time from a timestamp.
There are several possible sources for *timestamp*.
- time.time() returns a floating point number of seconds since the
UNIX epoch of Jan 1, 1970 UTC.
- time.... | 305e001bef5aa91d2524e152552073413d974577 | 75,768 |
from functools import reduce
def rank(B, S):
"""Return the rank of the subset S in base set B."""
return reduce(lambda a,b: a | b, [1 << (i if type(B) == int else B[1][i]) for i in S], 0) | fa81b882f27bb3bd0505c00b05dbe16653ff1927 | 150,961 |
def typed_property(name, expected_type):
"""Common function used to creating arguments with forced type
:param name: name of attribute
:param expected_type: expected type of attribute value
:return: property attribute
"""
private_name = '_' + name
@property
def prop(self):
retu... | d1cc4dd8ea01d2d32efeffe28dea3236b8ab30c2 | 33,156 |
def sign(l):
"""
:param l: ordered list of indices
:type l: list (or similar)
:return: sign of l
Compute the sign of an ordered list (-1 for each flip needed to get to ascending order)
"""
res = 1
for i in range(len(l)):
for j in range(i + 1, len(l)):
if l[i] > l[j]:... | f11a8ed5e8f6b01fb443c69aedb50e91e22dd4c5 | 458,802 |
import torch
def attention_bias(inputs, mode, inf=-1e20):
""" A bias tensor used in attention mechanism
:param inputs: A tensor
:param mode: either "causal" or "masking"
:param inf: A float, denoting an inf value
:returns: A tensor with shape [batch, heads, queries, memories]
"""
if mode... | c3e69d8c86b36d38ddc7fcad76013781f191223a | 266,707 |
def iou(polygon_1,polygon_2):
"""
Calculate intercept over union for shapely polygons.
Args:
polygon_1
polygon_2
Returns:
intercept over union
"""
area_intersection = polygon_1.intersection(polygon_2).area
area_polygon_1_poly... | 14d9bac353466abe1556393e2d33862e40e99225 | 534,474 |
def get_number(key, row):
"""Reads a number from a row (assume all as float)."""
if key in row and row[key]:
return float(row[key])
else:
return None | b0519ef90cdce3da49588c14887dc74113d542a2 | 256,240 |
def get_test_object_names(obj):
""" Returns all attribute names that starts with "test_" """
ret = []
for o in dir(obj):
if o.startswith("test_"):
ret.append(o)
return ret | ca22389234fdf98c1ec0405fa4871926f0c7165c | 547,944 |
def get_cpu_mask(cores):
"""Return a string with the hex for the cpu mask for the specified core numbers."""
mask = 0
for i in cores:
mask |= 1 << i
return '0x{0:x}'.format(mask) | 8034506756c5db0706070cefd6f231586cc816e2 | 535,596 |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
int value of interval in milliseconds
None if interval pre... | ab1745a846f7536e4e2c0c91dc482d754fa3d7f3 | 282,594 |
def get_id(corpus, key):
"""
Get the corpus ID of a word
(handle utf-8 encoding errors, following change
https://github.com/vered1986/LexNET/pull/2 from @gossebouma)
:param corpus: the corpus' resource object
:param key: the word
:return: the ID of the word or -1 if not found
"""
id ... | 84cfd2a12952ef1be984001304ad5c7c3ce161f2 | 549,440 |
from typing import Any
from typing import Literal
def _return_true(*_: Any) -> Literal[True]:
"""Always return true, discarding any arguments"""
return True | a72e74ecc942a36d472bae7e957a7a6fb0879403 | 48,682 |
def caption_fmt(caption):
""" Format a caption """
if caption:
return "\n== {} ==\n".format(caption)
return "" | e6e94efa5f16f9b0590e912e68ee1e3acfb4d54a | 41,712 |
def task_exists(twarrior, task_name: str) -> bool:
"""
Check if task exists before inserting it
in Task Warrior.
"""
tasks = twarrior.load_tasks()
for key in tasks.keys():
for task in tasks[key]:
if task['description'] == task_name:
return True
return Fals... | 1a5dbd790b11492c7417b7611c7f62af544a7862 | 36,471 |
def result_to_metrics(result):
"""Specific for the result dictionary of simpletransformers binary classification,
which is a dictionary including keys: `tp`, `fp`, `tn`, and `fn`.
TP = True Positive
FP = False Positive
TN = True Negative
FN = False Negative
accuracy = (TP + TN) / (TP + FP ... | 03fc76c88d3468d5ff518ae90ecba7db61ff947d | 458,175 |
import click
def detect_config_version(config):
"""Return version of an slo-generator config based on the format.
Args:
config (dict): slo-generator configuration.
Returns:
str: SLO config version.
"""
if not isinstance(config, dict):
click.secho(
'Config does... | 26cb4d7ae7eba981e456dc8f9201df719f720896 | 16,407 |
import yaml
def read_config(file_name="config.yaml"):
"""Read configurations.
Args:
file_name (str): file name
Returns:
configs (dict): dictionary of configurations
"""
with open(file_name, 'r') as f:
config = yaml.safe_load(f)
return config | 51faf47b4c28d1cbf80631d743d9087430efb148 | 14,643 |
import json
def _GenerateCopyCommand(from_path, to_path, comment=None):
"""Returns a Dockerfile entry that copies a file from host to container.
Args:
from_path: (str) Path of the source in host.
to_path: (str) Path to the destination in the container.
comment: (str) A comment explaining the copy ope... | c1c5fb832cbde60f4ebed675b231a15166159673 | 639,044 |
def dice_name_from_cost(cost: str) -> str:
"""Given a string like `magic:face` returns just `magic`"""
return cost.split(":")[0] | e72a9ed41b257c17e38d7b46f1ca19856d8bdb43 | 531,429 |
import inspect
def monkeypatch_methods(monkeypatch):
"""Monkeypatch all methods from `cls` onto `target`.
This utility lets you easily mock multiple methods in an existing class.
In case of classmethods the binding will not be changed, i.e. `cls` will
keep pointing to the source class and not the tar... | d3139c55831e03bc7a66d93a8fa81b1d3abcca4b | 425,724 |
def is_fittable(data_form, layers_form):
"""
Return True if a fit problem (comprised of all its forms)
is fittable or not. To be fittable, refl1d requires at least
one free parameter.
"""
has_free = data_form.has_free_parameter()
for layer in layers_form:
has_free = has_f... | 51b5375f7f56087f780079d44326b8c987048165 | 382,781 |
def specframe2sample(frame, hop_size=3072, win_len=4096):
"""
Takes frame index (int) and returns the corresponding central time (sec)
"""
return frame * hop_size + win_len / 2 | cffe9aca5d290368145aba2d5cc29b0e84f9696a | 444,546 |
def meta_command(name, bases, attrs):
"""
Look for attrs with a truthy attribute __command__ and add them to an
attribute __commands__ on the type that maps names to decorated methods.
The decorated methods' doc strings also get mapped in __docs__.
Also adds a method run(command_name, *args, **kwar... | 39ca4b4b7ffd9a09ba1e0715976d5a8c4c4b2b58 | 398,560 |
def gen_params(guess):
"""Return dict of parameters with guess string."""
return {'file': 'foo', 'signature': guess} | be82c04d61b1bf5115d65acc5fe08c23a0136619 | 332,496 |
from typing import Tuple
def is_parent(parent_key: Tuple[str], key: Tuple[str]) -> bool:
"""Determines if keys have parent:child relationship.
Example using dot notation:
is_parent(a.b, a.b.c) == True
is_parent(a.b, a.b.c.d) == True
is_parent(a.b, a.x.y) == False
"""
return ... | 10f13f05fac3495ace654528aa0bb249d235d6d4 | 134,405 |
def asint(value):
"""Coerce to integer."""
if value is None:
return value
return int(value) | d6372f0e545b6e4923c8fecf74a0817fb56a5699 | 548,416 |
def formatFieldEqVal(fieldNames, sepStr = " and "):
"""Format a (field1=value1) and (field2=value2)... clause
in the form used with a data dictionary.
This is intended to help generate select commands.
Inputs:
- fieldNames: a list or other sequence of field names
- sepStr: the string to separat... | abb1ee3f9b4d2fc145cc4b34094226d367821f13 | 439,311 |
def f2hex(flo):
"""Convert floating point value `flo` (`0 <= f <=1`) to a zero-padded hex string."""
if not 0 <= flo <= 1:
raise ValueError("value must be between 0 and 1 (inclusive)", flo)
intval = round(255 * flo)
return f"{intval:X}".zfill(2) | 96d5f7d1635b348c2224dcd11e6490770765b8bc | 469,535 |
def do_steps_help(cls_list):
"""Print out the help for the given steps classes."""
for cls in cls_list:
print(cls.help())
return 0 | 19ce1585f915183fcb38c2ea268a6f30780830bb | 689,001 |
def normalise_spaces(text: str) -> str:
"""Normalise spaces of arbitrary length to single spaces"""
return " ".join([s.strip() for s in text.split(" ")]) | 28c3ee96ddf57173335dea2271bf922ccf8174cb | 155,789 |
def _pop_all(kind, universe, iterable, validate=True):
"""
Removes all elements of 'iterable' from 'universe' and returns them.
If 'validate' is true, then a ValueError is raised if a element
would be removed multiple times, or if an element of 'iterable' does
not appear in 'universe' at all.
"... | 19843d6855270c35de2ff9c6e8a91e4f49c1e82d | 191,778 |
def get_model_name(obj):
"""
Returns the name of the model
"""
return obj._meta.model_name | 2a74e19aa618e759c06459c2ca8b577dffeef646 | 150,794 |
def get_destination_filename(path, prefix="t", overwrite=False):
"""
Get the output file name.
:param pathlib.Path path: Destination path
:param str prefix: prefix of filename.
:param bool overwrite: if True then
:return: file name for output
:rtype: str
"""
if overwrite:
n... | af57d27b04fa1040fa0584ca7e6250101a32d77f | 17,687 |
def num_in_row(board, row, num):
"""True if num is already in the row, False otherwise"""
return num in board[row] | ca9ab9de4514740e25e0c55f3613d03b2844cdb8 | 708,225 |
import textwrap
import itertools
def rewrap(text, width=None):
"""
Rewrap text for output to the console.
Removes common indentation and rewraps paragraphs according to the console
width.
Line feeds between paragraphs preserved.
Formatting of paragraphs that starts with additional indentatio... | a327e1828941422daa6f1f94cbbee14bb7433559 | 102,305 |
import re
def extract_sentence_id(tag):
"""
Extract the sentence ID of current sentence.
Args:
tag (str): Sentence tag
Returns:
str: sentence ID
"""
if "<s" not in tag:
return ""
pattern = re.compile('id="[a-z0-9]+?"(?=\s)')
res = re.findall(pattern, tag)
if len(res) == 0:
return None
return res[0... | 99a24d332e21b5861c74b00fdcb334892eda4b7c | 32,550 |
import math
def euclidean_distance(p1, p2):
"""
Precondition: p1 and p2 are same length
:param p1: point 1 tuple coordinate
:param p2: point 2 tuple coordinate
:return: euclidean distance between two points p1 and p2
"""
distance = 0
for dim in range(len(p1)):
distance += (p1[d... | e284e97f4cd92de55ea15b37f819301df007580a | 191,214 |
def get_exception_kwargs(e):
""" Extracts extra info (attributes) from an exception object. """
kwargs = {}
for attr, value in vars(e).items():
if not attr.startswith('_') and attr not in ('args', 'message'):
kwargs[attr] = value
return kwargs | 45b5a78c766c02ee49a3af4ed793a61025e9424a | 46,396 |
def _str_to_int_or_float(val):
"""helper function that tries to cast a str to int and if that fails then tries casting to float"""
try:
val = int(val)
except ValueError:
val = float(val)
return val | 7139ef92b0cc9f0db14e7ca0d0af24b272d6e50d | 504,878 |
def clean_styles(widget, styles) -> dict:
"""
Ensures safety while passing styles to tkinter objects. Normally tkinter objects raise errors for declaring
styles that are not allowed for a given widget. This function takes in the styles dictionary and removes
invalid styles for the particular widget retu... | efe325a0cc202ac5deff38547822156b8b40fae0 | 581,430 |
def catch(func, *args, **kwargs):
"""
Call the supplied function with the supplied arguments,
catching and returning any exception that it throws.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass int... | 23aa157713090c26d69f98599c9ce0b41c947ccc | 411,333 |
def aln_abuts_unknown_bases(tx, fasta):
"""
Do any exons in this alignment immediately touch Ns?
:param tx: a GenePredTranscript object
:param fasta: pyfasta Fasta object for genome
:return: boolean
"""
chrom = tx.chromosome
for exon in tx.exon_intervals:
if exon.start == 0: # ... | ceb31739be0091b3b52f763c0c0d6d15b1aebd19 | 22,188 |
def tartaglia(n):
""" Funzione per generare un triangolo di tartaglia.
Parametri
---------
n: int
Altezza del triangolo da generare
Output
------
triangolo: list of lists [[],[],[],...]
Lista di liste, corrispondenti alle righe del triangolo di tartaglia.
Esempio
-... | 1dbb18879e565feef3405e533da492936d4a4b20 | 630,373 |
def auto_str(cls):
"""
Add implementation of __str__ and __repr__ functions to a class
"""
def __str__(self):
return type(self).__name__ + '{' + ','.join(f'{k}={str(v)}' for k, v, in vars(self).items()) + '}'
def __repr__(self):
return type(self).__qualname__ + '{' + ','.join(f'{k}... | 7b03f04b7091fa32fb813fa6c04aac44815e2ff3 | 304,617 |
def _columns(cursor, table):
"""Return the columns of a table as a list."""
cursor.execute('''
SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = %s
''', (table, ))
return [column['column_name'] for column in cursor.fetchall()] | 03544abe0980dfa00b366b38687f4795707b9385 | 615,876 |
from typing import Sequence
from typing import Optional
def sequence_find(hay: Sequence, needle: Sequence) -> Optional[int]:
"""
Return the index for starting index of a sub-sequence within a sequence.
The function is intended to work similarly to the built-in `.find()` method for
Python strings, but... | 2601e73c4230292f558db4ad54e346a503f7ee43 | 566,347 |
def is_boolean(op):
"""
Tests whether an operation requires conversion to boolean.
"""
return op in ['or', 'and', '!'] | 5989c5db1befe76e61baa22a313b2d2e8f201553 | 659,748 |
def table(custom_headings, col_headings_formatted, rows, spec):
"""
Create a LaTeX table
Parameters
----------
custom_headings : None, dict
optional dictionary of custom table headings
col_headings_formatted : list
formatted column headings
rows : list of lists of cell-str... | 0ca28fce26fc7476aa5b88a621c5476ae8d381ce | 1,213 |
import pickle
def load_ddata(path, num):
"""
Load data for defender.
Input:
- path: path to pickled file
- num: number of (source,target) pairs
Return: graph, target nodes, community assignment, source nodes
"""
with open(path, "rb") as f:
data = pickle.load(f)
gra... | bbda82c773888b3534907f93f6312b55e7c34f4b | 153,180 |
from datetime import datetime
def better_time(text):
"""Convert the time format to a better format"""
dt = datetime.strptime(text, '%a %b %d %H:%M:%S %z %Y')
return dt.strftime('%c') | 5b5f7efa94e07d32956cfbeee6536b8a55c4b1cd | 431,525 |
def _convert_ketone_unit(raw_value):
"""Convert raw ketone value as read in the device to its value in mmol/L."""
return int((raw_value + 1) / 2.) / 10. | 804d34ecc9d901f3d958ebee34282885248c3499 | 697,361 |
import torch
from typing import Tuple
def sigmoid_soft_top_k(
logits: torch.Tensor,
k: int,
tau: float,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Calculate soft top k mask using a sigmoid function.
Args:
logits: Parameters used for weighting.
k: Number of elements that should be ... | e46726760d2c496e8eb34c34282a3bf9dd91f6d7 | 197,022 |
def _parse_restriction_split(source_object, restriction_split, search_low_dbnum,
search_high_dbnum):
"""
Parses a split restriction string and sets some needed variables.
Returns a tuple in the form of: (low dbnum, high dbnum)
"""
r... | bca959a7ab8a37f4c261e25fabfbd76e956f5cf6 | 352,522 |
def open_file(file_path, read_mode="r"):
"""
Opens a file from the OS and reads it to cast
it to string.
Args:
file_path (str): OS file path of the archive;
read_mode (str): read mode.
Returns:
(str): the file contents as a string.
"""
with open(file_path, read_mode... | 333297ed76b663872e6588dd5d495f27326d493d | 449,912 |
def generate_bps(perturbator, t):
"""Generate a motion perturbation field by using the method described in
:cite:`BPS2006`.
Parameters
----------
perturbator : dict
A dictionary returned by initialize_motion_perturbations_bps.
t : float
Lead time for the perturbation field (minutes)... | 481ac1f8c48d06ef7b1e05eca7fa4b89e6c65238 | 320,553 |
from typing import Any
def equals(check_value: Any, item: Any) -> bool:
"""Check if two values are equal.
:param check_value: Value to check.
:type check_value: Any
:param item: Item to check against.
:type item: Any
:return: Bool of comparison.
:rtype: bool
"""
return check_value... | 960fa68702f0ead68d6c64d55c863546db06e92a | 315,668 |
def convert_adsorption_energy_units(AE):
"""Converts the adsorption energy into units of KJ/mol
Parameters
----------
AE : :py:attr:`array_like`
array of adsorption energies
Returns
-------
:py:attr:`array_like`
array of adsorption energies in units of KJ/mol
"""
re... | f447f6b1e5edae12e293a5c06983ee625cc67296 | 407,580 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.