content stringlengths 42 6.51k |
|---|
def draw_turn(row, column, input_list, user):
"""
Draw the game board after user typing a choice.
Arguments:
row -- the row index.
column -- the column index.
input_list -- a two dimensional list for game board.
user -- the user who type the choice
Returns:
input_list -- a two ... |
def expressionfordatef(corpus, i):
"""
This function is a helper to check if next token
is a digit.
Args:
corpus (list), i (int)
Returns:
bool
"""
if i < (len(corpus) - 1) and corpus[i + 1].isdigit() is True:
return True
return False |
def _build_schema_resource(fields):
"""Generate a resource fragment for a schema.
Args:
fields [Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`]):
schema to be dumped
Returns: (Sequence[dict])
mappings describing the schema of the supplied fields.
"""
return... |
def package_name(requirement):
"""
Return the name component of a `name==version` formatted requirement.
"""
requirement_name = requirement.partition("==")[0].split("@")[0].strip()
return requirement_name |
def linearMap(x, a, b, A=0, B=1):
"""
.. warning::
``x`` *MUST* be a scalar for truth values to make sense.
This function takes scalar ``x`` in range [a,b] and linearly maps it to
the range [A,B].
Note that ``x`` is truncated to lie in possible boundaries.
"""
if a == b:
r... |
def reverse_dictionary(dict_var):
"""Reverse the role of keys and values in a dictionary
Parameters
----------
dict_var: dict
Returns
-------
dict
reversed of the enetered dictionary
"""
return {v:k for k,v in dict_var.items()} |
def isascii(s: str):
"""Determine if `s` is an entirely ascii string. Used for back-compatibility with python<3.7"""
try:
s.encode('ascii')
except UnicodeEncodeError:
return False
return True |
def category_data(c3):
"""Test data to make changes for validation or customization (testing)."""
return {"name": "CMS development", "parent": c3} |
def distinct(keys):
"""
Return the distinct keys in order.
"""
known = set()
outlist = []
for key in keys:
if key not in known:
outlist.append(key)
known.add(key)
return outlist |
def reverse_index_1d(state):
"""The inverse of index_1d. From an row number in the transition matrix return the row and column in the grid world.
Parameters
----------
state : int
An integer representing the row in the transition matrix.
Returns
-------
row : int
The row in... |
def upgradeDriverCfg(version, dValue={}, dOption=[]):
"""Upgrade the config given by the dict dValue and dict dOption to the
latest version."""
# the dQuantUpdate dict contains rules for replacing missing quantities
dQuantReplace = {}
# update quantities depending on version
if version == '1.0':... |
def is_decreasing(arr):
""" Returns true if the sequence is decreasing. """
return all([x > y for x, y in zip(arr, arr[1:])]) |
def configure_logger(logger_level):
"""Configure the python logger to show messages
Args:
logger_level (str): Level of logging to be used (DEBUG, INFO)
Returns:
logger: the configured logger
"""
import logging
numeric_level = getattr(logging, logger_level, None)
logging.bas... |
def convert_token(token):
""" Convert PTB tokens to normal tokens """
if token.lower() == "-lrb-":
return "("
elif token.lower() == "-rrb-":
return ")"
elif token.lower() == "-lsb-":
return "["
elif token.lower() == "-rsb-":
return "]"
elif token.lower() == "-lcb-... |
def check_teammate_nearby(data, blackboard):
"""A nearby teammate is in the same grid square as the attacker on the ball."""
nearby_teammates = []
for teammate in data["teammates"]:
if teammate["coordinates"] == data["attacker"]["coordinates"]:
nearby_teammates.append(teammate)
if n... |
def is_unary(s: str) -> bool:
"""Checks if the given string is a unary operator.
Parameters:
s: string to check.
Returns:
``True`` if the given string is a unary operator, ``False`` otherwise.
"""
return s == '~' |
def compare_arrays(arr1, arr2):
"""
Compares starting at last element, then second to last, etc.
"""
assert(len(arr1) == len(arr2))
for i in range(len(arr1) - 1, -1, -1):
if arr1[i].uint < arr2[i].uint:
return True
if arr1[i].uint > arr2[i].uint:
return False
... |
def fa(i, n):
"""Calculates the uniform series compound amount factor.
:param i: The interest rate.
:param n: The number of periods.
:return: The calculated factor.
"""
return ((1 + i) ** n - 1) / i |
def gen_spacer(spacer_char="-", nl=2):
"""
Returns a spacer string with 60 of designated character, "-" is default
It will generate two lines of 60 characters
"""
spacer = ""
for i in range(nl):
spacer += spacer_char * 60
spacer += "\n"
return spacer |
def get_text_from_tel_msg(tel_msg):
"""
Gets a telegram message and returns all text as string
:param tel_msg: Telegram message
"""
if isinstance(tel_msg['text'], str):
msg_ = tel_msg['text']
else:
msg_ = ""
for sub_msg in tel_msg['text']:
if isinsta... |
def durationToSeconds(durationStr):
"""
Converts a 1y2w3d4h5m6s format string duration into a number of seconds.
"""
try: # If it's just a number, assume it's seconds.
return int(durationStr)
except ValueError:
pass
units = {
"y": 31557600,
"w": 604800,
"d": 86400,
"h": 3600,
"m": 60
}
seconds =... |
def _count_intersection(l1, l2):
"""Count intersection between two line segments defined by coordinate pairs.
:param l1: Tuple of two coordinate pairs defining the first line segment
:param l2: Tuple of two coordinate pairs defining the second line segment
:type l1: tuple(float, float)
:type ... |
def threshold_linear(x):
"""Output non-linearity."""
return max(0, x) |
def agent_dead_id_list(agent_list, agent_type):
"""Return a list of agents that are dead from an API list of agents
:param agent_list: API response for list_agents()
"""
return [agent['id'] for agent in agent_list
if agent['agent_type'] == agent_type and agent['alive'] is False] |
def getMaxColumns(rows):
"""
Return number max of columns from rows
:param rows: list of rows <tr>
:return: int
"""
maxColumns = 0
for row in rows:
count = float(row.xpath('count(*)').extract()[0])
if count > maxColumns:
maxColumns = count
return int(maxColumn... |
def matrix4_to_3x4_array(mat):
"""Concatenate matrix's columns into a single, flat tuple"""
return tuple(f for v in mat[0:3] for f in v) |
def hcf(num1, num2):
"""
Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for
"""
if num1 > num2:
smaller = num2
else:
smaller = num1
... |
def get_views_sel(views):
"""Returns the current selection for each from the given views"""
selections = []
for view in views:
selections.append(view.sel())
return selections |
def get_common(counted, message_length, reverse):
"""Get most common letters from counted one letter per counted index."""
message = []
for index in range(message_length):
message.append(sorted(
counted[index],
key=counted[index].__getitem__,
reverse=reverse)[0])
... |
def jaccardize(set1, set2):
"""Compute jaccard index of two sets"""
denominator = min(len(set1), len(set2))
if denominator > 0:
return len(set1.intersection(set2)) / denominator
else:
return denominator |
def get_score_end_time(score):
"""Return the timestamp just after the final note in the score ends."""
if not score:
return 0
last_event = score[-1]
if last_event.time_delta is None:
return last_event.time
return last_event.time + last_event.time_delta.total_beats() |
def get_plugin_attrs(plugins: dict, attr: str = 'server_handle'):
"""Produces a dict {key: value.attr, ...} for each key,value pair in the 'plugins' dict."""
return {k: getattr(v, attr) for (k, v) in plugins.items() if hasattr(v, attr)} |
def isinvalid(actual, sub):
"""
Checks if submitted route is invalid.
Parameters
----------
actual : list
Actual route.
sub : list
Submitted route.
Returns
-------
bool
True if route is invalid. False otherwise.
"""
if len(actual) != len(sub) or set(ac... |
def _convert_string_to_unicode(string):
"""
If the string is bytes, decode it to a string (for python3 support)
"""
result = string
try:
if string is not None and not isinstance(string, str):
result = string.decode("utf-8")
except (TypeError, UnicodeDecodeError, AttributeErr... |
def days_in_month_366(month, year=0):
"""Days of the month (366 days calendar).
Parameters
----------
month : int
numerical value of the month (1 to 12).
year : int, optional
(dummy value).
Returns
-------
out : list of int
days of the month.
Notes
----... |
def find_group(groups, group_name):
"""
Take groups list and find group by the group name
:param groups:
:param group_name:
:return:
"""
for group in groups:
if group["group_name"] == group_name:
return group
else:
return "Group {} not in list".forma... |
def camelcase_to_pascal(argument):
"""Converts a camelCase param to the PascalCase equivalent"""
return argument[0].upper() + argument[1:] |
def strip_a_tags(pretty_html_text):
"""
Reformat prettified html to remove spaces in <a> tags
"""
pos = 0
fixed_html = ''
while True:
new_pos = pretty_html_text.find('<a', pos)
if new_pos > 0:
fixed_html += pretty_html_text[pos:new_pos]
end_tag = pretty_ht... |
def make_first_upper(in_string):
"""
Change first character in string into upper case
:param in_string: original string
:return: changed string
"""
return in_string[0].upper() + in_string[1:] |
def get_parameters(current, puzzle_input, opcode):
"""extracts the parameters from the input and updates the current location
"""
if opcode == '03' or opcode == '04':
params = [puzzle_input[current]]
current += 1
elif opcode == '05' or opcode == '06':
params = [puzzle_input[curre... |
def get_pos(i):
""" return key positions in N253 (1..10) from Meier's Table 2:
0 = blank, if you want to use the peak in the cube
11 = map center, the reference position of N253
See also http://adsabs.harvard.edu/abs/2015ApJ...801...63M
"""
pos = [ [], ... |
def build_section_markmap(section: dict):
"""Build all markmap with the content from markdown structure, and add a hash before to build the sequence
Args:
section (dict): structure from markdown header's sections
Returns:
str: All markmap content to insert
"""
section_str = ""
... |
def parse_list(val):
""" Parse a list of input strings """
val = (
val
.replace("[", "").replace("]", "")
.replace("(", "").replace(")", "")
.replace("{", "").replace("}", "")
.strip()
.lower())
if "," not in val:
val = ",".join(val.split())
val =... |
def _check_section_num(docInfo, check):
"""Helper function for provision_page()"""
tup = docInfo['section']['section_num']
if tup is not None and len(check) == 1:
return tup[0] == check[0]
elif tup is not None and len(check) > 1 and len(tup) > 1:
return tup[0] == check[0] and tup[1] == c... |
def sanitized_games(games):
""" Sanitizes a list of games into result tuples for rating.
A result tuple is the form (w, b, result, date, handicap, komi)
Where 'result' is 1 if w won and 0 otherwise.
"""
g_vec = []
for g in games:
if g.white.user_id is None or g.black.user_id is None:
... |
def string_to_bits(str):
"""
string_to_bits Function
Converts a Pythonic string to the string's
binary representation.
Parameters
----------
str: string
The string to be converted.
Returns
-------
data: string
The binary... |
def prob15(size=20):
"""
Starting in the top left corner of a 2*2 grid, there are 6 routes (without
backtracking) to the bottom right corner.
How many routes are there through a 20*20 grid?
"""
a = 1
for i in range(1, size + 1):
#print a
a = a * (size + i) / i
return a |
def pos_incsc(sentence, pos, variation=False, raw=True):
"""This function can be applied to compute for shared specific morphological
feature in Swedish and English. These parts of speech include
particle, punctuation, subjunction, adjective, adverb, noun, verb.
If variation is set to be True, the ba... |
def string_to_list(string_to_convert):
""" Returns the input string as a list object """
numbers = []
segments = [segment.strip() for segment in string_to_convert.split(",")]
for segment in segments:
if "-" in segment:
for i in range(int(segment.split("-")[0]), int(segment.split("-")... |
def fibonacci(n):
"""Calculates the fibonacci number of n."""
# Base case
if n <= 0:
return 0
elif n == 1:
return 1
# Recursive case
return fibonacci(n-1) + fibonacci(n-2) |
def size_as_recurrence_map(size, sentinel=''):
"""
:return: dict, size as "recurrence" map. For example:
- size = no value, will return: {<sentinel>: None}
- size = simple int value of 5, will return: {<sentinel>: 5}
- size = timed interval(s), like "2@0 22 * * *:24@0 10 *... |
def parse_war_path(war, include_war = False):
""" Parse off the raw WAR name for setting its context
"""
if '/' in war:
war = war.rsplit('/', 1)[1]
if include_war:
return war
else:
return war.split('.')[0] |
def seq_to_bits(seq):
""" ex) '01' -> [0, 1] """
return [0 if b == '0' else 1 for b in seq] |
def product_comprehension(dimension_1, dimension_2):
"""
>>> product_comprehension(3, 6)
18
"""
return sum([1 for _ in range(dimension_1) for __ in range(dimension_2)]) |
def get_coordinates( x,y,direction ):
"""
Given (x,y) coordinates and direction, this function returns the
coordinates of the next tile
The strange coordinate system used to represent hexagonal grids here
is called the 'Axial Coordinate System'.
Reference: https://www.redblobgames.co... |
def call_succeeded(response):
"""Returns True if the call succeeded, False otherwise."""
#Failed responses always have a success=False key.
#Some successful responses do not have a success=True key, however.
if 'success' in response.keys():
return response['success']
else:
retu... |
def genomic_dup2_abs_37(genomic_dup2_37_loc):
"""Create test fixture absolute copy number variation"""
return {
"type": "AbsoluteCopyNumber",
"_id": "ga4gh:VAC.L1_P5Tf41A-b29DN9Jg5T-c33iAhW1A8",
"subject": genomic_dup2_37_loc,
"copies": {"type": "Number", "value": 3}
} |
def find_levenshtein_distance(s1: str, s2: str) -> int:
"""Compute the Levenshtein distance between two strings (i.e., minimum number
of edits including substitution, insertion and deletion needed in a string to
turn it into another)
>>> find_levenshtein_distance("AT", "")
2
>>> find_levenshtein... |
def get_matches(match_files):
"""return matches played from file/(s)"""
all_matches = []
if isinstance(match_files, list):
for match in match_files:
with open(match, "r") as f:
round_matches = f.read()
all_matches.extend(round_matches.rstrip().split("\n"))
... |
def _escape(s: str) -> str:
"""Helper method that escapes parameters to a SQL query"""
e = s
e = e.replace('\\', '\\\\')
e = e.replace('\n', '\\n')
e = e.replace('\r', '\\r')
e = e.replace("'", "\\'")
e = e.replace('"', '\\"')
return e |
def descendants(cls: type) -> list:
"""
Return a list of all descendant classes of a class
Arguments:
cls (type): Class from which to identify descendants
Returns:
subclasses (list): List of all descendant classes
"""
subclasses = cls.__subclasses__()
for subclass in subclasses:
subclasses.extend(descen... |
def processing_combinations(hybridizations,aligned_peaks_dict):
"""
Function used to create a list of tuples containing the pair hybridization
and gene (Ex. (Hybridization1, Gfap)) that will be used to process the dots
removal in parallel.
Parameters:
-----------
hybridizations: l... |
def check_key_and_repeat(key, repeat):
"""
Ensure that the key was correctly typed twice
"""
if key != repeat:
print()
print('The master key does not match its confirmation. Please try again!')
print()
return False
return True |
def is_good_quality(cluster):
"""
Evaluate the quality of a cluster.
Returns True of the quality is evaluated to be good,
and False if the quality is evaluated to be poor.
"""
if (cluster['total_incoming'] != 0
and cluster['label'] is None
and cluster['unlabelled_fi... |
def getattr_path(obj, path):
"""Get nested `obj` attributes using dot-path syntax (e.g. path='some.nested.attr')."""
attr = obj
for item in path.split("."):
attr = getattr(attr, item)
return attr |
def is_int(obj):
"""Check if obj is integer."""
return isinstance(obj, int) |
def neighborsite(i, n, L):
"""
The coordinate system is geometrically left->right, down -> up
y|
|
|
|________ x
(0,0)
So as a definition, l means x-1, r means x+1, u means y+1, and d means y-1
"""
x = i%L
y = i//L # y denotes
site = None... |
def search_key(value, list, key):
"""
# Search for an element and return key
"""
for nb, element in enumerate(list):
if element[key] == value:
return nb
return False |
def is_member(musicians, musician_name):
"""Return true if named musician is in musician list;
otherwise return false.
Parameters:
musicians (list): list of musicians and their instruments
musician_name (str): musician name
Returns:
bool: True if match is made; otherwise False.... |
def checkItemsEqual(L1, L2):
"""
TestCase.assertItemsEqual() is not available in Python 2.6.
"""
return len(L1) == len(L2) and sorted(L1) == sorted(L2) |
def _split_quoted(text):
"""
Split a unicode string on *SPACE* characters.
Splitting is not done at *SPACE* characters occurring within matched
*QUOTATION MARK*s. *REVERSE SOLIDUS* can be used to remove all
interpretation from the following character.
:param unicode text: The string to split.... |
def parse_list_of_list_from_string(a_string):
"""
This parses a list of lists separated string. Each list is separated by a colon
Args:
a_string (str): This creates a list of lists. Each sub list is separated by colons and the sub list items are separated by commas. So `1,2,3:4,5` would produce [ [... |
def gen_features(columns, classes=None, prefix='', suffix=''):
"""Generates a feature definition list which can be passed
into DataFrameMapper
Params:
columns a list of column names to generate features for.
classes a list of classes for each feature, a list of dictionaries with
... |
def __str_to_path(target):
"""Fixes a string to make it compatible with paths. Converts spaces, colons, semi-colons, periods,
commas, forward and backward slashes ('/' and '\\'), single and double quotes (" and '), parenthesis,
curly braces ('{' and '}') to underscores
Args:
target (str): ... |
def clean(p):
"""Remove happy endings"""
while p and p[-1]:
p = p[:-1]
return p |
def _length(sentence_pair):
"""Assumes target is the last element in the tuple."""
return len(sentence_pair[-1]) |
def _get_lock_speed(postgame, de_data):
"""Get lock speed flag."""
if de_data is not None:
return de_data.lock_speed
if postgame is not None:
return postgame.lock_speed
return None |
def sigmoid_poly(x):
"""A Chebyshev polynomial approximation of the sigmoid function."""
w0 = 0.5
w1 = 0.2159198015
w3 = -0.0082176259
w5 = 0.0001825597
w7 = -0.0000018848
w9 = 0.0000000072
x1 = x
x2 = (x1 * x)
x3 = (x2 * x)
x5 = (x2 * x3)
x7 = (x2 * x5)
x9 = (x2 * ... |
def is_partitioned_line_blank(indent: str, text: str) -> bool:
"""Determine whether an indent-partitioned line is blank.
Args:
indent: The leading indent of a line. May be empty.
text: Text following the leading indent. May be empty.
Returns:
True if no text follows the indent.
... |
def parse_hex(hex_string):
"""
Helper function for RA and Dec parsing, takes hex string, returns list of floats.
:param hex_string: string in either full hex ("12:34:56.7777" or "12 34 56.7777"),
or degrees ("234.55")
:return: list of strings representing floats (hours:min:sec or deg:arcm... |
def check_if_duplicates(lsit_of_elems):
""" Check if given list contains any duplicates """
if len(lsit_of_elems) == len(set(lsit_of_elems)):
return False
else:
return True |
def password_rule_2(password: str) -> bool:
"""
Check if going from left to right, the digits never decrease; they only ever increase or
stay the same (like 111123 or 135679).
:param password: str
:return: bool
"""
if not password:
return False
previous = password[0]
for cha... |
def _separate_string(string: str, stride: int, separator: str) -> str:
"""Returns a separated string by separator at multiples of stride.
For example, the input:
* string: 'thequickbrownfoxjumpedoverthelazydog'
* stride: 3
* separator: '-'
Would produce a return value of:
'the-qui-ckb-row-nfo-xju-mpe-do... |
def round_two_dec(dic):
"""Round a rms dictionary to two digits."""
return dict((k, round(dic[k], 2)) for k in dic) |
def parse_codepoint_range(codepoints):
"""Parses a string that specifies a range of code points or a single code point.
Returns a range of (numeric) code points."""
begin, sep, end = codepoints.partition("..")
if not sep:
return [int(begin, 16)]
return range(int(begin, 16), int(end, 16) + 1... |
def format_csv_filepath(filepath):
"""
Makes sure the file name ends in '.csv'
:param filepath: full file path for CSV file (string)
:return: full file path ending in '.csv'
"""
if filepath[-4:] != ".csv":
filepath += ".csv"
return filepath |
def get_line_indent(lines, pos):
"""Get text line indentation.
Args:
lines: Source code lines.
pos: Start position to calc indentation.
Returns:
Next non empty indentation or ``None``.
Note:
``lines`` must have text with tabs expanded.
"""
sz = len(lines)
w... |
def merge_results(ips, useragent, domain, tcpml):
"""Merge results of the methods
:param ips: list of investigated IPs
:param useragent: result of UserAgent method
:param domain: result of Domain method
:param tcpml: result of Tcpml method
:return: Merged results
"""
result = {}
for ... |
def get_term_uri(term_id, extension="html", include_ext=False):
""":return: the URI of a term, given the retrieved ID"""
if "http://" in term_id:
return term_id
term_uri = "http://vocab.getty.edu/aat/" + term_id
if include_ext:
return term_uri + "." + extension
return term_uri |
def sep(value):
"""Turn value into a string and append a separator space if needed."""
string = str(value)
return string + ' ' if string else '' |
def reverse_complement(seq):
"""Get reverse complement of a given sequence"""
comp_dict = {'A':'T','T':'A','G':'C','C':'G','N':'N'}
return "".join([comp_dict[base] for base in reversed(seq)]) |
def get_indices(variable, x): # x = list
"""
Finds all indices of a given value in a list
:param variable: value to search in the list
:param x: the list to search in
:return: list of indices
"""
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
return get_... |
def dubunderscore_reducer(k1, k2):
"""
for use with flatten-dict
"""
if k1 is None:
return k2
else:
return k1 + "__" + k2 |
def bilinear_interp(p0, p1, p2, q11, q12, q21, q22):
"""
Performs a bilinear interpolation on a 2D surface
Four values are provided (the qs) relating to the values at the vertices of a square in the (x,y) domain
p0 - point at which we want a value (len-2 tuple)
p1 - coordinates bottom-left... |
def _beam_fit_fn_2(z, d0, Theta):
"""Fitting function for d0 and Theta."""
return d0**2 + (Theta*z)**2 |
def sanitize(name):
"""Replaces disallowed characters with an underscore"""
## Disallowed characters in filenames
DISALLOWED_CHARS = "\\/:<>?*|"
if name == None:
name = "Unknown"
for character in DISALLOWED_CHARS:
name = name.replace(character, '_')
# Replace " with '
name = ... |
def compute_lod_in(lod, cur_img, transition_kimg):
"""Compute value for lod_in, the variable that controls fading in new layers."""
return lod + min(
1.0, max(0.0, 1.0 - (float(cur_img) / (transition_kimg * 1000)))) |
def gridZone(lat, lon):
"""Find UTM zone and MGRS band for latitude and longitude.
:param lat: latitude in degrees, negative is South.
:param lon: longitude in degrees, negative is West.
:returns: (zone, band) tuple.
:raises: :exc:`ValueError` if lon not in [-180..180] or if lat
... |
def _xmlcharref_encode(unicode_data, encoding):
"""Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler."""
chars = []
# Step through the unicode_data string one character at a time in
# order to catch unencodable characters:
for char in unicode_data:
try:
chars.append... |
def array_to_string(lst):
"""Convert LST to string.
@param { Array } lst : List of object.
"""
form_str = ""
for item in lst:
form_str += str(item)
pass
return form_str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.