content stringlengths 42 6.51k |
|---|
def get_args_section_name(layer: int):
"""Return the specified layer's parser name"""
return "__layer{layer}_parser".format(layer=layer) |
def line_statements(line):
"""Break up line into a list of component Fortran statements
Note, because this is a simple script, we can cheat on the
interpretation of two consecutive quote marks.
>>> line_statements('integer :: i, j')
['integer :: i, j']
>>> line_statements('integer :: i; real :: ... |
def __collinear(a, b, c, thresh=1e-10):
"""Checks if 3 2D points are collinear."""
x1,y1 = a; x2,y2 = b; x3,y3 = c
return abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) < thresh |
def equals(col, val):
"""Return a string that has col = val."""
return f"{col} = {val}" |
def split(slicable, fraction):
"""
splits data into test-train set or dev-validation set; does not shuffle.
params: slicable - an object that responds to len() and [], works on dataframes
fraction - a value between 0 and 1
returns: (x, y) - where x has (1-fraction) percent entries and y has the rest
"""
... |
def check_start_or_end(dates, today):
"""
Function:
check_start_or_end
Description:
checks if given date starts or ends today
Input:
- dates - a list containing start and end date (strings) for an event
- today - today's date (string)
Output:
- 0 if no event s... |
def lines(a, b):
"""Return lines in both a and b"""
linesOfA = set()
tokensA = a.split("\n")
linesOfA.update(tokensA)
linesOfB = set()
tokensB = b.split("\n")
linesOfB.update(tokensB)
# compute intersection i.e. set which contains only lines of both, a and b
result = linesOfA.inter... |
def parse(line):
"""
"""
ret = []
index, start, end = 0, 0, 0
length = len(line)
while True:
if line[index] == '"':
index = index + 1
end = index + line[index:].find('"')
ret.append(line[index:end])
index = end + 1
start = end +... |
def filter_kwargs(kwargs, prefix):
"""Keep only kwargs starting with `prefix` and strip `prefix` from keys of kept items."""
return {k.replace(prefix, ''): v for k, v in kwargs.items() if k.startswith(prefix)} |
def cleanup_code(content: str):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n') |
def scoring_key(gender: str, event_code: str) -> str:
"""Utility function to get the <gender>-<event> scoring key."""
return ("%s-%s" % (gender, event_code)).upper() |
def hxltm_hastag_de_csvhxlated(csv_caput: list) -> list:
"""hxltm_hastag_de_csvhxlated [summary]
Make this type of conversion:
- 'item__conceptum__codicem' => '#item+conceptum+codicem'
- 'item__rem__i_ara__is_arab' => '#item+rem+i_ara+is_arab'
- '' => ''
Args:
csv_caput (list): Array o... |
def get_lru(mem_cells, max_size=100):
"""Least recently used (LRU) cache mechanism.
:param mem_cells - sequence of memory cells that should be placed in cache, list, in example, 1, 2, 3, 4, 5, 4, 6].
:param max_size - cache size, generally in memory cells, usually in bytes, in example, 4.
:return final ... |
def handle_object_placement(handle_to_self_field, potential_object, objectType, list=False):
"""
Helper function to checks to see if we can safely set a given field (handle_to_self_field)
to a potential_object by checking whether or not it is an instance of objectType.
:param handle_to_self_... |
def get_of_colour(shape, target_colours):
""" From a shape gets cells of colour.
>>> get_of_colour([(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5), (5, 1, 8)], [2])
[(0, 1, 2), (1, 1, 2)]
>>> get_of_colour([(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5), (5, 1, 8)], [2, 5])
[(0, 1, 2), (1, 1, 2), (3, 3, 5... |
def _enleverAlea(text):
"""Gets rid of the stupid thing that they did, idk what it really is for, but i guess it adds security"""
sansalea = []
for i, b in enumerate(text):
if i % 2 == 0:
sansalea.append(b)
return ''.join(sansalea) |
def append_write(filename="", text=""):
""" writes at the end of a file """
chars = 0
with open(filename, mode="a", encoding="utf-8") as f:
chars += f.write(text)
f.close()
return chars |
def string2numList(strn):
"""Converts a string to a list of integers based on ASCII values"""
"""origin pickle has bug """
return [ord(chars) for chars in list(strn)] |
def strCanFormPalindrome(keyStr):
"""
determine if any anagram of keyStr can form a palindrome
@param keyStr: a string for which to determine if any of its anagram can form a palindrome
@return boolean true or false.
ASSUMPTION: All characters are lower case.
"""
charOcc... |
def find_swift_version_copt_value(copts):
"""Returns the value of the `-swift-version` argument, if found.
Args:
copts: The list of copts to be scanned.
Returns:
The value of the `-swift-version` argument, or None if it was not found in the copt list.
"""
# Note that the argument ... |
def phase_signal_n_times(signal, times, phaser):
"""Phase signal number of times using phaser function."""
for _ in range(times):
signal = phaser(signal)
return signal |
def find_range(delT):
"""
tind the range to radar using Stull eq. 8.16
Parameters
----------
delT: float
the round-trip travel times (units: micro sec)
Returns
-------
radar_range: float
range from target to radar (units: km)
"""
### BEGI... |
def _k_simplex_neighbor_index_list(d, k):
"""Given a d-simplex with d being 2 or 3, indexes for neighbor simplexes in the scipy.Delaunay triangulation
are provided for all k-simplices with k<d that are part of the d-simplex."""
if d == 2 and k == 1:
return 2, 0, 1
elif d == 3 and k == 2:
... |
def get_vpath_list(vpath):
"""
return a list of the elements of the already canonicalized vpath
"""
vpath_list = [v for v in vpath.split("/") if len(v) > 0]
return vpath_list |
def as_undirected(edges):
"""
Represent a directed edge as undirected.
Parameters
---------
edges : array-like of Edge
array of directed edges (u,v,k)
Returns
-------
list of tuples
"""
edge_set = frozenset(
[ frozenset((edge[0], edge[1]))
... |
def is_square_free(n: int) -> bool:
"""
https://en.wikipedia.org/wiki/Square-free_integer
>>> is_square_free(1)
True
>>> is_square_free(4)
False
>>> is_square_free(46)
True
"""
from math import sqrt
for i in range(2, round(sqrt(n)) + 1):
if n % (i**2) == 0:
... |
def unchained_function(function):
"""Return true if the function is unchained."""
return function % 2 == 0 |
def ensure_raw(x):
"""Return raw tensor from x, unless it already is a raw tensor"""
try:
return x.raw
except AttributeError:
return x |
def DefineDofDependencyScalar(scalar, variable_list):
""" This method injects a dependency into a scalar from a variable list
Keyword arguments:
scalar -- The scalar to be injected
variable_list -- The variable list injected
"""
return scalar(*variable_list) |
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
... |
def identify(nick, host):
"""Return IRC commands which identify the bot to the server."""
fmt = {'nick': nick, 'host': host}
return 'NICK %(nick)s\r\nUSER %(nick)s %(host)s 0 :%(nick)s' % fmt |
def state2bin(s, num_bins, limits):
"""
:param s: a state. (possibly multidimensional) ndarray, with dimension d =
dimensionality of state space.
:param num_bins: the total number of bins in the discretization
:param limits: 2 x d ndarray, where row[0] is a row vector of the lower
limit... |
def rpad(array, n=70):
"""Right padding."""
current_len = len(array)
if current_len > n:
return array[: n - 1]
extra = n - current_len
return array + ([0] * extra) |
def _IgnorePaused(instance_info):
"""Removes information about whether a Xen state is paused from the state.
As it turns out, an instance can be reported as paused in almost any
condition. Paused instances can be paused, running instances can be paused for
scheduling, and any other condition can appear to be p... |
def convert_to_valid_colour_bounds(*arg):
"""
Purpose:
Converts a colour bound of strings/floats to a bound of ints
Args:
*arg - list of bounds passed into the function
Returns:
colours - a list of the updated bounds.
"""
args_num = len(arg)
colours = []
for i in ... |
def _correlation_matrix(oob_predictions_and_indices):
"""Computes the correlation between the single estimators of the ensemble model.
Args:
oob_predictions_and_indices (List[Tuple[np.array, np.array]]): Out-of-bag indices and predictions for each
estimator of the ensemble model.
Retur... |
def calc(kbps, burst_time=1.5):
"""Calculate Normal and Max Burst values"""
bps = kbps * 1000
burst_normal = int(round(bps / 8 * burst_time, 0))
burst_max = 2 * burst_normal
return (burst_normal, burst_max) |
def res_ene(alpha, beta):
"""
resonance energy Eres = Er - i*Gamma/2 from alpha and beta
assumes a quadratic term: lambda = k**2 + 2*a**2*k + a**4 + b**2
solve for lambda = 0
"""
Er = beta**2 - alpha**4
G = 4*alpha**2 * abs(beta)
return Er, G |
def is_derepFas(title):
"""
Takes a fasta title line (with or without the initial '>'), and tests to see whether it looks
like a usearch dereplicated title line - i.e., does it end "size=n;"?
"""
title = title.strip(';')
try:
countclause = title.split(';')[-1] #try to split at ';'
... |
def none_string(vr, def_str, none_str = ""):
"""Return DEF_STR or NONE_STR depends on weather VR is None or empty string.
@param { any } vr : Any variable you want to check.
@param { string } def_str : Default string.
@param { string } none_str : None string.
"""
if vr == None or vr == "" or vr... |
def splitMyString(c, str_in):
"""
Version 2: Using built-in methods
Returns a list of strings separated by character 'c' where 'c' is the
"splitter" character and 'str_in' is the string.
Example Usage:
splitMyString('*', 'aaa*sss*fff') returns: ['aaa', 'sss', 'fff']
splitM... |
def split_identifier(identifier):
"""Splits string at _ or between lower case and uppercase letters."""
prev_split = 0
parts = []
if '_' in identifier:
parts = [s.lower() for s in identifier.split('_')]
else:
for i in range(len(identifier) - 1):
if identifier[i + 1].isup... |
def get_human_readable(size, precision=2):
"""
Get human readable file size
"""
suffixes=['B','KiB','MiB','GiB','TiB']
suffixIndex = 0
while size >= 1024:
suffixIndex += 1
size = size/1024.0
return "%.*f %s"%(precision,size,suffixes[suffixIndex]) |
def or_query(*qrys):
"""create a and query from a given set of querys.
:param qrys: the respective queries
"""
return "(" + "|".join([qry for qry in qrys if qry]) + ")" |
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params
:param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree.
:param value: Param value
:... |
def inverse2d(a):
"""
Returns the matrix inverse of 2x2 matrix "a".
:param a: The original 2x2 matrix.
:return: Its matrix inverse.
"""
result = [[0, 0], [0, 0]]
det_a = (a[1][1] * a[0][0]) - (a[0][1] * a[1][0])
for a_row in range(len(result)):
for a_col in range(le... |
def format(cmds, sep=" , "):
"""Format the alias command"""
return sep.join(" ".join(cmd) for cmd in cmds) |
def maxima(records):
"""
Calculate the indices of the records in the provided list with the min buy and max sell prices.
:param records: List of dictionaries containing price information.
:return: A tuple containing the indices for the records with min buy and max sell price in the input list.
"""
... |
def str_to_bytes(value):
"""Return bytes object from UTF-8 formatted string."""
return bytes(str(value), 'UTF-8') |
def make_rename_col_dict(cols, graduating_year):
"""
Returns dictionary to rename columns respective to each graduating year
e.g., 'GPA_2008' --> 'GPA_8th_grade' for students in class of 2012
Returns
----------
dict
Parameters
----------
cols : array
list of all columns to ... |
def get_recipes_from_dict(input_dict: dict) -> dict:
"""Get recipes from dict
Attributes:
input_dict (dict): ISO_639_1 language code
Returns:
recipes (dict): collection of recipes for input language
"""
if not isinstance(input_dict, dict):
raise TypeError("Input is not typ... |
def deep_merge(a, b):
"""
Deep Merge. If a and b are both lists, all elements in b are
added into a. If a and b are both dictionaries, elements in b are
recursively added to a.
:param a: object items will be merged into
:param b: object items will be merged from
"""
if a is None:
... |
def inverse(a, n):
"""Find the multiplicative inverse of one number over a given range.
Adapted from Wikipedia: Extended Euclidian Algorithm -
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Returns the multiplicative inverse of a over the finite range n. The result
is a number which... |
def get_input_list(input_val, default_val):
"""
Method to get a list from a comma separated string.
:param input_val: Input string or list
:param default_val: Default value (generally used for a spider)
:return: listified string or default_val if input is not a list or string.
"""
if isinsta... |
def normalizeEntities(formattedEntities):
"""
Normalizes the provider's entity types to match the ones used in our evaluation.
Arguments:
formattedEntities {List} -- List of recognized named entities and their types.
Returns:
List -- A copy of the input list with modified entity types.... |
def shorten_authors(auth_string, display_auth = 5):
"""
Shortens article author list. By convention first display_auth-1 authors and
the last author are shown. The rest is replaced by '...'.
Parameters
----------
auth_string : str
Article authors separated by comma.
display_auth : ... |
def return_index(character: str) -> int:
"""
Computes the character index (which needs to fit into the 26 characters list)"""
if character.islower():
return ord(character) - ord("a")
else:
return ord(character) - ord("A") |
def parse_name(name):
"""
Parses a name to return the metadata.
Names are formatted like
PARAM1=VALUE1__PARAM2=VALUE2__PARAM3
(note PARAM3 has no value)
Parameters
----------
name: str
Name of the folder.
Output
------
out: dict
"""
entries = name.split('_... |
def convertActionToVelocity(action):
""" Converts the action (an integer from 0 to 8)
to the changes in velocity in x and y
according to the following table
dV_x
| -1 0 1
----------------
-1 | 0 1... |
def latex(input):
"""Create the latex output version of the input."""
if isinstance(input, float):
input = "%.4f" % input
return "{" + str(input) + "}"
elif isinstance(input, int):
return "{" + str(input) + "}"
elif isinstance(input, dict):
return str(input).replace('{', ... |
def dela1(n,a0,a1,x,y):
"""
Dela1 dela1 dela1 dela
Args:
n: (array): write your description
a0: (array): write your description
a1: (array): write your description
x: (array): write your description
y: (array): write your description
"""
s=0;
for i in r... |
def build_complement(dna):
"""
:param dna: str, a DNA stand
:return: str, the complement of dna
"""
ans = ''
for i in range(len(dna)):
if dna[i] == 'A':
ans += 'T'
elif dna[i] == 'T':
ans += 'A'
elif dna[i] == 'C':
ans += 'G'
el... |
def _sorted_nodes(nodes):
"""Sort nodes on their names."""
return sorted(nodes, key=lambda node: node.name) |
def utf8chars(u):
"""Format an Unicode character in a \\mubyte-friendly style.
character ordinal value should be < 0x10000."""
if u < 0x80:
return '^^%02x' % u
if u < 0x800:
return '^^%02x^^%02x' % (0xc0 | (u >> 6),
0x80 | (0x3f & u))
return '^^%02x^... |
def result(player_1, player_2):
"""Analyserar informationen som funktionen gameplay har genererat.
Parameters
----------
x : int
representerar spelare 1:s spelprestation
y : int
representerar spelare 2:s spelprestation
Returns
-------
str :
skriver ut resultatet
Exa... |
def get_rounds(number):
"""Create a list containing the current and next two round numbers.
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [number, number + 1, number + 2] |
def _get_border(border, size):
"""Get the border size of the image"""
i = 1
while size - border // i <= border // i:
i *= 2
return border // i |
def to_minus_plus(a):
"""
translate to -1 +1
"""
return 2*(a-0.5) |
def hasattr_recursive(item, attr_string):
"""hasattr for nested attributes
Parameters
----------
item : object
Any python object with attributes
attr_string : string
A string of attributes separated by periods (ex: first.second)
Note
----
An example would be a module wi... |
def _calculate_log2_num_bytes(value: int) -> int:
"""
Determine the number of bytes required to encode the input value.
Artificially limited to max of 8 bytes to be compliant
:param value:
:return: The calculate the number of bytes
"""
for log2_num_bytes in range(4):
limit = 1 << (... |
def split_stable_id(stable_id):
"""Split stable id, returning:
* Document (root) stable ID
* Context polymorphic type
* Character offset start, end *relative to document start*
Returns tuple of four values.
"""
split1 = stable_id.split("::")
if len(split1) == 2:
spl... |
def create_kp(args):
"""
Generate a KP given a tuple of input, edge, output
"""
source, edge, target = args
return {
"url": "http://mykp",
"infores": "mykp",
"maturity": "development",
"operations": [
{
"subject_category": source,
... |
def get_class_name(object):
"""Returns the class name of a given object."""
return object.__class__.__name__ |
def growth_pos_check(clods, pos):
"""for checking the position of a growing seed tip
Like position_calc but amended for growing seed
each time the seed grows there is a cheek for clod collisions
:param clods: All the clod objects in the bed
:param pos: The proposed position of the seed tip
... |
def _get_tags(tags):
"""Translate the {Name:x, Value:y} crap we get back from aws into a dictionary."""
if tags is None:
return {}
return {x['Key']: x['Value'] for x in tags} |
def encode_list_index(list_index: int) -> bytes:
"""Encode an index for lists in a key path to bytes."""
return list_index.to_bytes(2, byteorder='big') |
def cappa2npsh(cappa, head):
"""Calculate the npsh required for a given pump's typical number.
:param cappa (float): typical number
:param head (float): head [m]
:return npsh_req (float): neat positive suction head required [m]
"""
npsh_req = .25 * cappa**(4/3) * head
return npsh_req |
def vecDistanceSquared(inPtA, inPtB):
"""calculate the square of the distance between two points"""
ddx = inPtA[0] - inPtB[0]
ddy = inPtA[1] - inPtB[1]
ddz = inPtA[2] - inPtB[2]
return ddx*ddx + ddy*ddy + ddz*ddz |
def process_index(index, intensity, interaction_symbol):
"""
Process index to get edge tuple. Disregard edge weight.
Args:
index (str): index of the edge list dataframe.
intensity (float): intensity of the edge.
interaction_symbol (str): symbol used to separate node labels.
Ret... |
def format_sub_response(sub_response):
""" format and return given subscription response into dictionary """
return {
"transfer_to": sub_response["transfer_to"],
"transactions": sub_response["transactions"],
"verifications": sub_response["verifications"]
} |
def get_solution(story):
"""
Find the answer to the question: "What are the instances of vowels (excluding y) contained in story? Repeat them
in order."
:param story: the list of letters to find vowels in
:return: a list of vowels
"""
story.append('#')
my_outputs = story + [letter for le... |
def pretty_list(the_list, conjunction = "and", none_string = "nothing"):
"""
Returns a grammatically correct string representing the given list. For
example...
>>> pretty_list(["John", "Bill", "Stacy"])
"John, Bill, and Stacy"
>>> pretty_list(["Bill", "Jorgan"], "or")
"Bill or Jorgan"
>... |
def hasTag(tagName, typeOrPropertyObj):
"""check up if the as parameter given object has a tag with the
given name
Keyword arguments:
tagName -- name of the tag to look for
typeOrPropertyObj -- type or property object to check up
"""
if not hasattr(typeOrPropertyObj, 'tags'):
retur... |
def gcd(a, b):
"""Euclidean algorith of finding GCD"""
if b > a:
return gcd(b, a)
if a % b == 0:
return b
return gcd(b, a % b) |
def getjflag(job):
"""Returns flag if job in finished state"""
return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0 |
def get_text(value):
"""Get text from langstring object."""
return value["langstring"]["#text"] |
def field_to_markdown(field):
"""Genera texto en markdown a partir de los metadatos de un `field`.
Args:
field (dict): Diccionario con metadatos de un `field`.
Returns:
str: Texto que describe un `field`.
"""
if "title" in field:
field_title = "**{}**".format(field["title"]... |
def decode_rle(input):
"""
Gets a stream of data and decompresses it
under a Run-Length Decoding.
:param input: The data to be decoded.
:return: The decoded string.
"""
decode_str = ""
count = ""
for ch in input:
# If not numerical
if not ch.isdigit():
# ... |
def calc_incs(_span):
"""Calculate the increments needed for timesteps within table
:param flot _span: Span of time needed
:return: Range needed to complete timesteps
:rtype: int
"""
return int(_span*60/10) |
def makeList(roots):
"""Checks if the given parameter is a list. If not, creates a list with the parameter as an item in it.
Parameters
----------
roots : object
The parameter to check.
Returns
-------
list
A list containing the parameter.
"""
if isinstance(... |
def skip_instance(context, family_name):
"""
Skip process if instance exists.
:param context: (obj) Instance context
:param family_name: (str/list) F
:return: bool
"""
if not isinstance(family_name, list):
family_name = [family_name]
_exists = False
for instance in context:
... |
def get_security_args(security, d):
"""
Returns the parameters in d that are prepended with the string in security.
"""
ud = {}
for key in d:
if security + '_' in key:
if key.startswith(security + '_'):
ukey = key.replace(security + '_', '')
ud[uke... |
def _getNextCurrControl(curr_control, res_control, max_control):
"""Compute the next possible control instruction
Args:
curr_control (list of int|str): last executed control
res_control (list of int|str): resolution control
max_control (list of int|str): maximum control
Returns:
... |
def gql_project_users(fragment):
"""
Return the GraphQL projectUsers query
"""
return f'''
query($where: ProjectUserWhere!, $first: PageSize!, $skip: Int!) {{
data: projectUsers(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
''' |
def is_anagram_0(s1, s2):
"""
This is my first solution, and it's incorrect because this method checks palindrome, not anagram.
"""
if s1 is None or s2 is None:
return False
if len(s1) != len(s2):
return False
s1_list = list(s1)
s2_list = list(s2)
for i in range((len(s1... |
def get_source_shape(data_shape, value_shape):
"""Returns the shape of value that will be used to broadcast against data."""
cannot_broadcast = False
source_shape = value_shape
for i, j in zip(reversed(data_shape), reversed(value_shape)):
if j not in (1, i):
cannot_broadcast = True
... |
def mode_to_mime_type(url_mode):
"""This extracts the MIME type from a mode CGI parameter:
If the CGI parameter is for example: "...&mode=
This truncates the beginning of the tsring after "mime:", hence the length of five chars.
It sounds hard-coded byt in fact very stable and perfectly matches the need... |
def prepare_shortlistedFirms(shortlistedFirms):
""" Make list with keys
key = {identifier_id}_{identifier_scheme}_{lot_id}
"""
all_keys = set()
for firm in shortlistedFirms:
key = u"{firm_id}_{firm_scheme}".format(firm_id=firm['identifier']['id'],
... |
def check_num(number_):
"""
Checks if the number is valid or not if valid then returns the number.
"""
try:
if number_ == 'Q':
exit()
int(number_)
if len(number_) > 4 or len(number_) < 4:
print("Please check length of digits you entered: ")
... |
def PHMS2RA (rast, sep=":"):
""" Convert a right ascension string to degrees
return RA in degrees
rast RA string as "hh:mm:ss.s"
sep sympol to use to separate components instead of ":"
"""
################################################################
pp = rast.split(sep)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.