content
stringlengths 42
6.51k
|
---|
def _ev_charge_level_supported(data):
"""Determine if charge level is supported."""
return (
data["isElectric"]
and data["evStatus"]["chargeInfo"]["batteryLevelPercentage"] is not None
)
|
def genomic_del5_abs_37(genomic_del5_37_loc):
"""Create test fixture absolute copy number variation"""
return {
"type": "AbsoluteCopyNumber",
"_id": "ga4gh:VAC.9zhlg8DRSsE87N5SngYrMDWXStzp_WOX",
"subject": genomic_del5_37_loc,
"copies": {"type": "Number", "value": 2}
}
|
def _is_prefixed(cmd_line):
"""Whether the supplied command line has already been prefixed
with an OS specific operation.
"""
if cmd_line is None:
raise ValueError("CommandLine is required field for task.")
return cmd_line.startswith('cmd.exe /c') or \
cmd_line.startswith('cmd /c') or \
cmd_line.startswith('/bin/bash -c') or \
cmd_line.startswith('/bin/sh -c')
|
def microseconds(h, m, s, f):
"""
Returns an integer representing a number of microseconds
:rtype: int
"""
return (int(h) * 3600 + int(m) * 60 + int(s)) * 1000000 + int(f) * 1000
|
def is_proper_csd(csd_num):
""" Check we've a valid CSD number
Returns false if the array contains consequitive non-zero terms.
"""
for i in range(1, len(csd_num)):
if csd_num[i] != '0' and csd_num[i - 1] != '0':
return False
return True
|
def as_formatted_lines(lines):
"""
Return a text formatted for use in a Debian control file with proper
continuation for multilines.
"""
if not lines:
return ''
formatted = []
for line in lines:
stripped = line.strip()
if stripped:
formatted.append(' ' + line)
else:
formatted.append(' .')
return '\n'.join(formatted).strip()
|
def dp_fib_ls(n: int):
"""A dynamic programming version of Fibonacci, linear space"""
res = [0, 1]
for i in range(2, n+1):
res.append(res[i-2] + res[i-1])
return res[n]
|
def recode_dose(dose_value):
"""This function recode the doses in Level-4 data to 8 distinct dose classes"""
doses = [0.04,0.12,0.37,1.11,3.33,10.0,20.0,25.0]
for x in range(len(doses)-1):
if (dose_value > 0.0) & (dose_value <= 0.04):
dose_value = 0.04
elif doses[x] <= round(dose_value,2) < doses[x+1]:
dose_value = doses[x]
return dose_value
|
def asList(x):
""" Convert a variable to a list.
:param x: an object that you would like to convert to a list. Will raise an
exception if it is iterable but not already a tuple or list.
"""
if isinstance(x, list):
return x
elif isinstance(x, tuple):
return list(x)
elif not hasattr(x, '__iter__'):
return [x, ]
else:
raise ValueError('Could not convert {} to a list'.format(str(x)))
|
def shl(x, n):
"""Shift left n bits (zeros come in from the right)
>>> shl(0.5, 1)
1.0
>>> shl(0.1, 1)
0.2
"""
return x * 2 ** n
|
def ellipsis_after(text, length):
""" Truncates text and adds ellipses at the end. Does not truncate words in the middle. """
if not text or len(text) <= length:
return text
else:
return text[:length].rsplit(' ', 1)[0]+u"\u2026"
|
def distance(point1, point2):
""" calc distance between two 3d points """
return ((point1[0] - point2[0]) ** 2 +
(point1[1] - point2[1]) ** 2 +
(point1[2] - point2[2]) ** 2) ** 0.5
|
def list_ins_pkg(args_array, yum, **kwargs):
"""Function: list_ins_pkg
Description: This is a function stub for package_admin.list_ins_pkg.
Arguments:
args_array
yum
"""
status = (True, None)
class_cfg = kwargs.get("class_cfg", None)
if args_array and yum and class_cfg:
status = (True, None)
return status
|
def get_all_indices(element, alist):
"""
Find the index of an element in a list. The element can appear multiple times.
input: alist - a list
element - objective element
output: index of the element in the list
"""
result = []
offset = -1
while True:
try:
offset = alist.index(element, offset + 1)
except ValueError:
return result
result.append(offset)
|
def neg(element: str) -> str:
"""Negate a single element"""
return element[1:] if element.startswith("~") else "~" + element
|
def make_car(manufactory, type, **car_info):
"""Car informations"""
car_info = {}
car_info['car_manufactory'] = manufactory
car_info['car_type'] = type
for key, value in car_info.items():
car_info[key] = value
return car_info
|
def justTfandDf(terms):
""" Format the stats for each term into a compact tuple"""
tfAndDf = {}
for term, value in terms.items():
tfAndDf[term] = (value['term_freq'], value['doc_freq'])
return tfAndDf
|
def get_generic_bases(tp):
"""Get generic base types of a type or empty tuple if not possible.
"""
org = getattr(tp, '__origin__', None)
if org:
a = (org,)
else:
a = ()
return a + getattr(tp, "__orig_bases__", ())
|
def _flatten_state(state):
"""Reduce nested object to string."""
if isinstance(state, list):
return ",".join(map(_flatten_state, state))
elif isinstance(state, dict):
return ",".join(map(lambda x: ":".join(map(_flatten_state, x)), state.items()))
return str(state)
|
def format_multipart(props):
""" Flatten lists to fit the requrests multipart form data format """
ret = []
for k, v in props.items():
if type(v) == list:
for item in v:
ret.append((k, item))
else:
ret.append((k, v))
return tuple(ret)
|
def get_response_code(key):
"""
Translates numerical key into the string value for dns response code.
:param key: Numerical value to be translated
:return: Translated response code
"""
return {
0: 'NoError', 1: 'FormErr', 2: 'ServFail', 3: 'NXDomain', 4: 'NotImp', 5: 'Refused', 6: 'YXDomain',
7: 'YXRRSet', 8: 'NXRRSet', 9: 'NotAuth', 10: 'NotZone', 11: 'BADVERS', 12: 'BADSIG', 13: 'BADKEY',
14: 'BADTIME'
}.get(key, 'Other')
|
def epsilon(current_episode, num_episodes):
"""
epsilon decays as the current episode gets higher because we want the agent to
explore more in earlier episodes (when it hasn't learned anything)
explore less in later episodes (when it has learned something)
i.e. assume that episode number is directly related to learning
"""
# return 1 - (current_episode/num_episodes)
return .5 * .9**current_episode
|
def loudness_normalize(sources_list, gain_list):
"""Normalize sources loudness."""
# Create the list of normalized sources
normalized_list = []
for i, source in enumerate(sources_list):
normalized_list.append(source * gain_list[i])
return normalized_list
|
def adjust_release_version(release_name):
"""
Adjust release_name to match the build version from the executable.
executable: 1.8.0_212-b04 release_name: jdk8u212-b04
executable: 11.0.3+7 release_name: jdk-11.0.3+7
executable: 12.0.1+12 release_name: jdk-12.0.1+12
"""
if release_name.startswith('jdk8u'):
return release_name.replace('jdk8u', '1.8.0_')
else:
return release_name[4:]
|
def parse_type_encoding(encoding):
"""Takes a type encoding string and outputs a list of the separated type codes.
Currently does not handle unions or bitfields and strips out any field width
specifiers or type specifiers from the encoding. For Python 3.2+, encoding is
assumed to be a bytes object and not unicode.
Examples:
parse_type_encoding('^v16@0:8') --> ['^v', '@', ':']
parse_type_encoding('{CGSize=dd}40@0:8{CGSize=dd}16Q32') --> ['{CGSize=dd}', '@', ':', '{CGSize=dd}', 'Q']
"""
type_encodings = []
brace_count = 0 # number of unclosed curly braces
bracket_count = 0 # number of unclosed square brackets
typecode = b''
for c in encoding:
# In Python 3, c comes out as an integer in the range 0-255. In Python 2, c is a single character string.
# To fix the disparity, we convert c to a bytes object if necessary.
if isinstance(c, int):
c = bytes([c])
if c == b'{':
# Check if this marked the end of previous type code.
if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0:
type_encodings.append(typecode)
typecode = b''
typecode += c
brace_count += 1
elif c == b'}':
typecode += c
brace_count -= 1
assert(brace_count >= 0)
elif c == b'[':
# Check if this marked the end of previous type code.
if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0:
type_encodings.append(typecode)
typecode = b''
typecode += c
bracket_count += 1
elif c == b']':
typecode += c
bracket_count -= 1
assert(bracket_count >= 0)
elif brace_count or bracket_count:
# Anything encountered while inside braces or brackets gets stuck on.
typecode += c
elif c in b'0123456789':
# Ignore field width specifiers for now.
pass
elif c in b'rnNoORV':
# Also ignore type specifiers.
pass
elif c in b'^cislqCISLQfdBv*@#:b?':
if typecode and typecode[-1:] == b'^':
# Previous char was pointer specifier, so keep going.
typecode += c
else:
# Add previous type code to the list.
if typecode:
type_encodings.append(typecode)
# Start a new type code.
typecode = c
# Add the last type code to the list
if typecode:
type_encodings.append(typecode)
return type_encodings
|
def remove_suffix(input_string, suffix):
"""
Simple function to remove suffix from input_string if available
"""
try:
input_string = input_string.strip()
if not input_string.endswith(suffix):
return input_string
return input_string[0 : input_string.rfind(suffix)]
except Exception:
return input_string
|
def isValidBST(root, low_range=float('-inf'), high_range=float('inf')):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
else:
print ("root: " + str(root.val))
print ("low_range: " + str(low_range))
print ("high_range: " + str(high_range))
if root.val <= low_range or root.val >= high_range:
print ("huh")
return False
else:
return isValidBST(root.left, low_range, root.val) and isValidBST(root.right, root.val, high_range)
|
def get_cellname (ch):
"""Return name of cell used to store character data"""
prefix = "font_"
if (ord(ch) < 0x100):
cellname = "{:02X}".format(ord(ch))
elif (ord(ch) < 0x10000):
cellname = "{:04X}".format(ord(ch))
elif (ord(ch) < 0x1000000):
cellname = "{:06X}".format(ord(ch))
else:
cellname = "{:X}".format(ord(ch))
return prefix+cellname
|
def rfile(node):
"""
Return the repository file for node if it has one. Otherwise return node
"""
if hasattr(node, "rfile"):
return node.rfile()
return node
|
def _mac_to_oid(mac):
"""Converts a six-byte hex form MAC address to six-byte decimal form.
For example:
00:1A:2B:3C:4D:5E converts to 0.26.43.60.77.94
Returns:
str, six-byte decimal form used in SNMP OIDs.
"""
fields = mac.split(':')
oid_fields = [str(int(v, 16)) for v in fields]
oid = '.'.join(oid_fields)
return oid
|
def attrmod(list):
"""Calculates modifiers for a list of attributes
Returns a list of modifiers"""
out = []
for i in list:
if i in [0,1]:
out.append(-3)
elif i == 2:
out.append(-2)
elif i == 3:
out.append(-1)
elif i in [4,5,6,7]:
out.append(0)
else:
out.append((i // 2)-3)
return(out)
|
def format_data(data, es_index):
"""
Format data for bulk indexing into elasticsearch
"""
unit = data["unit"]
rate_unit = data["rateUnit"]
egvs = data["egvs"]
docs = []
for record in egvs:
record["unit"] = unit
record["rate_unit"] = rate_unit
record["@timestamp"] = record.pop("systemTime")
record.pop("displayTime")
record["realtime_value"] = record.pop("realtimeValue")
record["smoothed_value"] = record.pop("smoothedValue")
record["trend_rate"] = record.pop("trendRate")
docs.append({"_index": es_index, "_type": "document", "_source": record})
return docs
|
def get_part_around(content, index):
"""
Gets the part of the given `content` around the given `index`.
Parameters
----------
content : `str`
The content, around what the part will be cut out.
index : `str`
The index of around where the part will be cut out.
"""
result = []
low_limit = index-25
if low_limit < 0:
low_limit = 0
elif low_limit > 0:
result.append('... ')
high_limit = index+25
if high_limit > len(content):
high_limit = len(content)
result.append(content[low_limit:high_limit])
if high_limit < len(content):
result.append(' ...')
return ''.join(result)
|
def u64i(i: int):
"""uint64 from integer"""
return f"{i:#0{18}x}"
|
def callsign_to_slot(callsign):
"""
Convert callsign to IBP schedule time slot (0 ... 17)
This is required for migration reason.
"""
return {
'4U1UN': 0,
'VE8AT': 1,
'W6WX': 2,
'KH6WO': 3,
'KH6RS': 3,
'ZL6B': 4,
'VK6RBP': 5,
'JA2IGY': 6,
'RR9O': 7,
'VR2B': 8,
'4S7B': 9,
'ZS6DN': 10,
'5Z4B': 11,
'4X6TU': 12,
'OH2B': 13,
'CS3B': 14,
'LU4AA': 15,
'OA4B': 16,
'YV5B': 17
}[callsign]
|
def DeepSupervision(criterion, xs, y): #y.shape = bs * seqlen
"""DeepSupervision
Applies criterion to each element in a list.
Args:
criterion: loss function
xs: tuple of inputs
y: ground truth
"""
loss = 0.
for x in xs:
loss += criterion(x, y)
loss /= len(xs)
return loss
|
def migrate_report_settings_from_1_to_2(data):
"""
Migrate scrum report template of version 1 to version 2
"""
migrated = dict()
template_data = data.get("template", []) or []
migrated_template = []
for item in template_data:
migrated_template.append(item.replace("${today}", "${date}"))
migrated["version"] = 2
migrated["questions"] = data.get("questions", []) or []
migrated["template"] = {"sections": [migrated_template]}
return migrated
|
def median(x):
"""
Returns the median of the elements of the iterable `x`.
If the number of elements in `x` is even, the arithmetic mean of the upper
and lower median values is returned.
>>> median([3, 7, 4])
4
>>> median([3, 7, 4, 45])
5.5
"""
s = sorted(x)
N = len(s)
if (N % 2) == 1:
return s[(N - 1) // 2]
else:
M = N // 2
return 0.5 * (s[M - 1] + s[M])
|
def is_intel_email(email):
"""Checks that email is valid Intel email"""
return email and len(email) > 10 and " " not in email and email.lower().endswith("@intel.com")
|
def divide_numbers(numerator, denominator):
"""For this exercise you can assume numerator and denominator are of type
int/str/float.
Try to convert numerator and denominator to int types, if that raises a
ValueError reraise it. Following do the division and return the result.
However if denominator is 0 catch the corresponding exception Python
throws (cannot divide by 0), and return 0"""
try:
numerator = int(numerator)
denominator = int(denominator)
except ValueError:
raise
try:
func = numerator / denominator
return func
except ZeroDivisionError:
return 0
|
def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z
|
def get_child_nodes_osd_tree(node_id, osd_tree):
"""
This function finds the children of a node from the 'ceph osd tree' and returns them as list
Args:
node_id (int): the id of the node for which the children to be retrieved
osd_tree (dict): dictionary containing the output of 'ceph osd tree'
Returns:
list: of 'children' of a given node_id
"""
for i in range(len(osd_tree["nodes"])):
if osd_tree["nodes"][i]["id"] == node_id:
return osd_tree["nodes"][i]["children"]
|
def get_background_css(rgb, widget="QWidget", editable=False):
"""Returns the string that contain CSS to set widget background to specified color"""
rgb = tuple(rgb)
if len(rgb) != 3:
raise ValueError(r"RGB must be represented by 3 elements: rgb = {rgb}")
if any([(_ > 255) or (_ < 0) for _ in rgb]):
raise ValueError(r"RGB values must be in the range 0..255: rgb={rgb}")
# Shaded widgets appear brighter, so the brightness needs to be reduced
shaded_widgets = ("QComboBox", "QPushButton")
if widget in shaded_widgets:
rgb = [max(int(255 - (255 - _) * 1.5), 0) for _ in rgb]
# Increase brightness of editable element
if editable:
rgb = [255 - int((255 - _) * 0.5) for _ in rgb]
color_css = f"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})"
return f"{widget} {{ background-color: {color_css}; }}"
|
def _to_j2kt_native_name(name):
"""Convert a label name used in j2cl to be used in j2kt native"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-native" % name
|
def luhn_checksum(check_number):
"""http://en.wikipedia.org/wiki/Luhn_algorithm ."""
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(check_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d * 2))
return checksum % 10
|
def higher_follower_count(A, B):
""" Compares follower count key between two dictionaries"""
if A['follower_count'] >= B['follower_count']: return "A"
return "B"
|
def yatch(dice):
"""
Score the dice based on rules for YACHT.
"""
points = 0
if dice.count(dice[0]) == len(dice):
points = 50
return points
|
def isoddv2(n):
"""
Is odd number - Another way
>>> isoddv2(5)
True
"""
return n & 1 == 1
|
def deldoubleword(data):
"""
Args:
list of strings
Output:
list of strings without repeated words ('no more more please' -> 'no
more please')
"""
data = [x.split() for x in data]
datalist = []
for sen in data:
sen2 = []
for i in range(len(sen)):
if sen[i-1] != sen[i]:
sen2.append(sen[i])
senstring = ''.join(x + ' ' for x in sen2).rstrip()
datalist.append(senstring)
return datalist
|
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str:
"""Strips the suffix from a string if present.
https://stackoverflow.com/a/1038999
Arguments:
text {str} -- String to check for suffix
suffix {str} -- Suffix to look for.
Keyword Arguments:
case_insensitive {bool} -- Do a case insensitive match. (default: {False})
Returns:
str -- Suffix to look for.
"""
if case_insensitive:
if not text.lower().endswith(suffix.lower()):
return text
else:
if not text.endswith(suffix):
return text
return text[: len(text) - len(suffix)]
|
def solution(X, Y, D):
"""Calculates minimum amount of jumps from X to Y with jumps of length D
:param X: Start position (int)
:param Y: Target position (int)
:param D: Jump length (int)
:returns: Min number of jumps
:rtype: Integer
"""
# write your code in Python 3.6
distance = Y - X
modulo = divmod(distance, D)
if modulo[1] == 0:
jumps = modulo[0]
else:
# If there is a remainder add one jump
jumps = modulo[0] + 1
return jumps
|
def get_version(raw):
"""
This will parse out the version string from the given list of lines. If no
version string can be found a ValueError will be raised.
"""
for line in raw:
if line.startswith("# MODULE:"):
_, version = line.split(":", 1)
return version.strip()
raise ValueError("Could not determine the version")
|
def info_to_name(display):
"""extract root value from display name
e.g. function(my_function) => my_function
"""
try:
return display.split("(")[1].rstrip(")")
except IndexError:
return ""
|
def url_from_args(year, month):
"""
Generate Donation log url from args
e.g. https://dons.wikimedia.fr/journal/2013-12
"""
return "https://dons.wikimedia.fr/journal/%04d-%02d" % (year, month)
|
def makepath(path):
"""
from [email protected] 2002/03/18
See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117243
"""
from os import makedirs
from os.path import normpath,dirname,exists,abspath
dpath = normpath(dirname(path))
if not exists(dpath): makedirs(dpath)
return normpath(abspath(path))
|
def reverse_list(l):
"""
return a list with the reverse order of l
"""
return l[::-1]
|
def normalize_empty_to_none(text):
"""Return verbatim a given string if it is not empty or None otherwise."""
return text if text != "" else None
|
def addMortonCondition(mortonRanges, mortonColumnName):
"""
Composes the predicate with the morton ranges.
"""
elements = []
for mortonRange in mortonRanges:
elements.append('(' + mortonColumnName + ' between ' + str(mortonRange[0]) + ' and ' + str(mortonRange[1]) + ')')
if len(elements) == 1:
return elements[0]
elif len(elements) > 1:
return '(' + ' OR '.join(elements) + ')'
return None
|
def isfib(number):
"""
Check if a number is in the Fibonacci sequence
number:
Number to check
"""
num1 = 1
num2 = 1
while True:
if num2 < number:
tempnum = num2
num2 += num1
num1 = tempnum
elif num2 == number:
return True
else:
return False
|
def median_s (sorted_seq) :
"""Return the median value of `sorted_seq`.
>>> median ([1, 2, 2, 3, 14])
2
>>> median ([1, 2, 2, 3, 3, 14])
2.5
"""
l = len (sorted_seq)
if l % 2 :
result = sorted_seq [l // 2]
else :
l -= 1
result = (sorted_seq [l // 2] + sorted_seq [l // 2 + 1]) / 2.0
return result
|
def emotion_mapping(emotions, dataset_emotions):
"""
Arguments: {"joy": 1, "sadness": 0.8}, ["joy", "sadness", "trust"]
Returns: {"joy": 1, "sadness": 0.8, "trust": 0, "disgust": None, ...}
"""
all_emotions = [
"joy",
"anger",
"sadness",
"disgust",
"fear",
"trust",
"surprise",
"love",
"noemo",
"confusion",
"anticipation",
] # ALL of them; 11ish
d = {emotion: None for emotion in all_emotions}
for emotion in all_emotions:
if emotion in dataset_emotions:
d[emotion] = emotions.get(emotion, 0)
return d
|
def c2f(c: float, r: int = 2) -> float:
"""Celsius to Fahrenheit."""
return round((c * 1.8) + 32, r)
|
def sentence_case(item: str) -> str:
"""Returns the string sentence-cased in an 05AB1E manner"""
ret = ""
capitalise = True
for char in item:
ret += (lambda: char.lower(), lambda: char.upper())[capitalise]()
if capitalise and char != " ":
capitalise = False
capitalise = capitalise or char in "!?."
return ret
|
def full_colour(problem):
"""
Update the problem by setting the cells that can be inferred from the
onstraint that each row and column must have the same number of cells of
each colour.
The cells dictionary is directly updated. Returns True if any changes have
been made, False otherwise.
"""
changes = False
size = problem['size']
cells_same_colour = size // 2
cells = problem['variables']
# See if each row already has all the required cells of one colour
for row in range(size):
reds = sum(1 for col in range(size) if cells[(row, col)] == 'r')
blues = sum(1 for col in range(size) if cells[(row, col)] == 'b')
if reds == blues == cells_same_colour:
continue # Nothing to do here, all cells set
if reds == cells_same_colour:
new_colour = 'b' # All reds set, use blue to update this row
elif blues == cells_same_colour:
new_colour = 'r' # All blues set, red blue to update this row
else:
continue # The required number is not reached by either colour
for col in range(size): # Update unset cells with new colour
if len(cells[(row, col)]) > 1:
cells[(row, col)] = new_colour
changes = True
# See if each column already has all the required cells of one colour
for col in range(size):
reds = sum(1 for row in range(size) if cells[(row, col)] == 'r')
blues = sum(1 for row in range(size) if cells[(row, col)] == 'b')
if reds == blues == cells_same_colour:
continue # Nothing to do here, all cells set
if reds == cells_same_colour:
new_colour = 'b' # All reds set, use blue to update this row
elif blues == cells_same_colour:
new_colour = 'r' # All blues set, red blue to update this row
else:
continue # The required number is not reached by either colour
for row in range(size): # Update unset cells with new colour
if len(cells[(row, col)]) > 1:
cells[(row, col)] = new_colour
changes = True
return changes
|
def soma(x, y):
"""Soma x e y
>>> soma(10, 20)
30
>>> soma(-10, 20)
10
>>> soma('10', 20)
Traceback (most recent call last):
...
AssertionError: x precisa ser int ou float
"""
assert isinstance(x, (int, float)), "x precisa ser int ou float"
assert isinstance(y, (int, float)), "y precisa ser int ou float"
return x + y
|
def _escape_html_argument(text):
"""Escape a string to be usable as an HTML tag argument."""
result = ""
for c in text:
if c == "<":
result += "<"
elif c == ">":
result += ">"
elif c == "&":
result += "&"
elif c == '"':
result += """
elif c == "'":
result += "'"
elif c == " ":
result += " "
elif '0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z' or c in {'/', ':', '.', '@', '-', '_'}:
result += c
else:
result += '&#x{0};'.format(hex(ord(c))[2:])
return result
|
def hex_reverse(integer, size):
"""
Reverse a hex string, bf99 -> 99bf
"""
string = '{0:0{1}x}'.format(integer, size)
return ''.join([string[i-2:i] for i in range(len(string), 0, -2)])
|
def most_populous(locations):
"""Disambiguate locations by only keeping the most populous ones."""
new_locations = {}
for chunk in locations:
new_locations[chunk] = set()
for loc in locations[chunk]:
biggest = (loc[0], sorted(loc[1], key=lambda x: -int(x[-1]))[0])
new_locations[chunk].add(biggest)
return new_locations
|
def llhelper_can_raise(func):
"""
Instruct ll2ctypes that this llhelper can raise RPython exceptions, which
should be propagated.
"""
func._llhelper_can_raise_ = True
return func
|
def common_cells(region_one: list, region_two: list):
"""
Determines whether there are any cells in common between two lists of cells
NB does not take in to account resolution. Cells should be at the same input resolution.
:param region_one: a list of strings representing cell suids
:param region_two: a list of strings representing cell suids
:return: boolean
"""
if isinstance(region_one, str):
region_one = [region_one]
if isinstance(region_two, str):
region_two = [region_two]
for cell in region_one:
if cell in region_two:
return True
return False
|
def getSelectColumns(columns):
"""
Prepare the columns to be selected by the SELECT statement.
"""
if columns == '*':
return columns
else:
return ', '.join(columns)
|
def _StripLeadingOrTrailingDoubleColons(addr_string):
"""Strip leading or trailing double colon."""
if addr_string.startswith("::"):
return addr_string[1:]
if addr_string.endswith("::"):
return addr_string[:-1]
return addr_string
|
def sieve5(n):
"""Return a list of the primes below n."""
prime = [True] * n
result = [2]
append = result.append
sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd
for p in range(3, sqrt_n, 2):
if prime[p]:
append(p)
prime[p*p::2*p] = [False] * ((n - p*p - 1) // (2*p) + 1)
for p in range(sqrt_n, n, 2):
if prime[p]:
append(p)
return result
|
def convert_scan_cursor(cursor, max_cursor):
"""
See https://engineering.q42.nl/redis-scan-cursor/
Apply mask from max_cursor and reverse bits order
"""
N = len(bin(max_cursor)) - 2
value = bin(cursor)[2:]
s = ("{:>0%ss}" % N).format(value)
return int(s[::-1], base=2)
|
def move_path(current_dir, new_dir, path):
"""
Move a path from one directory to another. Given the directory the path is
currently in, moves it to be in the second. The path below the given
directory level remains the same.
"""
if current_dir[-1] != '/':
current_dir += '/'
if new_dir[-1] != '/':
new_dir += '/'
return path.replace(current_dir, new_dir, 1)
|
def update_office(old_office, new_office):
""" function returns a copy of old_office updated with values from new if applicable """
updated_office = old_office.copy()
# update each field in office
for newfield, newval in new_office.items():
for oldfield, oldval in old_office.items():
if oldfield == newfield and newval != oldval:
updated_office[oldfield] = newval
break
else:
# add new fields to updated office
updated_office[newfield] = newval
return updated_office
|
def is_edit( request, v, edit="Edit"):
"""
Was an \"edit server\" button pressed?
"""
return v.startswith("edit_") and request.vars.get(v) == edit
|
def modify_leaves(f, ds):
"""Walks a data structure composed of nested lists/tuples/dicts, and
creates a new (equivalent) structure in which the leaves of the data
structure (i.e the non-list/tuple/dict data structures in the tree) have
been mapped through f."""
if isinstance(ds, list):
return [modify_leaves(f, sds) for sds in ds]
if isinstance(ds, tuple):
return tuple(modify_leaves(f, sds) for sds in ds)
if isinstance(ds, dict):
return {k: modify_leaves(f, sds) for k, sds in ds.items()}
return f(ds)
|
def _parse_dunder(line):
"""Parse a line like:
__version__ = '1.0.1'
and return:
1.0.1
"""
item = line.split('=')[1].strip()
item = item.strip('"').strip("'")
return item
|
def post_data(data):
"""
Takes a dictionary of test data and returns a dict suitable for POSTing.
"""
r = {}
for key, value in data.items():
if value is None:
r[key] = ""
elif type(value) in (list, tuple):
if value and hasattr(value[0], "pk"):
# Value is a list of instances
r[key] = [v.pk for v in value]
else:
r[key] = value
elif hasattr(value, "pk"):
# Value is an instance
r[key] = value.pk
else:
r[key] = str(value)
return r
|
def float_f(f):
"""Formats a float for printing to std out."""
return '{:.0f}'.format(f)
|
def describe_something(game, *args):
"""Describe some aspect of the Item"""
(description) = args[0]
print(description)
return False
|
def urljoin(*args):
"""
Joins given arguments into an url. Trailing but not leading slashes are
stripped for each argument.
"""
return "/".join(map(lambda x: str(x).rstrip("/"), args))
|
def sanitize(lines):
""" remove non text unicode charachters; maybe some of them could be used
to give hints on parsing?. """
return [line.replace(u'\u202b','').replace(u'\u202c','').replace(u'\x0c','')
for line in lines]
|
def rewrite_kwargs(conn_type, kwargs, module_name=None):
"""
Manipulate connection keywords.
Modifieds keywords based on connection type.
There is an assumption here that the client has
already been created and that these keywords are being
passed into methods for interacting with various services.
Current modifications:
- if conn_type is not cloud and module is 'compute',
then rewrite project as name.
- if conn_type is cloud and module is 'storage',
then remove 'project' from dict.
:param conn_type: E.g. 'cloud' or 'general'
:type conn_type: ``str``
:param kwargs: Dictionary of keywords sent in by user.
:type kwargs: ``dict``
:param module_name: Name of specific module that will be loaded.
Default is None.
:type conn_type: ``str`` or None
:returns kwargs with client and module specific changes
:rtype: ``dict``
"""
if conn_type != 'cloud' and module_name != 'compute':
if 'project' in kwargs:
kwargs['name'] = 'projects/%s' % kwargs.pop('project')
if conn_type == 'cloud' and module_name == 'storage':
if 'project' in kwargs:
del kwargs['project']
return kwargs
|
def get_words(line):
"""Break a line into a list of words.
Use a comma as a separator.
Strip leading and trailing whitespace.
"""
return [word.strip() for word in line.split(',')]
|
def get_object_dir_prefix(objhash):
"""Returns object directory prefix (first two chars of object hash)"""
return objhash[0:2] + "/"
|
def Gte(field, value):
"""
A criterion used to search for a field greater or equal than a certain value. For example
* search for TLP >= 2
* search for customFields.cvss >= 4.5
* search for date >= now
Arguments:
field (value): field name
value (Any): field value
Returns:
dict: JSON repsentation of the criterion
```python
query = Gte('tlp', 1)
```
produces
```json
{"_gte": {"tlp": 1}}
```
"""
return {'_gte': {field: value}}
|
def set_combinations(iterable):
"""
Compute all combinations of sets of sets
example:
set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}}
"""
def _set_combinations(iter):
current_set = next(iter, None)
if current_set is not None:
sets_to_combine_with = _set_combinations(iter)
resulting_combinations = set()
for c in current_set:
if not sets_to_combine_with:
resulting_combinations.add(frozenset(c))
for s in sets_to_combine_with:
resulting_combinations.add(frozenset(c.union(s)))
return resulting_combinations
return set()
return _set_combinations(iter(iterable))
|
def simplify_stdout(value):
"""Simplify output by omitting earlier 'rendering: ...' messages."""
lines = value.strip().splitlines()
rendering = []
keep = []
def truncate_rendering():
"""Keep last rendering line (if any) with a message about omitted lines as needed."""
if not rendering:
return
notice = rendering[-1]
if len(rendering) > 1:
notice += ' (%d previous rendering line(s) omitted)' % (len(rendering) - 1)
keep.append(notice)
# Could change to rendering.clear() if we do not support python2
rendering[:] = []
for line in lines:
if line.startswith('rendering: '):
rendering.append(line)
continue
truncate_rendering()
keep.append(line)
truncate_rendering()
result = '\n'.join(keep)
return result
|
def cigar_correction(cigarLine, query, target):
"""
Read from CIGAR in BAM file to define mismatches.
Args:
*cirgarLine(str)*: CIGAR string from BAM file.
*query(str)*: read sequence.
*target(str)*: target sequence.
Returns:
*(list)*: [query_nts, target_nts]
"""
query_pos = 0
target_pos = 0
query_fixed = []
target_fixed = []
for (cigarType, cigarLength) in cigarLine:
if cigarType == 0: # match
query_fixed.append(query[query_pos:query_pos+cigarLength])
target_fixed.append(target[target_pos:target_pos+cigarLength])
query_pos = query_pos + cigarLength
target_pos = target_pos + cigarLength
elif cigarType == 1: # insertions
query_fixed.append(query[query_pos:query_pos+cigarLength])
target_fixed.append("".join(["-"] * cigarLength))
query_pos = query_pos + cigarLength
elif cigarType == 2: # deletion
target_fixed.append(target[target_pos:target_pos+cigarLength])
query_fixed.append("".join(["-"] * cigarLength))
target_pos = target_pos + cigarLength
return ["".join(query_fixed), "".join(target_fixed)]
|
def string_to_number(word):
""" Converts from number(string) to number(integer)
Args:
word (`str`): number (string)
Raise:
Exception
Returns:
ret_num ('int|float'): number (integer|float)
Example:
>>> dev.api.string_to_number('1')
1
>>> dev.api.string_to_number('1.1')
1.1
"""
try:
ret_num = int(word)
except Exception:
try:
ret_num = float(word)
except Exception:
raise Exception(
"'{word}' could not be converted to number.".format(word=word))
return ret_num
|
def s1_mission(title: str) -> str:
""" sentinel competition date extractor extractor from product name """
if not title.startswith(('S1B', 'S1A','S2A','S2B')):
raise ValueError("Title should start with ('S1B','S1A')")
return title[:3]
|
def snake_to_pascal(param):
""" Convert a parameter name from snake_case to PascalCase as used for AWS IAM api parameters.
:param word: Dictionary of Resilient Function parameters.
:return: Converted string.
"""
return ''.join(x.capitalize() or '_' for x in param.split('_'))
|
def first(X):
"""
Returns the first element of an iterable X.
"""
return next(iter(X))
|
def find_cluster(dd, clusters):
"""Find the correct cluster. Above the last cluster goes into "excluded (together with the ones from kitti cat"""
for idx, clst in enumerate(clusters[:-1]):
if int(clst) < dd <= int(clusters[idx+1]):
return clst
return 'excluded'
|
def egcd(a, b):
"""
Computes greatest common divisor (gcd) and coefficients of Bezout's identity
for provided integers `a` and `b` using extended Euclidean Algorithm.
Args:
a (long): First integer number.
b (long): Second integer number.
Returns:
(long, long, long): Three-tuple representing
(gcd, Bezout's identity coefficient, Bezout's identity coefficient).
"""
r1=a
r2=b
s1=1
s2=0
t1=0
t2=1
while r2>0:
q=r1//r2
r=r1-q*r2
r1=r2
r2=r
s=s1-q*s2
s1=s2
s2=s
t=t1-q*t2
t1=t2
t2=t
return (r1,s1,t1)
|
def pick_id(id, objects):
"""pick an object out of a list of objects using its id"""
return list(filter(lambda o: o["id"] == id, objects))
|
def size_gb(size):
"""
Helper function when creating database
:param size: interger (size in Gb)
:return: integer (bytes)
"""
return 1024*1024*1024*size
|
def clean_title(title):
"""Remove status instructions from title"""
replacements = ["RFR", "WIP", "[", "]", ":"]
for replacement in replacements:
title = title.replace(replacement, "")
return title.strip().capitalize()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.