content stringlengths 42 6.51k |
|---|
def parity(n):
"""Computes the sum of bits in n mod 2."""
# bin(n) returns 0b....
# bin(n)[2:] trims "ob"
return sum(int(x) for x in bin(n)[2:]) % 2 |
def format_term_stat(term_stat):
"""Turn term_stat dict from get_run_info into something human-readable."""
if term_stat['timed_out']:
desc = 'Killed by timeout; '
else:
desc = 'Ran to completion; '
if term_stat['bad_retcode']:
desc += 'signalled error on termination'
if ... |
def number(text):
"""Return floating point number."""
return float(text.replace('.', '').replace(',', '.')) |
def check_required_args(required_args, provided_args, logger=None, log_msg=None):
"""
@brief Checks to see if the provided args have the required args in them
@param required_args The required arguments
@param provided_args The provided arguments
@param logger The ... |
def list_concat(lists):
"""
Joins given list of lists into a single list
"""
final_list = []
for sublist in lists:
final_list.extend(sublist)
return final_list |
def set_max_length(difficulty_level: str) -> int:
"""
Return an integer representing the max character length
depending on the difficulty level given.
:param difficulty_level:
A string representing the level of difficulty. The
levels are Easy, Medium, and Hard. This string can be
... |
def similar_values(v1, v2, e=1e-6):
"""Return True if v1 and v2 are nearly the same."""
if v1 == v2:
return True
return ((abs(v1 - v2) / max(abs(v1), abs(v2))) <= e) |
def render_flags(flags, bit_list):
"""Show bit names.
"""
res = []
known = 0
for bit in bit_list:
known = known | bit[0]
if flags & bit[0]:
res.append(bit[1])
unknown = flags & ~known
n = 0
while unknown:
if unknown & 1:
res.append("UNK_%04... |
def searchInsertA(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
if len(nums) > 1:
for i in range(len(nums)-1):
if target > nums[i] and target < nums[i+1]:
... |
def string_list(s):
"""Convert a string to a list of strings using .split()."""
return s.split() |
def flatten_response(response):
"""Helper function to extract only the filenames from the list directory command"""
return [item['filename'] for item in response] |
def num_list(to_parse):
"""
Creates list from its string representation
Arguments:
to_parse {string} -- String representation of list, can include 'None' or internal lists, represented by separation with '#'
Returns:
list[int] -- List represented in to_parse
"""
if len(... |
def routeunpack(value):
"""UnpPack a route into a string"""
return str(value).replace("!","/") |
def stats_output(stats):
"""
This function just prepares the statistics' appearance to be written into the output file
:param stats: array of all the elements to be put into the statistics
:return: string containing the statistics with description
"""
stats = "Length: " + str(stats[0]) + "\n" + ... |
def is_wildcard(string_path):
"""Return true if string_path contains { and }, used to contruct wildcard matching"""
return "{" in string_path and "}" in string_path |
def CalculateMeanValue(str_lengths:list):
"""
This function calculates the mean over all values in a list.
:param str_lengths:list: lengths of all strings
"""
try:
return int(round(sum(str_lengths)/len(str_lengths)))
except Exception as ex:
template = "An exception of type {0... |
def is_float(value):
"""
Function is_float:
-This function is used to find if a string contains a float
Inputs:
- value: string
Output:
- Boolean
"""
try:
float(value)
return True
except ValueError:
return False |
def compute_shape_noise_power(sigma_e,n,fsky):
""" sigma_e: shape noise
n: galaxies per arcmin^2
A: surface per arcmin62
"""
Cl = fsky*sigma_e**2/n
return Cl |
def build_protected_range_request_body(
start_row_index,
num_rows,
start_col_index,
num_cols,
worksheet_id=0,
warning_only=False,
description=None,
): # pylint: disable=too-many-arguments
"""
Builds a request body that will be sent to the Google Sheets API to create a protected rang... |
def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for key, value in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json |
def get_fifo_name(fifo_dir, producer, producer_id, consumer=''):
"""Standard name for FIFO"""
if consumer:
return f'{fifo_dir}{producer}_{consumer}_P{producer_id}'
else:
return f'{fifo_dir}{producer}_P{producer_id}' |
def guard_from_parts(parts):
"""Combine parts of the path into a guard macro name."""
name = parts[-1]
# Remove .in suffix from config files
if name.endswith(".in"):
name = name[:-3]
parts[-1] = name.replace(".", "_")
return "_".join(part.upper() for part in parts) |
def _complete(options, name):
""" Complete name out of a list of options """
found = None
for n in options:
if n is None:
continue
if n.startswith(name.lower()):
if found is None:
found = n
else:
Ke... |
def flatten(seq):
"""Flatten a list of lists (NOT recursive, only works for 2d lists)."""
return [x for subseq in seq for x in subseq] |
def common_items_v2(seq1, seq2):
""" Find common items between two sequences - optimized version (v2) """
# return set(seq1).intersection(set(seq2))
seq_dict1 = {item: 1 for item in seq1}
for item in seq2:
try:
seq_dict1[item] += 1
except KeyError:
pass
retu... |
def passedCredits(classes):
"""Calculates the number of credits a student passed.
:param dict classes:
The class information. Format:
classes = {className: {"grade": grade, "credits",
numCredits}}
:return:
The number of credits the student passed.
:rtype: int
... |
def _ApplyVersionOverrides(version, keys, overrides, separator='.'):
"""Applies version overrides.
Given a |version| string as "a.b.c.d" (assuming a default separator) with
version components named by |keys| then overrides any value that is present
in |overrides|.
>>> _ApplyVersionOverrides('a.b', ['major',... |
def cast_int(value):
"""Cast a value to an int, or None if it can't be cast.
"""
try:
value = int(value)
except:
value = None
return value |
def create_link(href, label, disabled=False):
"""
Creates a simple button to redirect the user to a given link
Parameters:
href (string):
The link to redirect the user to
label (string):
The label to use as the button label
disabled (boolean):
... |
def get_size_in_gb(size_in_bytes):
"""convert size in gbs"""
return size_in_bytes/(1024*1024*1024) |
def _full_url(url):
"""
Assemble the full url
for a url.
"""
url = url.strip()
for x in ['http', 'https']:
if url.startswith('%s://' % x):
return url
return 'http://%s' % url |
def shift_left_bit_length(x: int) -> int:
""" Shift 1 left bit length of x
:param int x: value to get bit length
:returns: 1 shifted left bit length of x
"""
return 1 << (x - 1).bit_length() |
def _getdef(list, num, default=None):
"""
Get value from list with default
:param list: List to get value from
:param num: Index to get
:param default: Default to return if index isn't in list
:return: Value at index, or default
"""
if num < len(list):
return list[num]
re... |
def binary_search_ge(x, search_list):
"""
binary search for the first value from a list, whose value is greater or equal to x
:param x: float, the number to compare with
:param search_list: sorted list of numbers.
:return: float, the first value in the list satisfying the condition.
"""
# it... |
def ok_deptid(deptid, deptid_exceptions):
"""
Some deptids are in an exception dictionary of patterns. If a person is
in one of these departments, they will not be listed in VIVO.
Deptids in the exception dictionary are regular expressions
Given a dept id, the deptid exception list is checked. T... |
def Check_NOR(promotor1, promotor2, Output_P, Gates):
"""Check the whole list and returns the delay of the gate matching with inputs"""
#Checks both possiblities of inputs in case if inputs are swapped
for i in Gates:
if i[0] == promotor1 and i[1] == promotor2 and i[2] == Output_P: #e.g i... |
def is_valid_genomic_build(genomic_build_param):
"""
Returns: True if given genomic build is valid, otherwise False.
"""
return genomic_build_param == "HG19" or genomic_build_param == "HG38" |
def toGoTexter(downInt, toGoTens, toGoOnes):
"""If Down is blank, skips logic and blanks toGo. Otherwise, will add ' Down' if no data for ballOn,
or will add ampersand and parse spacing based on if data exists in 10s place. These steps are for text
formatting assuming display is formatted to display '1st & 10' n... |
def merge_histories(histories):
""" Takes a list of histories and merges their results
"""
res = {}
for history in histories:
if hasattr(history, 'history'):
res = {**res, **history.history}
return res |
def findClassroomID(input):
"""Find Classroom ID in a given GAM string and return the int gCourseID"""
tempstring = str(input).replace("\\", " ")
tempstring = tempstring.split()
parsedID = 0
for part in tempstring:
try:
parsedID = int(part)
break
except:
... |
def get_config_value(config_data, key_tuple):
"""Extract value from `config_data` by the given `key_tuple`
Arguments:
config_data (dict): data structure as returned by
:func:`read_config_str`.
key_tuple (tuple): tuple of keys. For example if `key_tuple` is
``('pulse', 0,... |
def normalized_error(value_1,value_2,uncertainty,expansion_factor=1):
"""normalized error returns the scalar normalized error (delta value/ (expansion_factor*uncertainty))"""
return (value_2-value_1)/(uncertainty*expansion_factor) |
def label_outlier(sugar_level: float, outlier_high: float, outlier_low: float) -> str:
"""Label if the given sugar level is an outlier: outside outlier high & low constraints."""
if sugar_level > outlier_high:
return "High"
elif sugar_level < outlier_low:
return "Low"
else:
retur... |
def adjust(text):
"""Adjust a code sample to remove leading whitespace."""
lines = text.split('\n')
if len(lines) == 1:
return text
if lines[0].strip() == '':
lines = lines[1:]
final_lines = []
first_line = lines[0].lstrip()
while len(first_line) == 0:
final_lines.a... |
def similarity(s1, s2):
"""
:param s1: str, long DNA sequence
:param s2: str, short DNA sequence
:return: str, the best matched part form s1
The is function find the best match.
"""
s1 = s1.upper() # case-insensitive
s2 = s2.upper()
if s2 in s1:
return s2 # shows 100% match... |
def downscale_shape(shape, scale_factor):
""" Compute new shape after downscaling a volume by given scale factor.
Arguments:
shape [tuple] - input shape
scale_factor [tuple or int] - scale factor used for down-sampling.
"""
scale_ = (scale_factor,) * len(shape) if isinstance(scale_facto... |
def get_option_name(name): # type: (str) -> str
"""Return a command-line option name from the given option name."""
if name == 'targets':
name = 'target'
return f'--{name.replace("_", "-")}' |
def dictionary_list_to_object_list(d, cls):
""" Utility function to convert list of dictionaries to list of corresponding objects.
The objects must have the function ``from_dict(.)`` associated with it.
:param d: List of dictionaries.
:paramtype d: list, dict
:param cls: Class to which ea... |
def is_completed(grid):
"""
Checks if a grid is completed.
Grids are completed when all cells in them contain non-zero values.
Arguments:
grid {number matrix} -- The matrix to check for unique values on rows and columns
Returns:
bool -- True if all numbers are unique on the... |
def frange(start, stop, step):
"""Range function for float values."""
if step == 0:
return [start]
if isinstance(step, int):
return range(start, stop, step)
v = start
vs = []
while v < stop:
vs.append(v)
v += step
return vs |
def events_for_forms(events_array):
"""parse each event in the events array (from the database)
into a ISO datetime range string, returning an array sorted oldest/newest.
"""
events = [
"{0}/{1}".format(e['dt_start'], e['dt_end']) for e in events_array
]
events.sort()
return events |
def join_data(msg_fields):
"""
Helper method. Gets a list, joins all of it's fields to one string divided by the data delimiter.
Returns: string that looks like cell1#cell2#cell3
"""
return "#" .join(map(str,msg_fields)) |
def validate_clockwise_points(points):
"""
Validates that the points that the 4 points that dlimite a polygon are in clockwise order.
"""
if len(points) != 8:
raise Exception("Points list not valid." + str(len(points)))
point = [
[int(points[0]) , int(points[1])],
... |
def _merge_consecutive_markdown_cells(cells):
"""Merge consecutive cells with cell_type == 'markdown'.
Parameters
----------
cells : a list of jupyter notebook cells.
"""
merged = []
tmp_cell = None
def done_merging():
"""execute, when switching back from a series of markdown
... |
def transpath_as_svids(transpath, transedge_to_svid):
"""
Each transpath is originally represented as a list of ordered transedges.
Each transedge maps to an unique svid.
Represent each transpath as a list of ordered svids.
... doctest:
>>> transpath_as_svids((0, 1, 2), {0: 7, 1:8, 2:9})
... |
def get_raw_txt_file_path(data_dir: str, data_type: str,
text_type: str, split: str = '1.0') -> str:
"""
Call as
get_raw_txt_file_path(data_dir=data_dir, data_type=data_type, text_type="questions")
:param data_dir:
:param data_type:
:param split:
:param te... |
def f_bad_sections(a, b):
"""Function f
Parameters
----------
a : int
Parameter a
b : float
Parameter b
Results
-------
c : list
Parameter c
"""
c = a + b
return c |
def sim_constant(var_dist_params):
"""
Function to simulate data for a
'constant' variable, in other words,
a variable that has one empirical value.
"""
data_sim = var_dist_params
return data_sim |
def sql_name_pattern(pattern):
"""
Takes a wildcard-pattern and converts to an appropriate SQL pattern to be
used in a WHERE clause.
Returns: schema_pattern, table_pattern
>>> sql_name_pattern('foo*."b""$ar*"')
('^(foo.*)$', '^(b"\\\\$ar\\\\*)$')
"""
inquotes = False
relname = ""
... |
def __get_poly_in_roi(roi_poly, poly_geometry):
"""[summary]
Args:
roi_poly ([type]): [description]
poly_geometry ([type]): [description]
Returns:
[type]: [description]
"""
if roi_poly is None:
return poly_geometry
return roi_poly.intersection(poly_geometry) |
def distance_from_origin(position):
"""
Get the 'taxicab geometry' distance of a position from the origin (0, 0).
"""
return sum([abs(x) for x in position]) |
def table_str(key):
"""Make (`schema`, `table`) tuple printable."""
table, schema = key
return "%s.%s" % (str(schema), (table)) if schema else str(table) |
def egcd(b, a):
""" return a triple (g, x, y), such that ax + by = g = gcd(a, b) """
x0, x1, y0, y1 = 1, 0, 0, 1
while a != 0:
q, b, a = b // a, a, b % a
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0 |
def _compute_castep_gam_offset(grids):
"""
Compute the offset need to get gamma-centred grids for a given grid specification
Note that the offset are expressed in the reciprocal cell units.
"""
shifts = []
for grid in grids:
if grid % 2 == 0:
shifts.append(-1 / grid / 2)
... |
def string_lower(string):
"""**string_lower(string)** -> return the lowercase value of the string
* string: (string) string to lower case.
<code>
Example:
string_lower('Linux')
Returns:
'linux'
</code>
"""
return string.lower() |
def parse_server_name(server_name):
"""Split a server name into host/port parts.
Args:
server_name (str): server name to parse
Returns:
Tuple[str, int|None]: host/port parts.
Raises:
ValueError if the server name could not be parsed.
"""
try:
if server_name[-1]... |
def splitdrive(p):#from os.path
"""Split a pathname into drive and path specifiers. Returns a 2-tuple
"(drive,path)"; either part may be empty"""
if p[1:2] == ':':
return p[0:2], p[2:]
return '', p |
def is_overlapping(segment_time, previous_segments):
"""
Checks if the time of a segment overlaps with the times of existing segments.
Arguments:
segment_time -- a tuple of (segment_start, segment_end) for the new segment
previous_segments -- a list of tuples of (segment_start, segment_end) for... |
def revers_str(input_string):
"""
Input:
input_string is str() type sequence
Output:
reversed input_string by str() type
"""
return input_string[::-1] |
def convert_to_list(item):
"""If item is not list class instance or None put inside a list.
:param item: object to be checked and converted
:return: original item if it is a list instance or list containing the item.
"""
return item if item is None or isinstance(item, list) else [item] |
def update_dict(data_dict, update_list):
"""Update the counts in a dictionary.
Updates the counts (values) of a dictionary based on an update list.
data_dict must be a dictionary where the value for each key is the count
of the appearance of each key in a set of data. Function adds to the count
... |
def rgb_hex_to_rgb_list(hex_string: str):
"""Return an RGB color value list from a hex color string."""
return [
int(hex_string[i: i + len(hex_string) // 3], 16)
for i in range(0, len(hex_string), len(hex_string) // 3)
] |
def safe_field_name(field_name):
"""strip all the non-alphanums from a field name"""
import re
pattern = re.compile(r"[^a-zA-Z0-9\_\-]+")
return pattern.sub("", field_name) |
def color_text(text, color):
"""Converts text to a string and wraps it in the ANSI escape sequence for
color, if supported."""
# No ANSI escapes on Windows.
#if sys.platform == 'win32':
return str(text)
#return color + str(text) + '\033[0m' |
def merge_sort(lst):
"""
Sorts list using merge sort
:param lst:
return: number of comparisons
"""
comp = 0
if len(lst) > 1:
middle = len(lst) // 2
left = lst[:middle]
right = lst[middle:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
... |
def duration_from_secs_v2(s):
"""Module to get the convert milliseconds to a time format."""
s = s
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
timely = "{:03d} Days {:02d} Hours {:02d} Min {:02d} Sec".format(int(d),
... |
def print_event(event):
"""
arg:
event: s3 trigger event
return:
None
"""
import json
print("Received event: " + json.dumps(event, indent=2))
return None |
def init(sequence):
"""Get all but the last element of a sequence.
Parameters
----------
sequence : Sequence[A]
The sequence from which to extract elements.
Returns
-------
Sequence[A]
The sequence with the tail chopped off.
"""
return sequence[:-1] |
def rgb2hex(r: int, g: int, b: int) -> str:
"""
Convert RGB color from decimal to hexadecimal
"""
return "#%02x%02x%02x" % (r, g, b) |
def np_elementwise(mat1, mat2):
"""
addition, subtraction, multiplication, and division
Returns the new matrix
"""
return(mat1 + mat2, mat1 - mat2, mat1 * mat2, mat1 / mat2) |
def rotate_truth_table(table, rotation_map):
"""
Rotates address bits of the truth table of a LUT given a bit map.
Rotation map key refers to the "new" address while its value to the
"old" one.
"""
# Get LUT width, possibly different than the current
width = max(rotation_map.keys()) + 1
... |
def _caseInsensitiveLookup(d, k, default=None):
"""Performs a case-insensitive lookup on the dictionary ``d``,
with the key ``k``.
This function is used to allow case-insensitive retrieval of colour maps
and lookup tables.
"""
v = d.get(k, None)
if v is not None:
return v
key... |
def response_sql(where):
""" The basic SQL query syntax.
The query category/value pair determines
how the resulting table is restricted.
"""
return ("SELECT DISTINCT studies.*,results.* "
"FROM results "
"LEFT JOIN studies ON results.study_id=studies.study_id "
... |
def GetAllConfigs(builder_groups):
"""Build a list of all of the configs referenced by builders.
"""
all_configs = {}
for builder_group in builder_groups:
for config in builder_groups[builder_group].values():
if isinstance(config, dict):
for c in config.values():
all_configs[c] = bui... |
def multiply(first_term, second_term):
"""Multiply first term by second term.
This function multiplies ``first_term`` with ``second_term``.
Parameters
----------
first_term : Number
First term for the multiplication.
second_term : Number
Second term for the multiplication.
... |
def optCreateNets(create_all_nets):
"""
replace individual create_net command by one command
"""
# previous format is:
# create -net XXX
# create -net YYY
# target format is :
# connect_net \
# XXX \
# YYY \
opt_commands = [command.replace('create_net', ' ') for command in create_all_nets... |
def get_parent_child_dict(company,parent,children_list):
"""
Build a dictionary that contains parent company, subsidiary company information
for a certain company
Parameters
----------
company: str
A company name to build dictionary for
parent: s... |
def reliable_test(test_fr, acceptable_fr, test_runs, min_run):
"""Check for a reliable test.
A test should then removed from the set of tests believed not to run reliably when it has
less than min_run executions or has a failure percentage less than acceptable_fr.
"""
return test_runs < min_run or ... |
def count_longest_heads_run(lst):
"""
Return longest Heads run in given experiment outcomes list
"""
count = X_longest_run = 0
for outcome in lst:
if outcome == 'H':
count += 1
else:
count = 0
if count > X_longest_run:
X_longest_run = count... |
def extract_players(game, playerkey, targetkey):
"""Get references to player and target"""
return game['players'][playerkey], game['players'][targetkey] |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
if(len(line) < 1):
return 0
elif(len(line) == 1):
return 1
counter = 0
index1 = 0
index2 = 1
max_temporary = 0
max_finally = 0
run = True
while(run):
... |
def _extract_qsub_j_id(out):
"""
Find j_id in out that looks like:
Your job {j_id}.{array_details} ("{job_name}") has been submitted
"""
tokens = out.split(' ')
for token in tokens:
if token and token[0].isdigit():
return token.split('.')[0]
return None |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2**(int(value)-1).bit_length() |
def find_location_abbreviations(question_tokens, question):
"""
This heuristic is just a very basic approximation for a much complexer problem. Location names are very divers and require a powerful
model to understand them properly.
"""
country_name_abbrevations_US = [
'USA', 'US', 'United S... |
def map_char_value(data, keys=[], string_fmt=False, one_line=True, sep=", "):
"""
Map characteristic value with the given keys, return dict or string
format
"""
if keys:
if not string_fmt:
return dict(zip(keys, list(data.values())[0]['Value'].values()))
else:
... |
def filter_range(IStart, IEnd, IStep):
"""
Filter current range.
:param IStart: current start point
:type IStart: float
:param IEnd: current end point
:type IEnd: float
:param IStep: current step
:type IStep: float
:return: filtered range as list
"""
temp = None
IStartO ... |
def get_tag_line(lines, revision, tag_prefixes):
"""Get the revision hash for the tag matching the given project revision in
the given lines containing revision hashes. Uses the given array of tag
prefix strings if provided. For example, given an array of tag prefixes
[\"checker-framework-\", \"checkers... |
def sizify(value, suffix=""):
"""
Simple kb/mb/gb size snippet for templates:
{{ product.file.size|sizify }}
"""
if value < 512000:
value = value / 1024.0
# ext = 'kb'
elif value < 4194304000:
value = value / 1048576.0
# ext = 'mb'
else:
value = value... |
def _iterify(x):
"""make x iterable"""
return [x] if not isinstance(x, (list, tuple)) else x |
def inject_pipeline(request, injectionstring):
"""
Generates a list of new pipelined requests
:param request: request instance
:param injection_string: list of strings to inject into the request
:return: list of requests
"""
requests = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.