content stringlengths 42 6.51k |
|---|
def createFont(family=None, size=16, bold=False, italic=False):
"""Creates a font for subsequent use"""
return {"font_name": family, "font_size": size, "bold": bold,
"italic": italic} |
def getFileName(name):
"""
reads the actual file name, e.g. '/home/molsson/1xnb.pdb' gives '1xnb.pdb'
"""
start = None
for i in range(len(name)):
if name[i] == '/':
start = i+1
return name[start:] |
def get_audio_track_titles(media_blocks):
"""Get audio track titles"""
if not media_blocks:
return '', ''
audio_track_title = media_blocks.get('audio_track', {}).get('title', '')
external_video_title = media_blocks.get('external_video', {}).get('title', '')
return audio_track_title, external... |
def mean2d(arrays):
"""calculate mean of 2d array"""
mean = arrays[0]
for image in arrays[1:]:
mean += image
mean /= len(arrays)
return mean |
def tf(term, doc_terms):
"""
Calculate tf measure for a document
"""
return doc_terms.count(term)*1.0/len(doc_terms) |
def get_fields_from_fieldsets(fieldsets):
"""Get a list of all fields included in a fieldsets definition."""
fields = []
try:
for name, options in fieldsets:
fields.extend(options['fields'])
except (TypeError, KeyError):
raise ValueError('"fieldsets" must be an iterable of tw... |
def isAscii(s):
"""
isAscii :: str -> bool
Selects the first 128 characters of the Unicode character set,
corresponding to the ASCII character set.
"""
return ord(s) < 128 |
def inner_prod(x, y):
"""Return the inner product of two lists of the same size."""
if len(x) != len(y):
raise Exception("The sequences must be of the same lenght.")
prod = 0
for i in range(len(x)):
prod += x[i] * y[i]
return prod |
def canBalance2(arr):
"""
Determine if a list of numbers is balance.
Parameter:
arr := list of numbers
Return:
True if a split position can be found in the arr such that
both halves sum of numbers are equal.
False otherwise.
Assuming numbers can be only integers
... |
def _make_filename(el_symbol, el_year, datatype):
"""_make_filename('ne', 96, 'scd') -> 'scd96_ne.dat' """
return datatype + str(el_year) + '_' + el_symbol + '.dat' |
def dkim_fold(header, length = 72):
"""
Folds a header line into multiple line feed separated lines
at column length defined (defaults to 72).
This is required so that the header field is defined according
to the dkim rules and the default mime encoding.
:type header: String
:para... |
def district_margins(state_lines):
"""
Return a dictionary with districts as keys, and the difference in
percentage between the winner and the second-place as values.
@lines The csv rows that correspond to the districts of a single state
"""
# Complete this function
return dict((int(x["D"]... |
def merge_list_of_dicts(left, right):
"""Merges dicts left[0] with right[0], left[1] with right[1], etc."""
output = []
for i in range(max(len(left), len(right))):
left_dict = left[i] if i < len(left) else {}
right_dict = right[i] if i < len(right) else {}
merged_dict = left_dict.copy()
merged_dic... |
def expandDotAttr(attr):
""" *attr* is str or list of str, each str can have a dot notation"""
if not isinstance(attr, (tuple, list)):
res = attr.split(".")
try:
return [eval(a) if '(' in a else a for a in res]
except Exception:
return res
expanded = []
fo... |
def exif_values_to_list(value):
"""Convert a value returned by ExifTool to a list if it is not already and filter out bad data"""
if isinstance(value, list):
value = [v for v in value if not str(v).startswith("(Binary data ")]
return [str(v) for v in value]
elif not str(value).startswith("(B... |
def gen_q_name(q_idx):
"""
Generate single query name
Parameters
----------
q_idx: int
Index of this query name.
Returns
-------
"""
result = "query_{:02d}".format(q_idx + 1) # One-based indexing
return result |
def is_over_slot_constraint(selected_recs, slots, group_id):
"""
judge whether a group slot constraint is violated
"""
max_slot = slots[group_id]
current_slot = 0
for (item, group) in selected_recs:
if group == group_id:
current_slot += 1
if current_slot > max_slot:
... |
def small_hash(instance, digits=9):
"""
Cytoscape.js has trouble with dealing large or negative integers.
Returns positive and n-digit hash of the passed instance.
:param instance: for which it's positive 9-digit hash is returned
:param digits: number of digits of the resulting hash. Default is 9... |
def apt_install(*packages: str) -> str:
"""Returns a command that will install the supplied list of packages without
requiring confirmation or any user interaction.
"""
package_str = ' '.join(packages)
no_prompt = "DEBIAN_FRONTEND=noninteractive"
return f"{no_prompt} apt-get install --yes --no-install-recom... |
def median(lst, lst_size=None):
"""Compute median."""
lst = sorted(lst)
if lst_size:
n = lst_size
n_diff = n - len(lst)
i = (n - 1) // 2 - n_diff
if i < 0:
if i == -1 and not n % 2:
return lst[0] / 2.
return 0
else:
n = len(... |
def format_timedelta(timedelta: float) -> str:
"""Custom date & time formatter"""
days = int(timedelta // (24 * 3600))
hours = int(timedelta % (24 * 3600) / 3600) # noqa: S001
minutes = int(timedelta % 3600 / 60)
seconds = int(timedelta % 60)
str_date = ''
if days:
str_date += f'{da... |
def removesuffix(s, suffix):
"""
Removes suffix a string
:param s: string to remove suffix from
:param suffix: suffix to remove
:type s: str
:type suffix: str
:return: a copy of the string with the suffix removed
:rtype: str
"""
return s if not s.endswith(suffix) else s[:-len(su... |
def untag_predicate(p):
"""
Given a tagged predicate, return a full predicate.
So, for example, given
rdf:type
return
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
"""
ns = {
"rdf:":"http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs:":"http://www.w3.org/2000/01... |
def bss_host_nid(host):
"""
Retrieves the nid from the BSS host object
"""
return host["NID"] |
def summary_table(counts):
"""Takes a dictionary of dbnames and counts and returns at table"""
# Filter for only wikis with non-zero counts
entries = {key: value for key, value in counts.items() if value != 0}
# Sum the per-wiki counts and count the wikis
total_pages = sum(entries.values())
tot... |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
num1:
The first number to find the lcm for
num2:
The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bi... |
def safe_div(x):
"""
For cases where 0/0 return None
Argument(s): x - row of pandas dataframe (supply columns as indices)
Output: x[0]/x[1] - division where denominator is not 0, else None
"""
if x[1] == 0:
return None
return x[0] / x[1] |
def _decode_bool(packet, offset=6):
"""Decode boolean value"""
return packet[6] == 0x00 |
def patch_invalid_aces_transform_id(aces_transform_id):
"""
Patches an invalid *ACEStransformID*, see the *Notes* section for relevant
issues supported by this definition.
Parameters
----------
aces_transform_id : unicode
Invalid *ACEStransformID* to patch.
Returns
-------
... |
def strings_to_ints(lst):
"""transforms a list of strings to a list of ints
ARGS:
list of strings
RETURNS:
list of ints
RAISES:
ValueError: when the string in the list is not a number
"""
return [int(x.strip()) for x in lst] |
def default_hash(i: int, x: int, n: int):
"""Return a hash value for x.
Arguments:
i: hash function index within family
x: value to be hashed
n: domain
"""
return (x + i) % n |
def treatAccNumber(accNumber, id_strain_bd):
"""
Used to return null if the acc does not exists
:param accNumber: gi number
:type accNumber: string
:return: None if the acc number is non-existent
:rtype None or string
"""
if accNumber == 'NA':
return 'remove_' + str(id_strain... |
def pyramid_steps_loop(n):
"""Return a list of "n" progression pyramid steps, using loops."""
import math
result = []
line_size = n * 2 - 1
line_mid = math.floor(line_size / 2)
for i in range(n):
line = ""
for j in range(line_size):
line += "#" if j >= line_mid - i an... |
def format_time(t, format_spec='dhms'):
"""
Return a formatted time string describing the duration of
the input in seconds in terms of days,hours,minutes and seconds.
"""
if format_spec == '':
sb, mb, hb, db = True, True, True, True
else:
sb = 's' in format_spec
mb = 'm' in format_spec
hb = 'h' in format... |
def durationBucket(durationStr):
"""
Return string category label for call duration
"""
duration = int(float(durationStr))
if duration < 60:
return "0 to 1 min"
elif duration < 120:
return "1 min to 2 min"
elif duration < 180:
return "2 min to 3 min"
elif duration... |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return (list(name_or_flags), kwargs) |
def getMtzLink(pdb_code):
"""Returns the html path to the mtz file on the pdb server
"""
file_name = 'r' + pdb_code + '_phases.mtz'
pdb_loc = 'https://edmaps.rcsb.org/coefficients/' + file_name
return file_name, pdb_loc |
def update_dict_deep(original, new_values):
""" Updates dict *in-place* recursively, adding new keys in depth
instead of replacing key-value pairs on top levels like `dict.update()` does.
Returns updated dict.
"""
for key in new_values:
if key not in original:
original[key] = new_values[key]
elif isinstance... |
def get_client_login_token_string(http_body):
"""Returns the token value for a ClientLoginToken.
Reads the token from the server's response to a Client Login request and
creates the token value string to use in requests.
Args:
http_body: str The body of the server's HTTP response to a Client Login
... |
def calc_num_terminal_mismatches(matches):
"""(Internal) Count the number of -1 entries at the end of a list of numbers.
These -1 correspond to mismatches in the sequence to sequence search.
"""
if matches[-1] != -1:
return 0
neg_len = -1
while matches[neg_len] == -1:
neg_len -=... |
def signum2str(signum):
"""Translates a signal number to a str.
Example::
>>> print signum2str(1)
SIGHUP
:param signum: The signal number to convert.
:returns: A str representing the signal.
"""
import signal as signal_module
for attr in dir(signal_module):
if attr... |
def iterative_gcd(a, b):
"""
:param a:
:param b:
:return:
"""
while True:
if b == 0:
return a
remainder = a % b
if remainder == 0:
return b
a, b = b, remainder |
def _check_stim_channel(stim_channel, ch_names, sel):
"""Check that the stimulus channel exists in the current datafile."""
if isinstance(stim_channel, str):
if stim_channel == 'auto':
if 'auto' in ch_names:
raise ValueError("'auto' exists as a channel name. Change "
... |
def transform_octet_to_mac(octet_string):
"""
Transforms SNMP Octet string to MAC address separated by ':'
Args:
octet_string: SNMP Octet string
Returns:
MAC address separated by ':'
"""
mac_address = ''
if isinstance(octet_string, bytes):
mac_address = u':'.join(u... |
def get_relative_coordinates(exon_exp_region, search_locus, directed, max_len=5000):
"""Get relative coordinates of expected regions.
Formatting for LASTZ-CESAR optimizer.
"""
include_regions = list(exon_exp_region.values())
_, start_end_str = search_locus.split(":")
start_str, end_str = start_... |
def neutronify(name):
"""Adjust the resource name for use with Neutron's API"""
return name.replace('_', '-') |
def route_kwargs(kwargs, count):
"""
Routes the given `kwargs` to the given `count` amount of copies.
If a value of a keyword is given as a `tuple` instance, then it will be routed by element for each applicable
client.
Parameters
----------
kwargs : `dict` of (`str`, `Any`) items
... |
def parse_allowed_graphs(allowed_graphs):
"""
Grabs allowed graphs for user
Args:
allowed_graphs: Allowed graphs
Returns: List of allowed graphs
"""
result = ''
for allowed_graph in allowed_graphs:
if allowed_graph is not None:
result += 'FROM <' + allowed_graph... |
def height_tree(n):
"""Recursive method to find height of binary node."""
if n is None:
return 0
return 1 + max(height_tree(n.left), height_tree(n.right)) |
def check_extractability(text):
"""
Given a text, check if it has some content.
Parameters
----------
text: string
Text.
Return
------
True or False.
"""
if text == "" or text is None:
return False
return True |
def make_color_tuple( color ):
"""
turn something like "#000000" into 0,0,0
or "#FFFFFF into "255,255,255"
"""
R = color[1:3]
G = color[3:5]
B = color[5:7]
R = int(R, 16)
G = int(G, 16)
B = int(B, 16)
return R,G,B |
def detect_cycles(data):
"""
Detects cycles in the data
Returns a tuple where the first item is the index at wich the cycle occurs
the first time and the second number indicates the lenght of the cycle
(it is 1 for a steady state)
"""
fsize = len(data)
# maximum size
for msize i... |
def map_to_range(old_min, old_max, new_min, new_max, value):
"""convert from one range to another"""
old_range = old_max - old_min
if old_range == 0:
new_value = new_min
return new_value
else:
new_range = new_max - new_min
new_value = (((value - old_min) * new_range) / ol... |
def get_color(color):
""" Can convert from integer to (r, g, b) """
if not color:
return None
if isinstance(color, int):
temp = color
blue = temp % 256
temp = int(temp / 256)
green = temp % 256
temp = int(temp / 256)
red = temp % 256
return... |
def pretty_dict(dic):
"""Printable string representation of a dictionary
Items are listed in alphabetical order of their keys,
to ensure a deterministic representation
(e.g. for unit tests)
Examples:
>>> pretty_dict({1: 2, 3: 4})
'{1: 2, 3: 4}'
>>> pretty_dict({'... |
def egcd(a, b):
"""
Compute extended euclidean for `a` and `b`
Pre-condition: a > b
"""
if a % b == 0:
return (None, None)
mem = [0, 1, 0, None]
while b != 1:
t = mem[1]
mem[1] = mem[0] - t * (a // b)
mem[0] = t
if mem[3] is None:
mem[3] ... |
def create_element(number,etype):
"""
Create an element:
Parameters
----------
number : int
Number of element
etype : str
Element type
::
# Example
create_element(1, "PLANE182") # -> ET,1,PLANE182
"""
_el = "ET,%g,%s"%(number,etyp... |
def get_address_area_or_none(address_area):
"""
Get Formatted Address Area Result
:param address_area: Address object returned on Company
:return: Address as an id name object or None
"""
return address_area and {
'id': str(address_area.id),
'name': address_area.name,
} or No... |
def secondsFromString(i):
"""convert from a string in the format output from timeStamptoDate to a 32bit seconds from the epoch.
The format accepted is \"DD/MM/YYYY HH:MM:SS\". The year must be the full number.
"""
import time
return int(time.mktime(time.strptime(i, "%d/%m/%Y %H:%M:%S"))) |
def grep_elements(elements, grep):
"""
Filter elements. Only keep the ones that match grep
"""
res = []
for e in elements:
keep_it = True
for g in grep:
s = ' '.join(str(v) for v in e.values())
if s.find(g) == -1:
keep_it = False
if ke... |
def get_commands_from_commanddict(commanddict):
"""
<Purpose>
Extracts the commands that are contained in the command dictionary.
The arguments of these commands are not included.
<Arguments>
commanddict: A command dictionary in the format specified in
seash_dictionary.
<Exceptions>
None... |
def my_sum_function(num_list):
"""Return the total of all numbers in the given list added together."""
my_sum = 0
for num in num_list:
my_sum += num
# Example error in function implementation (using wrong operator)
# my_sum *= num
return my_sum |
def asColor(r, g=None, b=None, a=None):
"""Convert the attribute to a color tuple that is valid in DrawBot.
"""
if isinstance(r, (tuple, list)):
if len(r) == 3:
r, g, b = r
return r, g, b, 1 # Return the color with undefined opacity.
if len(r) == 4:
return... |
def Hexify(value):
"""Returns the hexified string of the value.
Args:
value: integer or string.
Returns:
a string whose format looks like "0x0b".
"""
if isinstance(value, int):
number = value
elif value.startswith('0x'):
number = int(value, 16)
else:
number = int(value, 10)
return ... |
def validate_password(password):
"""Validate and reformat password argument.
Args:
password (str or bytes): Encryption password.
Returns:
str or bytes: The original password string.
"""
if password is None:
password = ""
if not isinstance(password, str) and not isinst... |
def format_fasta_entry(otu_name, isolate_name, sequence_id, sequence):
"""
Create a FASTA header for a sequence in a otu DNA FASTA file downloadable from Virtool.
:param otu_name: the otu name to include in the header
:type otu_name: str
:param isolate_name: the isolate name to include in the head... |
def get_summary_keys(classification):
"""Get the required summary keys for the experiment.
Args:
classification (boolean): Whether it is a classification task.
Returns:
The list of keys.
"""
summary_keys = [# Average training loss on last epoch.
'loss_train_last',
... |
def calculate_midpoint(l, r):
"""
@param l left index, included in the range of elements to consider
@param r right index, included in range of elements to consider
@return None if there's no elements to range over.
Returns the midpoint from the "left side" or "left half" if there's an even
num... |
def pad(t, padding):
"""Sum every non-zero item of t with padding*2"""
return [0 if n==0 else n+padding*2 for n in t] |
def merge(new_items, into_list):
"""
Appends items from `new_items` into `into_list`, only if they are not already there.
:param new_items:
:param into_list:
:return:
"""
at_least_one_added = False
for item in new_items:
if item not in into_list:
into_list.append(item... |
def serialize_object(obj):
"""Serialize zeep objects to native python data structures"""
if obj is None:
return obj
if isinstance(obj, list):
return [sub._xsd_type.serialize(sub) for sub in obj]
return obj._xsd_type.serialize(obj) |
def hyperlink(link: str, *, title=None):
"""A helper function to make links clickable when sent into chat."""
return f'[{title or link}]({link})' |
def averageSingleCondition(single_group_data):
"""
single_group_data should be a list of lists containing all data
that belongs to a single treatment group.
"""
averaged_data = [sum(e)/len(e) for e in zip(*single_group_data)]
return averaged_data |
def str_to_bool(s):
""" Convert a string value of a boolean in boolean.
Parameter :
- s : A boolean as String.
"""
s = str(s)
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise ValueError |
def get_prov_map(attr, ancestor_files):
"""Create a provenance record for the 2D diagnostic outputs."""
caption = (
"Thermodynamic Diagnostic Tool - Monthly mean {} (lat, lon) fields"
"for model {}.".format(attr[0], attr[1]))
record = {
'caption': caption,
'statistics': ['me... |
def ERR_NOTREGISTERED(sender, receipient, message):
""" Error Code 451 """
return "ERROR from <" + sender + ">: " + message |
def hashcode(string):
"""A string hash function for compatibility with spf.string.hashCode.
This function is similar to java.lang.String.hashCode().
The hash code for a string is computed as
s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
where s[i] is the ith character of the string an... |
def check_duplicates(text, duplicates, agencies_dict):
"""
For a given text, checks to see if there are duplicate agencies and returns
proper agency or agency abbreviation.
Args:
text: raw text of file from input json
duplicates: list of acronyms with multiple associated agencies
... |
def check_NWIS_bBox(input):
"""Checks that the USGS bBox is valid
"""
msg = 'NWIS bBox should be a string, list of strings, or tuple ' + \
'containing the longitude and latitude at the lower left corner ' + \
'of the bounding box followed by the longitude and latitude ' + \
'at... |
def compute_row(line):
"""Compute the row of the seat."""
low: int = 0
high: int = 127
for char in line[:7]:
diff: int = high - low
if char == 'F':
# lower half
high -= int(diff / 2 + 0.5)
elif char == 'B':
# upper half
low += int(... |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if ints is None or len(ints) == 0:
return None
max_num = -float('Inf')
min_num = float('Inf')
for num in ints:
... |
def _camelcase(value):
"""
Helper method to convert module name to class name.
"""
return ''.join(str.capitalize(x) if x else '_' for x in value.split('_')) |
def base10toN(num, base):
"""Change ``num'' to given base
Upto base 36 is supported."""
converted_string, modstring = "", ""
currentnum = num
if not 1 < base < 37:
raise ValueError("base must be between 2 and 36")
if not num:
return '0'
while currentnum:
mod = curren... |
def dict_add(*dicts):
"""
Returns a dictionary consisting of the keys in the argument dictionaries.
If they share a key, the value from the last argument is used.
>>> dictadd({1: 0, 2: 0}, {2: 1, 3: 1})
{1: 0, 2: 1, 3: 1}
"""
result = {}
for dct in dicts:
r... |
def merge_error_reports(*reports):
"""Merge error reports
Parameters
----------
*reports : list of dict
The error reports
Returns
-------
dict
Keyed by sample ID, valued by the list of observed errors. An empty
list is associted with a sample ID if no errors were ob... |
def get_sort_params(params, default_key='created_at', default_dir='desc'):
"""Retrieves sort keys/directions parameters.
Processes the parameters to create a list of sort keys and sort directions
that correspond to either the 'sort' parameter or the 'sort_key' and
'sort_dir' parameter values. The value... |
def is_prime(n):
"""Returns True if n is a prime number and False otherwise.
>>> is_prime(2)
True
>>> is_prime(16)
False
>>> is_prime(521)
True
"""
def factor(n, c):
if n == c:
return True
if n % c == 0:
return False
c += 1
ret... |
def is_int(value):
""" Is value integer
args:
value (str): string
returns:
bool
"""
try:
int(str(value))
return True
except (ValueError, TypeError):
pass
return False |
def is_in_image(x, y, a, L):
"""Determines if a square with defined vertices is contained in an image
with larger dimensions
Args:
x (int): Value for the x coordinate of the top left corner of the
square of interest
y (int): Value for the y coordinate of the top left corner of t... |
def submit(fn, *args, **kwargs):
"""return fn or Exception"""
try:
return fn(*args, **kwargs)
except Exception as e:
return e |
def _map_step_size(map_size: int, lod: int) -> int:
"""Return the step size in the tile grid for the given map.
Args:
map_size (int): The base map size in map units
lod (int): The LOD level for which to calculate step size
Returns:
int: The coordinate distance between two tiles in ... |
def overflow_wrap(keyword):
"""``overflow-wrap`` property validation."""
return keyword in ('normal', 'break-word') |
def sign(x):
"""
Sign function
"""
return 1 if x >= 0 else -1 |
def upper(value):
"""Converts a string into all uppercase."""
return value.upper() |
def priority_keyword_merge(*args):
"""Merge keyword lists, giving priority to entries in later lists.
*args is a list of keyword lists, these lists should be of tuples in the form
(keyword, type)
"""
keyword_lists = [*args]
base_list = []
if len(keyword_lists) == 1:
return keyword_... |
def package_exists(package_name):
"""This is a simple function returning True/False for if a requested package string exists
in the add-on repository."""
return package_name == "frank" |
def get_assigned_rids_from_vehplan(vehicle_plan):
""" this function returns a list of assigned request ids from the corresponding vehicle plan
:param vehicle_plan: corresponding vehicle plan object
:return: list of request ids that are part of the vehicle plan
"""
if vehicle_plan is None:
re... |
def one_semitone_down(freq, amount=1):
"""
Returns the key, one tone down
:param freq: the frequency in hz
:param amount: the amount of semitones down
:return: the frequency one semitone up in hz
"""
return freq / 2 ** (amount / 12) |
def apikey_header(apikey):
"""generate apikey header"""
return {'Authorization': f'Apikey {apikey}'} |
def mclag_domain_id_valid(domain_id):
"""Check if the domain id is in acceptable range (between 1 and 4095)
"""
if domain_id<1 or domain_id>4095:
return False
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.