content
stringlengths 42
6.51k
|
---|
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
"""
#first index change +1
#second index stays and its column_index
word = ''
for i in range(len(board)):
word = word + board[i][column_index]
return word
|
def insertTime(line, time):
"""
inserts a new time into an event file line.
"""
dt = line[0:line.find(' ')]
return line.replace(dt, time)
|
def remove_quotes(text):
"""Replace quote marks in text."""
index = 0
length = len(text)
while index < length:
if '\"' in text[index]:
text[index] = text[index].replace('\"','*')
if '\'' in text[index]:
text[index] = text[index].replace('\'','*')
index = index + 1
return text
|
def aic(log_lik, n_samples, dof):
"""
Calculates the Akaike Information Criterion.
Parameters
----------
log_lik: float
The observed data log-likelihood.
n_samples: int
Number of samples.
dof: int
Number of degrees of freedom.
Output
------
bic: float
"""
return - 2 * log_lik + 2 * dof
|
def bit_to_str(bit):
"""
Converts a tuple (frame, bit, value) to its string representation.
"""
s = "!" if not bit[2] else ""
return "{}{}_{:02d}".format(s, bit[0], bit[1])
|
def generate_symbol_definitions_table(symbols, prefix):
"""Generate a listing of symbol definitions for symbol table."""
ret = []
for ii in symbols:
ret += [ii.generate_rename_tabled(prefix)]
return "\n".join(ret)
|
def _add_columns(data):
""" This function return the list of columns with contains to display in custom view.
:param data: ctx_result["data"]
:return: list of columns to display
"""
columns_dict = []
available_columns = list(set().union(*data))
# Columns to display in view
columns_in_sequence = [
{"timestamp": None}, {"src_hostname": "host name"}, {"dst_hostname": "host name"},
{"src_address": "ip"}, {"dst_address": "ip"}, {"src_port": "port"}, {"dst_port": "port"},
{"proto": None}, {"start_timestamp": None}, {"src_scope_name": "cisco ta scope"},
{"dst_scope_name": "cisco ta scope"}, {"vrf_name": None}, {"srtt_usec": None},
{"total_network_latency_usec": None}, {"server_app_latency_usec": None},
{"fwd_pkts": None}, {"rev_pkts": None}, {"fwd_bytes": None}, {"rev_bytes": None}
]
# Get list of avaiable columns
for column in columns_in_sequence:
if set(column.keys()) < set(available_columns):
columns_dict.append(column)
return columns_dict
|
def _get_speaking_time(main_segment_list):
""" calculating the speaking time"""
duration = 0
for a_segment in main_segment_list:
duration += (a_segment[1] - a_segment[0])
return duration
|
def convert_range(p):
"""Convert a float from 0-1 range to integer 0-255 range."""
return max(0, min(255, round(255 * p)))
|
def get_status(runs):
"""Get the most recent status of workflow for the current PR.
Parameters
----------
runs : list
List of comment objects sorted by the time of creation in decreasing order.
Returns
-------
status : string
The most recent status of workflow.
Can be 'success', 'failure' or 'in-progress'.
"""
status = 'success'
for run in runs:
body = run['body']
if "Status: " in body:
if "Status: skipped" in body:
continue
if "Status: failure" in body:
status = 'failure'
break
if "Status: success" in body:
status = 'success'
break
else:
status = 'in-progress'
break
return status
|
def div(a, b):
"""Helper function for division
:param a: first parameter
:type a: int
:param b: second parameter
:type b: int
:return: integer division result
:rtype: int
"""
return int(a / b)
|
def check_length_for_tweet(revision, message):
"""
Recursively remove a word from the message until it is small enough to tweet
"""
# I think 115 is the hard limit once the url is shortened
if len(revision) + len(message) > 110:
# get rid of a word
message = ' '.join(message.split(' ')[:-1])
return check_length_for_tweet(revision, message)
return revision, message
|
def arraytoyf(args, lengths):
"""Inverse of yfarray()."""
return tuple(tuple(1 if a & (1 << m) else 0 for m in range(n))
for n, a in zip(lengths, args))
|
def dist_median(distribution, count):
"""Returns the median value for a distribution
"""
counter = 0
previous_value = None
for value, instances in distribution:
counter += instances
if counter > count / 2.0:
if (not count % 2 and (counter - 1) == (count / 2) and
previous_value is not None):
return (value + previous_value) / 2.0
return value
previous_value = value
return None
|
def calculate_ema(close, periods, previous_ema):
"""
Calculates the exponential moving average.
EMA = Price(t)*weighting_multipler + previous_ema*(1-weighting_multiplier)
*weighting_multiplier is given by 2/(periods + 1)
Args:
close: Float representing the exchange rate at the end of an interval
periods: Integer representing the number of days in the EMA period (commonly 12 or 26)
previous_ema: Float representing the last calculated EMA
Returns:
Float representing the new EMA
"""
return close*(2/(periods + 1)) + previous_ema*(1-(2/(periods + 1)))
|
def sgd(w, dw, learning_rate=1e-3, config=None):
"""
stochastic gradient descent
:param w: weights
:param dw: grads of weights
:param learning_rate: learning rate
:return: new weights
"""
w -= dw * learning_rate
return w, config
|
def strip_csv_row(row):
"""
Strip values in a CSV row, casing '' -> None.
"""
return {
key: val.strip() or None
for key, val in row.items()
}
|
def id_from_uri(uri: str) -> str:
"""Get the item ID from URI address."""
return uri.rstrip("/").split("/")[-1]
|
def index_to_voxel(index, Y_size, Z_size):
"""
index to voxel, eg. 0 -> (0,0,0).
"""
i = index % (Y_size)
index = index // (Y_size)
j = index % (Z_size)
index = index // (Z_size)
k = index
return (i, j, k)
|
def decimalTobinary(n):
"""Convert a decimal number to binary"""
assert int(n) == n, 'input number must be integer'
if n == 0:
return 0
else:
return n%2 + 10 * decimalTobinary(int(n/2))
|
def _average(expression, probes, *args, **kwargs):
"""
Averages expression data for probes representing the same gene
Parameters
----------
expression : list of (P, S) pandas.DataFrame
Each dataframe should have `P` rows representing probes and `S` columns
representing distinct samples, with values indicating microarray
expression levels
probes : pandas.DataFrame
Dataframe containing information on probes that should be considered in
representative analysis. Generally, intensity-based-filtering (i.e.,
`probe_ibf()`) should have been used to reduce this list to only those
probes with good expression signal
Returns
-------
representative : list of (S, G) pandas.DataFrame
Dataframes with rows representing `S` distinct samples and columns
representing `G` unique genes, with values indicating microarray
expression levels for each combination of samples and genes
"""
def _avg(df):
return df.join(probes['gene_symbol'], on='probe_id') \
.groupby('gene_symbol') \
.mean()
return [_avg(exp) for exp in expression]
|
def extract_value(val_info, yaml_dict=None):
"""
extract field value
"""
res = None
if "constant" in val_info:
res = val_info["constant"]["value"]
elif "constant_reference" in val_info:
val_list = []
for source_info in val_info["constant_reference"]["source_name"]:
val_list.append(source_info["text"])
res = ".".join(val_list)
if yaml_dict is not None:
if val_list[0] in yaml_dict["structs"] and\
val_list[1] in yaml_dict["structs"][val_list[0]]["fields"]:
res_temp = yaml_dict["structs"][val_list[0]]
res = res_temp["fields"][val_list[1]]["value"]
return res
|
def write_file(filename="", text=""):
"""writes a string to a text file (UTF8)
and returns the number of characters written"""
with open(filename, 'w', encoding='utf=8') as file:
return file.write(text)
|
def reduce_repeated_chars(str_in: str, char: str, remaining_chars: int) -> str:
"""
:param str_in: text to be cleaned
:param char: character that should not occur more than remaining_chars times in sequence
:param remaining_chars: remaining_chars
:return:
"""
cnt = 0
out = ""
for k in str_in:
if k == char:
cnt += 1
if cnt <= remaining_chars:
out = out + k
else:
cnt = 0
out = out + k
return out
|
def sort_members_key(name):
"""Sort members of an object
:param name: name
:type name: str
:return: the order of sorting
:rtype: int
"""
if name.startswith("__"):
return 3
elif name.startswith("_"):
return 2
elif name.isupper():
return 1
else:
return 0
|
def gen_obj_name(name: str) -> str:
""" Generates an object name from a menu title or name (spaces to underscores and lowercase) """
return name.replace(" ", "_").lower()
|
def read_codepage(text, codepage='cp437'):
"""
Keep only characters belonging to the character set of a language
Args:
-- text: input text
-- code page: for each language.
Example: Code page 437 is the original code page of the IBM PC.
https://www.ascii-codes.com/cp437.html
"""
text = text.encode(codepage, "ignore").decode(codepage)
text = text.encode('utf-8').decode('utf-8')
return text
|
def sql_convert(s):
"""format a string to be printed in an SQL statement"""
if isinstance(s, str):
s = "'"+s.replace("\\", "\\\\").replace("'", "\\'")+"'"
if isinstance(s, bytes):
s = "'"+s.decode('utf-8').replace("\\", "\\\\").replace("'", "\\'")+"'"
else:
s = str(s)
return s
|
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity [ms]."""
return 0.5 * mass * velocity ** 2
def test_calculate_kinetic_energy():
mass = 10 # [kg]
velocity = 4 # [m/s]
assert calculate_kinetic_energy(mass, velocity) == 80
|
def is_binary_file(file_obj):
"""
Returns True if file has non-ASCII characters (> 0x7F, or 127)
Should work in both Python 2 and 3
"""
start = file_obj.tell()
fbytes = file_obj.read(1024)
file_obj.seek(start)
is_str = isinstance(fbytes, str)
for fbyte in fbytes:
if is_str:
code = ord(fbyte)
else:
code = fbyte
if code > 127:
return True
return False
|
def remove_dups(head):
""" 2.1 Remove Dups! Write code to remove duplicates from an unsorted
linked list.
FOLLOW UP: How would you solve this problem if a temporary buffer is not allowed?
"""
def chase(node, val):
while node != None and node.value == val:
node = node.next
return node
node = head
while node != None:
first_distinct_node = chase(node, node.value)
node.next = first_distinct_node
node = first_distinct_node
return head
|
def get_mod_func(callback):
"""
Converts 'django.views.news.stories.story_detail' to
('django.views.news.stories', 'story_detail')
"""
try:
dot = callback.rindex('.')
except ValueError:
return callback, ''
return callback[:dot], callback[dot + 1:]
|
def extract_name(str):
""" Return string up to double underline """
return str[:str.find('__')]
|
def crop_from_right(sequence_string, crop_length):
"""
return a sequence string without last crop_length characters
drops values at end ie chops off right side
if crop_length > length sequence_string --> returns ""
if crop_length <= 0 returns string
"""
if (crop_length <= 0):
return sequence_string
seq_length = len(sequence_string)
if (crop_length > seq_length):
return ""
return sequence_string[:-crop_length]
|
def lines(data):
"""
Convenience function to format each element on its own line for output suitable to be
assigned to a bash array.
Example:
r = lines(_["foo"])
"""
return "\n".join(str(i) for i in data)
|
def filter_actuals_data(json):
"""
Filter "actuals" data from input, taken as parameter, and return it in dict format.
Return None if input is not valid.
"""
if not json:
return None
actuals_data = {}
for entry in json:
actuals_data[entry["state"]] = {"actuals":
{
"cases": entry["actuals"]["cases"],
"deaths": entry["actuals"]["deaths"],
"positiveTests": entry["actuals"]["positiveTests"],
"negativeTests": entry["actuals"]["negativeTests"],
"contactTracers": entry["actuals"]["contactTracers"],
"hospitalBedsCapacity": entry["actuals"]["hospitalBeds"]["capacity"],
"hospitalBedsCurrentUsageTotal": entry["actuals"]["hospitalBeds"]["currentUsageTotal"],
"hospitalBedsCurrentUsageCovid": entry["actuals"]["hospitalBeds"]["currentUsageCovid"],
"icuBedsCapacity": entry["actuals"]["icuBeds"]["capacity"],
"icuBedsCurrentUsageTotal": entry["actuals"]["icuBeds"]["currentUsageTotal"],
"icuBedsCurrentUsageCovid": entry["actuals"]["icuBeds"]["currentUsageCovid"],
"newCases": entry["actuals"]["newCases"],
"newDeaths": entry["actuals"]["newDeaths"],
"vaccinesDistributed": entry["actuals"]["vaccinesDistributed"],
"vaccinationsInitiated": entry["actuals"]["vaccinationsInitiated"],
"vaccinationsCompleted": entry["actuals"]["vaccinationsCompleted"],
"vaccinesAdministered": entry["actuals"]["vaccinesAdministered"],
"vaccinesAdministeredDemographics": entry["actuals"]["vaccinesAdministeredDemographics"],
"vaccinationsInitiatedDemographics": entry["actuals"]["vaccinationsInitiatedDemographics"]
}}
return actuals_data
|
def add_type_restriction(step):
"""
for a given step, look for object type and construct a SPARQL fragement to restrict the graph
to objects of the type. If the object does not have a type restriction, return an empty string.
:param step: The step for which an object restriction is requested
:return: the SPARQL fragement for thr restriction, or an empty string if no type is specified
"""
if 'type' in step['object']:
return '?' + step['object']['name'] + ' a <' + str(step['object']['type']) + '> . '
else:
return ""
|
def sum_of_n_odd_numbers(n):
"""
Returns sum of first n odd numbers
"""
try:
n+1
except TypeError: # invlid input hence return early
return
if n < 0: # invlid input hence return early
return
return n*n
|
def datatable(columns, rows):
"""Columns and rows are both arrays,
the former of (name, type) tuples"""
return {
"cols": [{"label": key, "type": val} for (key, val) in columns],
"rows": [
{"c": [{"v": cell} for cell in row]} for row in rows]
}
|
def sort(data):
"""Sorts data by allocated size and number of allocations"""
return sorted(
data, key=lambda info: (info.allocated_size, len(info.sizes)),
reverse=True)
|
def get_input_commands(input_data):
"""extract instructions che from input text
input data (str): plain text read from txt file"""
input_lines = input_data.split("\n")
result = []
for il in input_lines:
if il != "":
res = il.split(" ")
result.append([res[0], int(res[1])])
return result
|
def readadc(chip, channel):
"""read channel CHANNEL of the MCP3008
CHIP should be an SpiDev object"""
if ((channel > 7) or (channel < 0)):
return -1
r = chip.xfer2([1,(8+channel)<<4,0])
adcout = ((r[1]&3) << 8) + r[2]
return adcout
|
def project_metadata(data):
"""Returns project metadata"""
project = data["project"]
checkout_dir = project["checkout_dir"]
oath_token = project["oath"]
org = project["org"]
return checkout_dir, oath_token, org
|
def is_trash(text):
"""
Decide whether a sentence is of low quality based on simple heuristics.
Args:
text (str): The string to be analyzed.
Returns:
bool: True if string is trash, False otherwise.
"""
if not text.endswith(('.', ':', '!', '?')) or len(text) < 6:
return True
if text.count('&') > 3 or text.count(',') > 5:
return True
if '...' in text or '|' in text:
return True
if sum(char.isdigit() for char in text) > len(text)/2:
return True
return False
|
def hover_over(spell: str,
stopcast: bool = False,
dismount: bool = True,
) -> str:
""" Hover over target. """
macro = f'#showtooltip {spell}\n'
if stopcast:
macro += '/stopcast\n'
if dismount:
macro += '/dismount\n'
macro += f'/use [@mouseover, harm, nodead][@target, harm, nodead] {spell}'
return macro
|
def isLowerHull(dx, dy):
"""
Checks if a line is part of the lower hull
:param float dx:
:param float dy:
"""
lowerHull = (dx < 0.0) or (dx == 0.0 and dy < 0.0)
return lowerHull
|
def check_surname(collection, id_, cont):
""" Surname checking """
return cont.replace('-', '').isalpha()
|
def get_instrument(name):
"""Return the instrument inferred from the track name."""
if "viola" in name.lower():
return "Viola"
if "cello" in name.lower():
return "Cello"
for key in ("1st", "violin 1", "violin1", "violino i"):
if key in name.lower():
return "Violin 1"
for key in ("2nd", "violin 2", "violin2", "violino ii"):
if key in name.lower():
return "Violin 2"
return None
|
def max_subarray(L):
"""
Also known as Kadane's algorithm, this problem was first posed by Ulf
Grenander of Brown University in 1977. A linear time algorithm was found
soon afterwards by Jay Kadane of Carnegie Mellon University.
Performance
===========
O(n)
"""
max_ending_here = max_so_far = L[0]
for x in L[1:]:
# `max_ending_here` keeps a running total of the maximum subarray.
max_ending_here = max(x, max_ending_here + x)
# `max_so_far` changes only twice; once at the beginning of the maximum
# subarray and once at the end.
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
|
def gardner(vp, alpha=310, beta=0.25):
"""
Compute bulk density (in kg/m^3) from vp (in m/s)
"""
return alpha * vp**beta
|
def get_error(op):
"""Return the error structure for the operation."""
return op.get('error')
|
def square_root_convergents(n):
"""
This function calculates every number of the sequence defined by frac function,
and count the number of results that have a denominator with more digit than the numerator.
"""
i = 0
nb_frac = 0
num = 1
den = 2
while i < n:
if i % 10 == 0:
print(i, " : ", den + num, " / ", den)
if len(str(den + num)) > len(str(den)):
nb_frac += 1
i += 1
num, den = den, 2*den+num
return nb_frac
|
def fibonacci(n):
"""Return the nth Fibonacci number."""
if n == 1:
return 0
# r[i] will contain the ith Fibonacci number
r = [-1] * (n + 1)
r[0] = 0
r[1] = 1
for i in range(2, n + 1):
r[i] = r[i - 1] + r[i - 2]
return r[n - 1]
|
def sort(tupleo, key=None, reverse=False):
"""
sort(...) method of tupleo.tuple instance
T.sort(tupleo, key=None, reverse=False) -> None -- stable sort *IN PLACE tuple, tupleo*
"""
if type(tupleo) != tuple:
raise TypeError("{} is not tuple".format(tupleo))
convertlist = list(tupleo)
convertlist.sort(key=key, reverse=reverse)
return tuple(convertlist)
|
def mobile_path(s: str) -> bool:
"""
Checks if path specified points to a phone
On windows, path can have a drive letter and that adds : to the path.
To overcome that we only check for `:` that is not the second letter of string,
where the drive letter colon should always be.
"""
return s.find(':', 2) != -1
|
def ensure_list(val):
"""Converts the argument to a list, wrapping in [] if needed"""
return val if isinstance(val, list) else [val]
|
def change_to_pubs_test(pubs_url):
"""
flips pubs urls to pubs-test urls to work around annoying apache config on test tier
:param pubs_url: a pubs.er.usgs.gov url
:return: a pubs-test.er.usgs.gov url
"""
pubs_test_url = pubs_url.replace('pubs.er', 'pubs-test.er')
return pubs_test_url
|
def three_sum_closest(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# Like nomral 3-sum, but because we need to find the closest sum
# thus we need bookkeeping and use offset to adjust scan direction.
nums.sort()
sum, dist = 0, 1 << 31
i = 0
while i < len(nums) - 2:
l = i + 1
r = len(nums) - 1
while l < r:
attempt = nums[i] + nums[l] + nums[r]
offset = abs(attempt - target)
# New closest found
if offset < dist:
dist = offset
sum = attempt
# If attempt < target, the sum is at the left of the target.
# If attempt > target, the sum is at the right of the target.
if attempt < target:
l += 1
elif attempt > target:
r -= 1
else:
return sum
i += 1
return sum
|
def trapezoidal(f, a, b, n=10000):
"""trapez method for numerical integration; same result for n = 100000"""
s = 0.0
h = (b - a) / n
for i in range(0, n):
s += f(a + i * h)
return h * (s + 0.5 * (f(a) + f(b)))
|
def locality(values, locdef):
"""
"""
length = locdef[0]
repeat = locdef[1]
if repeat <= 1:
return values
values = [
values[i:i + length] * repeat
for i in range(0, len(values), length)
]
values = [item for sublist in values for item in sublist]
return values
|
def strip_right_multiline(txt: str) -> str:
"""Useful for prettytable output where there are a lot of right spaces."""
return '\n'.join([x.strip() for x in txt.splitlines()])
|
def _check_ncluster_nquestions(n_questions, n_pairs, n_clusters):
"""
Args:
n_questions (int):
n_clusters (int):
n_pairs (int):
Returns:
boolean
"""
if n_questions > n_pairs:
return False
elif n_questions * n_clusters > n_pairs:
return False
else:
return True
|
def _earth_check( game_data ):
"""
Without will,
an individual is unable to continue.
"""
for p in range(2):
if game_data[str(p)]['will'] > game_data[str(p)]['earth']:
game_data[str(p)]['will'] = game_data[str(p)]['earth']
if game_data['0']['will'] <= 0 and game_data['1']['will'] <= 0:
game_data['game']['gameover'] = 1
game_data['game']['gameover_message'] = 2
else:
for p in range( 2 ):
if game_data[str(p)]['will'] <= 0:
game_data['game']['gameover'] = 1
game_data['game']['gameover_message'] = p
return game_data
|
def subtract(matrix_a: list, matrix_b: list) -> list:
"""
Function for substracting two matrices
:param matrix_a: the first input matrix
:param matrix_b: the second input matrix
:return: the result matrix
"""
result = matrix_a.copy()
for i in range(len(matrix_a)):
for j in range(len(matrix_a[0])):
result[i][j] = matrix_a[i][j] - matrix_b[i][j]
return result
|
def arrays_to_list_of_tuples(arrays, colnames):
"""Convert a dict of arrays (as given by the numpy protocol handler) to a list of tuples"""
first_array = arrays[colnames[0]]
return [tuple(arrays[colname][i] for colname in colnames)
for i in range(len(first_array))]
|
def contestant_pick_again_swap(adjusted_stage, contestant_first_pick):
"""Contestant swaps choices with the remaining door."""
if contestant_first_pick == 0:
if adjusted_stage[1] == -1:
return 2
else:
return 1
elif contestant_first_pick == 1:
if adjusted_stage[0] == -1:
return 2
else:
return 0
else:
if adjusted_stage[0] == -1:
return 1
else:
return 0
|
def solution(A): # O(N/2)
"""
Write a function to check if the input string is a palindrome.
A palindrome is defined a string that reads the same backwards and forwards.
>>> solution('citic')
True
>>> solution('thisisapalindromemordnilapasisiht')
True
>>> solution('thisisnotapalindrome')
False
"""
i = 0 # O(1)
j = len(A) - 1 # O(1)
while i < j: # O(N/2)
if A[i] != A[j]: # O(1)
return False # O(1)
i += 1 # O(1)
j -= 1 # O(1)
return True # O(1)
|
def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
d[k] = v
return d
|
def stringify(message, *args):
"""Return formatted message by applying args, if any."""
if args:
return u'%s\n' % (message % (args))
else:
return u'%s\n' % (message)
|
def set_shared_crosshear(dashboard):
"""Enabled Shared Crosshear."""
if 'graphTooltip' not in dashboard.keys():
return dashboard
dashboard['graphTooltip'] = 1
return dashboard
|
def get_comping_long_help(self) -> str:
"""Returns the long help associated with process or action object. Defaults to
the docstring of the wrapped object, if available; otherwise a null string."""
try:
text = self.obj.__comping__.long_help
if text:
return text
except AttributeError:
pass
try:
return self.obj.__doc__
except AttributeError:
pass
return ""
|
def append(list, item):
"""Return a list with the given item added to the end."""
if list == ():
return (item, ())
else:
head, tail = list
return (head, append(tail, item))
|
def files_constraint(session, types):
"""
This function...
:param session:
:param types:
:return:
"""
return [("session", session), ("type", types)]
|
def StrChangeFileExt(FileName,NewExt):
"""
Example : StrChangeFileExt(FileName='1.txt',NewExt='py')
set new extesion for file.
"""
return FileName[:FileName.rfind('.')+1]+NewExt
|
def is_page_publisher(user, page):
"""
This predicate checks whether the given user is one of the publishers of the given page.
:param user: The user who's permission should be checked
:type user: ~django.contrib.auth.models.User
:param page: The requested page
:type page: ~cms.models.pages.page.Page
:return: Whether or not ``user`` is a publisher of ``page``
:rtype: bool
"""
if not page:
return False
return user in page.publishers.all()
|
def mel2hz(mel):
"""Convert Mel frequency to frequency.
Args:
mel:Mel frequency
Returns:
Frequency.
"""
return 700*(10**(mel/2595.0)-1)
|
def _check_if_found(new_term: str, targets: list) -> bool:
"""
Checks if `new_term` matches `targets`.
:param new_term: string to check
:param targets: list of strings to match to `new_term`. Targets can be a list of specific targets, e.g.
['UBERON:123219', 'UBERON:1288990'] or of general ontology prefixes, e.g. ['UBERON']
:return:
"""
if (':' in targets[0]) and (new_term in targets): # specific
relation_found = True
elif (':' not in targets[0]) and (new_term.split(':')[0] in targets): # general
relation_found = True
else:
relation_found = False
return relation_found
|
def ordinal_str(num: int) -> str:
"""
Converts a given integer to a string with an ordinal suffix applied, preserving the sign.
:param num: Any integer, be it positive, negative, or zero.
:return: The number as a string with the correct ordinal suffix applied. 0 becomes "0th",
1 becomes "1st", 10 becomes "10th", -2 becomes "-2nd", etc.
"""
def single_digit_ordinal(num: str) -> str:
"""
Helper function to append ordinal suffixes to single digit number strings.
:param num: A single character string containing one digit of a positive integer.
:return: The number string with the correct ordinal suffix appended.
"""
if num == "1":
return num + "st"
elif num == "2":
return num + "nd"
elif num == "3":
return num + "rd"
else:
return num + "th"
def two_digit_ordinal(num: str) -> str:
"""
Helper function to append ordinal suffixes to two-digit number strings.
:param num: A string representing a positive integer.
:return: The number string with the correct ordinal suffix appended.
"""
if num[0] != "1":
return num[0] + single_digit_ordinal(num[1])
else:
return num + "th"
# Convert the int to a str and extract the sign.
raw_num = str(num)
if raw_num[0] == "-":
sign = raw_num[0]
base_num = raw_num[1:]
else:
sign = ""
base_num = raw_num[:]
# Reassemble the sign and number, appending the appropriate ordinal suffix.
if len(base_num) == 1:
return sign + single_digit_ordinal(base_num)
else:
return sign + base_num[:-2] + two_digit_ordinal(base_num[-2:])
|
def extend_rsltdict(D, key, val, Extend=False):
"""Helper for form_delta()
---
Given a result dictionary D, extend it, depending on
the setting of Boolean Extend. For some dictionaries,
duplicates mean "extend"; for others, that means error.
This is a crucial helper used by "form_delta".
"""
if Extend:
if key in D:
D[key] = D[key] | set({ val })
else:
D[key] = set({ val })
else:
assert(key not in D
),("Error: Duplicate map at key " + str(key) +
"; duplicates: " + str(D[key]) + " and " + str(val)
)
D[key] = val # don't make a set
return D
|
def replace_repeated_characters(text):
"""Replaces every 3+ repetition of a character with a 2-repetition."""
if not text:
return text
res = text[0]
c_prev = text[0]
n_reps = 0
for c in text[1:]:
if c == c_prev:
n_reps += 1
if n_reps < 2:
res += c
else:
n_reps = 0
res += c
c_prev = c
return res
|
def check_substation_LTC(new_ckt_info, xfmr_name):
"""Function to assign settings if regulator upgrades are on substation transformer
"""
subltc_dict = None
if isinstance(new_ckt_info["substation_xfmr"], dict):
if new_ckt_info["substation_xfmr"]["name"].lower() == xfmr_name:
subltc_dict = {}
subltc_dict["at_substation"] = True
subltc_dict.update(new_ckt_info["substation_xfmr"])
return subltc_dict
|
def convert_encode(sequences, list_letters):
""" Return list of vector encoding the sequences letters transformed in 1000, 0100, 0010, 0001"""
dict_trad = {list_letters[0]:[1.,0.,0.,0.], list_letters[1]:[0.,1.,0.,0.], list_letters[2]:[0.,0.,1.,0.], list_letters[3]:[0.,0.,0., 1.] }
final = []
for i in range(len(sequences)):
sequence = sequences[i]
vect = []
for j in range(len(sequence)):
vect += dict_trad[sequence[j]]
final.append(vect)
return final
|
def scan_runtime(step, fname):
""" Find runtime of VPR log (if any), else returns empty str. """
try:
with open(fname, 'r') as f:
step_runtime = 0
total_runtime = 0
for line in f:
if line.startswith("# {} took".format(step)):
step_runtime = float(line.split()[3])
if line.startswith('The entire flow of VPR took'):
total_runtime = float(line.split()[6])
step_overhead = total_runtime - step_runtime
return str(step_runtime), str(step_overhead)
except FileNotFoundError:
return ""
|
def repeated(f, n, x):
"""Returns the result of composing f n times on x.
>>> def square(x):
... return x * x
...
>>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4
81
>>> repeated(square, 1, 4) # square(4)
16
>>> repeated(square, 6, 2) # big number
18446744073709551616
>>> def opposite(b):
... return not b
...
>>> repeated(opposite, 4, True)
True
>>> repeated(opposite, 5, True)
False
>>> repeated(opposite, 631, 1)
False
>>> repeated(opposite, 3, 0)
True
"""
"*** YOUR CODE HERE ***"
answer = x
while n != 0:
answer = f(answer)
n -= 1
return answer
|
def round_upper_bound (value):
"""
This method expects an integer or float value, and will return an integer upper
bound suitable for example to define plot ranges. The upper bound is the
smallest value larger than the input value which is a multiple of 1, 2 or
5 times the order of magnitude (10**x) of the value.
"""
bound = 0
order = 0
check = [1, 2, 5]
while True:
for c in check :
bound = c*(10**order)
if value < bound:
return bound
order += 1
|
def query(_port, prop, _repo=False):
"""Query a property of a package."""
if prop == "config":
return False
else:
assert not "unknown package property '%s'" % prop
|
def fix(x, field):
"""
makes square field feels like Thor
"""
a = len(field)
if x >= a:
return x - a
if x < 0:
return x + a
return x
|
def exists(var):
"""
Return a boolean value that indicate if a variable exists or not.
Parameters
----------
var
Variable to test
Returns
-------
bool
Boolean that indicate the existance or not of the variable
"""
try:
var
except NameError:
return False
else:
return True
|
def get_opacities(opacity):
"""
Provide defaults for all supported opacity settings.
"""
defaults = {
'wireframe' : 0.05,
'scalar_cut_plane' : 0.5,
'vector_cut_plane' : 0.5,
'surface' : 1.0,
'iso_surface' : 0.3,
'arrows_surface' : 0.3,
'glyphs' : 1.0
}
if isinstance(opacity, dict):
opacities = opacity
default = None
else:
opacities = {}
default = opacity
for key in ['wireframe', 'scalar_cut_plane', 'vector_cut_plane',
'surface', 'iso_surface', 'arrows_surface', 'glyphs']:
if default is None:
opacities.setdefault(key, defaults[key])
else:
opacities.setdefault(key, default)
return opacities
|
def from_string(val):
"""escape a python string"""
escape = val.translate(
str.maketrans({
"'": "''",
'\\': '\\\\',
'\0': '\\0',
'\b': '\\b',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
# ctrl z: windows end-of-file; escaped z deprecated in python
'\x1a': '\\x1a',
}))
return f"'{escape}'"
|
def cb_valid_actions(state):
"""
Helper function to return valid actions at conditional bandit states. Used for plotting maze.
:param state: state tuple
:return: list of valid actions
"""
if state == [3, 6]:
return [2, 3]
elif state == [9, 6]:
return [2, 3]
elif state == [6, 3]:
return [0, 1]
elif state == [6, 9]:
return [0, 1]
else:
return []
|
def varintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10
|
def webotsToScenicPosition(pos):
"""Convert a Webots position to a Scenic position.
Drops the Webots Y coordinate.
"""
x, y, z = pos
return (x, -z)
|
def mininet_dpid(int_dpid):
"""Return stringified hex version, of int DPID for mininet."""
return str('%x' % int(int_dpid))
|
def get_all_pixels(coordinates):
"""Get all pixel coordinates, given the top left and bottom right."""
pixels = []
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for ix in range(x1, x2 + 1):
for iy in range(y1, y2 + 1):
pixels.append((ix, iy))
return pixels
|
def MOSQ_MSB(A):
"""get most significant byte."""
return (( A & 0xFF00) >> 8)
|
def gridlookup(n, grid, valplace):
"""Check in which interval/ capital state valplace is"""
ilow = 0
ihigh = n-1
distance = 2
while (distance > 1):
inow = int((ilow+ihigh)/2)
valnow = grid[inow]
# The strict inequality here ensures that grid[iloc] is less than or equal to valplace
if (valnow > valplace):
ihigh = inow
else:
ilow = inow
distance = ihigh - ilow
iloc = ilow
return iloc
|
def vertical_check(board: list):
""" Check if board are ready for game in columns. Return True of False
>>> print(vertical_check(board = ["**** ****","***1 ****","** 3****",\
"* 4 1****"," 9 5 "," 6 83 *","3 1 **"," 8 2***",\
" 2 ****"]))
False
"""
for idx in range(len(board)):
lst_of_nums = []
for idx2 in range(len(board)):
if board[idx2][idx].isdigit():
lst_of_nums.append(board[idx2][idx])
if len(lst_of_nums) != len(set(lst_of_nums)):
return False
return True
|
def scan(str_data):
"""
Takes a string and scans for words, returning
a list of words.
"""
return str_data.split()
|
def _InsertString(original_string, inserted_string, index):
"""Insert a string into another string at a given index."""
return original_string[0:index] + inserted_string + original_string[index:]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.