content stringlengths 42 6.51k |
|---|
def curv(c1,c2,x1,x2,x3,de):
"""
Evaluates empirical curve fits used in the computation of the Vmd, sigma_T-, and sigma_T+
for estimating time variability effects as a function of the climatic region, as described
in equations (5.5) through (5.7) of of "The ITS Irregular Terrain Model, version 1.2.2:
... |
def image_suffix(func,options):
"""
Returns the suffix for this image operations and options
Parameter func: the image operation
Precondition: func is a string
Parameter options: the image options
Precondition: options is a dictionary
"""
suffix = func
if len(options) > 0:... |
def is_minority_classes_in_vector(predicted, minority_classes):
"""
Small help function that checks if a vector contains minority classes (only there to make the code more self-explaining).
"""
for m in minority_classes:
if m in predicted:
return True
return False |
def smartbytes(num):
""" Courtesy of: https://stackoverflow.com/a/39988702/1039510
this function will convert bytes to MiB.... GiB... etc
"""
for x in ['bytes', 'KiB', 'MiB', 'GiB', 'TiB']:
if num < 1024.0:
return f"{num:3.1f} {x}"
num /= 1024.0 |
def isnum(arg):
"""
@purpose: To check if the item is a number
@complexity:
Best & Worst Case: O(1)
@parameter arg: The integer to be tested for integerness
@precondition: None
@postcondition: True/False
"""
try:
int(arg)
return True
excep... |
def format_time(time):
""" It formats a datetime to print it
Args:
time: datetime
Returns:
a formatted string representing time
"""
m, s = divmod(time, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return ('{:02d}d {:02d}h {:02d}m {:02d}s').format(int(d), int(h), int(m), int(s)) |
def itk_5km_to_1km ( i_tk_5km ) :
"""
return the 1km grid index along track of a 5km pixel
"""
return 2 + 5 * i_tk_5km |
def concat(arr, sep=",\n", border=None):
"""
Concatenate items in an array using seperator `sep`.
"""
if border is None:
return sep.join(str(x) for x in arr)
return border.format(sep.join(str(x) for x in arr)) |
def extractFileName(path: str):
""" Extracts the file name of a file path """
from os.path import basename, splitext
return splitext(basename(path))[0] |
def str_to_float(in_val):
"""Convert human-readable exponential form to float.
:param in_val: (str) input string of the following formats:
'float_number' --> float_number
'float_number + white_space + exp_prefix + unit_string'
--> float_number * 10**ex... |
def to_bgr(color):
"""
Convert to `colRGB`.
This is a `wxPython` type which is basically `BGR`. We don't want to work with
`BGR`, so being able to simply convert `RGB` is preferable.
"""
return ((color & 0xFF0000) >> 16) | (color & 0xFF00) | ((color & 0xFF) << 16) |
def is_unique_1(given_string):
"""
Assumes that lowercase and uppercase letters are DIFFERENT.
E.g. Returns True for "AaBbCc"
"""
length_of_string = len(given_string)
converted_set = set(given_string)
length_of_set = len(converted_set)
if length_of_string == length_of_set:
print... |
def get_first_word(content, delimiter=' '):
"""
Returns the first word from a string.
Example::
>>> get_first_word('KEYWORD rest of message')
'KEYWORD'
:type content: str or None
:param content:
Content from which the first word will be retrieved. If the
content is Non... |
def _FixUnits(metric_name, units, values):
"""Fix units and metric name with values if required.
Args:
metric_name: origin metric name
units: raw trimmed units
values: origin values
Returns:
(metric_name, units, values) triple with fixed content
"""
if units == 'bps':
return metric_name,... |
def pod_index(room):
"""
Return index of first pod in room.
"""
for i, pod in enumerate(room):
if pod:
return i
return len(room) |
def read_paragraph_element(element):
"""Returns the text in the given ParagraphElement.
Args:
element: a ParagraphElement from a Google Doc.
"""
text_run = element.get("textRun")
if not text_run:
return ""
return text_run.get("content") |
def _set_index(x, index):
""" set the index attribute of something it is possible
if index is None, or x doesn't have an index attribute it won't do anything
"""
if index is None:
return x
if hasattr(x, "index"):
x.index = index
return x |
def are_points_adjacent(p0, p1, poswiggle):
"""Return True if two points are adjacent to each other"""
return abs(p0 - p1) <= abs(poswiggle) |
def is_upsidedown_wrong(name):
"""Tell if the string would get a different meaning if written upside down"""
chars = set(name)
mistakable = set("69NZMWpbqd")
rotatable = set("80oOxXIl").union(mistakable)
return chars.issubset(rotatable) and not chars.isdisjoint(mistakable) |
def hamming_distance(bytes1: bytes, bytes2: bytes) -> int:
""" Compute the Hamming distance between two bytes.
The Hamming distance is the number of differing bits between the two
bytes.
>>> hamming_distance(b"this is a test", b"wokka wokka!!!")
37
"""
return sum([bin(c1 ^ c2).count('... |
def citation_metrics(publications):
"""
Return the h_index and total number of citations calculated from a list of
publications.
"""
cite_counts = sorted([v['citations'] for v in publications], reverse=True)
for j, k in enumerate(cite_counts):
if j + 1 > k:
return j, sum(cite... |
def normalize_text(in_str, style):
"""Format a string to match the style pattern expected"""
decomposed_str = in_str.lower().replace("-", " ").replace("_", " ").split()
# check if the trailing S needs to be stripped
if style[-1] not in ["s", "S"]:
if decomposed_str[-1][-1] == "s" and not decompo... |
def digattr(obj, attr, default=None):
"""Perform template-style dotted lookup
Function is taken from https://github.com/funkybob/django-nap,
(c) Curtis Maloney. Thanks @FunkyBob for the hint to this solution.
"""
steps = attr.split('.')
for step in steps:
try: # dict lookup
... |
def guess(m, x):
"""
Determines accuracy of individual guess "m" relative to target "s".
:type m: int
:type x: int
:rtype: int
"""
if m == x:
return 0
elif m > x:
return -1
else:
return 1 |
def start_idx(n):
"""
:param n: name item, e.g.,
:return: the starting position of the name
e.g., start_idx([[13, 16], 1]) --> 13
"""
return n[0][0] |
def get_scale(value):
"""Get the scale for a numeric value stored as a string.
The scale is used for store libio attributes, dunno why.
"""
scales = {
"k": 1000,
"m": 1000000}
return scales.get(value[-1].lower()) |
def attrs_to_uri(user, passwd, host, port, db):
"""Receives db parameters and converts them into a sqlalchemy resource URI.
Returns a string preformatted for sqlalchemy.
"""
if any(v == '' for v in list(locals().values())):
raise ValueError('All arguments must be present.')
return "postgre... |
def force_slashend(path):
"""
Return ``path`` suffixed with ``/`` (path is unchanged if it is already
suffixed with ``/``).
"""
if not path.endswith('/'):
path = path + '/'
return path |
def array_pair_sum_v2(nums: list) -> int:
"""Use even indexes and Pythonic way"""
return sum(sorted(nums)[::2]) |
def to_dict(obj_list):
"""
Utility method accepts a passed list of objects and returns a list
of dictionaries.
"""
# Convert list of objects to list of dictionaries
new_list = []
for obj in obj_list:
new_list.append(obj.__dict__)
return new_list |
def get_value(str_val):
"""convert a string into float or int, if possible."""
if not str_val:
return ""
if str_val is None:
return ""
try:
val = float(str_val)
if "." not in str_val:
val = int(val)
except ValueError:
val = str_val
return val |
def free_bacon(opponent_score):
"""Return the points scored from rolling 0 dice (Free Bacon)."""
# BEGIN PROBLEM 2
# score <10, first of two digits is 0
# should call roll_dice
# player who chooses to roll 0 dice score = 1 + max (x,y) digit of oppontent's total score (assume opponent_score < 100)
... |
def to_ini(settings = {}):
"""
Custom Ansible filter to print out a YAML dictionary in the INI file format.
Similar to the built-in to_yaml/to_json filters.
"""
s = ''
# loop through each section
for section in settings:
# print the section header
s += '[%s]\n' % section
... |
def height(root):
"""Uses recursion to compute the height of a binary search tree; height is
defined as the number of edges - not nodes - between the root and the
deepest node. The height of an empty tree is defined as -1. When we
return a value, we add +1 to it for the current node."""
if root is... |
def genus_species_name(genus, species):
"""Return name, genus with species if present.
Copes with species being None (or empty string).
"""
# This is a simple function, centralising it for consistency
assert genus and genus == genus.strip(), repr(genus)
if species:
assert species == spe... |
def last_valid_event(subj):
""" Some of these subjects can't load eeg from event X and on.
I'm not really sure what the deal is, but this tells you what
event is the last valid event for loading eeg for that subject.
"""
subj_event_pairs = (('R1154D', 780), ('R1167M', 260), ('R1180C', 522),... |
def mkcidr(obj):
"""
Return cidr-formatted string.
:param obj:
Dict of an object
"""
return '%s/%s' % (obj['network_address'], obj['prefix_length']) |
def extract_parent_dir_name(value: str):
"""figures out what the clone directory will be called"""
# "git@github.com:esmf-org/esmf-test-summary.git"
return value.split("/")[-1].split(".")[0] |
def remove_duplicates(datasets):
"""
Removes duplicates in an list of lists, will return a ragged list.
Not ideal for applications where duplicates can come from different sources and are meaningful.
"""
for i in range(len(datasets)):
datasets[i] = list(set(datasets[i]))
return datasets |
def reducer(item):
"""Define reducer function.
Function to reduce partitioned version of intermediate data
to final output. Takes as argument a key as produced by
mapper and a sequence of the values associated with that
key.
Args:
item(tuple): word-values data structure
Returns:
... |
def levenshtein(s1, s2):
"""
Calculate the Levenshtein distance between two elements
:param s1: first element for the comparison
:param s2: second element for the comparison
:type s1: list
:type s2: list
:return: computed distance of the two elements
:rtype: int
:example:
levenshtein.levenshtein([... |
def get_zcl_attribute_size(code):
"""
Determine the number of bytes a given ZCL attribute takes up.
Args:
code (int): The attribute size code included in the packet.
Returns:
int: size of the attribute data in bytes, or -1 for error/no size.
"""
opts = (0x00, 0,
0x... |
def msg(test_id, test_description):
"""convenience function to print out test id and desc"""
return '{}: {}'.format(test_id, test_description) |
def is_overlapping(segment_time, previous_segments):
"""
Checks if the time of a segment overlaps with the times of existing segments.
Arguments:
segment_time -- a tuple of (segment_start, segment_end) for the new segment
previous_segments -- a list of tuples of (segment_start, segment_end) for the... |
def clean_hotel_category_stars(string):
"""
"""
if string is not None:
r = string.replace("b-sprite stars ratings_stars_","")
r = r.replace("star_track","")
r = r.strip()
else:
r = 0
return r |
def get_role_arn(user_arn, role, account_id=None):
"""
Creates a role ARN string based on a role name and, optionally, an
account ID.
If role is None or empty, '' will be returned. This value will indicate to
the mfa method that no role should be assumed.
Arguments:
user_arn: Arn retur... |
def getinitialscompact(nombre):
"""
Get the initials of a full name
e.g.: 'Jose Facundo' --> 'JF'
Args:
Returns:
"""
res = ''.join([a[0].upper() for a in nombre.split()])
return res |
def knights_tour(row, col, move_number, num_moves_taken, num_attempts):
"""
Move the knight to position [row][col]. Then recursively try
to make other moves. Return true if we find a valid solution.
Return a auccess code and the number of attempts.
"""
# Move the knight to this position.
... |
def corr_index(idx, n):
"""
Gets the index of the auto spectrum when getting all
pairwise combinations of n maps.
Arguments
---------
idx : int
The index of the map in the list of maps being looped through.
n : int
The number of maps being looped through.
Returns
--... |
def split_file_names(names):
"""
Splits file names from the response given by the selection dialog.
:param names: String with names separated with {}
:return: List with paths as string
"""
first = 0
counter = 0
names_list = list()
for letter in names:
if letter == "{":
... |
def extract_shopname(url, platform_type):
"""
"""
shop_name = ''
try:
if platform_type == 'TripAdvisor':
shop_names = ((url.split('-Reviews-'))[1].split('-'))
if len(shop_names) == 2:
shop_name = shop_names[0]
elif len(shop_names) == 3:
... |
def adjust_for_perfusion(volume, cbf, coef=0.8, exp=0.5, tissue_density=1.041):
"""
use Grubb's relationship to adjust a tissue volume
that accounts for CBV (calulation from CBF)
Parameters
----------
volume : float
The original volume of tissue.
cbf : float
the cererebral b... |
def bin_hamming_distance(histo1, histo2):
"""
jaccard distance between two histograms
:param histo1:
:param histo2:
:return:
"""
s1 = set(histo1.keys())
s2 = set(histo2.keys())
return len(s1) + len(s2) - len(s1.intersection(s2)) |
def number_of_satisfied_literals(clause, assignment):
"""Given a clause and an assignment, this function calculated the number of satisfied literals
in the clause w.r.t. the assignment.
"""
satisfied_lits = [var in assignment and polarity == assignment[var] for (polarity, var) in clause]
return sum(... |
def test_ico(h: bytes, f):
"""
Test for .ico files to be added to the ``imghdr`` module tests.
See `ICO file format`_ and `imghdr.tests`_.
.. _`ICO file format`: https://en.wikipedia.org/wiki/ICO_(file_format)
.. _`imghdr.tests`:
https://docs.python.org/3/library/imghdr.html#imghdr.tests
... |
def is_dna(poss_dna):
""" Check whether string is feasibly a DNA sequence read"""
return set(poss_dna.upper()).issubset({'A', 'C', 'G', 'T', 'N'}) |
def my_add(a: list ,b: list)-> list:
"""
This function takes two list, compares each element, if list 1 ahs even element and list
2 has odd element then they are added else ignored
# Input:
a: List (Input List 1)
b: List (Input List 2)
# Returns:
list: Once the addition is ... |
def power(a,n):
"""
Return `a` raised to the power `n`.
This implementation uses recursion.
"""
if n == 0:
return 1
elif n == 1:
return a
else:
return a * power(a, n - 1) |
def admiralty_credibility_to_value(scale_value):
"""
This method will transform a string value from the Admiralty Credibility
scale to its confidence integer representation.
The scale for this confidence representation is the following:
.. list-table:: Admiralty Credibility Scale to STIX Confidenc... |
def agdrat_point(anps, tca, pcemic_1_iel, pcemic_2_iel, pcemic_3_iel):
"""Point implementation of `Agdrat.f`.
Calculate the C/<iel> ratio of new material that is the result of
decomposition into "box B".
Parameters:
anps: <iel> (N or P) in the decomposing stock
tca: total C in ... |
def _parse_blacklist(path):
"""Return the strings from path if it is not None."""
if path is None:
return []
with open(path, 'rt') as f:
return [l.strip() for l in f] |
def sequence_combine(sequence_one,sequence_two):
"""
combine two sequence dicts according to key (date).
Arg:
sequence_one: dicts
sequence_two: dicts
Return: a combined dict.
"""
for (date,record) in sequence_two.items():
if date in sequence_one:
new_record=se... |
def make_pre_wrappable(html, wrap_limit=60,
split_on=';?&@!$#-/\\"\''):
"""
Like ``make_wrappable()`` but intended for text that will
go in a ``<pre>`` block, so wrap on a line-by-line basis.
"""
lines = html.splitlines()
new_lines = []
for line in lines:
if le... |
def triangle_shape(n):
"""Do triangle shape in string
Args:
n (int): [description]
Returns:
[type]: [description]
"""
base_n = 2 * n - 1
res = []
for i in range(1, n + 1):
step_n = 2 * i - 1
res.append(" " * ((base_n - step_n) // 2) + "x" * step_n + " " *
... |
def TrapezoidalRule(data, dx):
""" Calculate the integral according to the trapezoidal rule
TrapezoidalRule approximates the definite integral of f from a to b by
the composite trapezoidal rule, using n subintervals.
http://en.wikipedia.org/wiki/Trapezoidal_rule#Uniform_grid
Args:
data: A list of sample... |
def ChromeHeaders2Dict(chrome_headers_str: str) -> dict:
"""
:param chrome_headers_str:
:return: dict
"""
if not chrome_headers_str:
return {}
headers = {}
item_list = chrome_headers_str.splitlines(keepends=False)
for item in item_list:
item_str = item.strip()
i... |
def IsProjectParentValid(properties):
""" A helper function to validate that the project is either under a folder
or under an organization and not both
"""
# Neither specified
if "organization-id" not in properties and "folder-id" not in properties:
return False
# Both specified
elif "organization-id" in prop... |
def pedersenCommit(n,g,h,m,r):
"""Calculate a pedersen commit. Arguments:
n modulus (i.e. Z*_n)
g generator 1
h generator 2
m message
r random"""
return g**m*h**r % n |
def split(s,separator=None):
"""'this is "a test"' -> ['this', 'is', 'a test']"""
if separator is None:
from shlex import split
return split(s)
else: return s.split(separator) |
def send_to_device(tensor, device):
"""
Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device.
Args:
tensor (nested list/tuple/dictionary of :obj:`torch.Tensor`):
The data to send to a given device.
device (:obj:`torch.device`):
... |
def create_request_body_obj(query, size, from_time, to_time):
""" Creates request body to send to Logz.io API """
request_body = {
"query": {
"bool": {
"must": [{
"query_string": {
"query": query
}
... |
def NFW(r,a,rc,beta=0):
"""return unscaled NFW density"""
ra = r/a
return 1./((ra+rc)*((1+ra)**2.)) |
def replace_nones(dict_or_list):
"""Update a dict or list in place to replace
'none' string values with Python None."""
def replace_none_in_value(value):
if isinstance(value, str) and value.lower() == "none":
return None
return value
items = dict_or_list.items() if isinstan... |
def coefficients_from_points(p, q):
""" given 2 points p and q, give the coefficients (a,b,c) for the line
that runs from p to q: ax + by + c = 0
when a = 0, then the line is horizontal
when b = 0, then the line is vertical
see also:
https://www.mathcentre.ac.uk/resources/uploaded/mc-ty-strtl... |
def get_filename_pref(file_name):
"""Splits the filename apart from the path
and the extension. This is used as part of
the identifier for individual file uploads."""
while '/' in file_name:
file_name = file_name.split('/', maxsplit=1)[1]
while '\\' in file_name:
file_name = file_nam... |
def callMethod(connectionName, objectId, methodId, inputs):
"""Calls a method in an OPC UA server. To make the most of this
function, you'll need to be familiar with methods in the OPC-UA
server.
Args:
connectionName (str): The name of the OPC-UA connection to the
server that the me... |
def is_power_of_two(value: int) -> bool:
"""
Determine if the given value is a power of 2.
Negative numbers and 0 cannot be a power of 2 and will thus return `False`.
:param value: The value to check.
:return: `True` if the value is a power of two, 0 otherwise.
"""
if valu... |
def segmented_extrusion_coords_to_fisnar_commands(segments):
"""
given a segmented extrusion list (see function above), return the equivalent fisnar commands as a list of
dummy points. This can be used to determine where actual material will be layed down. All output commands are
of the form: ["Output",... |
def hsv2rgb_rainbow(hsv):
"""Generates RGB values from HSV that have an even visual
distribution. Be careful as this method is only have as fast as
hsv2rgb_spectrum."""
def nscale8x3_video(r, g, b, scale):
nonzeroscale = 0
if scale != 0:
nonzeroscale = 1
if r != 0:
... |
def check_for_output_match(output, test_suite):
"""Return bool list with a True item for each output matching expected output.
Return None if the functions suspects user tried to print something when
they should not have.
"""
output_lines = output.splitlines()
if len(output_lines) != len(t... |
def create_name_str_from_tup(name_tup):
"""
"""
#| - create_name_str_from_tup
name_list = []
for i in name_tup:
if type(i) == int or type(i) == float:
name_list.append(str(int(i)))
elif type(i) == str:
name_list.append(i)
else:
name_list.ap... |
def high_and_low(s):
"""Return the highest and lowest number in the given string.
input = string, space separated integers
output = output highest first + space + lowest number
ex. high_and_low("1 2 3 4 5") returns "5 1"
ex. high_and_low("1 2 -3 4 5") returns "5 -3"
ex. high_and_low("1 9 3 4 -5... |
def fahr_to_celsius(temp_fahr):
"""Convert temperature from Fahrenheit to Celsius"""
temp_celsius = (temp_fahr - 32) * 5 / 9.0
return temp_celsius |
def filter_dict(d, keys):
"""Returns a subset of dictionary `d` with keys from `keys`
"""
filtered = {}
for key in keys:
filtered[key] = d.get(key)
return filtered |
def csv_to_list(csv_string):
"""
Converts a string with comma-separated integer values to a Python list of integers.
Receives
--------
csv_string : string
Comma-separated integer values.
Returns
-------
integer_list : list
List of integer values.
"""
string_list ... |
def powersumavg(bar, series, period, pval=None):
"""
Returns the power sum average based on the blog post from
Subliminal Messages. Use the power sum average to help derive the running
variance.
sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/
... |
def ensure_list_or_tuple(obj):
"""
Takes some object and wraps it in a list - i.e. [obj] - unless the object
is already a list or a tuple instance. In that case, simply returns 'obj'
Args:
obj: Any object
Returns:
[obj] if obj is not a list or tuple, else obj
"""
return [ob... |
def strip(input_str):
"""Strip newlines and whitespace from a string."""
return str(input_str.replace('\n', '').replace(' ', '')) |
def clean_url(url):
"""
Removes .html from the url if it exists.
"""
parts = url.rsplit(".", 1)
if parts[1] == "html":
return parts[0]
return url |
def is_dicom(file: str) -> bool:
"""Boolean specifying if file is a proper DICOM file.
This function is a pared down version of read_preamble meant for a fast return.
The file is read for a proper preamble ('DICM'), returning True if so,
and False otherwise. This is a conservative approach.
Parame... |
def resultToString(result, white):
"""
The function returns if the game was won based on result and color of figures
Input:
result(str): result in format '1-0','1/2-1/2', '0-1'
white(bool): True if white, False if black
Output:
str: result of a game: 'won', 'lost', 'tie' or 'unknown'
""... |
def initialise_label_counts(label_list):
"""Get unique label list and label counts."""
label_counts = {}
for label in set(label_list):
label_counts[label] = 0
return label_counts |
def precision(tp,fp):
"""Computes precision for an array of true positives and false positives
Arguments:
tp {[type]} -- True positives
fp {[type]} -- False positives
Returns:
[type] -- Precision
"""
return tp / (tp+fp+1e-10) |
def margins_to_dict(margins):
"""Convert the margin's informations into a dictionary.
Parameters
----------
margins : the list of OpenTurns distributions
The marginal distributions of the input variables.
Returns
-------
margin_dict : dict
The dictionary with the informatio... |
def parse_slice(text):
"""Parse a string into list which can be converted into a slice object.
:param str text: the input string.
:return tuple: a list which can be converted into a slice object.
:raise ValueError
Examples:
Input IDs separated by comma:
parse_slice(":") == [None, None]... |
def get_page(data):
"""Determines the page number"""
try:
page = int(data.get('page', '1'))
except (ValueError, TypeError):
page = 1
return page |
def check_rule_exists(rules, address, port):
"""Check if the rule currently exists"""
for rule in rules:
for ip_range in rule['IpRanges']:
if ip_range['CidrIp'] == address and rule['FromPort'] == port:
return True
return False |
def parse_list_from_string(a_string):
"""
This just parses a comma separated string and returns either a float or an int.
Will return a float if there is a decimal in any of the data entries
Args:
a_string (str): The string to be parsed
Returns:
A list of integers or floats
A... |
def steps(number):
"""
Count steps needed to get to 1 from provided number.
:param number int - the number provided.
:return int - the number of steps taken to reach 1.
"""
if number < 1:
raise ValueError("Provided number is less than 1.")
steps = 0
while number != 1:
s... |
def slice_2d(X,rows,cols):
"""
Slices a 2D list to a flat array. If you know a better approach, please correct this.
Args:
X [num_rows x num_cols] multi-dimensional data
rows [list] rows to slice
cols [list] cols to slice
Example:
>>> X=[[1,2,3,4]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.