content stringlengths 42 6.51k |
|---|
def is_orientation(s):
"""Return True if s is a description of the base pair orientation.
s -- string
"""
if s == 'cis' or s == 'tran':
return True
return False |
def createrClassDoxygenString( moduleConfig ):
"""Creates the doxygen string for the class documentation"""
string = '/**\n'
string += '* @brief Class declaration for module: ' + moduleConfig['Class Name'] + '.\n'
string += '*/\n'
return string |
def get_difference(time, actual_time):
"""
Returns the difference in percent for two given times.
If it returns 1 it means that the task was finished as planned.
If it returns n > 1 it means that the task took n% longer than planned
If it returns n < 1 it means that the task took n% lesser than pla... |
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
Running time: O(n^2) because as items grow outter and inner loop both increases, also the function increases in a quadratic way
Memory... |
def _replace_phd(match):
"""
If the "PhD" professional title was matched, make sure it's got no punctuation in it.
:param match: a regular expression matched to a string
"""
if not match or len(match.groups()) < 1:
return match
return match.groups()[0] + "PhD" |
def invalid_utf8_indexes(bytes):
"""
"""
skips = []
i = 0
len_bytes = len(bytes)
while i < len_bytes:
c1 = bytes[i]
if c1 < 0x80:
# U+0000 - U+007F - 7 bits
i += 1
continue
try:
c2 = bytes[i + 1]
if ((c1 & 0xE0 =... |
def word_counts(list_of_sentences, raw_word):
"""Count how many times raw_word occurs in list_of sentences
list_of_sentences MUST be a list of textblob.Sentece objects
"""
raw_word_count = 0
for sentence in list_of_sentences:
raw_word_count = raw_word_count + sentence.word_counts[raw_word]... |
def child_request_dict(ts_epoch):
"""A child request represented as a dictionary."""
return {
'system': 'child_system',
'system_version': '1.0.0',
'instance_name': 'default',
'command': 'say',
'id': '58542eb571afd47ead90d25f',
'parameters': {},
'comment': ... |
def massage_error_code(error_code):
"""Massages error codes for cleaner exception handling.
Args:
int Error code
Returns:
int Error code. If arg is not an integer, will change to 999999
"""
if type(error_code) is not int:
error_code = 999999
return error_code |
def get_unsigned_js_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get unsigned remaped joystick value in reverse range
(For example if the limit is 2000, and the input valueis also 2000,
the value returned will be 1. And with the same limit, if the input value
is 1, the output value wwill ... |
def pt_to_tup(pt):
"""
Convenience method to generate a pair of two ints from a tuple or list.
Parameters
----------
pt : list OR tuple
Can be a list or a tuple of >=2 elements as floats or ints.
Returns
-------
pt : tuple of int
A pair of two ints.
"""
return (... |
def tts_ip_address(ip_address):
"""Convert an IP address to something the TTS will pronounce correctly.
Args:
ip_address (str): The IP address, e.g. '102.168.0.102'
Returns:
str: A pronounceable IP address, e.g. '192 dot 168 dot 0 dot 102'
"""
return ip_address.replace('.', ' punto... |
def floor_div(arr, val):
""" Floor division of array by value. """
return [i // val for i in arr] |
def best_per_pos(xs, x):
"""
:param xs: List of numbers
:param x: Number
:return: The positions in the list _xs_ where _x_ appears
"""
return [i for i, j in enumerate(xs) if j == x] |
def get_next_bytes(binary, bytes):
"""
This Function gets the next n bytes of data from a raw binary file and
returns both the n bytes and the original binary minus the n bytes
Args:
binary (List): List of bytes
bytes (int): n bytes to cut
Returns:
output (List): List of b... |
def dtime2a(dtime):
"""Converts time in seconds to 'HH:MM:SS'"""
dtime = int(dtime)
sec = dtime % 60
dtime /= 60
minute = dtime % 60
dtime /= 60
hour = dtime
return "%d:%02d:%02d" % (hour, minute, sec) |
def fixed_precision(A, prec=6):
""" Recursively convert nested iterables or coordinates to nested lists at
fixed precision. """
if hasattr(A, '__iter__'):
return [fixed_precision(el, prec=prec) for el in A]
else:
return round(A, prec) |
def has_alpha(string):
"""Return True if any char is alphabetic."""
return any(c.isalpha() for c in string) |
def green(message):
"""
green color
:return: str
"""
return f"\x1b[32;1m{message}\x1b[0m" |
def get_pie_size(val, verbose=False, getscale=False):
"""
Get the size of the pie chart based on val.
:param val: the value to test
:param verbose: more output
:param getscale: return the marker sizes regardless of val
:return: the size of the marker in pixels
"""
# these are the sizes ... |
def get_unique_numbers(num_list: list) -> set:
"""Returns unique values from a list."""
return {num for num in num_list} |
def GetStaticPipelineOptions(options_list):
"""
Takes the dictionary loaded from the yaml configuration file and returns it
in a form consistent with the others in GenerateAllPipelineOptions: a list of
(pipeline_option_name, pipeline_option_value) tuples.
The options in the options_list are a dict:
Key i... |
def convert_edif_orientation_to_hv(prop_orientation, shape_orientation):
""" Determine the text orientation, H or V, from shape and
property text orientation
"""
orientation = "H"
horizontal_set = {'R0', 'R180', 'MY', 'MX'}
vertical_set = {'R90', 'R270', 'MYR90', 'MXR90'}
if prop_orient... |
def make_pip_install_command(packages):
"""
Examples
--------
>>> make_pip_install_command(["foo", "bar"])
"pip install 'foo' 'bar'"
"""
return "pip install " + " ".join("'{}'".format(x) for x in packages) |
def _ms_tuple(z_tup):
"""Stringify a tuple into a Mathematica-like argument list."""
return '[' + ','.join(map(str, z_tup)) + ']' |
def binary_search(lst: list, value: object) -> int:
"""
Return the index <i> of the first occurance of <value>
in the list <lst>, else return -1.
Precondition: assume that the list is sorted
"""
start = 0
end = len(lst) - 1
while start <= end:
mid = (start + end) // 2
... |
def _empty_to_None(x):
"""Replace an empty list from params with None"""
if isinstance(x, list):
if not x:
x = None
return x |
def clearBit(int_type, offset):
"""clearBit() returns an integer with the bit at 'offset' cleared."""
mask = ~(1 << offset)
return int_type & mask |
def parse_bot_commands(slack_events):
"""
Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None.
"""
for event in slack_event... |
def path_to_class(path):
"""Given a class path, returns the class"""
module_path, cls_name = path.split(':')
module = __import__(module_path, fromlist=[cls_name])
cls = getattr(module, cls_name)
return cls |
def text_transform(ftpp, filename, content):
"""
if filename is rss.xml, replaces the string *__BLOG_ROOT__* by *self._root_web*
@param ftpp object FolderTransferFTP
@param filename filename
@param content content of the file
@return new content
... |
def emphasis(text: str) -> str:
"""Emphasizes (italicizes) the given text by placing <em> tags around it.
:param text: The text to be emphasized
"""
return f'<em>{text}</em>' |
def sort_results(results: list) -> list:
"""
The results will be in decreasing order of their length
and when they have the same length sorted in ascending
lexicographic order (letters and digits - more precisely
sorted by code-point)
:param results:
:return:
"""
results = sorted(res... |
def check_horizontal_visibility(board: list) -> bool:
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
... |
def args2string(args: dict) -> str:
"""Convert args dictionary to a string.
Args:
args (dict): A dictionary that contains parsed args.
Return:
A converted string.
Example:
>>> args = {
'arg1': [value1, value2],
'arg2': [value3],
'arg3': [val... |
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str
"""
return format(x, 'b').zfill(n) |
def _process_line(request: dict, cost_price_delta: int):
"""The function that builds out the report line by line"""
asset = request["asset"]
created = request["created"]
try:
qty = int(asset["items"][0]["quantity"]) # [0] to filter out irrelevant skus
except IndexError:
# to handl... |
def __get_moderation_dataset(_query_uri):
"""This function identifies the appropriate moderation dataset."""
_dataset = "moderation"
if 'pending/counts' in _query_uri:
_dataset = "moderation_pending_count"
elif 'pending' in _query_uri:
_dataset = "moderation_pending"
return _dataset |
def time_str(string):
""" Super error prone function, deal with it """
# input is eg: "40 min" or "1 t 34 min"
if len(string) > 10:
print(f'Fejl i tid? Tid: {string}')
return 60
return eval(string.replace('t', '*60 +').replace('min', '')) |
def S_adjust_phase_data(_data_list, _transform):
"""
Returns data samples where the phase is moved by transform amount.
"""
a_data = []
ds = len(_data_list)
for i in range(ds):
a_data.append((_data_list[i][0]+_transform, _data_list[i][1]))
return a_data |
def calc_st_pos_for_centering(bg_size, fg_size):
"""
Calculate start postion for centering.
Parameters
----------
bg_size : touple(int)
(width, height) of the background image.
fg_size : touple(int)
(width, height) of the foreground image.
Returns
-------
touple (i... |
def encode(buf):
"""
COBS encode buf, buf should be a packed structure
returns: COBS encoded packed structure
"""
out = [1] # save one free space for code
code_idx = 0 # index to be replaced with code
code = 1 # the next code to generate -- initialy 1
for i in range(len(b... |
def do_paths_match(request_path, cookie_path):
"""
Implements path matching adhering to RFC 6265.
Parameters
----------
request_path : `str`
The request's path.
cookie_path : `str`
The cookie's path.
Returns
-------
path_matching : `bool`
"""
if not ... |
def _report_error(info):
""" Interprets the return code of the odr routine.
Parameters
----------
info : int
The return code of the odr routine.
Returns
-------
problems : list(str)
A list of messages about why the odr() routine stopped.
"""
stopreason = ('Blank',
... |
def permutations(n):
"""
Generate list of all possible permutations of n bools
N.B First permutation in list is always the all True permutation and final
permutation in list is always the all False permutationself.
perms[1] = [True, ..., True]
perms[-1] = [False, ..., False]
Arguments:
... |
def get_point(points, cmp, axis):
""" Get a point based on values of either x or y axys.
:cmp: Integer less than or greater than 0, representing respectively
< and > singhs.
:returns: the index of the point matching the constraints
"""
index = 0
for i in range(len(points)):
if cmp <... |
def logical_name(session, Type='String', RepCap='', AttrID=1050305, buffsize=2048, action=['Get', '']):
"""[Get/Set Logical Name]
"""
return session, Type, RepCap, AttrID, buffsize, action |
def invoke_member(obj, membername, *args, **kwargs):
"""Retrieves a member of an object, then calls it with the provided arguments.
Args:
obj: The object to operate on.
membername: The name of the member to retrieve from ojb.
args: Positional arguments to pass to the method.
kwargs: Keyword argumen... |
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
is represented as a list of words
... |
def sum_elements(elems):
"""Sum numbers stored as sequence of two digits pairs."""
nums = [a * 100 + b for a, b in zip(elems, elems[1:])]
if len(nums) == len(set(nums)):
return sum(nums)
return 0 |
def combine_values(*values):
"""Return the last value in *values* that is not ``None``.
The default combiner; useful for simple values (booleans, strings, numbers).
"""
for v in reversed(values):
if v is not None:
return v
else:
return None |
def prime_adam_check(number: int) -> bool:
"""
Check if a number is Adam Integer.
A number is Adam if the square of the number and square
of the reverse of the number are reverse of each other.
Example : 11 (11^2 and 11^2 are reverse of each other).
"""
# Get the square of the number.
... |
def _num_ngrams(words, n):
"""
Return the number of nth gram of words.
>>> _num_ngrams([1, 2, 3], 3)
1
>>> _num_ngrams([1, 2, 3], 2)
2
:param words: a list of tokens.
:param n: int.
:return: number of n-gram.
"""
return max(len(words) - n + 1, 0) |
def colourise(colour, text):
""" Colourise - colours text in shell. """
""" Returns plain if colour doesn't exist """
if colour == "black":
return "\033[1;30m" + str(text) + "\033[1;m"
if colour == "red":
return "\033[1;31m" + str(text) + "\033[1;m"
if colour == "green":
ret... |
def checkInput(startLink):
"""
Use for check user input and correct if need
"""
if "bitly.com" in startLink:
print("Service can't short link cantained 'bitly.com' in any condition.")
startLink = str(input("Enter your link for short: "))
if startLink[:5] not in ["https", "http:"]:
... |
def is_palindrome_v1(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
return s[:] == s[::-1] |
def rgb_to_hex(r, g, b):
""" Convert ``(r, g, b)`` in range [0.0, 1.0] to ``"RRGGBB"`` hex string. """
return hex((
((int(r * 255) & 0xff) << 16) |
((int(g * 255) & 0xff) << 8) |
(int(b * 255) & 0xff))
)[2:] |
def GetBytes(byte, size):
"""Get a string of bytes of a given size
Args:
byte: Numeric byte value to use
size: Size of bytes/string to return
Returns:
A bytes type with 'byte' repeated 'size' times
"""
return bytes([byte]) * size |
def get_vm_resource_id(subscription_id=None,
resource_group=None,
vm_name=None):
"""
Return full resource ID given a VM's name.
"""
return "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}".format(subscription_id, resource_g... |
def get_target_ids(node_field_values):
"""Get the target IDs of all entities in a field.
"""
target_ids = []
for target in node_field_values:
target_ids.append(target['target_id'])
return target_ids |
def validate_uuid(given_uuid):
"""
A simple check for the UUID validity.
"""
from uuid import UUID
try:
parsed_uuid = UUID(given_uuid, version=4)
except ValueError:
# If not a valid UUID
return False
# Check if there was any kind of conversion of the hex during
#... |
def bytes(size: float) -> str:
"""humanize size"""
if not size:
return ""
power = 1024
t_n = 0
power_dict = {0: " ", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
while size > power:
size /= power
t_n += 1
return "{:.2f} {}B".format(size, power_dict[t_n]) |
def validate_supported(valname, val, supported):
"""Checks that val is not None
:param valname: the name of the value being validated
:type valname: string
:param val: the value to be validated
:type val: any
:param supported: a list or tuple of allowed values for val
:type supported: list,... |
def get_sum(a, b):
""" Given two integers a and b, which can be positive or negative,
find the sum of all the numbers between including them too and return it.
If the two numbers are equal return a or b.
"""
return sum(range(min(a, b), max(a, b) + 1)) |
def gen_default_return_for_plot_func(outputs: dict) -> dict:
"""Generate answer for plot component if it should not be executed
If plot component is not executed, its PlotlyJson outputs should be empty dicts.
This function prepares this output from the provided outputs
"""
return {key: {} for key i... |
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# Iterates through the rows and finds winning patterns.
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] is not None:
return board[i][0]
# Iterates through the columns and finds winnin... |
def approximate_xswap_prior(source_degree, target_degree, num_edges):
"""
Approximate the XSwap prior by assuming that the XSwap Markov Chain is stationary.
While this is not the case in reality, some networks' priors can be estimated
very well using this equation.
Parameters
----------
sou... |
def _obj_as_list(obj):
"""Converts strings as 1 entry list."""
if not isinstance(obj, (tuple, list)):
return [obj]
return obj |
def score_similarity_strings(nbr_name, overpass_name):
"""Given two strings, give a score for their similarity
100 for match and +10 for each matching word. Case-insensitive"""
# fixme: there are a number of good python tools for looking at similar strings
# use one! This will not catch spelling errors.... |
def _trim_barcode(barcode: str) -> str:
"""Trim the trailing 1 or 2 ASCII NULL (0x00) characters off barcode."""
if barcode[11] != chr(0):
return barcode
if barcode[10] != chr(0):
return barcode[:11]
return barcode[:10] |
def merge_junctions(junction_sets):
"""
Merge the given set of junctions and return
the union
@param junction_sets: list of list of junctions
@type junction_sets: list
@return: merged junctions
@rtype: set
"""
s = set([])
for js in junction_sets:
if s is None:
... |
def is_newline_error(e):
"""
Return True is e is a new line error based on the error text.
Otherwise return False.
"""
newline_error = u'new-line character seen in unquoted field - do you need'\
u' to open the file in universal-newline mode?'
return newline_error == str(e) |
def combine_manifests(new_manifest, previous_manifest):
"""Create a combined manifest by modifying old and new manifest files."""
if not previous_manifest:
return new_manifest
for _, entry in new_manifest['files'].items():
# hash equal, use previous manifest entry's version
if not p... |
def calculate_exam_average(lst, exam):
"""
Takes a list and exam type and returns the average of the exam.
Args:
lst: list of tuples created in convert function
exam: string speciefies the type of the exam
Return:
average: float that is the average of an exam specified with exam... |
def xstr(s):
""" Convert NoneType to blank ('') string."""
if s is None:
return ""
else:
return str(s) |
def navigate_ship( instructions ):
"""
From the starting point of the ship (0,0), the ship has to be navigated
based on the command and delta mentioned in each instruction.
The positions are modelled as complex numbers. The direction conventions
can be understood by referring to move_along diction... |
def check_real_vals(H_fft, W_fft, h, w, value):
"""
Check if x,y coordinates are subject to the real value constraint. If so,
add the imaginary part to the real one, and set the imaginary part to 0.
:param xfft: the input fft map
:param H_fft: the height of the fft map
:param W_fft: the width o... |
def every_n(n, height):
"""
Parameters
n: int
height: int
Returns
=======
List of every nth nonzero int up to and not including height
"""
return [i for i in range(1, height) if i % n == 0] |
def polygon_area(points):
"""Return the area of the polygon whose vertices are given by the
sequence points.
"""
area = 0
q = points[-1]
for p in points:
area += p[0] * q[1] - p[1] * q[0]
q = p
# 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
return abs(area / ... |
def pack_batch_attention_dict(
base_index,
source_tokens,
candidate_tokens,
attentions):
""" Packs the attention information into a dictionary for visualization.
Args:
base_index: An integer.
source_tokens: A list of samples. Each sample is a list of string token... |
def _no_Ns(nt_seq):
""" Returns True if a sequence does not have any N's """
if 'N' not in nt_seq:
return True
else:
return False |
def get_tf_type_name(tf_type):
"""Converts tf.dtype (eg: tf.float32) to str (eg: "tf.float32")."""
return "tf." + tf_type.name if tf_type else None |
def _eq(left, right):
"""
Equality comparison that allows for equality between tuple and list types
with equivalent elements.
"""
if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)):
return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right))
else:... |
def y_fitted_line(m_val, b_val, vec_x):
"""
This function returns the fitted baseline constructed
by coeffecient m and b and x values.
----------
Parameters
----------
x : Output of the split vector function. x value of the input.
m : inclination of the baseline.
b : y intercept of t... |
def getUsersWithCompetencies(categories, usercompetencies):
"""
Lists competences and their corresponding user IDs and returns the user ID
matching the needed competence
:param categories: Needed competence category
:type categories: list
:param usercompetencies: User IDs and their competences
... |
def append_user_profile_features(x_corpus: list, user_ids: list, user_profile: dict) -> list:
"""
append neutral, racism, sexism user profile probability feature to the end of each sentence
:param x_corpus: corpus with coded to integers
:param user_ids: list of user ids in the order of x_corpus
:par... |
def parse_response(message):
""" parse the http response """
result = message.decode()
return result |
def norm_L1(a):
"""L1 norm"""
return sum(abs(ai) for ai in a) |
def _format_time(total_seconds):
"""Format a time interval in seconds as a colon-delimited string [h:]m:s"""
total_mins, seconds = divmod(int(total_seconds), 60)
hours, mins = divmod(total_mins, 60)
if hours != 0:
return f"{hours:d}:{mins:02d}:{seconds:02d}"
else:
return f"{mins:02d}... |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return f'{num:.1f} {x}'
num /= 1024.0 |
def find_mode(x):
"""
find the mode (most common value reported)
will return median (center of sorted list)
should mode not be found
"""
n = len(x)
max_count = 0
mode = 0
bimodal = 0
counter = 0
index = 0
while index < (n - 1):
prev_count = counter
count... |
def tostr(v):
"""Check and convert a value to a string"""
return v if isinstance(v, str) else str(v) |
def rhyme_designator(index):
"""
Returns a string with an uppercase letter and a modifier.
The modifier indicates how many times around the alphabet the index has
gone, e.g. for index = 27, the string is A'.
"""
from string import ascii_uppercase
num = len(ascii_uppercase)
letter = asci... |
def check_protocol(url):
"""Check URL for a protocol."""
if url and (url.startswith('http://') or url.startswith('https://')):
return True
return False |
def base36_decode(_string):
"""
Decode a number from a base36 encoded string.
:param str _string: base36 encoded value
:returns: decoded value
:rtype: int
"""
return int(_string, base=36) |
def get_orientation(strategy, **kwargs):
"""
Determine a PV system's surface tilt and surface azimuth
using a named strategy.
Parameters
----------
strategy: str
The orientation strategy.
Allowed strategies include 'flat', 'south_at_latitude_tilt'.
**kwargs:
Strategy... |
def maxprod(a,b,c,d):
"""Devuelve el maximo producto entre 2 de 4 numeros"""
return max(a*b, a*c, a*d, b*c, b*d, c*d) |
def _dict_key_to_key(dictionary):
"""creates a dummy map from the nominal key to the nominal key"""
return {key : key for key in dictionary.keys()} |
def add_or_remove(item, items):
"""Adds the item to the list if it is not in there and remove it
otherwise.
"""
if item in items:
items.remove(item)
else:
items.append(item)
return items |
def _update_show_col_groups(show_col_groups, column_groups):
"""Set the value of show_col_groups to False or True given column_groups.
Updates the default None to True if column_groups is not None. Sets to False
otherwise.
"""
if show_col_groups is None:
if column_groups is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.