content stringlengths 42 6.51k |
|---|
def tanh_d(x: float) -> float:
"""
The gradient of the Hyperbolic Tangent activation function
Args:
x: The point at which to take the gradient
Returns:
The gradient of the tanh activation function
"""
return 1 - x ** 2 |
def http_header(value):
"""Converts Django HTTP headers to standard format
e.g.
HTTP_ACCEPT -> Accept
HTTP_CACHE_CONTROL -> Cache-Control
"""
parts = value.split('_')
header_parts = [part.title() for part in parts[1:]]
formatted = '-'.join(header_parts)
return formatted |
def insertionSort(array):
"""Apply insertion sort to an array. Returns a sorted array."""
for i in range(1, len(array)):
key = array[i]
j = i-1
while j >= 0 and key < array[j]:
array[j+1] = array[j]
j -= 1
array[j+1] = key
return array |
def convert_quality_filter(quality):
"""Jinja2 Filter to convert quality score."""
quality_map = {
"A01": "Poor",
"A02": "OK",
"A03": "Moderate",
"A04": "Good",
}
if quality not in quality_map:
raise ValueError("The quality is not a valid value. It must be A01 - A04")
return quality_map[quality] |
def _fixup_find_links(find_links):
"""Ensure find-links option end-up being a list of strings."""
if isinstance(find_links, str):
return find_links.split()
assert isinstance(find_links, (tuple, list))
return find_links |
def hex_byte_str(value: int) -> str:
"""
Convert a "char" to a hexadecimal number.
"""
if not (0 <= value <= 0xFF):
raise ValueError(f"value must be between 0 and 255: {value}")
hex_value = hex(value)[2:]
if value < 0x10:
hex_value = "0" + hex_value
return hex_value |
def get_dict_values(dic: dict) -> list:
"""
Insert the dictionary values into the list
:param dic: The desired dictionary to be converted
:return :list will be returned with the dictionary values
"""
return list(dic.values()) |
def is_str(value):
"""Must be of type `str`"""
return isinstance(value, str) |
def fib(n):
"""
input: positive integer 'n'
returns the n-th fibonacci term , indexing by 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for i in range(n-1):
tmp = ans
ans += fib1
fib1 = tmp
return ans |
def first_occurrence_index(l, val, after_index=None):
"""
Find the first occurrence of some value, after_index will
not be included in the possible return value
:param l:
:param val: value to look for
:param after_index: exclusive beginning of the range
:return: zero-based index
"""
if after_index is None:
after_index = -1
return after_index + 1 + l[after_index+1:].index(val) |
def get_jsonpath(obj: dict, jsonpath):
"""
Gets a value from a dictionary based on a jsonpath. It will only return
one result, and if a key does not exist it will return an empty string as
template tags should not raise errors.
:param obj: The dictionary to query
:param jsonpath: The path to the object (singular)
:return: The most relevant object in the dictionary
"""
try:
keys = str(jsonpath).split(".")
val = obj
for key in keys:
val = val[key]
return val
except (KeyError, TypeError):
return "" |
def disable_tc_type_selector_dropdowns(acq_state, div_style):
# pylint: disable=invalid-name
"""
A callback function to disable all TC Type selector dropdowns when
the application status changes to configured or running.
"""
div_style['pointer-events'] = 'auto'
div_style['opacity'] = 1.0
if acq_state == 'configured' or acq_state == 'running':
div_style['pointer-events'] = 'none'
div_style['opacity'] = 0.8
return div_style |
def get_nested_labels(flattened_labs, len_list):
"""
Given an utterance-level flattened list of labels, and the lengths (in utterance) of each sessions,
get a session-level nested list of labels.
Parameters
----------
flattened_labs : list[int] or np.array[int]
1-d list or np.array with size (N, )
len_list : list[int]
1-d list or np.array with size (S, )
Returns
-------
list[list[int]]
with size (S, N_s)
* N: total number of utterances
* S: number of sessions
* N_s : number of utterances in each session
"""
fr, to = 0, 0
nested_labs = []
for slen in len_list:
to = fr + slen
nested_labs.append(flattened_labs[fr:to])
fr = to
return nested_labs |
def format_ft_comp(q, a1, a2, context=False):
"""Formats prompt for fine-tuned semantic similarity with GPT-3"""
if context:
prompt = '{0}\n1: {1}\n2: {2}\nEqual:'.format(q.strip(), a1.strip(), a2.strip())
else:
prompt = '1: {0}\n2: {1}\nEqual:'.format(a1, a2)
return prompt |
def normalize(testURL):
"""Normalize the URL."""
testURL = testURL.split('//', 1)[1]
# testURL = re.sub("^http(s)?://", "", testURL)
if testURL.endswith('/'):
testURL = testURL[:-1]
# testURL = re.sub("/$", "", testURL)
components = testURL.split('/')
return components |
def is_function(var):
"""
Test if variable is function (has a __call__ attribute)
:return: True if var is function, False otherwise.
:rtype: bol
"""
return hasattr(var, '__call__') |
def pixel_sum(position):
"""
Sums up the total count of pixels in the area limited by the coordinate points in position.
"""
if (position != None):
return position.get("width", 0) * position.get("height", 0)
else:
return 0 |
def pointing_tuple2str(dirtuple):
"""
Convert a direction tuple to a string
Inverse of pointing_str2tuple().
Parameters
----------
dirtuple : tuple or None
Direction tuple defined as (angle1: float, angle2: float, refsys: str)
or None if beamctldirarg was not correct format.
Returns
-------
beamctldirarg : str
String with format 'angle1,angle2,refsys'. Returns None if input is incorrect value.
Examples
--------
>>> from ilisa.monitorcontrol.directions import pointing_tuple2str,
... pointing_str2tuple
>>> pointing_tuple2str((1.0,2.0,'AZELGEO'))
'1.0,2.0,AZELGEO'
>>> pointing_str2tuple(pointing_tuple2str((1.0,2.0,'AZELGEO')))
(1.0, 2.0, 'AZELGEO')
"""
beamctldirarg = None
if type(dirtuple) is tuple and len(dirtuple) == 3:
dir_str_tuple = (str(dirtuple[0]), str(dirtuple[1]), dirtuple[2])
beamctldirarg = ",".join(dir_str_tuple)
return beamctldirarg |
def head(sequence):
"""
Returns first item from `sequence` or :const:`None` if sequence is empty.
>>> head([1])
1
>>> head([2, 3])
2
>>> head([(1, 2), (3, 4)])
(1, 2)
>>> head()
"""
try:
return next(iter(sequence))
except StopIteration:
return None |
def is_curious_fraction(numerator, denominator):
"""
Determine if two numbers form a curious fraction.
A curious fraction is where removing a number common to the numerator and
denominator is equal to the original fraction.
:param numerator: The numerator of the fraction as an int.
:param denominator: The denominator of the fraction as an int.
:returns: True if the fraction is curious else False.
"""
fraction = numerator / denominator
numerator = str(numerator)
denominator = str(denominator)
if len(numerator) == 1:
return False
if numerator.endswith('0') or denominator.endswith('0'):
return False
for number in numerator:
new_numerator = numerator.replace(number, '', 1)
new_denominator = denominator.replace(number, '', 1)
new_fraction = int(new_numerator) / int(new_denominator)
if new_fraction == fraction:
return True
return False |
def extractAliasFromContainerName(containerName):
""" Take a compose created container name and extract the alias to which it
will be refered. For example bddtests_vp1_0 will return vp0 """
return containerName.split("_")[1] |
def edges_index(edges):
"""Edges are given as (v1,v2)
Return the indexes of those vertices (v1-1, v2-1)"""
edges_idx = [(e[0] - 1, e[1] - 1) for e in edges]
return edges_idx |
def validate_description(value):
"""Raise exception if description exceeds length."""
if value and len(value) > 128:
return "have length less than or equal to 128"
return "" |
def is_hex(s):
"""
Explicit name, used to detect errors in to be sent hashes
"""
try:
int(s, 16)
return True
except ValueError:
return False |
def find_peak(list_of_integers):
"""
Args:
list_of_integers(int): list of integers to find peak of
Returns: peak of list_of_integers or None
"""
size = len(list_of_integers)
mid_e = size
mid = size // 2
if size == 0:
return None
while True:
mid_e = mid_e // 2
if (mid < size - 1 and
list_of_integers[mid] < list_of_integers[mid + 1]):
if mid_e // 2 == 0:
mid_e = 2
mid = mid + mid_e // 2
elif mid_e > 0 and list_of_integers[mid] < list_of_integers[mid - 1]:
if mid_e // 2 == 0:
mid_e = 2
mid = mid - mid_e // 2
else:
return list_of_integers[mid] |
def get_label_name(node, dialogue_list):
"""
Takes a node and returns the name for its label
"""
for dialogue in dialogue_list:
if dialogue["Id"] == node["Parent"]:
label_name = "{}_{}".format(dialogue["DisplayName"], node["Id"])
return label_name |
def source_peer(peer):
"""Sets environment variables for that peer"""
return "source /etc/hyperledger/crypto-config/tools/set_env." + peer+".sh" |
def bytesToSigned32(bytearr):
"""
converts the last 4 bytes of a 5 byte array to a signed integer
"""
unsigned=(bytearr[1]<<24)+(bytearr[2]<<16)+(bytearr[3]<<8)+bytearr[4]
return unsigned-4294967296 if bytearr[1]&128 else unsigned |
def masked(supported_resource_type_control=None):
""" check if force_url_override is set in SupportedResourceType """
mask = False
if supported_resource_type_control:
if supported_resource_type_control.override_url_id:
mask = True
return mask |
def split_list(input_list):
"""
Splits a list in half (assumes even length)
:param input_list:
:return: Tuple of the first and second halves of the list
"""
if len(input_list) % 2 == 0:
half = len(input_list) // 2
return input_list[:half], input_list[half:]
else:
raise NotImplementedError("split_list requires a list of even length") |
def retry_if_Index_Exception(exception):
"""
There is a bug when importing pybel that triggers this error:
https://github.com/MD-Studio/MDStudio/issues/29
"""
return isinstance(exception, IndexError) |
def makeProperMAC(s):
""" create a MAC address string in SNIPEIT format (eg XX:XX:...)"""
#option one: this is already XX:XX:XX:XX:XX:XX
if len(s.split(':')) ==6:
return s
if len(s)==12: #option 2 aabbccddeeff
return ":".join([s[i:i+2] for i in range(0, len(s), 2)])
# option 3: aa-bb-cc-dd-ee-ff
if len(s.split('-')) == 6:
return ":".join(s.split('-')) |
def write_codelist_to_xls(worksheet, rows, header, row_nbr=0):
"""
write code list, value level, or where clause rows to the odmlib worksheet
:param worksheet: odmlib worksheet object to write to
:param rows: a list of dictionaries (rows) to write to the worksheet
:param row_nbr: integer row number that indicates which worksheet row to begin appending terms
:return: integer row number that indicates the next row to begin appending content
"""
for row in rows:
row_nbr += 1
for c, col_name in enumerate(header):
worksheet.write(row_nbr, c, row[col_name])
return row_nbr |
def follow_wall(front, left, right):
"""Simple follow wall controller."""
change_direction = 0
F = (0 < front < 4)
L = (0 < left < 4)
R = (0 < right < 4)
if 0 < front < 3:
change_direction = -10
elif 1.0 <= left <= 2.0:
# we're good
change_direction = 0
elif 0 < left < 1.0:
change_direction = -10
elif left > 2.0:
change_direction = 10
return change_direction |
def colordiff(diff):
"""convert git diff data to html/bootstrap color code"""
if diff == '':
return ''
diff = diff.strip()
diff = diff.replace('\n', ' \n')
diffData = diff.split('\n')
openTag = '<tr><td class="'
openTagEnd = '">'
nbsp = ' '
data = '\n'.join([('%s%s%s%s<samp>%s</samp><td></tr>' %
(openTag,
'bg-info' if line.startswith('---') or line.startswith('+++')
else ('bg-danger' if line.startswith('-')
else ('bg-success' if line.startswith('+')
else ('bg-info' if line.startswith('@')
else ''))),
openTagEnd,
nbsp * line.count('\t'), line)) for line in diffData])
return '<table width="100%">' + data + '</table>' |
def str_true(v):
"""The string representation of a true value will be 'TRUE'. False will
be the empty string.
"""
if v:
return "TRUE"
else:
return "" |
def _rlz(s: str) -> str:
"""
Removes the leading zeroes from a number in string form.
"""
x = 0
while s[x] == '0' and x < len(s) - 1:
x += 1
return s[x:] |
def get_min_taxa(num_taxa,max_missing=1):
""" often lots of clusters with full taxon occupancy when num_taxa is small
don't want to print out too many clusters for a test run"""
return num_taxa - int(max_missing) if num_taxa >= 10 else num_taxa |
def merge_logs(bet_logs, bet_results_logs):
"""Merges bet logs (LogBet) with bet results logs (LogResult)."""
merged_logs = ()
# per bet ID dictionary
bet_results_dict = {}
for bet_result in bet_results_logs:
bet_id = bet_result["bet_id"]
bet_results_dict = dict(bet_results_dict, **{bet_id: bet_result})
for bet_log in bet_logs:
bet_id = bet_log["bet_id"]
bet_result = bet_results_dict.get(bet_id)
merged_log = {"bet_log": bet_log, "bet_result": bet_result}
merged_logs += (merged_log,)
return merged_logs |
def make_stat(opt_fp, opt_tp, max_fp, len_df):
"""
Called by loanpy.sanity.postprocess2.
Calculates statistics from optimum, max nr of guesses and length \
of input data frame.
:param opt_fp: The optimal false positive rate as a fraction of the \
maximal false positive rate, i.e. last (=highest) element of \
list passed to param <guesslist> in loanpy.sanity.eval_all.
:type opt_fp: float
:param opt_tp: The optimal true positive rate as a fraction of the \
total number of input words for predictions, i.e. length of data frame.
:type opt_tp: float
:param max_fp: The maximal false positive rate is the \
highest number of possible guesses, i.e. the last element of the list \
passed to param <guesslist> in loanpy.sanity.eval_all.
:type max_fp: int | float
:param len_df: The total number of input words for predictions.
:type len_df: int
:returns: The optimal setting for param <howmany> in \
loanpy.adrc.Adrc.adapt or loanpy.adrc.Adrc.reconstruct.
:rtype: tuple of int, str, str
:Example:
>>> from loanpy.sanity import make_stat
>>> make_stat(opt_fp=0.099, opt_tp=0.6, max_fp=1000, len_df=10)
(100, "6/10", "60%")
"""
# howmany = 1 more than fp (opt_fp is a % of max_guess)
opt_howmany = round(opt_fp*max_fp) + 1
# how many did it find out of all, e.g. 10/100
opt_tp_str = str(round(opt_tp*len_df)) + "/" + str(len_df)
# how many percent is that, e.g. 10/100 would be 10%
opt_tpr = str(round(opt_tp*100)) + "%"
return opt_howmany, opt_tp_str, opt_tpr |
def get_exec_log_name(execname, comp_opts_count=None, exec_opts_count=None):
"""Returns the execution output log name based on number of comp and exec opts."""
suffix = '.exec.out.tmp'
if comp_opts_count is None and exec_opts_count is None:
return '{0}{1}'.format(execname, suffix)
else:
return '{0}.{1}-{2}{3}'.format(execname, comp_opts_count, exec_opts_count, suffix) |
def pagodaValue(gameState):
#################################################
#
# A function evaluating the board state, whose
# value is non-increasing with every move. When
# we reach a game state, not the goal, whose
# Pagoda Value is less than the goal state, we
# will not expand that state as it will obviously
# never lead to a solution.
#
#################################################
"""pagoda = [[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 2, 1, 0, 0],
[1, 1, 2, 3, 2, 1, 1],
[1, 2, 3, 5, 3, 2, 1],
[1, 1, 2, 3, 2, 1, 1],
[0, 0, 1, 2, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0]]"""
"""pagoda = [[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]"""
pagoda = [[0, 0, -1, 0, -1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[-1, 1, 0, 1, 0, 1, -1],
[0, 1, 1, 2, 1, 1, 0],
[-1, 1, 0, 1, 0, 1, -1],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, -1, 0, -1, 0, 0]]
value = 0
for i in range(7):
for j in range(7):
if gameState.count((i,j)) == 1:
value += pagoda[i][j]
return value |
def int_to_string(value, dp=0):
"""Converts a python int to a homie string"""
return str(round(value, dp)) |
def get_status(scores, expected, status_match, status_not_match):
"""
Simple status helper.
"""
if scores == expected:
return status_match
else:
return status_not_match |
def array_equal(current_arr: list, new_arr: list) -> bool:
"""Test whether two seating arrangements are equal
:param current_arr: Current seating arrangement
:param new_arr: New seating arrangement
:return: True if arrays are equal, False otherwise
"""
for i in range(len(current_arr)):
for j in range(len(current_arr[0])):
if new_arr[i][j] != current_arr[i][j]:
return False
return True |
def _set_default_stats_options(stats_options):
"""Define some default summary statistics to display in estimation table."""
if stats_options is None:
stats_options = {
"n_obs": "Observations",
"rsquared": "R$^2$",
"rsquared_adj": "Adj. R$^2$",
"resid_std_err": "Residual Std. Error",
"fvalue": "F Statistic",
}
else:
if not isinstance(stats_options, dict):
raise TypeError(
f"""stats_options can be of types dict or NoneType.
Not: {type(stats_options)}."""
)
return stats_options |
def combine_lists(one_list):
"""
Combine a set of lists into one list.
"""
final_list = []
for l in one_list:
final_list += l
return final_list |
def formatExc(exc):
""" format the exception for printing """
try:
return f"<{exc.__class__.__name__}>: {exc}"
except:
return "<Non-recognized Exception>" |
def leaky_ReLU_1d(d, negSlope):
"""
one dimensional implementation of leaky ReLU
"""
if d > 0:
return d
else:
return d * negSlope |
def interval_overlap(a: int, b: int, x: int, y: int) -> int:
"""Returns by how much two intervals overlap
assumed that a <= b and x <= y"""
if b <= x or a >= y:
return 0
elif x <= a <= y:
return min(b, y) - a
elif x <= b <= y:
return b - max(a, x)
elif a >= x and b <= y:
return b - a
else:
assert False |
def intervalComparison(x, lowerBound, upperBound):
"""
classify a value relative to the interval between two bounds:
returns -1 when below the lower bound
returns 0 when between the bounds (inside the interval)
returns +1 when above the upper bound
"""
if (x < lowerBound): return -1
if (x > upperBound): return 1
return 0 |
def get_finalscore(score, counter):
""" sent when quiz completed and give final score """
return "Your final score is " +str(score) +" out of " +str(counter) + ". " |
def partition(seq):
"""
pick the first element in seq as the pivot
elements <= pivot goes to the left
elements > pivot goest to the right
return the left, pivot, right
"""
pivot, seq = seq[0], seq[1:]
low = [x for x in seq if x <= pivot]
high = [x for x in seq if x > pivot]
return low, pivot, high |
def set(list, index, item):
"""
Return a list with the item at the specified index replaced with the
given item. If the index is out of bounds, return the list unmodified.
"""
if list == () or index < 0:
return list
else:
head, tail = list
if index == 0:
return (item, tail)
else:
return (head, set(tail, index - 1, item)) |
def quote(s, unsafe="/"):
"""Pass in a dictionary that has unsafe characters as the keys, and the percent
encoded value as the value."""
res = s.replace("%", "%25")
for c in unsafe:
res = res.replace(c, "%" + (hex(ord(c)).upper())[2:])
return res |
def firstLetter(text: str):
"""
Returns the first letter of every word in the `text`.
"""
return "".join(letter[0] for letter in text.split()) |
def pow(A, B, C):
"""pow(x, n) % d"""
res = 1 % C
while B > 0:
if B & 1: # Odd
res = (res * A) % C
A = A**2 % C
B >>= 1
return res |
def none2Empty(value):
"""Answers an empty string if value is None, otherwise pass it through To
make sure that 0 empty objects show as result."""
if value is None:
return ''
return value |
def _is_zip_file(path):
"""Returns whether to treat the given file as a zip file."""
return path[-4:] in ('.zip') |
def de_median_redshift(wavelength, median_z):
"""De-redshifts the same way as above
Parameters:
wavelength (array): wavelength values to convert
median_z (int): redshift to change the wavelength by
Returns:
wavelength_red (array): redshifted wavelength
"""
wavelength_red = wavelength / (1 + median_z)
return wavelength_red |
def mean(my_list):
"""
This function calculates the mean of a list
Parameters
----------
my_list: list
The list of numbers that we want to average
Returns
-------
mean_list : float
The mean of the list
Examples
-------
>>> mean ([1,2,3,4,5])
3.0
"""
if not isinstance(my_list, list):
raise TypeError("Mean: {} is not a list".format(my_list))
return sum(my_list) / len(my_list) |
def safe_string(msg):
"""
Make the string safe, by trying to convert each character in turn to
string, replacing bad ones with ?
"""
def map_char(c):
try:
return str(c)
except:
return "?"
return "".join(map_char(c) for c in msg) |
def coullet(XYZ, t, a=0.8, b=-1.1, c=-0.45, d=-1):
"""
The Coullet Attractor.
x0 = (0.1,0,0)
"""
x, y, z = XYZ
x_dt = y
y_dt = z
z_dt = a * x + b * y + c * z + d * x**3
return x_dt, y_dt, z_dt |
def lines_to_chars(text1, text2):
"""Split two texts into a list of strings. Reduce the texts to a string
of dicts where each Unicode character represents one line.
Args:
text1: First string.
text2: Second string.
Returns:
Three element tuple, containing the encoded text1, the encoded text2 and
the list of unique strings. The zeroth element of the list of unique
strings is intentionally blank.
"""
line_list = [] # e.g. line_list[4] == "Hello\n"
line_dict = {} # e.g. line_dict["Hello\n"] == 4
# "\x00" is a valid character, but various debuggers don't like it.
# So we'll insert a junk entry to avoid generating a null character.
line_list.append('')
def lines_to_chars_munge(text):
"""Split a text into a list of strings. Reduce the texts to a string
of dicts where each Unicode character represents one line.
Modifies line_list and lineHash through being a closure.
Args:
text: String to encode.
Returns:
Encoded string.
"""
chars = []
# Walk the text, pulling out a substring for each line.
# text.split('\n') would would temporarily double our memory footprint.
# Modifying text would create many large strings to garbage collect.
line_start = 0
line_end = -1
while line_end < len(text) - 1:
line_end = text.find('\n', line_start)
if line_end == -1:
line_end = len(text) - 1
line = text[line_start:line_end + 1]
line_start = line_end + 1
if line in line_dict:
chars.append(chr(line_dict[line]))
else:
line_list.append(line)
line_dict[line] = len(line_list) - 1
chars.append(chr(len(line_list) - 1))
return ''.join(chars)
chars1 = lines_to_chars_munge(text1)
chars2 = lines_to_chars_munge(text2)
return (chars1, chars2, line_list) |
def _to_absolute(detection, box):
"""Convert detection relative to box to absolute coordinates."""
x0, y0, x1, y1, p = detection
bx0, by0, *_ = box
return x0 + bx0, y0 + by0, x1 + bx0, y1 + by0, p |
def update_entries(entries, new_entry):
"""Adds the new_entry to the entries.
1. If new_entry URL is already in there, do not add to the list.
2. It sorts the list according to the created date.
"""
if not any(d['created'] == new_entry['created'] for d in entries):
entries.append(new_entry)
entries = sorted(entries, key=lambda k: k['created'])
return entries |
def _alpn_list_to_str(alpn_list):
"""
Transform ['h2', 'http/1.1'] -> "h2;http/1.1"
None is returned if list is None or empty
"""
if alpn_list:
assert not isinstance(alpn_list, str)
return ';'.join(alpn_list)
return None |
def search_tweets(api, keyword, date_start, lang):
"""Creates a query and searches for Tweets"""
query = '%s %s' % (keyword, date_start)
print('')
print('Query created: %s' % query)
print('Searching tweets...')
searched_tweets = []
max_tweets = 20000
last_id = -1
while len(searched_tweets) < max_tweets:
count = max_tweets - len(searched_tweets)
try:
new_tweets = api.search(q=query, lang=lang, count=count, max_id=str(last_id - 1))
if not new_tweets:
break
searched_tweets.extend(new_tweets)
last_id = new_tweets[-1].id
except:
break
print('Tweets found: %d' % len(searched_tweets))
for tweet in searched_tweets[0:4]:
try:
print('\tUSER: ' + str(tweet.author.screen_name)[0:20] +
'; TWEET: ' + str(tweet.text).replace('\n', ' ').replace('\r', ' ')[0:30] +
'...; DATE: ' + str(tweet.created_at))
except:
continue
return searched_tweets |
def _instance_callable(obj):
"""Given an object, return True if the object is callable.
For classes, return True if instances would be callable."""
if not isinstance(obj, type):
# already an instance
return getattr(obj, '__call__', None) is not None
# *could* be broken by a class overriding __mro__ or __dict__ via
# a metaclass
for base in (obj,) + obj.__mro__:
if base.__dict__.get('__call__') is not None:
return True
return False |
def hamming(s1, s2):
"""Count the number of differing bits between two strings"""
total = 0
for c1, c2 in zip(s1, s2):
total += sum(((ord(c1)^ord(c2)) >> i) & 1 for i in range(8))
return total |
def split_seconds_human_readable(seconds):
""" splits the seconds argument into hour, minute, seconds, and fractional_seconds components.
Does no formatting itself, but used by format_seconds_human_readable(...) for formatting seconds as a human-redable HH::MM:SS.FRACTIONAL time.
"""
if isinstance(seconds, int):
whole_seconds = seconds
fractional_seconds = None
else:
whole_seconds = int(seconds)
fractional_seconds = seconds - whole_seconds
m, s = divmod(whole_seconds, 60)
h, m = divmod(m, 60)
return h, m, s, fractional_seconds |
def testif(b, testname, msgOK="", msgFailed=""):
"""Function used for testing.
:param b: boolean, normaly a tested conditionL true if passed, false otherwise
:param testname: the test name
:param msgOK: string to be printed if param b==True ( test condition true )
:param msgFailed: string to be printed if param b==False ( tes condition false)
:return: b
"""
if b:
print("Success: ", testname, "; ", msgOK)
else:
print("Failed: ", testname, "; ", msgFailed)
return b |
def get_current_line(target, mini):
""" # xxx\n...min....\nxxx """
start = target.rfind("\n", 0, mini) +1
if start < 0:
start = 0
end = target.find("\n", mini)
if end < 0:
end = len(target)
return (start, end) |
def build_response(session_attributes, speechlet_response):
"""
Build the full response JSON from the speechlet response
"""
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} |
def to_int_keys_best(l):
"""
l: iterable of keys
returns: a list with integer keys
"""
seen = set()
ls = []
for e in l:
if not e in seen:
ls.append(e)
seen.add(e)
ls.sort()
index = {v: i for i, v in enumerate(ls)}
return [index[v] for v in l] |
def height(node):
"""
compute the height of a binary tree
"""
if not node:
return 0
else:
# Compute the height of each subtree
left_height = height(node.left)
right_height = height(node.right)
# Use the larger one
if left_height > right_height:
return left_height + 1
else:
return right_height + 1 |
def num_spectral_coeffs_up_to_order(b):
"""
The SO(3) spectrum consists of matrices of size (2l+1, 2l+1) for l=0, ..., b - 1.
This function computes the number of elements in a spectrum up to (but excluding) b - 1.
The number of elements up to and including order L is
N_L = sum_{l=0}^L (2l+1)^2 = 1/3 (2 L + 1) (2 L + 3) (L + 1)
:param b: bandwidth
:return: the number of spectral coefficients
"""
L_max = b - 1
assert L_max >= 0
return ((2 * L_max + 1) * (2 * L_max + 3) * (L_max + 1)) // 3 |
def eff_nocc(nelec, nspin, ispin):
"""
Find the number of effective electrons to indicate the Fermi level
example:
spin = 1 2
nelec
13(odd) 6.5 (up = 7, down = 6)
12(even) 6 (up = 6, down = 6)
"""
if nspin == 1:
return nelec / 2.0
else:
return nelec / 2 + (1 - ispin) * (nelec % 2) |
def cardinalityGate(argumentValues,l,h):
"""
Method that evaluates the CARDINALITY gate
@ In, argumentValues, list, list of values
@ In, l, float, min number of allowed events
@ In, h, float, max number of allowed events
@ Out, outcome, float, calculated outcome of the gate
"""
nOcc = argumentValues.count(1)
if nOcc >= l and nOcc <= h:
outcome = 1
else:
outcome = 0
return outcome |
def create_dictionary(string, value):
"""
Creating dictionary based on string and value order
args:
string: string with comma seperated no spaces
value: list of value to be assigned
return:
dictionary with {string-keys: value}
example:
create_dictionary('a,b,c,d', [1,10,20,300])
return {'a':1, 'b':10, 'c':20, 'd':300}
create_dictionary('a', [1])
return {'a':1}
"""
dictionary = {}
keys = string.split(',')
for index, value in enumerate(value):
dictionary[keys[index]] = value
return dictionary |
def char_waveform(length):
"""
Helper function for creating a char waveform PV.
Args:
length: The length of the array.
Return:
The dictionary to add to the PVDB.
"""
return {'type': 'char', 'count': length, 'value': [0]} |
def max_depth(d):
"""Return maximum depth of given dict."""
return (0 if not isinstance(d, dict) or len(d) == 0 else
1 + max(max_depth(v) for v in d.values())) |
def is_int(s: str) -> bool:
"""
A method to determine if the string is indeed an integer.
Returns True if it is an integer, False otherwise
"""
try:
return float(str(s)).is_integer()
except:
return False |
def trim(text, max_length):
"""Trims text to be at most `max_length`, without splitting apart words."""
if len(text) <= max_length:
return text
text = text[:max_length + 1]
# Trim until the last two characters are the boundary between an
# alphanumeric character, and a non-alphanumeric character.
while len(text) > 1 and (text[-1].isalnum() == text[-2].isalnum()):
text = text[:-1]
return text[:-1] |
def is_fill_request_el(obj):
"""Object contains executable methods 'fill' and 'request'."""
return hasattr(obj, 'fill') and hasattr(obj, 'request') \
and callable(obj.fill) and callable(obj.request) |
def _should_update_date(verified_mode):
""" Returns whether or not the verified mode should be updated. """
return not(verified_mode is None or verified_mode.expiration_datetime_is_explicit) |
def is_list(obj):
"""Helper method to see if the object is a Python list.
>>> is_list([4])
True
"""
return type(obj) is list |
def getcolor(string, code):
"""Return a given string in color depending on the code provided.
:param string: String to color.
:param code: Corresponding ANSI escape code.
:return: The colored string.
"""
return f"\u001b[0;3{code};40m{string}\u001b[0;0m" |
def match(cmd, s):
""" Check if cmd has the required parts of s and any of the optional part.
"""
parts = s.split('-')
start = parts[0]
if len(parts) > 1:
end = parts[1]
else:
end = ""
return cmd.startswith(start) and (start+end).startswith(cmd) |
def _textDD(t):
"""t is a tuple (d, f)"""
if 0 <= t[0] <= 360:
dd = t[0]
if 0.0 <= t[1] < 0.5:
dd = 0.0
return '%02d0' % int((dd+5)/10.0)
else:
return '' |
def filter_dict(d, keys):
"""Returns a dictionary which contains only the keys in the list `keys`."""
return {k: v for k, v in d.items() if k in keys} |
def is_sequence(arg):
"""Return if an object is iterable (you can loop over it) and not a string."""
return (not hasattr(arg, "strip") and hasattr(arg, "__iter__")) |
def domain_to_filename(domain):
"""All '/' are turned into '-', no trailing. schema's
are gone, only the raw domain + ".txt" remains
"""
filename = domain.replace('/', '-')
if filename[-1] == '-':
filename = filename[:-1]
filename += ".txt"
return filename |
def f2str(number, decimals, lt=None, gt=None):
"""
Formats a number to be displayed
Parameters
----------
number : float
number to be formatted
decimals : float
decimal points to be displayed
lt : float or None
gt : float or None
Returns
-------
f : str
formatted number to be displayed
"""
f = "{:." + str(decimals) + "f}"
if lt is not None and gt is not None:
if abs(number) < lt or abs(number) > gt:
f = "{:." + str(decimals) + "e}"
elif lt is not None:
if abs(number < lt):
f = "{:." + str(decimals) + "e}"
elif gt is not None:
if abs(number > gt):
f = "{:." + str(decimals) + "e}"
return f.format(number) |
def count_pages(s):
"""Attempt to compute the number of pages of an article."""
try:
parts = s.split("-")
return int(parts[1]) - int(parts[0])
except (AttributeError, IndexError, ValueError):
return None |
def reconstruct_path(came_from, current_node):
"""
came_from : dictionary of nodes and nodes before them in the shortest found path
current_node : the last node of the path
"""
if current_node in came_from:
p = reconstruct_path(came_from,came_from[current_node])
return p + [current_node]
else:
return [] |
def jaccard(x, y) -> float:
"""
Compute jaccard similarity (intersection over union).
Args:
x: Array-like object
y: Array-like object
Returns:
Intersection Over Union score
"""
s1 = set(x)
s2 = set(y)
if len(s1) == 0 and len(s2) == 0:
return 0
return len(s1 & s2) / len(s1 | s2) |
def _get_hashable(v):
"""if a list - would cast to tuple"""
if isinstance(v, list):
return tuple(v)
else:
return v |
def multiply(x, y):
"""Multiply x and y in GF(2^8)."""
res = 0
for _ in range(8):
if y & 0x1:
res ^= x
y = y >> 1
x = x << 1
if x & 0x100:
x ^= 0x11B
return res |
def _flat(obj):
"""
:param obj:
:return: Return a list
"""
if hasattr(obj, "js_dependencies"):
return list(obj.js_dependencies)
if isinstance(obj, (list, tuple, set)):
return obj
return (obj,) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.