content stringlengths 42 6.51k |
|---|
def invert(d: dict) -> dict:
"""Invert keys and values in a dictionary"""
return {
v: k for k, v in d.items()
} |
def capfirst(value):
"""Capitalizes the first character of the value."""
return value and value[0].upper() + value[1:] |
def len_ignore_leading_ansi(s: str) -> int:
"""Returns the length of the string or 0 if it starts with `\033[`"""
return 0 if s.startswith("\033[") else len(s) |
def h(x):
"""Convert an integer into a raw hexadecimal representation."""
return hex(x).replace("0x", "").replace("L", "").upper() |
def strip_type_prefix(path, prefix):
"""Strip source type prefix from the path.
This function strips prefix from strings like::
[<prefix>]://<path>
For example::
pyfile://home/me/config.py -> /home/me/config.py
json://path/to/some.cfg -> /path/to/some.cfg
Args:
path:... |
def algebraic_equasion_defunction(x):
"""
This function makes a calculation for an Algebraic equasion
It calculates f'(x) with the given equasion and x as a parameter
"""
formula = 2*x + 6
return formula |
def groupSubjects(segments):
"""Group subjects by parent page mongo id"""
grouped = {}
for s in segments:
if s['parent_subject_id']['$oid'] in grouped:
grouped[s['parent_subject_id']['$oid']].append(s)
else:
grouped[s['parent_subject_id']['$oid']] = [s]
return gro... |
def get_protocol(request = None):
""" Return the protocol of the current request. """
if request is None:
# We have no request, we return an empty string
return ''
return 'https' if request.is_secure() else 'http' |
def get_capillary_diameter(line1, line2):
"""
Defines capillary diameter in pixel length.
line1 = int32 - first point on left edge of capillary
line2 = int32 - second point on right edge of capillary
"""
#express first points on opposite side of capillary as x,z coordinates
... |
def function(domain_set, target_set):
"""
Determine if a relation is a function and tupe of the function.
:return: Function or not and type of the function.
"""
if len(domain_set) == len(set(domain_set)):
function_type = 'General function'
if len(target_set) != len(set(target_set))... |
def ordinal(value):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'
u'6th'
u'7th'
u'8th'
u'9th'
u'10th'
u'11th'
u'1... |
def say_hello(name):
"""
Say hello
"""
return "Hello {}".format(name) |
def get_alt_support_by_color(support_color):
"""
:return:
"""
if 240.0 <= support_color <= 255.0:
return 1
if 0.0 <= support_color <= 10.0:
return 0 |
def sort_and_format_devices(devices):
"""
Takes a (list) of (dict)s devices and returns a (list) of (dict)s.
Sorts by SCSI ID acending (0 to 7).
For SCSI IDs where no device is attached, inject a (dict) with placeholder text.
"""
occupied_ids = []
for device in devices:
occupied_ids.... |
def get_earliest(*dates):
"""
Find earliest date in list of provided date strings
Parameters:
dates (list): List of date strings in format "mm/dd/yyyy"
Returns:
str: Earliest date found in list of date strings
"""
earliest = "99/99/9999"
for date in list(dates):
if... |
def housecall_status(events):
"""Returns how many housecalls there are on the calendar."""
if not events: # no events means no housecalls
print('No upcoming events found.')
return 0
count = 0
for event in events:
name = event['summary'].lower()
if ('house' in name) and (... |
def _new_activity_share_format(share):
"""
Convert the share from the internal format used by FTS3 to the RESTful one
[{"A": 1}, {"B": 2}] => {"A": 1, "B": 2}
"""
new_share = dict()
for entry in share:
new_share.update(entry)
return new_share |
def check_for_radicals(mol_list):
"""Check if list of molecules contains a radical.
"""
to_remove = []
for name in mol_list:
if 'radical' in name:
# new_name = name.replace('radical', '').lstrip().rstrip()
# if new_name in mol_list:
print('removing', name, '... |
def roundto(num, nearest):
"""
Rounds :param:`num` to the nearest increment of :param:`nearest`
"""
return int((num + (nearest / 2)) // nearest * nearest) |
def filter_ensuretrailingslash(host):
"""
Adds a trailing slash to URLs (or anything, really) if one isn't present
Usage: {{ 'www.example.com' | ensuretrailingslash }}
Output: 'www.example.com/'
"""
if not host.endswith("/"):
host = host + "/"
return host |
def _compute_timeout(count: int, delay: float) -> int:
"""Dumb logic for a max timeout, this could be better
``max_tasks_fn_timeout`` is the amount of seconds and is the anticipated
amount of time to do all concurrent requests in the workflow's
(see ``tasks_fn``).
Empirically, when all default tas... |
def create_y_range(motile_count,
non_motile_count,
auto_motile_count,
auto_non_motile_count):
"""
Generate the y range on the motility bar
:param motile_count: the amount of motile life at this frame
:param non_motile_count: the amount of non mot... |
def _apply_func(func, x, none_safe):
"""Helper for `update_with_redict()` containing logic for running func(x).
"""
if func is not None:
if not none_safe:
x = func(x)
else:
if x is not None:
x = func(x)
return x |
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
a_index = text.index(begin)
b_index = text.index(end)
return text[a_index + 1 : b_index] |
def split_string(text, chars_per_string):
"""
Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string.
This is very useful for splitting one giant message into multiples.
:param text: The text to split
:param chars_per_string: The number of characte... |
def xy2z(x, y):
"""
Interleave lower 16 bits of x and y, so the bits of x
are in the even positions and bits from y in the odd;
z gets the resulting 32-bit Morton Number.
x and y must initially be less than 65536.
Source: http://graphics.stanford.edu/~seander/bithacks.html
"""
B = [0x5... |
def getR(m, t, a):
"""
Returns the matrix R as in the canonical form [[Q,R],[0,I]]
m is the input matrix, t is the list of the transient states,
a is the list of the absorbing states.
"""
R = []
for r in range(len(t)):
qrow = []
for c in range(len(a)):
qrow.append(m[t[r]... |
def evenOdd(num):
"""Returns the string "even", "odd", or "UNKNOWN"."""
if num % 2 == 0:
return "even"
elif num % 2 == 1:
return "odd"
else:
return "UNKNOWN" |
def make_shit_comma_separated_func(x, y):
"""
func for use in reduce() methods to make a list a comma separated string
:param x:
:param y:
:return:
"""
return str(x) + ',' + str(y) |
def mean( xs ):
"""
Return the mean value of a sequence of values.
>>> mean([2,4,4,4,5,5,7,9])
5.0
>>> mean([9,10,11,7,13])
10.0
>>> mean([1,1,10,19,19])
10.0
>>> mean([10,10,10,10,10])
10.0
>>> mean([1,"b"])
Traceback (most recent call last):
...
ValueError: I... |
def FindPart(part: dict, mime_type: str):
"""
Recursively parses the parts of an email and returns the first part with the requested mime_type.
:param part: Part of the email to parse (generally called on the payload).
:param mime_type: MIME Type to look for.
:return: The part of the email with the... |
def gcd(x, y):
"""This function implements the Euclidian algorithm
to find G.C.D. of two numbers"""
while(y):
x, y = y, x % y
return x |
def allpairs(x):
"""
return all possible pairs in sequence *x*
"""
return [(s, f) for i, f in enumerate(x) for s in x[i + 1:]] |
def dividir(a, b):
"""
DIVIDIR realiza la division de 2 numeros
"""
try:
return a/b
except Exception as e:
print(e)
return 0 |
def assert_raises(ex_type, func, *args, **kwargs):
"""
Checks that a function raises an error when given specific arguments.
Args:
ex_type (Exception): exception type
func (callable): live python function
Example:
>>> ex_type = AssertionError
>>> func = len
>>> ... |
def bit_bitlist_to_str(ordlist):
"""Given a list of ordinals, convert them back to a string"""
return ''.join(map(chr, ordlist)) |
def initial_state(loops):
"""Given a set of loops, create the initial counters"""
return tuple(row[2] for row in loops) |
def get_song_stereotypy(sequence_linearity: float, sequence_consistency: float) -> float:
"""Average between linearity and consistency"""
song_stereotypy = (sequence_linearity + sequence_consistency) / 2
return song_stereotypy |
def overall_chromatic_response(M_yb, M_rg):
"""
Returns the overall chromatic response :math:`M`.
Parameters
----------
M_yb : numeric
Yellowness / blueness response :math:`M_{yb}`.
M_rg : numeric
Redness / greenness response :math:`M_{rg}`.
Returns
-------
numeri... |
def process_tweet(text, target, do_short):
"""Check it's ok and remove some stuff"""
# print(len(text) > 140, len(text))
if not text:
return None
if do_short and len(text) > 141:
return None
elif not do_short and len(text) <= 140:
return None
if (text.startswith("RT ")... |
def convert_keyname_to_safe_field(obj):
"""convert keyname into safe field name.
when dict key include dash(-), convert to safe field name under_score(_).
"""
if isinstance(obj, dict):
for org_key in list(obj.keys()):
new_key = org_key
if '-' in org_key:
... |
def str_to_int(text, default=0):
"""
>>> str_to_int("3")
3
>>> str_to_int("moo")
0
>>> str_to_int(None)
0
>>> str_to_int(str_to_int)
0
>>> str_to_int("cake", default=6)
6
"""
try:
return int(text)
except (ValueError, TypeError):
return default |
def color(string, color=None):
"""
Change text color for the Linux terminal. (Taken from Empire: https://github.com/EmpireProject/Empire/blob/master/lib/common/helpers.py)
"""
attr = []
# bold
attr.append('1')
if color:
if color.lower() == "red":
attr.append('31')
... |
def count_random_set_bits(n, k, random_set):
"""Counts the number of ones in the randomly chosen k digits of binary.
Args:
n: Integer, the integer of interest.
k: Integer, the number of binary digits that the subset parity acts on.
random_set: List of integers, random binary string with ones in k locat... |
def isOccluded(match, tiles):
"""Returns true if the match is already occluded by another match
in the tiles list.
"Note that "not occluded" is taken to mean that none of the tokens
Pp to Pp+maxmatch-1 and Tt to Tt+maxmatch-1 has been marked during
the creation of an earlier t... |
def GetMaxRounds(board_list):
""" Gets the maximum number of rounds any team has played in the tournament. """
if not board_list:
return 0
board_counts = {}
for bs in board_list:
for bsl in bs.ScoreBoard():
hr = bsl.hr()
board_counts[hr.ns_pair_no()] = 1 + board_counts.get(hr.ns_pair_no(), 0... |
def bool_to_bin(bool_value):
"""
Helper function to map a boolean value to a binary value.
:param bool_value: boolean boolean value [bool]
:return: binary value [int]
"""
if bool_value:
return 1
else:
return 0 |
def add_webmention_endpoint(response):
"""
This publishes a webmention endpoint for everything, including error pages
(necessary for receiving pings to private entries) and image resources.
Please fix the endpoint URL before uncommenting this.
"""
#response.headers.add('link', '<https://webmenti... |
def parse_single_alignment(string, reverse=False, one_add=False, one_indexed=False):
"""
Given an alignment (as a string such as "3-2" or "5p4"), return the index pair.
"""
assert '-' in string or 'p' in string
a, b = string.replace('p', '-').split('-')
a, b = int(a), int(b)
if one_indexed... |
def load32(byte):
"""
bytearray to int (little endianness)
"""
return sum((byte[i] << (8 * i)) for i in range(4)) |
def cleandef(s):
"""E.g. given a def string 'C & ~Z', return ' C & ~Z' so it lines
up with other table rows i.e.
BEFORE:
| eq 4'h0 | Z | -------- | hi 4'h8 | C & ~Z |
| ne 4'h1 | ~Z | -------- | ls 4'h9 | ~C \| Z |
AFTER:
| eq 4'h0 | Z | -------- | hi 4'h8 | C & ~Z |
... |
def map_field(fn, m) :
"""
Maps a field name, given a mapping file.
Returns input if fieldname is unmapped.
"""
if m is None:
return fn
if fn in m:
return m[fn]
else:
return fn |
def shell_strip_comment(cmd):
""" hi # testing => hi"""
if '#' in cmd:
return cmd.split('#', 1)[0]
else:
return cmd |
def Get_LonghurstProvinceName4Num(input):
"""
Get full Longhurst Province for given number
"""
LonghurstProvinceDict = {
'ALSK': 'AlaskaDownwellingCoastalProvince',
'ANTA': 'AntarcticProvince',
'APLR': 'AustralPolarProvince',
'ARAB': 'NWArabianUpwellingProvince',
... |
def _strip_trailing_newline(s):
"""Returns a modified version of the string with the last character
truncated if it's a newline.
:param s: string to trim
:type s: str
:returns: modified string
:rtype: str
"""
if s == "":
return s
else:
return s[:-1] if s[-1] == '\n'... |
def html_document(text):
"""Wrap an HTML snippet in <body> tags, etc. to make it a full document."""
return f"""<!DOCTYPE html>
<html>
<body>
{text}
</body>
</html>
""" |
def ngrams(sentence, n):
"""
Returns:
list: a list of lists of words corresponding to the ngrams in the sentence.
"""
return [sentence[i:i + n] for i in range(len(sentence)-n+1)] |
def mergesort_lists(*lists):
"""Supposet that lists are sorted
Complexity is O(n+m+l+...)
"""
def next_(iterator):
""" Provide dict {"id":id , ...} for id comparison"""
return next(iterator, {'id': float("inf")})
iters = [] # List iterators are stored here
items = [] # Dictio... |
def upper(value):
"""
convert to uppercase
:param value:
:return:
"""
return value.upper() |
def parse_custom_command(command: str) -> list:
"""
Convert custom medusa command from string to list to be usable in subprocess.
:param command: Custom medusa command
:return: Parameters for medusa command
"""
command_split = command.split(" ")
command_list = []
for parameter in comma... |
def get_list(text, delim=',', lower=False):
"""
Take a string and return trim segments given the delimiter:
"A, B,\tC" => ["A", "B", "C"]
:param text:
:param delim: delimiter str
:param lower: True if you want items lowercased
:return: array
"""
if not text:
return []
... |
def asFloat(val):
"""Converts floats, integers and string representations of either to floats.
Raises ValueError or TypeError for all other values
"""
if hasattr(val, "lower") and val.lower() == "nan":
raise ValueError("%s is not a valid float" % (val,))
else:
return float(val) |
def count_query(tablename,condition):
"""
Function to process query for count process
"""
if isinstance(tablename, str):
pass
else:
raise ValueError("Tablename should be a String")
if condition == None or isinstance(condition, str):
pass
else:
raise ValueErr... |
def new_task_id(sources, prefix=""):
"""Generate a new unique task ID
The task ID will be unique for the given sources, and with the given prefix.
"""
existing_ids = set()
for source in sources:
existing_ids |= {int(key[len(prefix):]) for key in source.task_ids
if ke... |
def is_hex(HEX_MAYBE):
""" Checks if a string could be expressed in hexidecimal. """
try:
int(HEX_MAYBE, 16)
return True
except ValueError:
return False |
def is_string_palindrom(string):
"""Testuje, zdali je zadany retezec (string) palindrom
a to bez pouziti funkce reverse. Vraci True v pripade,
ze je palindrom, jinak False.
"""
if string is None:
return False
i = 0
while i < len(string):
if string[i] == string[len(string) -1... |
def check_skip(selector, chrom):
"""
:param selector:
:param chrom:
:return:
"""
if selector is None:
return False
elif selector.match(chrom) is None:
return True
else:
return False |
def get_attr_value(attrs, key):
"""Read attr value from terncy attributes."""
for att in attrs:
if "attr" in att and att["attr"] == key:
return att["value"]
return None |
def active_llr_level(i, n):
"""
Find the first 1 in the binary expansion of i.
"""
mask = 2**(n-1)
count = 1
for k in range(n):
if (mask & i) == 0:
count += 1
mask >>= 1
else:
break
return min(count, n) |
def count_sql(name):
"""
Generate SQL to count the number of rows in a table
:param name: table name
:return: SQL string
"""
return f'SELECT COUNT(*) FROM "{name}";' |
def unique_group(groups):
"""Find unique groups in list not including None."""
ugroups = set(groups)
ugroups -= set((None,))
ugroups = list(ugroups)
ugroups.sort()
return ugroups |
def toFloat( value, shift=0 ):
"""Take single-byte integer value return floating point equivalent"""
return ((value&(255<<shift))>>shift)/255.0 |
def get_tarball_valid_unpack_directory_name(package_name: str, version_number: str) -> str:
"""
get the name of the folder that should be obtained by unpacking the tarball
:param package_name: name of the package to check
:param version_number: version number
:return: the name of the folder that is ... |
def normalize_teh_marbuta_xmlbw(s):
"""Normalize all occurences of Teh Marbuta characters to a Heh character
in a XML Buckwalter encoded string.
Args:
s (:obj:`str`): The string to be normalized.
Returns:
:obj:`str`: The normalized string.
"""
return s.replace(u'p', u'h') |
def print_heading_structure(h: int, text: str) -> str:
"""
This method prints our heading, represented as an integer (which is the level of the heading, h1 is 1 ...)
:param h: Integer that represents our headings (which is the level of the heading, h1 is 1 ...)
:param text: Text to add to our headings, ... |
def sanitize_line(line, commenter='!'):
"""Clean up input line."""
return line.split(commenter, 1)[0].strip() |
def next_good(bad_samples_idx, i):
"""
Find the index of the next good item in the list.
:param bad_samples_idx: List of the indices of the bad samples.
:param i: Index of the current item.
:return: Index of the next good item.
"""
while True:
i += 1
if i >= (len(bad_sampl... |
def dict_remove_empty(d):
"""remove keys that have [] or {} or as values"""
new = {}
for k, v in d.items():
if not (v == [] or v == {}):
new[k] = v
return new |
def drange(v0, v1, d):
"""Returns a discrete range."""
assert v0 < v1, str((v0, v1, d))
return list(range(int(v0) // d, int(v1 + d) // d)) |
def bubbleSort(myList: list):
"""
Sorts the list in Ascendant mode and returns it properly sorted.
"""
listLen = len(myList)
for i in range(listLen):
for j in range(0, listLen-i-1): # O(n) * O(n) = O(n*n) = O(n**2)
if (myList[j] > myList[j+1]):
myList[j], myList... |
def UNKNOWN_FILE(project_id, file_id):
"""Error message for requests that access project files.
Parameters
----------
project_id: string
Unique project identifier.
file_id: string
Unique file identifier.
Returns
-------
string
"""
msg = "unknown file '{}' or pro... |
def filter_dictionary_by_resolution(raw_data, threshold=False):
"""Filter SidechainNet data by removing poor-resolution training entries.
Args:
raw_data (dict): SidechainNet dictionary.
threshold (float, bool): Entries with resolution values greater than this value
are discarded. T... |
def abband(matrix, vecin, vecout, neq, iband):
"""
Multiplies [ banded ]{vector} = {vector}
"""
for i in range(neq):
jlim = max(0, i - iband + 1)
for j in range(jlim, i):
val = vecin[j]
vecout[i] += val * matrix[j][i - j + 1]
#
jlim = min(iband, ne... |
def is_pos_int(num):
"""Function: is_pos_int
Description: Returns True|False if number is an integer and positive.
Arguments:
(input) num -> Integer value.
(output) True|False -> Number is an integer and positive.
"""
return isinstance(num, int) and num > 0 |
def generate_hypotheses_for_effect(cause_alpha, effect, window_start, window_end):
"""
Lists all hypotheses for a given effect. Excludes hypotheses where the cause and effect are the same variable.
See the docs of `generate_hypotheses_for_effects`
"""
hyps = []
for cause in cause_alpha:
... |
def _normalize_integer_rgb(value):
"""
Internal normalization function for clipping integer values into
the permitted range (0-255, inclusive).
"""
return 0 if value < 0 \
else 255 if value > 255 \
else value |
def unescape(text):
"""
Do reverse escaping.
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
text = text.replace(''', '\'')
return text |
def are_entities_in_augmented_text(entities: list, augmented_text: str) -> bool:
"""
Given a list of entities, check if all the words associated to each entity
are still present in augmented text.
Parameters
----------
entities : list
entities associated to initial text, must be in the ... |
def transition_filename(tr):
"""Get the part of the filename specifying the transition (e.g. BKstar)
from a transition string (e.g. B->K*)."""
return tr.replace('->', '').replace('*', 'star') |
def extract_validatable_type(type_name, models):
"""Returns a jsonschema-compatible typename from the Swagger type.
This is necessary because for our Swagger specs to be compatible with
swagger-ui, they must not use a $ref to internal models.
:returns: A key-value that jsonschema can validate. Key wil... |
def xorCrypt(str, key=6):
"""Encrypt or decrypt a string with the given XOR key."""
output = ""
for x in range(0, len(str)):
output += chr(key ^ ord(str[x]))
return output |
def compute_inv_permute_vector(permute_vector):
""" Given a permutation vector, compute its inverse permutation vector s.t. an array will have the same shape after permutation and inverse permutation.
"""
inv_permute_vector = []
for i in range(len(permute_vector)):
# print('i = {}'.format... |
def _get_character_pairs(text):
"""Returns a defaultdict(int) of adjacent character pair counts.
>>> _get_character_pairs('Test is')
{'IS': 1, 'TE': 1, 'ES': 1, 'ST': 1}
>>> _get_character_pairs('Test 123')
{'23': 1, '12': 1, 'TE': 1, 'ES': 1, 'ST': 1}
>>> _get_character_pairs('Test TEST')
{... |
def format_weight_imperial(weight):
"""Formats a weight in hectograms as L lb."""
return "%.1f lb" % (weight / 10 * 2.20462262) |
def str_to_enum(name):
"""Create an enum value from a string."""
return name.replace(' ', '_').replace('-', '_').upper() |
def __replaceMonth(_strFecha, _intMonth):
"""Reemplaza en Mes en Ingles por el Mes en Espanol de la cadena del parametro y segun el numero de mes"""
result = ''
if 1 == _intMonth:
result = _strFecha.replace('January', u'Enero')
elif 2 == _intMonth:
result = _strFecha.replace('February',... |
def ConvertDecimalToHexadecimal (integer: int, minimumLength: int = -1) -> str:
"""
Convert integer to hexadecimal string
:type integer: int
:param minimumLength: If the hexadecimal is shorter than this number it will be padded with extra zeros.
:type minimumLength: int
:type: str
"""
hexString = hex(integer)[... |
def get_WNID_from_line(line):
"""Return the WNID without anything else from categories.txt"""
WNID = line.split(" ")[0]
return WNID |
def generate_bounding_coordinates(lat_list, lng_list):
"""
This function takes in two lists containing coordinates in the latitude and longitude direction and generates a
list containing coordinates for each bounding box.
"""
lat_list = list(reversed(lat_list))
coordinate_list = []
for i in ... |
def is_between(value,
minimum = None,
maximum = None,
**kwargs):
"""Indicate whether ``value`` is greater than or equal to a supplied ``minimum``
and/or less than or equal to ``maximum``.
.. note::
This function works on any ``value`` that support compari... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.