content
stringlengths 42
6.51k
|
---|
def turn_right(block_matrix, debug=False):
"""block turn right."""
new_block = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in range(4):
for j in range(4):
new_block[3-j][i] = block_matrix[i][j]
if debug:
print(new_block)
return new_block
|
def scott(n: int, ess: float):
"""
Returns Scott's factor for KDE approximation.
Args:
n: See ``silverman``.
ess: See ``silverman``.
"""
return 1.059 * ess ** (-1 / (n + 4))
|
def format_license(license: str) -> str:
"""
Format license using a short name
"""
MAX = 21
if len(license) > MAX:
license = license[:MAX-3] + '...'
return license
|
def dummy_flow(positional_str, positional_bool, positional_int,
positional_float, optional_str='default', optional_bool=False,
optional_int=0, optional_float=1.0, optional_float_2=2.0):
""" Workflow used to test the introspective argument parser.
Parameters
----------
positional_str : string
positional string argument
positional_bool : bool
positional bool argument
positional_int : int
positional int argument
positional_float : float
positional float argument
optional_str : string, optional
optional string argument (default 'default')
optional_bool : bool, optional
optional bool argument (default False)
optional_int : int, optional
optional int argument (default 0)
optional_float : float, optional
optional float argument (default 1.0)
optional_float_2 : float, optional
optional float argument #2 (default 2.0)
"""
return positional_str, positional_bool, positional_int,\
positional_float, optional_str, optional_bool,\
optional_int, optional_float, optional_float_2
|
def ordered_dict_to_pref(obj, member, val):
""" Function to convert an OrderedDict to something that can
be easily stored and read back, in this case a list of tuples.
Parameters
----------
obj: Atom
The instance calling the function
member: Member
The member that must be stored
val: OrderedDict
The current value of the member
Returns
-------
value : str
the serialized value
"""
return repr(list(val.items()))
|
def _get_ratio(user_a, user_b):
"""Get ratio."""
user_b = 1 if int(user_b) == 0 else user_b
user_a = 1 if int(user_b) == 0 else user_a
return user_a/user_b
|
def extractSentencePairs(conversations):
"""
Extract the sample lines from the conversations
"""
qa_pairs = []
for conversation in conversations:
# Iterate over all the lines of the conversation
for i in range(len(conversation["lines"]) - 1): # We ignore the last line (no answer for it)
inputLine = conversation["lines"][i]["text"].strip()
targetLine = conversation["lines"][i+1]["text"].strip()
if inputLine and targetLine: # Filter wrong samples (if one of the list is empty)
qa_pairs.append([inputLine, targetLine])
return qa_pairs
|
def str2bin(s):
"""
String to binary.
"""
ret = []
for c in s:
ret.append(bin(ord(c))[2:].zfill(8))
return ''.join(ret)
|
def slider_command_to_str(arguments):
"""
Convert arguments for slider and arrowbox command into comment string
for config file.
:param arguments: slider arguments
:return: Formatted string for config file.
"""
return '; '.join(arguments)
|
def length_vector_sqrd_numba(a):
""" Calculate the squared length of the vector.
Parameters
----------
a : array
XYZ components of the vector.
Returns
-------
float: The squared length of the XYZ components.
"""
return a[0]**2 + a[1]**2 + a[2]**2
|
def colorinterval(x, y, z):
"""
test for y < x < z with tupples
:param x:
:param y:
:param z:
:return:
"""
a = y[0] <= x[0] <= z[0]
b = y[1] <= x[1] <= z[1]
c = y[1] <= x[1] <= z[1]
return a and b and c
|
def get_prefix(headword, length):
"""
Return the prefix for the given headword,
of length length.
:param headword: the headword string
:type headword: unicode
:param length: prefix length
:type length: int
:rtype: unicode
"""
if headword is None:
return None
lowercased = headword.lower()
if ord(lowercased[0]) < 97:
return u"SPECIAL"
if len(lowercased) < length:
return lowercased
return lowercased[0:length]
|
def bmin(L,M,s=0.20):
"""
Return minimum number of precincts that could be "bad".
L = list of n precincts: n (size,name) pairs
M = margin of victory as number of votes separating winner
from runner-up
s = maximum within-precinct miscount
"""
assert 0 <= M <= sum(x[0] for x in L)
votes_so_far = 0
k = 0 # precincts taken
while votes_so_far < M and k < len(L):
votes_so_far += 2.0*s*L[k][0]
k += 1
return k
|
def vmul(vect, s):
"""
This function returns the vector result of multiplying each entries of a vector by a scalar. Works also for flat matrices
:param vect: the vector to be multiplied with the scalar value
:param s: the scalar value
:type vect: double or integer iterable
:type s: double or integer
:return: The resulting vector s(vect1)
:rtype: double iterable
"""
ret=[]
for x in vect:
ret.append(x*s)
return ret
|
def print_clean(item):
"""
Helper function for print_board
Returns "." if the element is a list
"""
if len(item) == 1:
print(item[0]),
else:
print("."),
return 0
|
def salutation(hour: int) -> str:
"""Determine the correct salutation using the hour parameter."""
greetings = ((range(0, 12), "Good Morning",),
(range(12, 17), "Good Afternoon"),
(range(17, 24), "Good Evening"),)
return list(filter(lambda x: hour in x[0], greetings))[0][1]
|
def docs_with_low_token_count(corpus_statistics, max_token_count=350):
"""
"""
# Gather list of doc_ids and total token count
docs_2_tokens = {}
for report in corpus_statistics:
docs_2_tokens.update({report['doc_id']: report['num_tokens']})
# Subset dictionary to get only records wth value below the max
short_docs = {key: value for key, value in docs_2_tokens.items() if value < max_token_count}
# return dictionary with doc_id and token_count if count is lower than max_token_count
return (short_docs, max_token_count)
|
def _splice_comma_names(namelist):
""" Given a list of names, some of the names can be comma-separated lists.
Return a new list of single names (names in comma-separated lists are
spliced into the list).
"""
newlist = []
for name in namelist:
if ',' in name:
newlist.extend(name.split(','))
else:
newlist.append(name)
return newlist
|
def is_mci(code):
"""
ICD9
331.83 Mild cognitive impairment, so stated
294.9 Unspecified persistent mental disorders due to conditions classified elsewhere
ICD10
G31.84 Mild cognitive impairment, so stated
F09 Unspecified mental disorder due to known physiological condition
:param code: code string to test
:return: true or false
"""
assert isinstance(code, str)
code_set = ('331.83', '294.9', 'G31.84', 'F09', '33183', '2949', 'G3184')
return code.startswith(code_set)
|
def extractrelation(s, level=0):
""" Extract discourse relation on different level
"""
items = s.lower().split('-')
if items[0] == 'same':
rela = '_'.join(items[:2])
else:
rela = items[0]
return rela
|
def vector_average(vv):
"""Calculate average from iterable of vectors."""
c = None
for i, v in enumerate(vv):
c = v if c is None else tuple((i*a+b)/(i+1) for (a, b) in zip(c, v))
return c
|
def safer_getattr(object, name, default=None, getattr=getattr):
"""Getattr implementation which prevents using format on string objects.
format() is considered harmful:
http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/
"""
if isinstance(object, str) and name == 'format':
raise NotImplementedError(
'Using format() on a %s is not safe.' % object.__class__.__name__)
if name.startswith('_'):
raise AttributeError(
'"{name}" is an invalid attribute name because it '
'starts with "_"'.format(name=name)
)
return getattr(object, name, default)
|
def prl_utils(device_type='kinect', camera_name='', quality=()):
"""Returns default rgb and depth topics for the kinect sensors
Keyword Arguments:
device_type {str} -- device type, one of 'kinect', 'kinect2', 'realsense' (default: {'kinect'})
camera_name {str} -- camera unique identifier (default: {''})
quality {tuple} -- rgb and depth quality, only for kinect2 (default: {()})
Raises:
RuntimeError -- for unknown device type
Returns:
tuple -- rgb and depth topics
"""
if device_type == 'kinect':
camera_name = camera_name or 'camera'
color_topic = '/{}/rgb/image_rect_color'.format(camera_name)
depth_topic = '/{}/depth_registered/image'.format(camera_name)
elif device_type == 'kinect2':
camera_name = camera_name or 'kinect2'
quality = quality or ('sd', 'sd')
color_topic = '/{}/{}/image_color_rect'.format(camera_name, quality[0])
depth_topic = '/{}/{}/image_depth_rect'.format(camera_name, quality[1])
elif device_type == 'realsense':
camera_name = camera_name or 'camera'
color_topic = '/{}/color/image_rect_color'.format(camera_name)
depth_topic = '/{}/depth/image_rect_raw'.format(camera_name)
else:
raise RuntimeError('Unknown RGBD device type: {}'.format(device_type))
return color_topic, depth_topic
|
def undistill_link(Ftarget, Finitial):
"""
Obtains the fidelity of a link when reversing distillation of the target link assuming Werner states
:param Ftarget: type float
Fidelity of the distilled link
:param Finitial: type float
Fidelity of the second link used to produce the distilled link
:return: type float
Fidelity of the first link used to produce the distilled link
"""
return (2 * Ftarget * Finitial - Finitial - 5 * Ftarget + 1) / \
(8 * Ftarget * Finitial - 10 * Finitial - 2 * Ftarget + 1)
|
def get_unique_open_finding_hr(unique_open_finding):
"""
Prepare open findings dictionary for human readable data.
This method is used in 'risksense-get-unique-open-findings' command.
:param unique_open_finding: Dictionary representing open host findings.
:return: None.
"""
return {
'Title': unique_open_finding.get('title', ''),
'Severity': unique_open_finding.get('severity', ''),
'Asset Count': unique_open_finding.get('hostCount', ''),
'Source': unique_open_finding.get('source', ''),
'Source ID': unique_open_finding.get('sourceId', '')
}
|
def format_plaintext_email(message):
"""Replace \n by <br> to display as HTML"""
return message.replace('\n', '<br>')
|
def from_two_bytes(bytes):
"""
Return an integer from two 7 bit bytes.
>>> for i in range(32766, 32768):
... val = to_two_bytes(i)
... ret = from_two_bytes(val)
... assert ret == i
...
>>> from_two_bytes(('\\xff', '\\xff'))
32767
>>> from_two_bytes(('\\x7f', '\\xff'))
32767
"""
lsb, msb = bytes
try:
# Usually bytes have been converted to integers with ord already
return msb << 7 | lsb
except TypeError:
# But add this for easy testing
# One of them can be a string, or both
try:
lsb = ord(lsb)
except TypeError:
pass
try:
msb = ord(msb)
except TypeError:
pass
return msb << 7 | lsb
|
def index(tup, ind):
"""Fancy indexing with tuples."""
return tuple(tup[i] for i in ind)
|
def average_t(ave, number, new):
"""
Add up all the temperature and count average.
:param ave: Integer, The average of all temperature before last input
:param number: Integer, number>0. The total amount of temperature
:param new: Integer, new!=EXIT, The lasted temperature input
:return: ave: Integer, The current average temperature
"""
ave = (ave*(number-1)+new) / number
return ave
|
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"tty": string,
"hostname": string,
"login": string,
"logout": string,
"duration": string
}
]
"""
for entry in proc_data:
if 'user' in entry and entry['user'] == 'boot_time':
entry['user'] = 'boot time'
if 'tty' in entry and entry['tty'] == '~':
entry['tty'] = None
if 'tty' in entry and entry['tty'] == 'system_boot':
entry['tty'] = 'system boot'
if 'hostname' in entry and entry['hostname'] == '-':
entry['hostname'] = None
if 'logout' in entry and entry['logout'] == 'still_logged_in':
entry['logout'] = 'still logged in'
if 'logout' in entry and entry['logout'] == 'gone_-_no_logout':
entry['logout'] = 'gone - no logout'
return proc_data
|
def _secs_to_ms(value):
"""Converts a seconds value in float to the number of ms as an integer."""
return int(round(value * 1000.))
|
def check_timestamp_event_type(event_list):
"""For the given event_list, determine whether physical
or spell offensive actions take place"""
for line in event_list:
if 'You perform' in line \
or 'You attack ' in line \
or 'You shot' in line \
or 'You miss' in line \
or 'You fumble' in line \
or 'evades your attack' in line:
return 'physical'
elif 'you cast' in line \
or 'You hit' in line \
or 'resists the effect' in line:
return 'spell'
return 'no-op'
|
def power(x: int, y: int) -> int:
"""Returns x to the power of non-negative integer y."""
assert not y < 0, "Non-negative integer y only."
if y == 0:
return 1
return x * power(x, y - 1)
|
def _strip_comments_from_pex_json_lockfile(lockfile_bytes: bytes) -> bytes:
"""Pex does not like the header Pants adds to lockfiles, as it violates JSON.
Note that we only strip lines starting with `//`, which is all that Pants will ever add. If
users add their own comments, things will fail.
"""
return b"\n".join(
line for line in lockfile_bytes.splitlines() if not line.lstrip().startswith(b"//")
)
|
def vec_sub (x, y):
"""[Lab 14] Returns x - y"""
return [x_i - y_i for (x_i, y_i) in zip (x, y)]
|
def _nb_models_and_deficit(nb_targets, potential_targets):
""" Calculates the number of models to learn based on the number of targets and the potential targets
Args:
nb_targets: number of targets
potential_targets: attributes that can be used as targets
Returns:
nb_models: number of models
nb_leftover_targets: number of potential targets which will not be used
"""
nb_potential_targets = len(potential_targets)
nb_models = nb_potential_targets // nb_targets
nb_leftover_targets = nb_potential_targets % nb_targets
return nb_models, nb_leftover_targets
|
def flatten(S):
""" Flattens a list of lists, but leaves tuples intact"""
flatlist = [val for sublist in S for val in sublist]
return flatlist
|
def longest_palindrom_ver1(strs: str) -> str:
"""Dynamic programing"""
if len(strs) < 2 or strs == strs[::-1]:
return strs
palins = []
for num in range(1, len(strs)):
for i in range(len(strs) - num):
if strs[i:i + num + 1][::-1] == strs[i:i + num + 1]:
palins.append(strs[i:i + num + 1])
break
palins.sort(key=len)
return palins[-1]
|
def sample(i):
"""
Helper method to generate a meaningful sample value.
"""
return 'sample{}'.format(i)
|
def get_tile_url(xtile, ytile, zoom):
"""
Return a URL for a tile given some OSM tile co-ordinates
"""
return "http://tile.openstreetmap.org/%d/%d/%d.png" % (zoom, xtile, ytile)
|
def shock_standoff(R_n, rho_inf, rho_s):
"""
Approximates supersonic shock stand-off distance for the stagnation
point of an obstacle with equivalent radius R_n
Input variables:
R_n : Obstacle radius
rho_inf : Freestream density
rho_s : Density at point immediately behind shock
"""
delta = R_n * (rho_inf / rho_s)
return delta
|
def cell_volume(a1,a2,a3):
"""
returns the volume of the primitive cell: |a1.(a2xa3)|
"""
a_mid_0 = a2[1]*a3[2] - a2[2]*a3[1]
a_mid_1 = a2[2]*a3[0] - a2[0]*a3[2]
a_mid_2 = a2[0]*a3[1] - a2[1]*a3[0]
return abs(float(a1[0]*a_mid_0 + a1[1]*a_mid_1 + a1[2]*a_mid_2))
|
def dealign(text):
"""
Original text is limited to 72 characters per line, paragraphs separated
by a blank line. This function merges every paragraph to one line.
Args:
text (str): Text with limited line size.
Returns:
str: Text with every paragraph on a single line.
"""
original_lines = text.splitlines()
paragraphs = []
i = 0
while i < len(original_lines):
paragraph_lines = []
while True:
line = original_lines[i]
i += 1
if line:
paragraph_lines.append(line)
if not line or i == len(original_lines):
if paragraph_lines:
paragraphs.append(' '.join(paragraph_lines))
break
if i == len(original_lines):
break
return '\n'.join(paragraphs)
|
def area_square(r):
"""Return the area of a square with side length R."""
assert r > 0, 'A length must be positive'
return r * r
|
def extract_teams(picks_bans, radiant_win):
"""
Unest teams field from STEAM API
"""
teams = {
'winners': [],
'loosers': []
}
for pick_ban in picks_bans:
if pick_ban['is_pick']:
# radiant team id is 0
is_win = (pick_ban['team'] != radiant_win)
# add to the collection of the winner or looser team
teams['winners' if is_win else 'loosers']\
.append(pick_ban['hero_id'])
for team in teams.keys():
teams[team].sort()
return teams
|
def findLength(lst):
"""Given a list of bytestrings and NamedInts, return the total
length of all items in the list.
"""
return sum(len(item) for item in lst)
|
def get_metadata(data):
"""Converts metadata from CVAT format.
Args:
data (OrderedDict): CVAT annotation
Returns:
dict: Annotation metadata
"""
metadata = {}
metadata['source_name'] = data['source']
metadata['frames_size'] = data['task']['size']
metadata['start_frame'] = data['task']['start_frame']
metadata['stop_frame'] = data['task']['stop_frame']
metadata['video_width'] = data['task']['original_size']['width']
metadata['video_height'] = data['task']['original_size']['height']
return metadata
|
def maf_binary(sorted_array, value):
"""
In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.
"""
err = "Not Found"
min = 0
max = len(sorted_array) - 1
while min <= max:
mid = (min + max) // 2
if sorted_array[mid] > value:
max = mid - 1
elif sorted_array[mid] < value:
min = mid + 1
else:
return mid
|
def _build_time_predicates(
from_date=None,
to_date=None,
):
"""
Build time range predicates
"""
must = []
if from_date:
must.append("start={}".format(from_date))
if to_date:
must.append("end={}".format(to_date))
return "&".join(must)
|
def delete_part(sentence, delete_part, mainword, **kwargs): #Done with testing
"""Delete all words in the sentence coming either <delete_part>='before'
or <delete_part>='after'"""
if mainword not in sentence:
return False, sentence
senthalved = sentence.split(mainword)
if delete_part == 'after':
return True, senthalved[0]
if delete_part == 'before':
#if the word occurs more than once then we want to make sure we delete
#everything before the LAST occurrence
return True, senthalved[-1]
|
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
return sum(hand.values())
|
def Sub(matA, matB):
"""
Sub(matrix1, matix2):
Subtracts both matices and returns -1 if order of both matrices different or else returns resultant matrix
"""
A=len(matA)
B=len(matB)
#checks number of columns equal of not for both matices, same as previous
if A!=B:
return -1
C=[[]]
for i in range(A):
for j in range(B):
C[-1].append(matA[i][j]-matB[i][j])
C.append([])
return C
|
def tag_only(tag):
"""
simple function to remove the elements token from a tag name
e.g. tag_only('tag_name{10}') -> 'tag_name'
"""
if '{' in tag:
return tag[:tag.find('{')]
else:
return tag
|
def bin_to_int(bin_str: str, signed: bool = True) -> str:
"""Converts binary string to int string
Parameters
----------
bin_str : str
binary string to convert
signed : bool, optional
if the binary string should be interpreted as signed or not, default True
Returns
-------
str
integer as string
"""
if signed:
# if negative two's complemented #
if bin_str[0] == "1":
int_str = f"{int(bin_str,2) - 2**(len(bin_str))}"
# if pos
else:
int_str = f"{int(bin_str,2)}"
else:
int_str = f"{int(bin_str,2)}"
return int_str
|
def rb_is_true(value: str) -> bool:
"""String to bool conversion function for use with args.get(...).
"""
return value.lower() == "true"
|
def default_opinions(codel_size=1, noncoding='block', sliding='halting', color_dir_h='-', color_dir_l='-'):
"""Constructs an opinions dictionary for a repiet compiler pass
(implicity filling in defaults)"""
return dict(codel_size=codel_size,
noncoding=noncoding,
sliding=sliding,
color_dir_h=color_dir_h,
color_dir_l=color_dir_l)
|
def formatColoria(a):
"""int array to #rrggbb"""
return '#%02x%02x%02x' % (a[0],a[1],a[2])
|
def recursive_fibonacci_cache(
n: int
) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raises a ValueError.
>>> recursive_fibonacci_cache(0)
0
>>> recursive_fibonacci_cache(1)
1
>>> recursive_fibonacci_cache(2)
1
>>> recursive_fibonacci_cache(10)
55
>>> recursive_fibonacci_cache(-2)
Traceback (most recent call last):
...
ValueError: n must be more or equal than 0
"""
cache = {}
def _fib(_n):
if _n < 0:
raise ValueError('n must be more or equal than 0')
if _n == 0:
return 0
elif _n == 1:
return 1
if _n not in cache:
if _n - 1 not in cache:
cache[_n - 1] = _fib(_n - 1)
if _n - 2 not in cache:
cache[_n - 2] = _fib(_n - 2)
cache[_n] = cache[_n - 1] + cache[_n - 2]
return cache[_n]
return _fib(n)
|
def get_min_sec_stocks(nr_of_stocks, sectors):
"""
Returns the Number of minimum stocks per sector requiered to get to the nr_of_stocks with the selected sectors
Args:
nr_of_stocks (ind): Readout of the 'nr_of_stocks' input in the interface.
sectors (list): List that is returned from the 'sectors' selectionbox in the interface
Returns:
mss (int): Number of minimum stocks per sector
10 (int): If no sectors are selected it returns 10 as a default argument.
"""
try:
mss = int(round((nr_of_stocks / len(sectors)+0.5)))
return mss
except ZeroDivisionError:
return 10
|
def is_valid(name):
"""Return whether name is valid for Pygame Zero.
name can contain lowercase letters, numbers and underscores only.
They also have to start with a letter.
Args:
name: String name to test.
Returns:
True if name is valid for Pygame Zero. False otherwise.
"""
if not isinstance(name, str):
return False
if len(name) <= 0:
return False
if not name[0].isalpha():
return False
no_underscore = name.replace('_', '')
if no_underscore.islower() and no_underscore.isalnum():
return True
return False
|
def isSpace(s):
"""
isSpace :: str -> bool
Returns True for any Unicode space character, and the control characters
\t, \n, \r, \f, \v.
"""
return s in " \t\n\r\f\v"
|
def index_structure(structure, path, path_separator="/"):
"""Follows :obj:`path` in a nested structure of objects, lists, and dicts."""
keys = path.split(path_separator)
for i, key in enumerate(keys):
current_path = "%s%s" % (path_separator, path_separator.join(keys[:i]))
if isinstance(structure, list):
try:
index = int(key)
except ValueError:
raise ValueError("Object referenced by path '%s' is a list, but got non "
"integer index '%s'" % (current_path, key))
if index < 0 or index >= len(structure):
raise ValueError("List referenced by path '%s' has length %d, but got "
"out of range index %d" % (current_path, len(structure), index))
structure = structure[index]
elif isinstance(structure, dict):
structure = structure.get(key)
if structure is None:
raise ValueError("Dictionary referenced by path '%s' does not have the "
"key '%s'" % (current_path, key))
else:
structure = getattr(structure, key, None)
if structure is None:
raise ValueError("Object referenced by path '%s' does not have the "
"attribute '%s'" % (current_path, key))
return structure
|
def get_metrics_names(metrics):
"""Gets the names of the metrics.
Args:
metrics: Dict keyed by client id. Each element is a dict of metrics
for that client in the specified round. The dicts for all clients
are expected to have the same set of keys."""
if len(metrics) == 0:
return []
metrics_dict = next(iter(metrics.values()))
return list(metrics_dict.keys())
|
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '='* (4 - missing_padding)
return data
|
def _expand_check_paths(template, lookup_key):
"""Generate paths to examine from a variable-type template.
`template` may be one of three data structures:
- str: search for files matching this exact template
- list of str: search for files matching each template listed.
- dict: use `lookup_key` to determine the element in the dictionary
to use as the template. That value is treated as a new `template`
object and can be of any of these three types.
Args:
template (str, list, or dict): Template string(s) which should be passed
to datetime.datetime.strftime to be converted into specific
time-delimited files.
lookup_key (str or None): When `type(template)` is dict, use this key
to identify the key-value to use as template. If None and
``template`` is a dict, iterate through all values of `template`.
Returns:
list: List of strings, each describing a path to an existing HDF5 file
that should contain data relevant to the requested start and end dates.
"""
check_paths = []
if isinstance(template, dict):
if lookup_key is None:
check_paths += _expand_check_paths(list(template.values()), lookup_key)
else:
check_paths += _expand_check_paths(template.get(lookup_key, []), lookup_key)
elif isinstance(template, list):
for value in template:
check_paths += _expand_check_paths(value, lookup_key)
else:
check_paths += [template]
return check_paths
|
def resultlist_reader(response, all_unicode=False):
""" Returns a list
"""
links = []
def get_self(links):
for link in links:
if link['rel'] == "self":
return link['uri']
for result in response:
links.append(get_self(result['links']))
return links
|
def pageurl_template(category, pagenum, date):
"""
Function to return formatted URL given category, page number, date
"""
assert len(str(date)) == 8, 'Invalid input date format'
return f"https://news.daum.net/breakingnews/{category}?page={pagenum}®Date={date}"
|
def _times_2(number: int) -> int:
"""
If number * 2 is greater than 9, return 1
otherwise return the number * 2
:param number:
:return:
"""
return int(list(str(number * 2))[0])
|
def cyan(x):
"""Format a string in cyan.
Returns:
The string `x` made cyan by terminal escape sequence.
"""
return f"\033[36m{x}\033[0m"
|
def validate_rng_seed(seed, min_length):
"""
Validates random hexadecimal seed
returns => <boolean>
seed: <string> hex string to be validated
min_length: <int> number of characters required. > 0
"""
if len(seed) < min_length:
print("Error: Computer entropy must be at least {0} characters long".format(min_length))
return False
if len(seed) % 2 != 0:
print("Error: Computer entropy must contain an even number of characters.")
return False
try:
int(seed, 16)
except ValueError:
print("Error: Illegal character. Computer entropy must be composed of hexadecimal characters only (0-9, a-f).")
return False
return True
|
def _attributes_from_line(line):
"""Parse an attribute line.
Arguments:
line -- a single line from the tlpdb
Returns:
A dictionary of attributes
Example input lines:
arch=x86_64-darwin size=1
details="Package introduction" language="de"
RELOC/doc/platex/pxbase/README details="Readme" language="ja"
"""
key = None
value = None
chars = []
quote_count = 0
attrs = {}
for c in line:
if c == "=":
if key == None:
assert quote_count == 0, "possibly quoted key in line %s" % (
line)
key = "".join(chars)
chars = []
else:
chars.append(c)
elif c == "\"":
quote_count += 1
elif c == " ":
# if quotes are matched, we've reached the end of a key-value pair
if quote_count % 2 == 0:
assert key != None, "no key found for %s" % (line)
assert key not in attrs, "key already assigned for line %s" % (
line)
attrs[key] = "".join(chars)
# reset parser state
chars = []
key = None
quote_count = 0
else:
chars.append(c)
else:
chars.append(c)
assert key != None, "no key found for %s" % (line)
assert len(chars), "no values found for line %s" % (line)
attrs[key] = "".join(chars)
return attrs
|
def normalizeAnswer (answer, yes=None, missing=None):
"""Special-case hackery, perhaps eventually more parameterized ..."""
if answer in (None, ""):
answer = missing
# Special-case hackery ...
elif answer.lower() == yes:
answer = "yes"
else:
answer = "no"
return answer
|
def tot(sequence, total=0):
"""Helper method: returns total of string sequence."""
total = counter = 0
temp = ''
plus_minus = 1 # variable for managing + and -
while counter < len(sequence):
try:
int(sequence[counter])
temp += sequence[counter]
except ValueError:
total += int(temp)*plus_minus
temp = ''
if sequence[counter] == u'-':
plus_minus = -1
if sequence[counter] == u'+':
plus_minus = 1
counter += 1
total += int(temp)*plus_minus
return total
|
def get_bert_dataset_name(is_cased):
"""Returns relevant BERT dataset name, depending on whether we are using a cased model.
Parameters
----------
is_cased: bool
Whether we are using a cased model.
Returns
-------
str: Named of the BERT dataset.
"""
if is_cased:
return 'book_corpus_wiki_en_cased'
else:
return 'book_corpus_wiki_en_uncased'
|
def save_list(input_list, file_name):
"""A list (input_list) is saved in a file (file_name)"""
with open(file_name, 'w') as fh:
for item in input_list:
fh.write('{0}\n'.format(item))
return None
|
def get_target_start_date_col(forecast_id):
"""Returns the name of the target start date col for dataframes
associated with the given forecast identifier
Args:
forecast_id: string identifying forecast (see get_forecast)
"""
if forecast_id.startswith("nmme"):
return "target_start"
if forecast_id.startswith("cfsv2"):
return "start_date"
raise ValueError("Unrecognized forecast_id "+forecast_id)
|
def which(program):
"""The Unix which command in Python."""
import os
def is_exe(fpath):
"""Check if file is executable."""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, _ = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
|
def isnumber(s):
""" Is number or not
"""
try:
val = int(s)
return True
except ValueError:
return False
|
def no_filter(f_0, F, X_target, y_target, metric=None, vote_func=None):
"""Apply no filter to the data, just merge F and F_0 and return
Args:
f_0: baseline learner
F: set of possible learners
X_target: target training instances
y_target: target training labels
metric: unuse params
Returns:
list: F with f_0 added to it
"""
F.append(f_0)
return F
|
def _get_time_axis(time_list, units='hours'):
"""Convert time to sequential format and convert time units."""
time_axis = []
for i in range(len(time_list)):
time_sum = sum(time_list[:i])
if units == 'seconds':
pass
elif units == 'minutes':
time_sum /= 60.0
elif units == 'hours':
time_sum /= 3600.0
time_axis.append(time_sum)
return time_axis
|
def mean(iterable):
"""
Compute the mean value of the entries in {iterable}
"""
# make an iterator over the iterable
i = iter(iterable)
# initialize the counters
count = 1
total = next(i)
# loop
for item in i:
# update the counters
count += 1
total += item
# all done
return total * 1/count
|
def locate(x1, y1, x2, y2, x3):
"""An equation solver to solve: given two points on a line and x, solve the
y coordinate on the same line.
Suppose p1 = (x1, y1), p2 = (x2, y2), p3 = (x3, y3) on the same line.
given x1, y1, x2, y2, x3, find y3::
y3 = y1 - (y1 - y2) * (x1 - x3) / (x1 - x3)
"""
return y1 - 1.0 * (y1 - y2) * (x1 - x3) / (x1 - x2)
|
def guess_number(f_guess, f_turns_left):
"""Obtain player guess
Params:
f_guess: int
f_turns_left: int
Returns:
int, str
"""
try:
if f_guess < 1 or f_guess > 9:
raise ValueError
return f_guess, f_turns_left - 1
except ValueError:
return '\nRULES: Please enter a number between 1 and 9.', f_turns_left - 1
except TypeError:
return '\nRULES: Please enter a number between 1 and 9.', f_turns_left - 1
|
def zipmap(keys, vals):
"""Return a map from keys to values"""
return dict(zip(keys, vals))
|
def calculate(puzzle_input):
"""Tracks Santa's steps"""
x = y = rx = ry = 0
visited = set()
robot = False
for step in puzzle_input:
if step == "^":
if robot:
ry += 1
else:
y += 1
elif step == "v":
if robot:
ry -= 1
else:
y -= 1
elif step == "<":
if robot:
rx -= 1
else:
x -= 1
elif step == ">":
if robot:
rx += 1
else:
x += 1
if robot:
visited.add((rx, ry))
robot = False
else:
visited.add((x, y))
robot = True
return len(visited)
|
def del_empty_space(list):
"""deletes empty elements with "space" in it"""
for x in range(len(list)):
if " " in list[x - 1]:
del list[x - 1]
return list
|
def is_stressful(subj):
"""
recoognise stressful subject
"""
import re
return (subj.isupper() or subj.endswith('!!!') or
any(re.search('+[.!-]*'.join(word), subj.lower())
for word in ['help', 'asap', 'urgent']
# 'h+[.!-]*e+[.!-]*l+[.!-]*p'
# 'a+[.!-]*s+[.!-]*a+[.!-]*p'
)
)
|
def get_drop_indices(num_chunks, keep_indices):
"""obtain the drop_indices given the keep_indices.
Args:
num_chunks (int): The total number of chunks
keep_indices (List): The keep indices.
Returns: List. The dropped indices (frozen chunks).
"""
drop_indices = []
for i in range(num_chunks):
if i not in keep_indices:
drop_indices.append(i)
return drop_indices
|
def calculate_kill_death_assists_ratio(kills, deaths, assists):
"""
kda = kills + (assists / 2) / deaths
Ensure the MLG's have some deaths.
"""
numerator = kills + (assists / 2)
if deaths > 0:
kda = numerator / deaths
else:
kda = numerator
return round(kda, 2)
|
def get_log(name=None):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Python,
http://docs.python.org/library/logging.html
"""
import logging
if name is None:
name = 'oct2py'
else:
name = 'oct2py.' + name
log = logging.getLogger(name)
return log
|
def unit_conversion(current_values, unit_type, current_unit, new_unit):
"""
Converts given values between the specified units
:param current_values: the current values that you want converted between units. It can be any type, so long as
arithmetic operations with scalars behave appropriately. A numpy array will work; a list will not.
:param unit_type: the type of unit (e.g. mixing ratio, length, mass) as a string
:param current_unit: a string representing the current unit
:param new_unit: a string representing the desired unit
:return: the same type as current_values converted to be the new units
"""
if not isinstance(unit_type, str):
raise TypeError('unit_type must be a string')
if not isinstance(current_unit, str):
raise TypeError('current_unit must be a string')
if not isinstance(new_unit, str):
raise TypeError('new_unit must be a string')
try:
current_values + 1.0
current_values - 1.0
current_values * 1.0
current_values / 1.0
except:
raise TypeError('Cannot perform one or more arithmetic operations on current_values')
# Define the conversions here. conv_factors must be a dictionary where the keys are the units and the values are
# the factor that multiplying the a base unit by converts it to the unit in question.
if unit_type.lower() == 'mixing ratio' or unit_type.lower() == 'vmr':
base_unit = 'ppp'
conv_factors = {'ppp': 1.0, 'ppm': 1.0e6, 'ppmv': 1.0e6, 'ppb': 1.0e9, 'ppbv': 1.0e9, 'ppbC': 1.0e9}
else:
raise ValueError('Unit type "{0}" not recognized'.format(unit_type))
if current_unit not in list(conv_factors.keys()):
raise KeyError('{0} unit "{1}" not defined'.format(unit_type, current_unit))
if new_unit not in list(conv_factors.keys()):
raise KeyError('{0} unit "{1}" not defined'.format(unit_type, new_unit))
return current_values * conv_factors[new_unit] / conv_factors[current_unit]
|
def _get_pattern_list(testdata, global_obj, pattern="start"):
"""
Get the pattern attribute from either the current testdata block
or from the global section
"""
global_var_pattern = global_obj.find("variable_pattern") if global_obj is \
not None else None
if pattern == "start":
resultant = "${"
else:
resultant = "}"
if testdata.get(pattern+"_pattern") is not None:
resultant = testdata.get(pattern+"_pattern")
elif global_var_pattern is not None and global_var_pattern.\
get(pattern+"_pattern") is not None:
resultant = global_var_pattern.get(pattern+"_pattern")
return resultant
|
def region_append_without_whitespace(book, rclass, start, end, *extra):
"""
Shrink the region (start, end) until there is no whitespace either end of
the region. Then if it is non-zero, append the region to (rclass)
Return true iff a region is added.
"""
if start is None:
return
if start >= len(book['content']):
return (-1, -1) + extra # Outside the range, return something that will get ignored
while book['content'][start].isspace():
start += 1
if start >= len(book['content']):
# Fallen off the end of the book, this isn't a useful region
return
while book['content'][end - 1].isspace():
end -= 1
if end < 0:
# Fallen off the start of the book, this isn't a useful region
return
if end > start:
if rclass not in book:
book[rclass] = []
book[rclass].append((start, end) + extra)
return True
return False
|
def distinct(lst1, lst2):
"""
Argument order: source following list, accumulated source's following list
"""
following = lst1
second_layer_following = lst2
unique = set(following)
final = [x for x in second_layer_following if x not in unique]
return final
|
def get_columns(filters):
"""return columns based on filters"""
columns = [
{
"fieldname":"item",
"fieldtype":"Link",
"label":"Item",
"options":"Item",
"width":250
},
{
"fieldname":"open_qty",
"fieldtype":"Float",
"label":"Opening Qty",
"width":100
},
{
"fieldname":"in_qty",
"fieldtype":"Float",
"label":"In Qty",
"width":100
},
{
"fieldname":"out_qty",
"fieldtype":"Float",
"label":"Out Qty",
"width":100
},
{
"fieldname":"balance_qty",
"fieldtype":"Float",
"label":"Balance Qty",
"width":100
},
{
"fieldname":"unconfirmed_qty",
"fieldtype":"Float",
"label":"Unconfirmed Qty",
"width":100
},
{
"fieldname":"undelivered_qty",
"fieldtype":"Float",
"label":"Undelivered Qty",
"width":100
},
{
"fieldname":"defective_qty",
"fieldtype":"Float",
"label":"Defective Qty",
"width":100
}
]
return columns
|
def solution(a: int, b: int, k: int) -> int:
"""
:return: The number of integers within the range [a..b]
that are divisible by k.
>>> solution(6, 11, 2)
3
>>> solution(3, 14, 7)
2
"""
count = (b - a + 1) // k
if b % k == 0:
count += 1
return count
|
def allZero(buffer):
"""
Tries to determine if a buffer is empty.
@type buffer: str
@param buffer: Buffer to test if it is empty.
@rtype: bool
@return: C{True} if the given buffer is empty, i.e. full of zeros,
C{False} if it doesn't.
"""
allZero = True
for byte in buffer:
if byte != 0:
allZero = False
break
return allZero
|
def pick_one(l: list):
"""Pick one of the items from the list."""
# special case for picking only one item
if len(l) == 1:
return l[0]
for i, item in enumerate(l):
print(f"{i + 1}) {item}")
while True:
try:
val = input("Pick one (leave blank for 1): ")
if val == "":
index = 0
else:
index = int(val) - 1
except ValueError:
continue
if not 0 <= index < len(l):
continue
return l[index]
|
def del_comment(string):
"""Delete the comment from the parameter setting string.
Parameters
----------
string : str, default None
The parameter setting string probably with the comment.
Returns
-------
string : str
The parameter setting string without the comment.
"""
return string.split('#')[0].replace(' ', '')
|
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.