content stringlengths 42 6.51k |
|---|
def SummarizeResources(res_dict):
"""Summarizes the name of resources per resource type."""
result = {}
for res in res_dict:
result.setdefault(res['type'], []).append(res['name'])
return result |
def reverseWords(string):
""" reverse_words == PEP8 (forced mixedCase by CodeWars) """
return ' '.join(reversed(string.split())) |
def firehose_data_bucket(config):
"""Get the bucket name to be used for historical data retention
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string|bool: The bucket name to be used for historical data retention. Returns
False if firehose is not c... |
def _escape(data, entities={}):
"""Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
data = data.replace("... |
def escape_chars(text, chars):
"""Helper function to escape uncomfortable characters."""
text = str(text)
chars = list(set(chars))
if '\\' in chars:
chars.remove('\\')
chars.insert(0, '\\')
for ch in chars:
text = text.replace(ch, '\\' + ch)
return text |
def ensureTuple(value):
"""
Function that wraps an input value in a tuple if it is not already a tuple
"""
if isinstance(value, tuple):
value_tuple = value
else:
value_tuple = (value,) # comma creates the tuple
return value_tuple |
def str2bool(val):
"""Check if str is true boolean."""
return val.lower() in ("yes", "true", "t", "1") |
def bindata(n, lst, v=1):
"""
Bins a list of values into bins of size *n*.
**Parameters**
n: *int*
Number of values to bin together. e.g. ``n = 4`` would bin the first four values into a single value, then the next 4, etc.
lst: *list*
List of values to bin.
v: *int* or *f... |
def new_xform(val, reverse=False):
"""
Mock transformation to replace existing xforms in KEY_TRANSFORMS
:param val: Any value.
:param reverse: 'reverse' place holder for conversion methods
:return: (1, 1)
"""
if reverse:
return 1
return 1, 1 |
def generate_gt_string(tokens):
"""
Given a list of GT labels corresponding to a single event, convert them to a string formatted according to
Twitter-Event-Data-2019 GT format.
parameters
-----------
:param tokens: list
:return: str
"""
str = ""
for duplicate in tokens:
... |
def _getLocationWords(location, words_index):
"""
Retrieves the words found at the passage location
:param location: The passage location e.g. book/chapter/verse without z-padding
:param words_index:
:return: a list of words
"""
if location in words_index:
return words_index[location... |
def _moder_input(nin, nout, **kwargs):
"""
Write moder input.
Parameters
----------
nin : `int`
tape number for input file
nout : `int`
tape number for output file
Returns
-------
`str`
moder input text
"""
text = ["moder"]
text += [f"{nin:d} {no... |
def get_col_idx(i):
"""
define some colors for plotting
"""
cols = 'rkgbmckrgbmckrkgbmckrgbmckrkgbmckrgbmck'
return cols[i] |
def is_distributed_table(v):
"""Determine if an object is a DistributedTable."""
return v.__class__.__name__ in ("DistributedTable",
"RestoredDistributedTable") |
def aggregate(state, q, aggs, facets):
"""Generate aggregations, a generalized way to do facetting."""
for facet in facets:
aggs.update({facet: {
'terms': {'field': facet, 'size': state.facet_size}}
})
return aggs |
def transform_chi_eff_chi_a_s1zs2z(mass1, mass2, chi_eff, chi_a):
"""Returns spin1z.
"""
spin1z = (mass1 + mass2) / (2.0 * mass1) * (chi_eff - chi_a)
spin2z = (mass1 + mass2) / (2.0 * mass2) * (chi_eff + chi_a)
return spin1z,spin2z |
def to_marker_edge(marker_size, marker):
"""
get edge shrink_target
:param marker_size: int
:param marker: default 'o'
:return: float
"""
if marker in "s^>v<d": # `large` markers need extra space
return pow(2*marker_size,0.5)/2
else:
return pow(marker_size,0.5)/2 |
def findMyIndex(syllableCounter, phonemeCounter, seq):
"""
:param syllableCounter:
:param phonemeCounter:
:param seq:
:return:
"""
total = 0
n = 0
while n < (syllableCounter - 1):
total += len(seq[n])
n += 1
total += phonemeCounter
return (total - 1) |
def cons_merge(car_part, cdr_part):
"""Merge a car with a list or tuple cdr."""
return type(cdr_part)([car_part]) + cdr_part |
def read_float_with_comma(num):
"""Helper method to parse a float string representation that has
a comma as decimal separator.
Can't use locale as the page being parsed could not be in the
same locale as the python running environment
Args:
num (str): the float string to parse
Returns... |
def normalise_round(val, minimum, maximum):
"""
Normalise a value between two values and round it to nearest integer
:param val: value to normalise
:param minimum: minimum boundary
:param maximum: maximum boundary
:return: integer value
"""
return round((val - minimum) / float(maximum - ... |
def repo_name_from_uri(uri):
"""
Given a valid and complete URI, return just the repo name portion. Does no validation as to whether this is a
valid repo or uri.
:param uri:
The valid and complete URI.
:return:
A repo name.
"""
return uri.split(":/")[0] |
def gen_state_string(l):
"""Given a list of strings, generate the latex '\\vert {} \\rangle' representation of this in superposition."""
result = ""
str_template = r"\vert {} \rangle"
for idx,i in enumerate(l):
result += r"b_{{{}}}\vert \textrm{{{}}} \rangle ".format(idx, i[0])
if i != l... |
def reduce_by_multiple(trajectory, integer):
"""
keep only control points in given trajectory which are multiple of @integer
:param trajectory: array that describes the trajectory
:param integer: the multiple used for reducing
:return: the reduced trajectory
"""
reduced = trajectory[0:len(tr... |
def category_table_build(osm_table_name, categorysql):
"""
Returns an SQL OSM category table builder
Args:
osm_table_name (string): a OSM PostGIS table name
Returns:
sql (string): a sql statement
"""
sql = ("INSERT INTO category_%s (osm_id, cat) "
"SELECT DISTINCT o... |
def whisper(text):
"""
whisper
:param text:
:return:
"""
return text.lower() + '...' |
def getFirstPlist(byteString):
"""Gets the next plist from a byte string that may contain one or
more text-style plists.
Returns a tuple - the first plist (if any) and the remaining
string after the plist"""
plist_header = b'<?xml version'
plist_footer = b'</plist>'
plist_start_index = byteS... |
def list_prod(lst):
"""
Calculate the product of all numbers in a python list.
"""
prod = 1
for itm in lst:
prod *= itm
return prod |
def split_model_name(model_name):
"""
Split model name with ':'
Args:
model_name: the original model name
Returns: source name, and the model name
"""
model_split = model_name.split(":", 1)
if len(model_split) == 1:
return "", model_split[0]
else:
source_name, ... |
def _has_all_keys(op_dict, all_ops):
"""Check all keys."""
return all([k in op_dict.keys() for k in all_ops]) and len(all_ops) == len(op_dict) |
def concat_commands(commands):
"""Join UNIX commands with concat operator"""
return '; '.join(commands) |
def translate(text):
"""
Translate text into pig latin.
:param text string - text to translate.
:return string = translated text.
"""
translated = ""
vowels = "aeiou"
vowel_sounds = ["xr", "yt"]
for word in text.split(" "):
translated_word = ""
if word[0] in vowels ... |
def only_existing(l, haystack):
"""
Helper to filter elements not already on the haystack in O(n)
"""
s = set(haystack)
return [item for item in l if item in s] |
def calculate_token_freq(
token,
file_tokens
) -> int:
"""
Calculate the token frequency in the file corpus
:type token: str
:type file_tokens: list
"""
counter = 0
for file_token in file_tokens:
if token == file_token:
counter += 1
return counter |
def parse_helm_list_output(helm_list_output):
"""
Function will perform a manipulation on a string output from the 'helm list' command
Returns an array of dicts with installed chart names and namespaces as strings
as [{'chart_name': 'some_chart_name', 'name_space': 'some_name_space'}]
by validatin... |
def array_strip_units(data):
""" strip the units of a quantity """
try:
return data.magnitude
except AttributeError:
return data |
def solution(number):
""" Thanks to 'M.Gaidamaka' from CodeWars """
number -= 1
a = number // 3
b = number // 5
c = number // 15
return [a - c, b - c, c] |
def mod_by_AES(hex_num):
""" Here we take a hex_num and we mod it by the AES irreducible.
This is a helper method to the russian_peas method
"""
AES_IRREDUCIBLE = 0x11A
if hex_num > 0xFF:
hex_num = hex_num % AES_IRREDUCIBLE
return hex_num |
def bool_to_int(matrix):
"""
I find it much easier to read 0s and 1s than boolean words, so I wrote this helper function.
:param matrix: A matrix to translate to integers.
:return: A matrix of integers.
"""
for row in range(len(matrix)):
for col in range(len(matrix[0])):
mat... |
def pyfloat(v_str):
"""Convert string repr of Fortran floating point to Python double."""
# NOTE: There is no loss of information from SP to DP floats
return float(v_str.lower().replace('d', 'e')) |
def construct_url(ip_address: str) -> str:
"""Construct the URL with a given IP address."""
if "http://" not in ip_address and "https://" not in ip_address:
ip_address = "{}{}".format("http://", ip_address)
ip_address = ip_address.rstrip("/")
return ip_address |
def base_to_str( base ):
"""Converts 0,1,2,3 to A,C,G,T"""
if 0 == base: return 'A'
if 1 == base: return 'C'
if 2 == base: return 'G'
if 3 == base: return 'T'
raise RuntimeError( 'Bad base: %d' % base ) |
def clean_white_spaces(string):
"""Gets rid of white spaces in the string
:param string: string to be processed
"""
try:
# in case it is in byte value
string = string.decode('utf-8')
except:
pass
res = ''
words = string.split()
for word in words:
res = ... |
def _get_units(intuple):
"""
Extract Units from metadata.
>>> _get_units([("fmap.nii.gz", {"Units": "rad/s"})])
'rad/s'
>>> _get_units(("fmap.nii.gz", {"Units": "rad/s"}))
'rad/s'
"""
if isinstance(intuple, list):
intuple = intuple[0]
return intuple[1]["Units"] |
def build_fullauth_config(settings):
"""Build fullauth configuration dictionary."""
fullauth_config = {
"authtkt": {
"secret": settings.get("fullauth.authtkt.secret", "fullauth_psst"),
"hashalg": settings.get("fullauth.authtkt.hashalg", "sha512"),
},
"session": {
... |
def shortened_interface(name):
"""Condenses interface name. Not canonical - mainly for brevity"""
name = name.replace("GigabitEthernet", "ge")
name = name.replace("0/0/0/", "")
return name |
def normalize_baseuri(baseuri: str) -> str:
"""Normalize a baseuri
If it doesn't end in a slash, add one.
"""
if baseuri[-1] != "/":
return baseuri + "/"
return baseuri |
def primes(num):
"""
Get a list of a desired count of prime numbers.
:param num: Number of prime numbers (N).
:type num: short, int, long
:return: List of prime numbers, readable in Python.
:rtype: list
>>> primes(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
"""
prime_list = [0]*num... |
def user_info(
first_name,
last_name,
**profile):
"""Function that builds user information."""
profile['firstname'] = first_name
profile['lastname'] = last_name
return profile |
def _read_to_str(path):
"""Read a file into a string"""
with open(path, "r") as f:
return f.read() |
def valid_block(top_row, mid_row, bot_row, pos):
"""
Is the 3x3 pattern at a given position of a 3-row rectangle valid?
I.e. does it map to 0 in GoL?
"""
mid_cell = mid_row[pos+1]
ring_sum = sum(top_row[pos:pos+3]) + mid_row[pos] + mid_row[pos+2] + sum(bot_row[pos:pos+3])
if m... |
def linearSearch(myList, objetive, iter_lin=0):
"""
Searches in the list, the objetive number in a iteratively way.
"""
match = False
for element in myList:
iter_lin += 1
if element == objetive:
match = True
break
return (match, iter_lin) |
def get_duplicates(iterable):
"""Return a set of the elements which appear multiple times in iterable."""
seen, duplicates = set(), set()
for elem in iterable:
if elem in seen:
duplicates.add(elem)
else:
seen.add(elem)
return duplicates |
def get_items_markdown(items, indent=""):
"""Return a list of NEWS entries as a Markdown list"""
return "".join([indent + "* %s\n" % item for item in items]) |
def kvret_get_constructed_history_and_golden_response(usr_utterances, sys_utterances):
"""
This function construct the reversed order concat of dialogue history from dialogues from users and system.
as well as the last response(gold response) from user.
@param usr_utterances:
@param sys_utterances:
... |
def sql_concurrently(index):
"""
Is the index concurrently or not
return : string
"""
res = "CONCURRENTLY"
if "concurrently" in index:
if index["concurrently"] is False:
res = ""
return res |
def format_floats(data):
"""Returns formatted list of floats from unformatted list of floats
Parameters
----------
data : list
The list of floats to be formatted
Returns
-------
list
Formatted floats (now string).
"""
return ['{0:.3f}'.format(elem) for elem in data... |
def paginate(items, items_per_page):
"""Splits `items` list into lists of size `items_per_page`.
>>> paginate([1, 2, 3], 1)
[[1], [2], [3]]
>>> paginate([1, 2, 3, 4, 5, 6, 7], 3)
[[1, 2, 3], [4, 5, 6], [7]]
>>> paginate([], 3)
[]
"""
result = []
for i in range(0, len(items), i... |
def html(content, **kwargs):
"""HTML (Hypertext Markup Language)"""
if hasattr(content, "read"):
return content
elif hasattr(content, "render"):
return content.render().encode("utf8")
return str(content).encode("utf8") |
def solution1(n):
"""
This function returns list of prime factors.
(This is my own solution... but it is complicated and slow)
"""
def find_next_prime_factor(startIndex):
"""
Find the next valid prime factor with given startIndex(inclusive)
"""
while True:
... |
def move_list_item(mod_list, item, new_pos):
"""Reposition an item in a list"""
if item in mod_list:
old_pos = mod_list.index(item)
mod_list.pop(old_pos)
mod_list.insert(new_pos, item)
return mod_list |
def floor2(i):
"""Find greatest even integer less than or equal to given integer.
Arguments:
i (int): starting integer
Returns:
(int): greatest even integer
"""
return i - (i%2) |
def sort_objects_by_score(objects, reverse=True):
"""
Put any set of objects in order from high score to low score.
"""
if reverse:
sign = -1
else:
sign = 1
return sorted(objects, key=lambda k: sign*k['score']) |
def mmirror4(matrix):
"""Do a 4-way mirroring on a matrix from top-left corner."""
width = len(matrix[0])
height = len(matrix)
for i in range(height):
for j in range(width):
x = min(i, height - 1 - i)
y = min(j, width - 1 - j)
matrix[i][j] = matrix[x][y]
r... |
def check_fields(default_dict, new_dict):
"""
Return the dictionary with default keys and values updated by using the information of ``new_dict``
:param dict default_dict:
Dictionary with default values.
:param dict new_dict:
Dictionary with new values.
:return: dict.
"""
# ... |
def format_frequency(value: str) -> str:
"""Format frequency value to more human-readable form."""
return f"{value} " |
def format_color(r, g, b):
"""Format a color as a string.
r, g, b -- integers from 0 to 255
"""
return '#{0:02x}{1:02x}{2:02x}'.format(int(r * 255), int(g * 255), int(b * 255)) |
def has_new_status(metric, new_status: str, most_recent_measurement_seen: str) -> bool:
"""Determine if a metric got a new status after the timestamp of the most recent measurement seen."""
recent_measurements = metric.get("recent_measurements") or []
if len(recent_measurements) < 2:
return False #... |
def is_json(metadata: str) -> bool:
"""Check whether the string is a json."""
return metadata[0] in ['{', '['] |
def centre_to_box(centre_width):
""" A function to convert from centre and width notation to start and stop notation (in both x and y directions).
Inputs:
centre_wdith
Returns:
History:
2020_10_28 | MEG | Wrote the docs.
"""
x_start = centre_width[0] - centre_width[2]
... |
def find_defining_class(obj, method_name):
"""Finds and returns the class object that will provide
the definition of method_name (as a string) if it is
invoked on obj.
obj: any python object
method_name: string method name
"""
for ty in type(obj).mro():
if method_name in ty.__dict__... |
def is_numlike(obj):
"""Return True if obj looks like a number or numerical array."""
try:
obj = obj + 1
except:
return False
# all cool
return True |
def is_sorted (l, ascending = True):
"""
Check whether array is sorted.
source: https://stackoverflow.com/questions/3755136/pythonic-way-to-check-if-a-list-is-sorted-or-not
:param l: list
:return: is sorted
"""
if ascending:
return all (l[i] <= l[i+1] for i in range (len (l)-1))
... |
def checkH(board, intX, intY, newX, newY):
"""Check if the horse move is legal, returns true if legal"""
tmp=False
if abs(intX-newX)+abs(intY-newY)==3:
if intX!=newX and intY!=newY:
tmp=True
return tmp |
def ktmetric(kt2_i, kt2_j, dR2_ij, p = -1, R = 1.0):
"""
kt-algorithm type distance measure.
Args:
kt2_i : Particle 1 pt squared
kt2_j : Particle 2 pt squared
delta2_ij : Angular seperation between particles squared (deta**2 + dphi**2)
R : Radius paramete... |
def flatten_proposal_field(representation, allow_fields=[]):
"""
The helper function that used in `to_representation()` for
flattening the `proposal` object from serialized
`ProposedTalkEvent` or `ProposedTutorialEvent`.
"""
proposal_repr = representation.pop('proposal')
for key in proposal_... |
def modus_ponens(p, q):
"""Implements the modus ponens logic table: p -> q"""
if p:
return q
else:
return not p |
def list2row(worksheet, row, col, values, positions=None):
"""
Create header of the template xlsx file
:param Worksheet worksheet: Worksheet class to write info
:param int row: Row number to start writing
:param int col: Column number to start writing
:param list values: List of ... |
def _score_for_model(meta):
""" Returns mean score between tasks in pipeline that can be used for early stopping. """
mean_acc = list()
pipes = meta["pipeline"]
acc = meta["accuracy"]
if "tagger" in pipes:
mean_acc.append(acc["tags_acc"])
if "parser" in pipes:
mean_acc.append((ac... |
def dumb_filter(line: str) -> bool:
"""Filters a Wikidata line that is a dictionary in string format.
Applies a simple check that tests if the currenty entity line has a English
Wikipedia article before loading. The reason is that loading a JSON object is slow
before running it, that speeds up code. Re... |
def align(value, alignment):
"""Align `value` upward towards the nearest multiple of `alignment`."""
return ((value + alignment - 1) // alignment) * alignment |
def calc_intersection_with_chroma_axis(inner_cusp, outer_cusp):
"""
calculate the intersection of the two cusps
and chroma axis in L*-Chroma plane.
Returns
-------
touple
(L*star, Chroma). It is the coordinate of the L_cusp.
"""
x1 = inner_cusp[1]
y1 = inner_cusp[0]
x2 =... |
def standardize(obj):
"""
Take any Deezer obj and return a standard object (e.g. artist or author keys are renammed as creator)
"""
if 'picture_medium' in obj.keys():
obj['image'] = obj.pop('picture_medium')
if 'cover_medium' in obj.keys():
obj['image'] = obj.pop('cover_medium')
return obj |
def t(milliseconds: int) -> str:
"""Inputs time in milliseconds, to get beautified time,
as string"""
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days... |
def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part including and after the substring."""
i = s.find(find)
return s[:i], s[i:] |
def j2_quote(s):
"""Jinja2 custom filter that quotes a string
"""
return '"{}"'.format(s) |
def get_username(current_user):
"""
Return the current username. If the user already logged out, return None
"""
try:
return current_user.username
except:
return None |
def get_reformatted_target_dir(path: str):
"""Get reformatted target dir with trailing '/'.
Args:
path: (str): Original path.
Returns:
str: Reformatted path.
"""
if not path.endswith("/"):
path = path + "/"
return path |
def match(texts, substr):
"""Text match.
Ctrl/command + F for now.
"""
ret = []
for t in texts:
if substr in t:
ret.append(t)
return ret |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if type(number) != int:
return "INVALID INPUT, ENTER AN INTEGER!"
start, end = 0, number + 1
while s... |
def portrange2str(port_range):
"""port_range is a tuple of 2 ports
"""
if port_range[1]:
portstr = "port range %s-%s" % (port_range[0], port_range[1])
else:
portstr = "port %s" % (port_range[0],)
return portstr |
def get_missing_residues(uniprot_seq, pdb_seq):
"""
Comparing the structural and UniProt sequence to identify the different
residues.
Arguments:
parameter 1: The UniProt sequence.
parameter 2: The PDB sequence.
Returns:
This is a description of what is returned.
"""
# pdb_seq_ind... |
def _1(value):
"""
Integer decoder.
```python
>>> from Tyf import decoders
>>> decoders._1((1, ))
1
>>> decoders._1((1.0, "6", 0b111))
(1, 6, 7)
```
"""
return int(value[0]) if len(value) == 1 else tuple(int(v) for v in value) |
def SplitPatch(data):
"""Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename.
"""
patches = []
filename = None
diff = []
for line in data.splitline... |
def map_1d_to_2d(index, N, M):
"""
Function: map_1d_to_2d\n
Parameter: index -> index which needs to be mapped to the 2D coordinates, N -> number of rows in the grid, M -> number of columns in the grid\n
Return: the location of the mapped index\n
"""
x = index // (N - 1)
y = index % M
re... |
def update_cv_validation_info(test_validation_info, iteration_validation_info):
"""
Updates a dictionary with given values
"""
test_validation_info = test_validation_info or {}
for metric in iteration_validation_info:
test_validation_info.setdefault(metric, []).append(iteration_validation_... |
def hflip_pattern(pattern):
"""Flip a pattern horizontally"""
newpattern = ["".join(reversed(j)) for j in pattern]
return newpattern |
def get_curr_max_virtual_slots_cmd(lparid=1):
"""
Get the current max virtual slots limit for the LPAR
:param lparid: LPAR ID. For IVM this parameter is not needed
:returns: A HMC command to get the maximum number of virtual slots
configurable on the VIOS.
"""
return ("lshwres -r ... |
def escape_ntfs_invalid(name):
"""
Escapes characters which are forbidden in NTFS, but are not in ext4.
:param name: Path potentially containing forbidden NTFS characters.
:return: Path with forbidden NTFS characters escaped.
"""
return name.replace('*', '#002A').replace('|', '#007C').replace(':', '#003A').repl... |
def mock_platform_list_2():
"""System and version doesn't match with the mocked one"""
return [
{"name": "macos", "platform_info": {"system": "test1", "version": "test3"}},
{"name": "ubuntu", "platform_info": {"system": "test2", "version": "test4"}},
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.