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 dimensional list for game board after changed. If the position has been change perviously, return False.
"""
mark_dict = {'player1':'X', 'player2':'O'}
if input_list[row-1][column-1] == ' ':
input_list[row-1][column-1] = mark_dict[user]
else:
print('That position has been taken, please input a new place:')
return input_list
return input_list
|
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 [field.to_api_repr() for field in fields]
|
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:
res = B
else:
res = (x - a) / (1. * (b - a)) * (B - A) + A
if res < A:
res = A
if res > B:
res = B
return res
|
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 the grid world.
column : int
The column in the grid world.\
"""
max_cols = 9
row = state / max_cols
col = state % max_cols
return row, col
|
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':
# convert version 1.0 -> 1.1
# changes:
# re-label AWG -> Ch, change in trig mode
version = '1.1'
# rename AWG -> Ch
before_after = [
['AWG1 - Waveform', 'Ch1 - Waveform'],
['AWG1 - Trig mode', 'Ch1 - Trig mode'],
['AWG1 - Trig', 'Ch1 - Trig'],
['AWG1 - Cycles', 'Ch1 - Cycles'],
['AWG2 - Waveform', 'Ch2 - Waveform'],
['AWG2 - Trig mode', 'Ch2 - Trig mode'],
['AWG2 - Trig', 'Ch2 - Trig'],
['AWG2 - Cycles', 'Ch2 - Cycles'],
['AWG3 - Waveform', 'Ch3 - Waveform'],
['AWG3 - Trig mode', 'Ch3 - Trig mode'],
['AWG3 - Trig', 'Ch3 - Trig'],
['AWG3 - Cycles', 'Ch3 - Cycles'],
['AWG4 - Waveform', 'Ch4 - Waveform'],
['AWG4 - Trig mode', 'Ch4 - Trig mode'],
['AWG4 - Trig', 'Ch4 - Trig'],
['AWG4 - Cycles', 'Ch4 - Cycles'],
]
for before, after in before_after:
dQuantReplace[before] = after
if before in dValue:
dValue[after] = dValue.pop(before)
# replace trig mode labels
rule = {
'Auto': 'Continuous',
'Software': 'Software',
'Software (per cycle)': 'Software',
'External': 'External',
'External (per cycle)': 'External',
}
# apply rule for all trig modes
for n in range(4):
label = 'Ch%d - Trig mode' % (n + 1)
if label in dValue:
dValue[label] = rule[dValue[label]]
elif version == '1.1':
# convert version 1.1 -> 1.2
version = '1.2'
# replace trig mode labels
rule = {
'Continuous': 'Continuous',
'Software': 'Software / HVI',
'External': 'External',
}
# apply rule for all trig modes
for n in range(4):
label = 'Ch%d - Trig mode' % (n + 1)
if label in dValue:
dValue[label] = rule[dValue[label]]
# return new version and data
return (version, dValue, dOption, dQuantReplace)
|
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.basicConfig(format= '%(asctime)s %(levelname)s:%(message)s', level=numeric_level)
return logging.getLogger()
|
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-":
return "{"
elif token.lower() == "-rcb-":
return "}"
return token
|
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 nearby_teammates:
blackboard[check_teammate_nearby.__name__] = nearby_teammates
print(f"Teammates nearby . . .")
return True
print("No pass on")
return False
|
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
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 isinstance(sub_msg, str):
msg_ += " " + sub_msg
elif 'text' in sub_msg:
msg_ += " " + sub_msg['text']
return msg_
|
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 = 0
count = []
for char in durationStr:
if char.isdigit():
count.append(char)
else:
if not count:
continue
newSeconds = int("".join(count))
if char in units:
newSeconds *= units[char]
seconds += newSeconds
count = []
return 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 l2: tuple(float, float)
:return: Coordinates of the intersection
:rtype: tuple(float, float)
"""
x1, y1 = l1[0]
x2, y2 = l1[1]
x3, y3 = l2[0]
x4, y4 = l2[1]
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if denominator == 0.0: # lines are parallel
if x1 == x2 == x3 == x4 == 0.0:
# When lines are parallel, they must be on the y-axis.
# We can ignore x-axis because we stop counting the
# truncation line when we get there.
# There are no other options as UI (x-axis) grows and
# OI (y-axis) diminishes when we go along the truncation line.
return (0.0, y4)
x = (
(x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)
) / denominator
y = (
(x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)
) / denominator
return (x, y)
|
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(maxColumns)
|
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
for i in range(1, smaller + 1):
if ((num1 % i == 0) and (num2 % i == 0)):
return i
|
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])
return ''.join(message)
|
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(actual) != set(sub):
return True
elif actual[0] != sub[0]:
return True
else:
return False
|
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, AttributeError):
# Sometimes the string actually is binary or StringIO object,
# so if you can't decode it, just give up.
pass
return result
|
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
-----
Appropriate for use as 'days_in_cycle' function in :class:`Calendar`.
This module has a built-in 366 days calendar with months:
:data:`Cal366`.
"""
days_in_months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return list(range(1, days_in_months[month-1] + 1))
|
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".format(group_name)
|
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_html_text.find('>', new_pos + 1)
end_pos = pretty_html_text.find('</a>', end_tag + 1)
fixed_html += pretty_html_text[new_pos:end_tag + 1]
tag_content = pretty_html_text[end_tag + 1:end_pos]
fixed_html += tag_content.strip() + '</a>'
pos = end_pos + 4
else:
fixed_html += pretty_html_text[pos:]
break
return fixed_html
|
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[current],
puzzle_input[current+1]]
current += 2
else:
params = [puzzle_input[current],
puzzle_input[current+1],
puzzle_input[current+2]]
current += 3
return params, current
|
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 = [ [], # 0 = blank
['00h47m33.041s', '-25d17m26.61s' ], # pos 1
['00h47m32.290s', '-25d17m19.10s' ], # 2
['00h47m31.936s', '-25d17m29.10s' ], # 3
['00h47m32.792s', '-25d17m21.10s' ], # 4
['00h47m32.969s', '-25d17m19.50s' ], # 5
['00h47m33.159s', '-25d17m17.41s' ], # 6
['00h47m33.323s', '-25d17m15.50s' ], # 7
['00h47m33.647s', '-25d17m13.10s' ], # 8
['00h47m33.942s', '-25d17m11.10s' ], # 9
['00h47m34.148s', '-25d17m12.30s' ], # pos 10
['00h47m33.100s', '-25d17m17.50s' ], # map reference
]
return pos[i]
|
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 = ""
for key in section:
for header in section[key]:
section_str += f"#{header.strip()}\n"
section_str += "\n"
return 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 = "[{0}]".format(val)
return 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] == check[1]
else:
return False
|
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:
print('No ids : ', g) #should probably strip them from the db.
pass
elif g.handicap > 1 and (-1 > g.komi > 1):
#print('bad komi : ', g)
pass
elif g.handicap > 6:
continue
elif g.komi < 0 or g.komi > 8.6:
#print('bad komi : ', g)
pass
elif not (g.result.startswith('W') or g.result.startswith('B')):
print('unknown result: ', g)
pass
elif g.date_played is None or g.date_played.timestamp() == 0.0:
print('No date played: ', g)
pass
else:
# Vector of result_tuples. Just what we need to compute ratings...
g_vec.append( (g.white.id,
g.black.id,
1.0 if g.result.startswith('W') else 0.0,
g.date_played.timestamp(),
g.handicap,
g.komi))
return g_vec
|
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 representation of the
input string.
"""
data = (''.join(format(ord(x), 'b') for x in str))
return(data)
|
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 base is changed from all parts of speech
into content parts of speech: noun, verb, adverb, adjective
"""
if not sentence:
return 0.0
if variation:
t = 0
for token in sentence.tokens:
# propn is not included as lexical category
if token.upos in ["NOUN", "ADJ", "ADV", "VERB"]:
t += 1
else:
t = len(sentence.tokens)
p = 0
for token in sentence.tokens:
if token.upos == pos:
p += 1
if raw:
return p, t
if not t:
return 0.0
return float(1000 * p) / t
|
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("-")[1]) + 1):
numbers.append(i)
else:
numbers.append(int(segment))
return numbers
|
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 * * *", will return: {'0 10 * * *': 24,
'0 22 * * *': 2}
"""
if not size and size != 0:
return {sentinel: None}
return {sentinel: int(size)} if str(size).isdigit() else {
part.split('@')[1]: int(part.split('@')[0])
for part in str(size).split(':')}
|
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.com/grids/hexagons/
"""
coordinate_transform = {
'e' : ( x+1, y ),
'se': ( x , y+1 ),
'sw': ( x-1, y+1 ),
'w' : ( x-1, y ),
'nw': ( x , y-1 ),
'ne': ( x+1, y-1 ),
}
return coordinate_transform[ direction ]
|
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:
return True
|
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_distance("AT", "ATC")
1
>>> find_levenshtein_distance("ATG", "ATC")
1
>>> find_levenshtein_distance("ATG", "TGA")
2
>>> find_levenshtein_distance("ATG", "ATG")
0
>>> find_levenshtein_distance("", "")
0
>>> find_levenshtein_distance("GAGGTAGCGGCGTTTAAC", "GTGGTAACGGGGTTTAAC")
3
>>> find_levenshtein_distance("TGGCCGCGCAAAAACAGC", "TGACCGCGCAAAACAGC")
2
>>> find_levenshtein_distance("GCGTATGCGGCTAACGC", "GCTATGCGGCTATACGC")
2
"""
# initializing a matrix for with `len(s1) + 1` rows and `len(s2) + 1` columns
D = [[0 for x in range(len(s2) + 1)] for y in range(len(s1) + 1)]
# fill first column
for i in range(len(s1) + 1):
D[i][0] = i
# fill first row
for j in range(len(s2) + 1):
D[0][j] = j
# fill rest of the matrix
for i in range(1, len(s1) + 1):
for j in range(1, len(s2) + 1):
distance_left = D[i][j - 1] + 1 # deletion in pattern
distance_above = D[i - 1][j] + 1 # insertion in pattern
distance_diagonal = D[i - 1][j - 1] + (
s1[i - 1] != s2[j - 1]
) # substitution
D[i][j] = min(distance_left, distance_above, distance_diagonal)
# return the last value (i.e., right most bottom value)
return D[-1][-1]
|
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"))
elif isinstance(match_files, str):
with open(match_files, "r") as f:
round_matches = f.read()
all_matches.extend(round_matches.rstrip().split("\n"))
return all_matches
|
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(descendants(subclass))
return(subclasses)
|
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: list
List of the hybridization to process
(ex. [Hybridization1, Hybridization2]).
aligned_peaks_dict: dict
Dictionary containing only the coords of the selected peaks after
registration (still with pos information).
Returns:
---------
combinations: list
List containing the pairs hybridization and gene
(Ex. (Hybridization1, Gfap))
"""
combinations_tmp=list()
if isinstance(hybridizations,list):
for hybridization in hybridizations:
combinations_tmp.append([(hybridization,gene) for gene in aligned_peaks_dict[hybridization].keys()])
combinations=[el for grp in combinations_tmp for el in grp]
else:
hybridization=hybridizations
combinations=[(hybridization,gene) for gene in aligned_peaks_dict[hybridization].keys()]
return combinations
|
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_files'] > cluster['labelled_files']):
return True
else:
return False
|
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
# ludr :
if (n==0):
if (x-1>=0):
site = (x-1) + y*L
elif (n==1):
if (y+1<L):
site = x + (y+1)*L
elif (n==2):
if (y-1>=0):
site = x + (y-1)*L
elif (n==3):
if (x+1<L):
site = (x+1) + y*L
return site
|
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.
"""
i = 0 # counter
while i < len(musicians): # guard against infinite loop
musician = musicians[i].split(', ')[0].lower()
if musician_name.lower() == musician:
return True # preferable to break statement
i += 1 # MUST INCREMENT
return 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.
:return: A two-tuple of unicode giving the two split pieces.
"""
quoted = False
escaped = False
result = []
for i, ch in enumerate(text):
if escaped:
escaped = False
result.append(ch)
elif ch == u'\\':
escaped = True
elif ch == u'"':
quoted = not quoted
elif not quoted and ch == u' ':
return u"".join(result), text[i:].lstrip()
else:
result.append(ch)
return u"".join(result), u""
|
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 [ [1,2,3],[4,5]]
Returns:
list_of_list (list): A list of lists
Author: SMM
Date: 11/01/2018
"""
if len(a_string) == 0:
print("No list of list found. I will return an empty list.")
list_of_list = []
else:
listified_entry = [item for item in a_string.split(':')]
list_of_list = []
# now loop through these creating a dict
for entry in listified_entry:
split_entry = [int(item) for item in entry.split(',')]
list_of_list.append(split_entry)
print("This list of lists is: ")
print(list_of_list)
return list_of_list
|
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
transformer class and init parameters, or None.
If list of classes is provided, then each of them is
instantiated with default arguments. Example:
classes = [StandardScaler, LabelBinarizer]
If list of dictionaries is provided, then each of them should
have a 'class' key with transformer class. All other keys are
passed into 'class' value constructor. Example:
classes = [
{'class': StandardScaler, 'with_mean': False},
{'class': LabelBinarizer}
}]
If None value selected, then each feature left as is.
prefix add prefix to transformed column names
suffix add suffix to transformed column names.
"""
if classes is None:
return [(column, None) for column in columns]
feature_defs = []
for column in columns:
feature_transformers = []
arguments = {}
if prefix and prefix != "":
arguments['prefix'] = prefix
if suffix and suffix != "":
arguments['suffix'] = suffix
classes = [cls for cls in classes if cls is not None]
if not classes:
feature_defs.append((column, None, arguments))
else:
for definition in classes:
if isinstance(definition, dict):
params = definition.copy()
klass = params.pop('class')
feature_transformers.append(klass(**params))
else:
feature_transformers.append(definition())
if not feature_transformers:
feature_transformers = None
feature_defs.append((column, feature_transformers, arguments))
return feature_defs
|
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): the string to convert
Return:
Returns the converted string
Exceptions:
RuntimeError is raised if the target parameter is not a string
"""
if not isinstance(target, str):
raise RuntimeError("Invalid parameter type specified when coverting a string to be path-compatible")
return_str = target
for match in " :;.,/\\\'\"(){}":
return_str = return_str.replace(match, '_')
return return_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 * x7)
y1 = w1 * x1
y3 = w3 * x3
y5 = w5 * x5
y7 = w7 * x7
y9 = w9 * x9
z = y9 + y7 + y5 + y3 + y1 + w0
return z
|
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.
"""
return len(text) == 0
|
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:arcmin:arcsec).
"""
colon_list = hex_string.split(':')
space_list = hex_string.split() # multiple spaces act as one delimiter
if len(colon_list) >= len(space_list):
return [x.strip() for x in colon_list]
return space_list
|
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 char in password:
if char < previous:
return False
previous = char
return True
|
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-dov-ert-hel-azy-dog'
Args:
string: The string to split.
stride: The interval to insert the separator at.
separator: The string to insert at every stride interval.
Returns:
The original string with the separator present at every stride interval.
"""
result = ''
for (i, c) in enumerate(string):
if (i > 0 and i % stride == 0):
result += separator
result += c
return result
|
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)
while pos < sz:
text = lines[pos]
stripped = len(text.lstrip())
if not stripped:
pos += 1
continue
return len(text) - stripped
|
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 ip in ips:
result[ip] = {}
for ip, os_dict in tcpml.items():
tmp = result[ip]
for os_name, prob in os_dict.items():
tmp[os_name] = tmp.get(os_name, 0) + prob
for ip, os_dict in useragent.items():
tmp = result[ip]
for os_name, prob in os_dict.items():
tmp[os_name] = tmp.get(os_name, 0) + prob
for ip, os_dict in domain.items():
tmp = result[ip]
for os_name, prob in os_dict.items():
updated = False
for present_name in tmp:
if os_name in present_name:
tmp[present_name] += prob
updated = True
if not updated:
tmp[os_name] = prob
return result
|
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_indexes(variable, x)
|
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 corner (1,1) of the square in the (x,y) domain (len-2 tuple)
p2 - upper-right corner (2,2) of the square in the (X,y) domain (len-2 tuple)
qs - values at the vertices of the square (See diagram), any value supporting +/-/*
right now: floats, ints, np.ndarrays
(1,2)----(2,2)
| |
| |
(1,1)----(2,1)
"""
# check this out for the math
# https://en.wikipedia.org/wiki/Bilinear_interpolation
x0 = p0[0]
x1 = p1[0]
x2 = p2[0]
y0 = p0[1]
y1 = p1[1]
y2 = p2[1]
if not (x0>=x1 and x0<=x2):
raise ValueError("You're doing it wrong. x0 should be between {} and {}, got {}".format(x1,x2,x0))
if not (y0>=y1 and y0<=y2):
raise ValueError("You're doing it wrong. y0 should be between {} and {}, got {}".format(y1,y2,y0))
# this is some matrix multiplication. See the above link for details
# it's not magic, it's math. Mathemagic
mat_mult_1 = [q11*(y2-y0) + q12*(y0-y1) , q21*(y2-y0) + q22*(y0-y1)]
mat_mult_final = (x2-x0)*mat_mult_1[0] + (x0-x1)*mat_mult_1[1]
return( mat_mult_final/((x2-x1)*(y2-y1)) )
|
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 = name.replace('"', "'")
return 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
has no corresponding band letter.
:todo: handle polar (UPS_) zones: A, B, Y, Z.
"""
if -180.0 > lon or lon > 180.0:
raise ValueError('invalid longitude: ' + str(lon))
zone = int((lon + 180.0)//6.0) + 1
band = ' '
if 84 >= lat and lat >= 72: band = 'X'
elif 72 > lat and lat >= 64: band = 'W'
elif 64 > lat and lat >= 56: band = 'V'
elif 56 > lat and lat >= 48: band = 'U'
elif 48 > lat and lat >= 40: band = 'T'
elif 40 > lat and lat >= 32: band = 'S'
elif 32 > lat and lat >= 24: band = 'R'
elif 24 > lat and lat >= 16: band = 'Q'
elif 16 > lat and lat >= 8: band = 'P'
elif 8 > lat and lat >= 0: band = 'N'
elif 0 > lat and lat >= -8: band = 'M'
elif -8 > lat and lat >= -16: band = 'L'
elif -16 > lat and lat >= -24: band = 'K'
elif -24 > lat and lat >= -32: band = 'J'
elif -32 > lat and lat >= -40: band = 'H'
elif -40 > lat and lat >= -48: band = 'G'
elif -48 > lat and lat >= -56: band = 'F'
elif -56 > lat and lat >= -64: band = 'E'
elif -64 > lat and lat >= -72: band = 'D'
elif -72 > lat and lat >= -80: band = 'C'
else: raise ValueError('latitude out of UTM range: ' + str(lat))
return (zone, band)
|
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(char.encode(encoding, 'strict'))
except UnicodeError:
chars.append('&#%i;' % ord(char))
return ''.join(chars)
|
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.