content stringlengths 42 6.51k |
|---|
def sort_key(model):
"""key function for case-insensitive sort by name and type"""
iname = model['data']['name'].lower()
type_key = {
'directory' : '0',
'notebook' : '1',
'file' : '2',
}.get(model['data']['type'], '9')
return u'%s%s' % (type_key, iname) |
def format_quote(q, num, n_quotes):
"""Returns a formatted string of a quote"""
ctime, nick, msg = q
return "[{}/{}] <{}> {}".format(num, n_quotes,
nick, msg) |
def str2bool(v):
"""
converts a string to a boolean
"""
return v.lower() in ("yes", "true", "t", "1") |
def as_int(obj, quiet=False):
"""Converts an arbitrary value into a integer."""
# Try "2" -> 2
try:
return int(obj)
except (ValueError, TypeError):
pass
# Try "2.5" -> 2
try:
return int(float(obj))
except (ValueError, TypeError):
pass
# Eck, not sure what this is then.
if not quiet:
raise TypeError("Can not translate %s to an integer." % (obj))
return obj |
def handle(event, context):
"""handle a request to the function
Args:
event (dict): request params
context (dict): function call metadata
"""
return {
"message": "Hello From Python3 runtime on Serverless Framework and Scaleway Functions"
} |
def _describe_instances_response(response):
"""
Generates a response for a describe instance request.
@param response: Response from Cloudstack.
@return: Response.
"""
return {
'template_name_or_list': 'instances.xml',
'response_type': 'DescribeInstancesResponse',
'response': response
} |
def maxSubArray(nums) -> int:
"""
https://leetcode-cn.com/problems/maximum-subarray/
:param nums:
:return:
"""
n = len(nums)
matrix = [0 for i in range(n)]
ans = matrix[0] = nums[0]
for j in range(1, n):
matrix[j] = max(matrix[j - 1] + nums[j], nums[j])
print(matrix)
return max(matrix) |
def into_path(item, after, last_title):
"""
(Pdb) pp item, after, last_title
('features/termcasts/zab/baz.md', 'features/termcasts/index.md', '3.Features.3.TermCasts.0.Overview')
Then we return '3.Features.3.TermCasts.0'
"""
while not item.startswith(after):
after = after.rsplit('/', 1)[0]
parts = after.split('/')
return '.'.join(last_title.split('.', 2 * len(parts) + 1)[:-1]) |
def str_to_hex(string):
""" Returns a string in readable hex encoding.
Args:
string: A string to convert to readable hex.
Returns:
A string in hex format.
"""
return ":".join(x.encode('hex') for x in string) |
def _remove_by_index_list(text, index_list):
"""Remove all substrings inside a string, thanks to the given list of indexes """
len_removed = 0
for i in index_list:
i_start = i[0] - len_removed
i_end = i[1]-len_removed
text = text[:i_start] + text[i_end:]
len_removed += i[1]-i[0]
return text |
def get_games_per_worker(games, max_workers):
"""Calculates the number of games each processor should play.
Args:
games (int): Total number of games to be played.
max_workers (int): Number of processors that will play those games.
Returns:
list[int]: Number of games each processor should play. The list
contains one element per processor.
"""
d_games = games // max_workers
r_games = games % max_workers
n_games = [d_games] * max_workers
if r_games != 0:
for i in range(r_games):
n_games[i] += 1
return n_games |
def _children_key(key):
"""Create a key that corresponds to the group's children
Parameters
----------
key : str
The group key
Returns
-------
str
The augmented key
"""
return key + ':children' |
def condense_classification(classification):
"""Returns a condensed classification string"""
return { 'classif': [_.strip() for _ in classification.split(",")] } |
def dictionary_filter(dictionary, cols) -> dict:
"""Can be used to filter certain keys from a dict
:param dictionary: The original dictionary
:param cols: The searched columns
:return: A filtered dictionary
"""
return {key:value for (key,value) in dictionary.items() if key in cols} |
def join_regex(regexes):
"""Combine a list of regexes into one that matches any of them."""
if len(regexes) > 1:
return "(" + ")|(".join(regexes) + ")"
elif regexes:
return regexes[0]
else:
return "" |
def remove_duplicates(seq, keep=()):
"""
Remove duplicates from a sequence while perserving order.
The optional tuple argument "keep" can be given to specificy
each string you don't want to be removed as a duplicate.
"""
seq2 = []
seen = set()
for i in seq:
if i in (keep):
seq2.append(i)
continue
elif i not in seen:
seq2.append(i)
seen.add(i)
return seq2 |
def iops(parameter='nodisk'):
"""
Get amount of IOs per second
"""
return 'disk', '0' |
def update_detections(visualizer, old_det_geometries, new_det_geometries):
"""Update detections that has a previous geometry object."""
for geometry in old_det_geometries:
visualizer.remove_geometry(geometry, False)
for geometry in new_det_geometries:
visualizer.add_geometry(geometry, False)
return new_det_geometries |
def sort_toc(toc):
""" Sort the Table of Contents elements. """
def normalize(element):
""" Return a sorting order for a TOC element, primarily based
on the index, and the type of content. """
# The general order of a regulation is: regulation text sections,
# appendices, and then the interpretations.
normalized = []
if element.get('is_section'):
normalized.append(0)
elif element.get('is_appendix'):
normalized.append(1)
elif element.get('is_supplement'):
normalized.append(2)
for part in element['index']:
if part.isdigit():
normalized.append(int(part))
else:
normalized.append(part)
return normalized
return sorted(toc, key=lambda el: tuple(normalize(el))) |
def freq(mylist, item):
"""Return the relative frequency of an item of a list.
:param mylist: (list) list of elements
:param item: (any) an element of the list (or not!)
:returns: frequency (float) of item in mylist
"""
return float(mylist.count(item)) / float(len(mylist)) |
def windows(lst):
"""Return a list of 3-element sliding windows from a list"""
return list(zip(lst, lst[1:], lst[2:])) |
def is_number(string):
"""String is a number."""
try:
float(string)
return True
except ValueError:
return False |
def is_even(x):
"""True if x is even, False if x is odd"""
return x % 2 == 0 |
def list2cmdline(lst):
""" convert list to a cmd.exe-compatible command string """
nlst = []
for arg in lst:
if not arg:
nlst.append('""')
else:
nlst.append('"%s"' % arg)
return " ".join(nlst) |
def diff_lists(list1,list2, option=None):
"""
if option equal 'and', return a list of items which are in both list1
and list2. Otherwise, return a list of items in list1 but not in list2.
"""
if option and option == 'and':
return [x for x in list1 if x in list2]
else:
return [x for x in list1 if x not in list2] |
def loop_erasure(path):
"""Return the loop-erasure of a discrete sample path.
Parameters
----------
path : sequence
A sequence of hashable values.
Returns
-------
tuple
The loop erasure of `path`.
"""
if len(path) == 0:
return ()
last_index = {x: k for k, x in enumerate(path)}
sel = [0]
while path[sel[-1]] != path[-1]:
sel.append(last_index[path[sel[-1]]] + 1)
return tuple(path[k] for k in sel) |
def integer_log2_round_up(x):
"""
Returns the number of bits required to represent `x` distinct values---i.e.
log2(x) rounded up.
"""
assert x > 0
bits = 1
representable = 2 ** bits
while representable < x:
bits += 1
representable *= 2
return bits |
def parentIdx(idx):
"""
>>> parentIdx(1)
0
>>> parentIdx(2)
0
>>> parentIdx(3)
1
>>> parentIdx(4)
1
"""
return (idx - 1) // 2 |
def get_origin(array, plot_origin):
"""Get the (y,x) origin of the ccd data if it going to be plotted.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The array from which the origin is extracted.
plot_origin : True
If true, the origin of the data's coordinate system is returned.
"""
if plot_origin:
return array.origin
else:
return None |
def quick_pow(n: int, k: int, p: int) -> int:
"""Find n^k % p quickly"""
if k == 0:
return 1
tmp = quick_pow(n, k // 2, p) ** 2
return tmp % p if k % 2 == 0 else tmp * n % p |
def rescale(start, stop, length_sequence):
"""Rescales negative strand start-stop positions to positive strand indexing"""
rescaled_start = length_sequence - stop - 1
rescaled_stop = length_sequence - start - 1
return(rescaled_start, rescaled_stop) |
def basic_detokenizer(words):
""" This is the basic detokenizer helps us to resolves the issues we created by our tokenizer"""
detokenize_sentence =[]
pos = 0
while( pos < len(words)):
if words[pos] in '-/.' and pos > 0 and pos < len(words) - 1:
left = detokenize_sentence.pop()
detokenize_sentence.append(left +''.join(words[pos:pos + 2]))
pos +=1
elif words[pos] in '[(' and pos < len(words) - 1:
detokenize_sentence.append(''.join(words[pos:pos + 2]))
pos +=1
elif words[pos] in ']).,:!?;' and pos > 0:
left = detokenize_sentence.pop()
detokenize_sentence.append(left + ''.join(words[pos:pos + 1]))
else:
detokenize_sentence.append(words[pos])
pos +=1
return ' '.join(detokenize_sentence) |
def mu(alpha, beta):
"""The mean of the Beta distribution."""
return alpha / (alpha + beta) |
def add_predecessor(predecessor_list, xml_data_list, output_xml):
"""
Check if input lists is not empty, write in xml for each list and return update list if some
updates has been made
Parameters:
predecessor_list ([Data, Data(predecessor)]) : Data object to set new predessor and
predecessor Data
xml_data_list ([Data]) : Data list from xml parsing
output_xml (GenerateXML object) : XML's file object
Returns:
update_list ([0/1]) : Add 1 to list if any update, otherwise 0 is added
"""
if not predecessor_list:
return 0
output_xml.write_predecessor(predecessor_list)
# Warn the user once added within xml
for data_predecessor in predecessor_list:
for d in xml_data_list:
if data_predecessor[0].id == d.id:
d.add_predecessor(data_predecessor[1])
print(f"{data_predecessor[1].name} predecessor for "
f"{data_predecessor[0].name}")
return 1 |
def add_labels_to_predictions_strict(preds, golds, strict=True):
"""
Returns predictions and missed gold annotations with
a "label" key, which can take one of "TP", "FP", or "FN".
"""
pred_spans = {(s["start"], s["end"]) for s in preds}
gold_spans = {(s["start"], s["end"]) for s in golds}
outspans = []
for pred in preds:
pred_span = (pred["start"], pred["end"])
if pred_span in gold_spans:
label = "TP"
else:
label = "FP"
pred_copy = dict(pred)
pred_copy["label"] = label
outspans.append(pred_copy)
for gold in golds:
if (gold["start"], gold["end"]) not in pred_spans:
gold_copy = dict(gold)
gold_copy["label"] = "FN"
outspans.append(gold_copy)
return sorted(outspans, key=lambda s: s["start"]) |
def bucket_sort(arr, k):
"""
Based on Data Structures and Algorithms in Python
This can't handle decimals
:param arr: Sequence of integer keys
:param k: an integer such that all keys are in the range [0, k-1]
:return: arr in sorted order
"""
output = [] # n space O(n)
# this operation dominated by k O(k), O(k) space and time
buckets = [[] for _ in range(k)] # let B be an array of k sequences (acting as queues)
for key in arr: # O(n) time
buckets[key].append(key)
for bucket in buckets: # O(k) time
for element in bucket: # if elements distributed well, then constant?
output.append(element) # else worst case everything is in one bucket O(n)
print(buckets)
return output |
def isPrefixOf(xs, ys):
"""
isPrefixOf :: Eq a => [a] -> [a] -> Bool
The isPrefixOf function takes two lists and returns True iff the first list
is a prefix of the second.
"""
return xs == ys[:len(xs)] |
def serialize_dimensions(dims):
"""
>>> serialize_dimensions({})
""
>>> serialize_dimensions({'time': 'foo', 'eleveation': '100m'})
"elevation=100m,time=foo"
"""
if not dims:
return ""
return ','.join(k + '=' + dims[k] for k in sorted(dims.keys())) |
def _validate_condition(password, fn, min_count):
"""
Validates the password using the given function. This is performed by
iterating through each character in the password and counting up the number
of characters that satisfy the function.
Parameters:
password (str): the password
fn: the function to be tested against the string.
min_count (int): the minimum number of characters that must satisfy the function
Return:
True if valid_count >= min_count, else False
"""
valid_count = len([c for c in password if fn(c)])
return valid_count >= min_count |
def CleanUpUserInput(mask):
"""Removes spaces from a field mask provided by user."""
return mask.replace(" ", "") |
def to_left(d):
"""return direction as vector, rotated 90 degrees left"""
return -d[1], d[0] |
def merge_street_address(*address_vals):
"""Merge the different pieces of a street address into a single, space-separated string.
Returns
-------
str
The merged address
"""
valid_vals = [str(c).strip() for c in address_vals if str(c) not in ("nan", "None")]
return " ".join(valid_vals) |
def _extract_prop_set(line):
"""
Extract the (key, value)-tuple from a string like:
>>> 'set foo = "bar"'
:param line:
:return: tuple (key, value)
"""
token = ' = "'
line = line[4:]
pos = line.find(token)
return line[:pos], line[pos + 4:-1] |
def slice_params(axis, factor):
"""Get the start and stop indices to slice a dimension of size `axis` into
a multiple of `factor`, keeping it centered."""
new_size = (axis // factor) * factor
start = (axis - new_size) // 2
end = axis - (axis - new_size - start)
return start, end |
def make_interval_weight(num_intervals):
""" Used to calculate loss event rate. """
return [
(1 if i < num_intervals / 2 else
2 * (num_intervals - i) / (num_intervals + 2))
for i in range(num_intervals)] |
def make_pin_name(port, index):
"""
Formats a pin name of a multi-bit port
"""
return "{}_b{}".format(port, index) |
def irc_split(buf):
"""
Split a protocol line into tokens (without decoding or interpreting).
"""
buf = buf.rstrip(b"\r\n").split(b" ")
i, n = 0, len(buf)
parv = []
# Skip leading whitespace
while i < n and buf[i] == b"":
i += 1
# Get @tags if present
if i < n and buf[i].startswith(b"@"):
parv.append(buf[i])
i += 1
while i < n and buf[i] == b"":
i += 1
# Get :prefix if present
if i + 1 < n and buf[i].startswith(b":"):
parv.append(buf[i])
i += 1
while i < n and buf[i] == b"":
i += 1
# Get parameters until :trailing
while i < n:
if buf[i].startswith(b":"):
break
elif buf[i] != b"":
parv.append(buf[i])
i += 1
# Get trailing parameter
if i < n:
trailing = b" ".join(buf[i:])
parv.append(trailing[1:])
return parv |
def make_slack_msg(target_list, player_list):
"""Emit a message suitable for posting to the assassing slack channel."""
msg = '\n'.join(["This week's assassins and targets are assigned, and emails have been sent.",
'The roster is:',
'*Targets*: "{}"',
'*Players*: "{}"',
'*GAME ON*'])
return msg.format(', '.join(target_list), ', '.join(player_list)) |
def all_equal(iterable):
"""Return True if all elements of iterable are equal.
iterable must contain at least one element.
>>> all_equal([1, 1.0])
True
>>> all_equal([1, 2])
False
"""
iterator = iter(iterable)
first = next(iterator)
for element in iterator:
if element != first:
return False
return True |
def merge_dicts(x, y):
""" Merge two dicts together, returns a new dict """
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z |
def validate_extended(mwtabfile, data_section_key):
"""Validate ``EXTENDED_MS_METABOLITE_DATA``, ``EXTENDED_NMR_METABOLITE_DATA``, and ``EXTENDED_NMR_BINNED_DATA`` sections.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile` or
:py:class:`collections.OrderedDict`
:param data_section_key: Section key (either MS_METABOLITE_DATA, NMR_METABOLITE_DATA, or NMR_BINNED_DATA)
:type data_section_key: :py:class:`str`
"""
extended_errors = list()
sample_id_set = {subject_sample_factor["Sample ID"] for subject_sample_factor in
mwtabfile["SUBJECT_SAMPLE_FACTORS"]}
for index, extended_data in enumerate(mwtabfile[data_section_key]["Extended"]):
if "sample_id" not in extended_data.keys():
extended_errors.append("EXTENDED_{}: Data entry #{} missing Sample ID.".format(data_section_key, index + 1))
elif not extended_data["sample_id"] in sample_id_set:
extended_errors.append(
"EXTENDED_{}: Data entry #{} contains Sample ID \"{}\" not found in SUBJECT_SAMPLE_FACTORS section.".format(
data_section_key, index + 1, extended_data["sample_id"]
))
return extended_errors |
def _insert(lst: list, i: int) -> None:
""" Move L[i] to where it belongs in L[i + 1]
Precondition: L[:i] is sorted from smallest to largest.
>>> L = [7, 3, 5, 2]
>>> _insert(L, 1)
>>> L
[3, 7, 5, 2]
"""
# The value to be inserted into the sorted part of the list
value = lst[i]
# Find the index, j, where the value belongs.
# Make room for the value by shifting
while i > 0 and lst[i - 1] > value:
# Shift L[j - 1] one position to the right
lst[i] = lst[i - 1]
i -= 1
# Put the value where it belongs
lst[i] = value
return None
# Alternative version
# j = i
# while j != 0 and lst[j - 1] > value:
# Shift L[j - 1] one position to the right
# lst[j] = lst[j - 1]
# j -= 1
# Put the value where it belongs
# lst[j] = value
# return None |
def _exclusions_1_3(bonds_mol):
"""
Based on the information inside bonds_mol determine the 1-3 exclusions
ToDo: write a non-naive version of this
"""
angles_mol = []
for idx, i in enumerate(bonds_mol):
a, b = i
for j in bonds_mol[idx + 1:]:
c, d = j
if (a == c and b != d):
angles_mol.append((b, d))
elif (a == d and b != c):
angles_mol.append((b, c))
elif b == c and d != a:
angles_mol.append((a, d))
elif b == d and c != a:
angles_mol.append((a, c))
exclusions = bonds_mol + angles_mol
return set([tuple(sorted(i)) for i in exclusions]) |
def get_media_urls_from_list(tweets,limit):
"""
Returns the set of media URLs from a list of tweets
"""
cnt = 0
media_files = set()
for status in tweets:
media = status.entities.get('media',[])
if (len(media) > 0): # each status may have multiple
for i in range (0, len(media)):
if (media[i]['type'] == 'photo'):
media_files.add(media[i]['media_url'])
cnt = cnt + 1
print (len(media_files))
if (limit != -1 and cnt >= limit): return media_files
return media_files |
def normalize(value, value_min, value_max):
"""Map value from [value_min, value_max] to [-1, 1]"""
return 2 * ((value - value_min) / (value_max - value_min)) - 1 |
def clean_value(value):
"""
Clean the value; if N/A or empty
:param value: original value
:return: cleaned value
"""
if value:
value = value.strip()
if value.lower() == 'n/a':
value = None
if value == '':
value = None
return value |
def getMeasureString(measureName, value):
"""Returns the string represenation of one measure with its value."""
return "measure{\n key: \"" + measureName + "\"\n value: \"" + str(value) + "\"\n}" |
def get_uid_cidx(img_name):
"""
:param img_name: format output_path / f'{uid} cam{cidx} rgb.png'
"""
img_name = img_name.split("/")[-1]
assert img_name[-8:] == " rgb.png"
img_name = img_name[:-8]
import re
m = re.search(r'\d+$', img_name)
assert not m is None
cidx = int(m.group())
img_name = img_name[:-len(str(cidx))]
assert img_name[-4:] == " cam"
uid = img_name[0:-4]
return uid, cidx |
def prepare_droid_list(device):
"""
Convert single devices to a list, if necessary.
:param device: Device to check.
:type device: str
"""
if isinstance(device, list):
devs = device
else:
devs = [device]
return devs |
def is_valid_event(event):
"""
Check the validation of the s3 event.
"""
s3_bucket_name = event["s3"]["bucket"]["name"]
if s3_bucket_name:
return True
else:
return False |
def str_list(pyList, interface):
"""
method str_list
Return a string containing the str( ) of the items in the given pyList
Arguments:
pyList - python list to be converted to string
"""
new_str = ""
for list_item in pyList:
new_str += str(list_item.__repr__(interface))
return new_str |
def replace_with_flag(locale):
"""The filter replaces the locale with the CSS flag classes of the flag-icon-css library."""
locale = locale.replace('-', '_').lower().rsplit('_', maxsplit=1)
if len(locale) == 2:
return f'flag-icon flag-icon-{locale[-1]}'
return '' |
def rsa_compare_keys(a, b):
"""
Compares the base64 encoded DER structure of the keys
"""
# Filter removes possible empty lines.
# We then slice away header and footer.
a_b64 = "".join(list(filter(None, a.splitlines()))[1:-1])
b_b64 = "".join(list(filter(None, b.splitlines()))[1:-1])
return a_b64 == b_b64 |
def __get_key(peak1, peak2):
"""Generates a "key" from two peaks.
Parameters
----------
peak1, peak2 : List[Tuple[int, int]]
The two peaks to generate a key from, where each peak is
given by Tuple[<time>, <freq>]. Assumes `peak2` occurs concurrently or
after `peak1`.
Returns
-------
key : Tuple[int, int, int]
`key` is given by Tuple[<freq_i>, <freq_n>, <dt>]
"""
return peak1[1], peak2[1], peak2[0] - peak1[0] |
def clamp(test, lower, upper):
"""Force a number to be within a given range, with minimal efficiency."""
return max(lower, min(upper, test)) |
def add_multi_amounts(ma1,ma2):
"""
Add two multi amounts.
"""
# Union all possible currencies:
currencies = set(ma1.keys())
currencies.update(set(ma2.keys()))
# Initialize resulting multi amount:
ma = {}
# Initialize all currencies to be 0:
for c in currencies:
ma[c] = 0
# Add currencies from both multi amounts:
for c in currencies:
if c in ma1:
ma[c] += ma1[c]
if c in ma2:
ma[c] += ma2[c]
return ma |
def per_shortest(total, x, y):
"""Divides total by min(len(x), len(y)).
Useful for normalizing per-item results from sequences that are zipped
together. Always returns 0 if one of the sequences is empty (to
avoid divide by zero error).
"""
shortest = min(len(x), len(y))
if not shortest:
return 0
else:
return total / shortest |
def ffs(n):
"""find first set bit in a 32-bit number"""
r = 0
while r < 32:
if (1<<r)&n:
return r
r = r+1
return -1 |
def add_to_tuple(var, *args, **kw):
"""
Append new items inside a tuple.
This utility method should be used to modify settings tuples and lists.
Features:
* Avoid duplicates by checking whether the items are already there;
* Add many items at once;
* Allow to add the items before some other items, when order is important
(by default it appends). If the before item does not exist, just insert
the value at the end;
Example:
INSTALLED_APPS = add_to_tuple(INSTALLED_APPS, 'foo')
INSTALLED_APPS = add_to_tuple(INSTALLED_APPS, 'foo', 'bar')
INSTALLED_APPS = add_to_tuple(INSTALLED_APPS, 'first' before='second')
INSTALLED_APPS = add_to_tuple(INSTALLED_APPS, 'second', after='first')
"""
before = kw.get('before')
after = kw.get('after')
var = list(var)
for arg in args:
if arg not in var:
if before and before in var:
var.insert(var.index(before), arg)
elif after and after in var:
var.insert(var.index(after)+1, arg)
else:
var.append(arg)
return tuple(var) |
def lift_list(input_list):
"""
List of nested lists becomes a list with the element exposed in the main list.
:param input_list: a list of lists.
:return: eliminates the first nesting levels of lists.
E.G.
>> lift_list([1, 2, [1,2,3], [1,2], [4,5, 6], [3,4]])
[1, 2, 1, 2, 3, 1, 2, 4, 5, 6, 3, 4]
"""
if input_list == []:
return []
else:
return lift_list(input_list[0]) + (lift_list(input_list[1:]) if len(input_list) > 1 else []) \
if type(input_list) is list else [input_list] |
def rational_function(X):
"""
Benchmark rational function f(x) = x/(x + 1)*2
"""
return X/((X+1)**2) |
def str_skip_bytes(s, dels):
"""
"""
if not dels:
return s
return ''.join(c for i, c in enumerate(s) if i not in dels) |
def oraclechr_encode(encvalue):
""" Oracle chr encode the specified value. """
charstring = ""
for item in encvalue:
val = "chr(" + str(ord(item)) + ")||"
charstring += val
return(charstring.rstrip("||")) |
def insertion_sort(l, r):
"""
Sorts a list using Insertion Sort Algorithm
"""
k = 0
l = l.copy()
for i in range(1, r, 1):
k = l[i]
j = i - 1
while j >= 0 and k < l[j]:
l[j + 1] = l[j]
j -= 1
l[j + 1] = k
return l |
def severity_to_level(severity):
"""
Maps severity to a level represented by number.
"""
if severity == 'Informational':
return 0.5
elif severity == 'Low':
return 1
elif severity == 'Medium':
return 2
elif severity == 'High':
return 3
return 0 |
def sort_addresstuple(cube_dimensions, unsorted_addresstuple):
""" Sort the given mixed up addresstuple
:param cube_dimensions: list of dimension names in correct order
:param unsorted_addresstuple: list of Strings - ['[dim2].[elem4]','[dim1].[elem2]',...]
:return:
Tuple: ('[dim1].[elem2]','[dim2].[elem4]',...)
"""
sorted_addresstupple = []
for dimension in cube_dimensions:
# could be more than one hierarchy!
address_elements = [item for item in unsorted_addresstuple if item.startswith('[' + dimension + '].')]
# address_elements could be ( [dim1].[hier1].[elem1], [dim1].[hier2].[elem3] )
for address_element in address_elements:
sorted_addresstupple.append(address_element)
return tuple(sorted_addresstupple) |
def extract_id(argument: str, strict: bool=True):
"""Extract id from argument."""
"""
Parameters
----------
argument: str
text to parse
Returns
----------
str
the bare id
"""
ex = ''.join(list(filter(str.isdigit, str(argument))))
if strict:
if len(ex) < 15:
return None
return ex |
def is_quoted_identifier(identifier, sql_mode=""):
"""Check if the given identifier is quoted.
Args:
identifier (string): Identifier to check.
sql_mode (Optional[string]): SQL mode.
Returns:
`True` if the identifier has backtick quotes, and False otherwise.
"""
if "ANSI_QUOTES" in sql_mode:
return ((identifier[0] == "`" and identifier[-1] == "`") or
(identifier[0] == '"' and identifier[-1] == '"'))
else:
return identifier[0] == "`" and identifier[-1] == "`" |
def bases_overlap(frst, scnd):
"""
Get the number of overlapping bases.
:param frst: a tuple representing the first region
with chromosome, start, end as the first
3 columns
:param scnd: a tuple representing the second region
with chromosome, start, end as the first
3 columns
:return: the number of overlapping bases
"""
if frst[0] != scnd[0]:
return 0
rstart = max(frst[1], scnd[1])
rend = min(frst[2], scnd[2])
if rend < rstart:
return 0
return rend - rstart |
def _EvaluateCondition(condition):
"""Evaluates |condition| using eval().
Args:
condition: A condition string.
Returns:
The result of the evaluated condition.
"""
return eval(condition, {'__builtins__': {'False': False, 'True': True}}) |
def prep_carrier_query(npc, device, upg, forced):
"""
Prepare carrier query XML.
:param npc: MCC + MNC (see `func:return_npc`)
:type npc: int
:param device: Hexadecimal hardware ID.
:type device: str
:param upg: "upgrade" or "repair".
:type upg: str
:param forced: Force a software release.
:type forced: str
"""
query = '<?xml version="1.0" encoding="UTF-8"?><updateDetailRequest version="2.2.1" authEchoTS="1366644680359"><clientProperties><hardware><pin>0x2FFFFFB3</pin><bsn>1128121361</bsn><imei>004401139269240</imei><id>0x{0}</id></hardware><network><homeNPC>0x{1}</homeNPC><iccid>89014104255505565333</iccid></network><software><currentLocale>en_US</currentLocale><legalLocale>en_US</legalLocale></software></clientProperties><updateDirectives><allowPatching type="REDBEND">true</allowPatching><upgradeMode>{2}</upgradeMode><provideDescriptions>false</provideDescriptions><provideFiles>true</provideFiles><queryType>NOTIFICATION_CHECK</queryType></updateDirectives><pollType>manual</pollType><resultPackageSetCriteria><softwareRelease softwareReleaseVersion="{3}" /><releaseIndependent><packageType operation="include">application</packageType></releaseIndependent></resultPackageSetCriteria></updateDetailRequest>'.format(device, npc, upg, forced)
return query |
def parsesplittedproperty(property, separator=';'):
"""
:param property
:return: a list single properties, possibly empty
"""
properties = []
if property and len(property) > 0:
for splittedproperty in property.split(separator):
properties.append(splittedproperty.strip())
return properties |
def fuzzbuzz(num):
"""
>>> fuzzbuzz(4)
4
>>> fuzzbuzz(3)
'fuzz'
>>> fuzzbuzz(5)
'buzz'
>>> fuzzbuzz(9)
'fuzz'
>>> fuzzbuzz(10)
'buzz'
>>> fuzzbuzz(15)
'fuzzbuzz'
"""
if num % 3 == 0 and num % 5 == 0:
return 'fuzzbuzz'
elif num % 3 == 0:
return 'fuzz'
elif num % 5 == 0:
return 'buzz'
return num |
def index_of_first_negative(numbers):
"""
What comes in:
-- a sequence of numbers
What goes out: Returns the INDEX of the first negative number
in the given sequence of numbers, or -1 if the sequence
contains no negative numbers.
Note: "first" negative number means the negative number
whose index is smallest -- see the examples.
Side effects: None.
Examples: If the argument is:
-- [4, 30, -19, 8, -3, -50, 100], this function returns 2
since the first negative number is -19, which is at index 2
-- [-8, 44, 33], this function returns 0
since the first negative number is -8, which is at index 0
-- [1, 29, 22, 8], this function returns -1
since the list contains no negative numbers
Type hints:
:type numbers: list | tuple of float | int
:rtype: int
"""
for k in range(len(numbers)):
if numbers[k] < 0:
return k
return -1
# -------------------------------------------------------------------------
# DONE: 4. Implement and test this function.
# The testing code is already written for you (above).
# If you have questions about the testing code, ask for help.
# ------------------------------------------------------------------------- |
def _get_received_for(received_header):
"""
Helper function to grab the 'for' part of a Received email header
WARNING: If 'for' is not there, the entire Received header is returned.
"""
received_header = received_header.replace('\r', '').replace('\n', '')
info = received_header.split('for ')
try:
return info[-1].split(';')[0]
except:
return '' |
def check_coarse_pipeline(msgs):
# type: (str) -> bool
"""
Check if coarse pipeline is enabled as expected
"""
for msg in msgs:
if msg.find('\"coarse_grained_pipeline": \"off') != -1:
return False
return True |
def all_subclasses(cls):
"""Returns a set of all the subclasses of the given class"""
subs = cls.__subclasses__()
return set(subs).union([s for c in subs for s in all_subclasses(c)]) |
def reverse_integer(integer):
""" runtime complexity of this algorithm is O(n) """
reversed = 0
# Pop the last digit of the integer after each iteration
# Then update the value of the integer
while integer > 0 :
remainder = integer % 10
reversed = reversed*10 + remainder
integer = integer // 10
return reversed |
def intro(word, attempt_left):
"""
:param word: str, the word randomly selected from our word bank.
:param attempt_left: int, the guessing attempts left for players, before guessing.
:return: str, number of alphabets in the given words, presented in '-'
"""
ans = ''
for i in range(len(word)):
ans += '-'
print('The word looks like: ' + ans)
print('You have ' + str(attempt_left) + ' guess left.')
return ans |
def update_output_frame_video_rate_metric(ml_output_names):
"""Update the metrics of the "Output Video Frame Rate (avg)" dashboard dashboard widget"""
result = []
for output in ml_output_names:
if output["Pipeline"] == "0":
entry = ["MediaLive", "OutputVideoFrameRate", "ChannelId", output["ChannelId"], "OutputName",
output["OutputName"], "Pipeline", "0"]
result.append(entry)
elif output["Pipeline"] == "1":
entry = ["MediaLive", "OutputVideoFrameRate", "ChannelId", output["ChannelId"], "OutputName",
output["OutputName"], "Pipeline", "1", {"yAxis": "right"}]
result.append(entry)
return result |
def ordinal(n):
"""Return the ordinal for an int, eg 1st, 2nd, 3rd. From user Gareth on
codegolf.stackexchange.com """
suffixes = {1: "st", 2: "nd", 3: "rd"}
return str(n) + suffixes.get(n % 10 * (n % 100 not in [11, 12, 13]), "th") |
def sphinx_lang(env, default_value='en'):
"""
Returns the language defined in the configuration file.
@param env environment
@param default_value default value
@return language
"""
if hasattr(env, "settings"):
settings = env.settings
if hasattr(settings, "language_code"):
lang = env.settings.language_code # pragma: no cover
else:
lang = "en"
else:
settings = None # pragma: no cover
lang = "en" # pragma: no cover
return lang |
def leastSignificant(sum, base):
"""Takes the sum and returns only the one's place of its value in the chosen base."""
return (sum % base) |
def cleanup_functions(instructions):
"""Remove functions that are not called"""
# This is an iterative processor. Once a function is removed,
# there may be more unused functions
while True:
# find function calls
live_functions = {}
for instruction in instructions:
if instruction["op"] == "call":
if instruction["label"].startswith("function"):
live_functions[instruction["label"]] = None
# remove instructions without function calls
kept_instructions = []
generate_on = True
for instruction in instructions:
if instruction["op"] == "label":
if instruction["label"].startswith("function"):
if instruction["label"] in live_functions:
generate_on = True
else:
generate_on = False
if generate_on:
kept_instructions.append(instruction)
if len(instructions) == len(kept_instructions):
return kept_instructions
instructions = kept_instructions |
def until(p, f, a):
"""
until :: (a -> Bool) -> (a -> a) -> a -> a
until(p, f, a) yields the result of applying f until p(a) holds.
"""
while not p(a):
a = f(a)
return a |
def plugin_send(raw_data, stream_id):
""" Empty translator """
data_sent = ()
new_position = 0
num_sent = 0
return data_sent, new_position, num_sent |
def common_elem(start, stop, common, solution):
"""
Return the list of common elements between the sublists.
Parameters:
start -- integer
stop -- integer
common -- list of Decimal
solution -- list of Decimal
Return:
sub -- list of Decimal
"""
sub = [elem for elem in common[start:stop] if elem in solution[start:stop]]
return sub |
def find(word, letter, start):
"""Modify find so that it has a third parameter, the index in word where it should start looking."""
if start > len(word):
return -1
index = start
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1 |
def _el_orb_tuple(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (`str`): The selected elements and orbitals in in the form:
`"Sn.s.p,O"`.
Returns:
A list of tuples specifying which elements/orbitals to plot. The output
for the above example would be:
`[('Sn', ('s', 'p')), 'O']`
"""
el_orbs = []
for split in string.split(','):
splits = split.split('.')
el = splits[0]
if len(splits) == 1:
el_orbs.append(el)
else:
el_orbs.append((el, tuple(splits[1:])))
return el_orbs |
def get_value_or_list(current_value, additional_value):
"""
Add a new value to another existing value/s. If a value doesn't exist it returns the new value otherwise
returns a list with the existing value/s and the new value.
:param current_value: the current value
:param additional_value: the new value
:return: a single value or a list
"""
if current_value:
if isinstance(current_value, list):
return current_value + [additional_value]
else:
return [current_value, additional_value]
else:
return additional_value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.