content
stringlengths 42
6.51k
|
---|
def empty_operation(ops):
""" Returns True if the operation is an empty list or only contains positive integers """
return (ops == [] or all([isinstance(x, int) and (x > 0) for x in ops]))
|
def patched_path(path):
"""Return 'path', doctored for RPC."""
if not path.endswith('/'):
path += '/'
if path.startswith('/RPC2/'):
# strip the first /rpc2
path = path[5:]
return path
|
def get_count(value):
"""
Count bottle of beer
"""
beer = str(value) if value != 0 else "No more"
return beer + " bottles of beer" if value != 1 else beer + " bottle of beer"
|
def remove_redacted(obj):
"""
Removes all string object with the value __redacted__
"""
if isinstance(obj, str):
if obj == "__redacted__":
return True, obj
else:
return False, obj
elif isinstance(obj, list):
for index, item in enumerate(obj):
remove, obj[index] = remove_redacted(item)
if remove:
del obj[index]
return False, obj
elif isinstance(obj, dict):
to_remove = []
for k, v in obj.items():
remove, obj[k] = remove_redacted(v)
if remove:
to_remove.append(k)
for k in to_remove:
del obj[k]
return False, obj
return False, obj
|
def match_word(word, word_):
"""
word: The word to be matched
word_: The set of alphabets
This matches the characters of the word to the set of alphabets.
"""
for word_char, alphabet in zip(word, word_):
if word_char not in alphabet:
return False
return True
|
def side(a,b,c):
""" Returns a position of the point c relative to the line going through a and b
Points a, b are expected to be different
"""
d = (c[1]-a[1])*(b[0]-a[0]) - (b[1]-a[1])*(c[0]-a[0])
return 1 if d > 0 else (-1 if d < 0 else 0)
|
def format_str(unformatted_str):
"""
Formats the output into a multi column list, output1 | output2 | output3
"""
output = []
for word in enumerate(unformatted_str):
if word != '':
output.append(word[1])
return output
|
def evaluate_error(z1, z2):
"""
# cette methode ne marche pas car le numero de cluster pourra changer
:param z1: actual clustering
:param z2: clustering done by CEM algorithm
:return: error in percentage
"""
err = 0
n = len(z1)
for i in range(n):
if z2[i] != z1[i]:
err += 1
return (err/n)*100
|
def format_metrics(metrics, split):
"""Format metric in metric dict for logging."""
return " ".join(
["{}_{}: {:.8f}".format(split, metric_name, metric_val) for metric_name, metric_val in metrics.items()])
|
def validate_path(path, configuration):
"""
Args:
path(str): incoming request path
configuration(dict): config dict
Returns:
(dict|none): returns config if path is valid, None otherwise
"""
subpaths = list(filter(''.__ne__, path.split('/')))
for index, sub_path in enumerate(subpaths):
if sub_path in configuration.keys():
configuration = configuration.get(sub_path)
if configuration.get("interactive", False) and index + 1 == len(subpaths) - 1:
return subpaths, configuration, subpaths[index + 1]
else:
return None, None, None
return subpaths, configuration, None
|
def _filter_featured_downloads(lst):
"""Filter out the list keeping only Featured files."""
ret = []
for item in lst:
if 'Featured' in item['labels']:
ret.append(item)
return ret
|
def getParentDirList(path):
""" Returns the directories up to a (posix) path
:param path: The path to process
:type path: ``str``
:return: The directory list
:rtype: ``list``
"""
import posixpath
path = posixpath.normpath("/%s" % path)
if path[:2] == '//':
path = path[1:]
dirs = []
path = posixpath.dirname(path)
while path != '/':
dirs.append(path)
path = posixpath.dirname(path)
dirs.append('/')
return dirs
|
def basename(p):
"""Returns the basename (i.e., the file portion) of a path.
Note that if `p` ends with a slash, this function returns an empty string.
This matches the behavior of Python's `os.path.basename`, but differs from
the Unix `basename` command (which would return the path segment preceding
the final slash).
Args:
p: The path whose basename should be returned.
Returns:
The basename of the path, which includes the extension.
"""
return p.rpartition("/")[-1]
|
def fib_recursive(n):
""" Fibonacci sequence:
f_n = f_(n-1) + f_(n-2); with f_0 = 0, f_1 = 1
Uses recusive methods to solve
"""
if n == 0:
res = 0
elif n == 1:
res = 1
else:
res = fib_recursive(n - 1) + fib_recursive(n - 2)
return res
|
def convert_none_to_empty_string(value):
"""Convert the value to an empty string if it's None.
:param value: The value to convert.
:returns: An empty string if 'value' is None, otherwise 'value'.
"""
return '' if value is None else value
|
def _create_subscript_in(maker, index, root):
"""
Find or create and insert object of type `maker` in `root` at `index`.
If `root` is long enough to contain this `index`, return the object at that
index. Otherwise, extend `root` with None elements to contain index
`index`, then create a new object by calling `maker`, insert at the end of
the list, and return this object.
Can therefore modify `root` in place.
"""
curr_n = len(root)
if curr_n > index:
return root[index]
obj = maker()
root += [None] * (index - curr_n) + [obj]
return obj
|
def paths_and_probs_to_dict(paths, probs, normalize=False):
"""Turn paths and path probabilities as returned from Transition Path Theory into dictionary.
Parameters
----------
paths : 1D numpy.ndarray.
Array of paths where each path is a numpy array of integer on its own.
probs : 1D numpy.ndarray.
Array of path probabailities.
Returns
-------
paths_dict : dict.
Dictionary of paths (tuples) and probabilities (float)
"""
pathlist = list(tuple(path) for path in paths)
if normalize:
psum = sum(probs)
pathproblist = [prob/psum for prob in probs]
else:
pathproblist = list(probs)
paths_dict = dict(zip(pathlist, pathproblist))
return paths_dict
|
def choose(dict):
"""
This function is very important in the theory.
This is important because when given a distribution of options, and you're trying to guess
the correct one, your best strategy is always to pick the one with highest probability.
It's also important because when predicting a binary variable (or any categorical variable, for that matter),
each time you make an entropy-reducing split, it does not necessarily mean that either side of the split needs to have a different guess.
For example, let's say you have the following points:
(0,0)
(1,0)
(2,0)
(3,1)
(4,0)
(5,0)
Your initial prediction is just to guess zeros, and your entropy is -5/6 * log2(5/6) - 1/6 * log2(1/6) = 0.6500
And then the entropy-reducing split would be at 2.5, so you'd have:
(0,0)
(1,0)
(2,0)
-------
(3,1)
(4,0)
(5,0)
and on either side of the split, you'd still predict 0 as your best guess. Your new entropy is:
1/2 * ( 0 ) + 1/2 * ( -1/3 * log2(1/3) - 2/3 * log2(2/3) ) = 0.4591
Thus, entropy has been reduced, but you still make the same predictions -- the benefit is that you're more confident about the guess.
I found this implementation here: https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
"""
return max(dict, key=dict.get)
|
def get_unique_char_name(toon_name, realm_name):
""" globally unique toon name in Name - Realm format"""
gu_char_name = toon_name + " - " + realm_name
return gu_char_name
|
def is_reflexive(universe, relation):
"""
Function to determine if a relation of a set is reflexive
:param universe: a set
:param relation: a relation on set universe
return: True if relation is a reflexiver relation of set universe
"""
new_set = {(a, b) for a in universe for b in universe if a == b}
if relation >= new_set:
return True
return False
|
def num_digits(number):
"""
Returns number of digits in an integer.
:param number: Integer
:return: Number of digits
"""
return len(str(number))
|
def sanitize(value):
""" Sanitize program strings to make them easier to compare. """
return ''.join(value.split())
|
def __switch_dias(dia):
"""
Funcion que hace de swicth porque no se les ocurrio hacerlo a los que crearon el lenguaje
y tengo que estar haciendolo yo aunque ahora no la uso
"""
switcher = {
1: "MON",
2: "TUE",
3: "WED",
4: "THU",
5: "FRI",
6: "SAT",
7: "SUN"
}
return switcher.get(dia, "MON")
|
def flatten(lol):
"""
Flatten a list of lists
"""
return [item for sublist in lol for item in sublist]
|
def shall_exclude_diagnostic_message(message):
"""Exclude certain diagnostics messages"""
exclusion_list = [
"-fno-canonical-system-headers",
"-Wunused-but-set-parameter",
"-Wno-free-nonheap-object",
"-Werror=init-list-lifetime",
"-Werror=class-conversion",
]
return any(word in message for word in exclusion_list)
|
def build_article_url(root_url, article_path):
"""
Build URL for blog article. Using this function will ensure the URL is constructed correctly, regardless of what
platform the article path is for.
Args
root_url: URL string to website root directory.
article_path: Path to the article on the server relative to the website root as either a string or Path object.
Return
A URL string for the blog article.
"""
article_path_string = str(article_path)
# Convert backlashes to forward slashes in case this is a Windows path.
article_path_string = article_path_string.replace('\\', '/')
# Remove existing slashes between parts of the URL to make sure they're joined correctly.
if root_url[-1] == '/':
root_url = root_url[:-1]
if article_path_string[0] == '/':
article_path_string = article_path_string[1:]
article_url = '/'.join((root_url, article_path_string))
return article_url
|
def iseven(n):
"""Return true if n is even."""
return n%2==0
|
def weights(b):
"""Return a heuristic value based on the weights of specified locations."""
value, n = 0, len(b)
weights = [
[2048, 1024, 512, 256],
[1024, 512, 256, 128],
[256, 8, 2, 1],
[4, 2, 1, 1]
]
for i in range(n):
for j in range(n):
value += (b[i][j] * weights[i][j])
return value
|
def dh_get_matching_company_contact(first_name, last_name, email, company_contacts):
"""
Performs check identifying whether an enquirer exists in their company's contact
list in |data-hub-api|_.
:param first_name:
:type first_name: str
:param last_name:
:type last_name: str
:param email:
:type email: str
:param company_contacts:
:type company_contacts: list
:returns: The first matching contact if any exist
:rtype: dict or None
"""
return next((
company_contact for company_contact in company_contacts
if company_contact["first_name"].lower() == first_name.lower()
and company_contact["last_name"].lower() == last_name.lower()
and company_contact["email"].lower() == email.lower()
),
None
)
|
def sort_priority4(values, group):
"""
sort_priority4(python2)
:param values:
:param group:
:return:
"""
found = [False]
def helper(x):
nonlocal found
if x in group:
found[0] = True
return (0, x)
return (1, x)
values.sort(key=helper)
return found[0]
|
def loadCTD(ctd):
"""
Loads standard ctd data from a dictionary of ctd values
"""
S = ctd['s']
T = ctd['t']
p = ctd['p']
lat = ctd['lat']
lon = ctd['lon']
return S, T, p, lat, lon
|
def callable_get(collection, key, default=None, args=[]):
"""Get item from collection. Return collection applied to args, if it is callable"""
result = collection.get(key, default)
if callable(result):
return result(*args)
return result
|
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (
service.users().messages().send(userId=user_id, body=message).execute()
)
#print(f'Message Id: {message["id"]}')
return message
except Exception as e:
print(f"An error occurred: {e}")
|
def raw_resp_to_int(raw_resp):
"""
# convert response to int
('xxx 224rfff ')) # -->224
:param raw_resp: float or str collect from keyboard response
:return: int response
"""
if isinstance(raw_resp, float):
return int(raw_resp)
# apply to rows with str
if isinstance(raw_resp, str):
if not raw_resp:
return None
res_s = ""
for c in filter(str.isdigit, raw_resp):
res_s += c
if res_s == "":
return None
else:
return int(res_s)
|
def format_remap_name(remap):
"""Format remap value for DT node name
Args:
remap: Remap definition.
Returns:
DT remap definition in lower caps
"""
if remap == 0 or remap is None:
return ""
elif "REMAP0" in remap:
return ""
elif "REMAP1" in remap:
return "_remap1"
elif "REMAP2" in remap:
return "_remap2"
elif "REMAP3" in remap:
return "_remap3"
else:
return ""
|
def how_many(aDict):
"""
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
"""
return sum(len(value) for value in aDict.values())
|
def PadForGenerics(var):
"""Appends a space to |var| if it ends with a >, so that it can be compiled
within generic types.
"""
return ('%s ' % var) if var.endswith('>') else var
|
def parse_state(state):
""""
prepare input for gcodeGenerator
i/p:state varible
o/p:list of tuple <formatted argument, orientation>
"""
args = []
for heightmap in state["heightmaps"]:
arg = str(heightmap["length"]) + " " +str(heightmap["width"]) + " "
if heightmap["orientation"] == "xy+" or heightmap["orientation"] == "xy-":
arg += str(state["model"]["height"]) + "\n"
elif heightmap["orientation"] == "xz+" or heightmap["orientation"] == "xz-":
arg += str(state["model"]["width"]) + "\n"
elif heightmap["orientation"] == "yz+" or heightmap["orientation"] == "yz-":
arg += str(state["model"]["length"]) + "\n"
arg += heightmap["raw"]
args.append((arg, heightmap["orientation"]))
return args
|
def _check_standardization_interval(standardize_by):
"""Check standardization interval is valid."""
valid_intervals = ['dayofyear', 'month']
is_valid = standardize_by is None or standardize_by in valid_intervals
if not is_valid:
raise ValueError(
"Unrecognized standardization interval '%r'" % standardize_by)
return standardize_by
|
def melt_curve(start=65, end=95, inc=0.5, rate=5):
"""Generate a melt curve on the fly
No inputs neded for a standard melt curve.
Example
-------
.. code-block:: python
melt_params = melt_curve()
protocol.thermocycle(dest_plate,
thermocycle_dict,
volume="15:microliter",
dataref="data",
dyes={"SYBR":dest_plate.all_wells().indices()},
**melt_params)
Parameters
----------
start : int, float
Temperature to start at
end : int, float
Temperature to end at
inc : int, float
Temperature increment during the melt_curve
rate : int
After x seconds the temperature is incremented by inc
Returns
-------
melt_params : dict
containing melt_params
Raises
------
ValueError
If start, end or inc are not of type `float` or `int`. And if rate is
not of type `int`
"""
assert isinstance(start, (float, int))
assert isinstance(end, (float, int))
assert isinstance(inc, (float, int))
assert isinstance(rate, int)
melt_params = {"melting_start": "%.2f:celsius" % start,
"melting_end": "%.2f:celsius" % end,
"melting_increment": "%.2f:celsius" % inc,
"melting_rate": "%.2f:second" % rate}
return melt_params
|
def expand_curie_to_uri(curie, context_info):
"""Expand curie to uri based on the context given
:arg str curie: curie to be expanded (e.g. bts:BiologicalEntity)
:arg dict context_info: jsonld context specifying prefix-uri relation (e.g. {"bts": "http://schema.biothings.io/"})
"""
# as suggested in SchemaOrg standard file, these prefixes don't expand
PREFIXES_NOT_EXPAND = ["rdf", "rdfs", "xsd"]
if not curie:
return curie
if type(curie) == int:
curie = str(curie)
# determine if a value is curie
if len(curie.split(':')) == 2:
prefix, value = curie.split(":")
if prefix in context_info and prefix not in PREFIXES_NOT_EXPAND:
return context_info[prefix] + value
# if the input is not curie, return the input unmodified
else:
return curie
else:
return curie
|
def _doublequote(str):
"""
Replace double quotes if it's necessary
"""
return str.replace('"', '\\"')
|
def simplify_parenthesis(textline: str) -> str:
"""Remove enclosing parenthesis if available."""
if textline.startswith("(") and textline.endswith(")"):
textline = textline[1:-1]
return textline
|
def retrieval_precision(gold, predicted):
"""
Compute retrieval precision on the given gold set and predicted set.
Note that it doesn't take into account the order or repeating elements.
:param gold: the set of gold retrieved elements
:param predicted: the set of predicted elements
:return: precision value
>>> retrieval_precision({1,2,3},{2})
1.0
>>> retrieval_precision({2}, {1,2,3})
0.3333333333333333
>>> retrieval_precision({2,3,4,8}, {1,6,3})
0.3333333333333333
"""
gold = set(gold)
predicted = set(predicted)
tp = len(gold & predicted)
fp_tp = len(predicted)
return tp/fp_tp
|
def get_nested_expression(adders):
"""Return a string representing the addition of all the input bitvectors.
Args:
adders: An integer, the number of nested addition operations.
Returns:
The full addition string.
"""
nested_expressions = []
for i in range(adders):
rhs = "x_0" if i == 0 else nested_expressions[i - 1]
expression = ["(bvadd", f"x_{i + 1}", rhs + ")"]
nested_expressions.append(" ".join(expression))
return nested_expressions[-1]
|
def is_int(obj, digit=False):
"""Check if obj is int typeable.
Args:
obj (:obj:`object`): object to check
digit (:obj:`bool`, optional): default ``False`` -
* if ``True`` obj must be (str/bytes where isdigit is True) or int
* if ``False`` obj must be int
Returns:
:obj:`bool`: bool reflecting if obj is int typeable
"""
if digit:
if (isinstance(obj, str) or isinstance(obj, bytes)) and obj.isdigit():
return True
return not isinstance(obj, bool) and isinstance(obj, int)
|
def validate_bed_format(row):
"""Error check correct BED file formatting.
Does a quick assert that row was successfully split into multiple
fields (on tab-character).
Args:
row (list): list of BED fields
Returns:
None
"""
assert len(row) >= 3, 'Bed Files must have at least 3 tab separated fields.'
return True
|
def arb_profit(arb_percent, stake):
"""
:param arb_percent: List. Helper function must be used with arb_percentage. This is sum of combined implied probabilities < 100% mean arb opportunity
:param stake: Float. How much you intend to throw down on the wager.
:return: Float. Riskless profit if executed at the terms of the parameters.
"""
return stake / arb_percent[0] - stake
|
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
if not name:
return u''
return name.replace('_', ' ').capitalize()
|
def elem_C(w, C):
"""
Simulation Function: -C-
Inputs
----------
w = Angular frequency [1/s]
C = Capacitance [F]
"""
return 1 / (C * (w * 1j))
|
def get_edit_type(word, lemma):
""" Calculate edit types. """
if lemma == word:
return 'identity'
elif lemma == word.lower():
return 'lower'
return 'none'
|
def get_order_by_querytring(ordering, current_order=None, remove=False):
"""
Using the ordering parameter (a list), returns a query string with the
orders of the columns
The parameter current_order can be passed along to handle the specific
order of a single column. So for example if you are ordering by 'email' and
'first_name', you can pass on 'email' as the current order, so the system
can keep every other order, but inverse the order of the email field.
"""
if not current_order:
return '&'.join(['o={}'.format(o) for o in ordering])
reversed_current_order = '-{}'.format(current_order)
query_string = []
for order in ordering:
if order == current_order:
if remove:
continue
query_string.append(reversed_current_order)
elif order == reversed_current_order:
if remove:
continue
query_string.append(current_order)
else:
query_string.append(order)
# if the current orderd and it's reversed are not being currently used
if not (current_order in ordering or reversed_current_order in ordering):
if not remove:
query_string.append(current_order)
return '&'.join(['o={}'.format(o) for o in query_string])
|
def lines(string, keepends=False):
"""
Split a string into a list of strings at newline characters. Unless
*keepends* is given and true, the resulting strings do not have newlines
included.
"""
return string.splitlines(keepends)
|
def compress_state(state):
"""
Compress state to combine special cards
"""
compressed_state = {
'total': state['total'],
'trumps': state['trump1'] + state['trump2'] + state['trump3'],
'dealer_card': state['dealer_card']
}
return compressed_state
|
def nested_set(dic, keys, value):
"""
:param dic:
:param keys:
:param value:
:return:
"""
dictionary = dic
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
return dictionary
|
def wasserstein_loss(real_logit, fake_logit):
"""
:param real_logit: logit(s) for real images (if None just return generator loss)
:param fake_logit: logit(s) for fake images
:return: loss for discriminator and generator (unless real_logit is None)
"""
loss_generator = - fake_logit
if real_logit is None:
return loss_generator
loss_discriminator_real = - real_logit
loss_discriminator_fake = fake_logit
# this actually negates the need for a bias in the FC layer, it's cancelled out
loss_discriminator = loss_discriminator_real + loss_discriminator_fake
return loss_discriminator, loss_generator
|
def fact(n):
"""Calculate n! iteratively"""
result = 1
if n > 1:
for f in range(2 , n + 1):
result *=f
return result
|
def to_bool(bool_str: str):
"""Convert str to bool."""
bool_str_lc = bool_str.lower()
if bool_str_lc in ("true", "1", "t"):
return True
if bool_str_lc in ("false", "0", "f", ""):
return False
raise ValueError(f"cannot interpret {bool_str} as a bool")
|
def remove_deprecated_elements(deprecated, elements, version):
"""Remove deprecated items from a list or dictionary"""
# Attempt to parse the major, minor, and revision
(major, minor, revision) = version.split('.')
# Sanitize alphas and betas from revision number
revision = revision.split('-')[0]
# Iterate over deprecation lists and remove any keys that were deprecated
# prior to the current version
for dep in deprecated:
if (major >= dep['major']) \
or (major == dep['major'] and minor >= dep['minor']) \
or (major == dep['major'] and minor == dep['minor']
and revision >= dep['revision']):
if type(elements) is list:
for key in dep['keys']:
if key in elements:
elements.remove(key)
if type(elements) is dict:
for key in dep['keys']:
if key in elements:
del elements[key]
return elements
|
def round_to_num_gran(size, num=8):
"""Round size to nearest value that is multiple of `num`."""
if size % num == 0:
return size
return size + num - (size % num)
|
def two_yr_suffix(year):
"""Return a suffix string of the form ``_XXYY`` based on year,
where XX = the last 2 digits of year - 1,
and YY = the last 2 digits of year
:arg year: Year from which to build the suffix;
2nd year in suffix;
e.g. 1891 produces ``_8081``
:type year: int
:returns: String of the form ``_XXYY`` like ``_8081`` for 1981
"""
return ('_{year_m1}{year}'
.format(
year_m1=str(year - 1)[-2:],
year=str(year)[-2:]))
|
def user_in_role(user, roles):
"""
True if user has one of specified roles
"""
if user:
result = False
for role in roles:
result |= (role in user.roles)
return result
return False
|
def convert_into_nb_of_seconds(freq: str, horizon: int) -> int:
"""Converts a forecasting horizon in number of seconds.
Parameters
----------
freq : str
Dataset frequency.
horizon : int
Forecasting horizon in dataset frequency units.
Returns
-------
int
Forecasting horizon in seconds.
"""
mapping = {
"s": horizon,
"H": horizon * 60 * 60,
"D": horizon * 60 * 60 * 24,
"W": horizon * 60 * 60 * 24 * 7,
"M": horizon * 60 * 60 * 24 * 30,
"Q": horizon * 60 * 60 * 24 * 90,
"Y": horizon * 60 * 60 * 24 * 365,
}
return mapping[freq]
|
def rotatedDigits(N):
"""
:type N: int
:rtype: int 2 5 6 9
"""
count = 0
for i in range(1,N+1):
i = str(i)
if '3'in i or '4'in i or '7' in i:
continue
if '2'in i or '5'in i or '9' in i or '6' in i:
count +=1
return count
|
def initialize(boardsize):
""" The new game state """
game_state = []
for i in range(0, boardsize):
game_state.append([])
for j in range(0, boardsize):
game_state[i].append('-')
return game_state
|
def close_connection(connection) -> bool:
"""Function to close Database connection.
Args:
connection (mysql.connector.connection_cext):
The argument received is a MySQL connection.
Returns:
bool: The original return was False when database
connection was closed. But, I forced the return
to be True when the database connection is closed.
"""
if not connection:
return False
else:
connection.close()
return True
|
def get_table_titles(data, primary_key, primary_key_title):
"""Detect and build the table titles tuple from ORM object, currently only support SQLAlchemy.
.. versionadded:: 1.4.0
"""
if not data:
return []
titles = []
for k in data[0].__table__.columns.keys():
if not k.startswith('_'):
titles.append((k, k.replace('_', ' ').title()))
titles[0] = (primary_key, primary_key_title)
return titles
|
def update_portfolio(api_data, csv_target):
"""Prepare updated csv report for destination csv file"""
updates = []
for row in api_data:
symbol = row[0]
latest_price = round(float(row[1]), 3)
for item in csv_target:
if row[0] == item['symbol']:
units = int(item['units'])
cost = float(item['cost'])
book_value = round(cost * units, 3)
new_data = {'symbol': symbol, 'latest_price': latest_price, 'units': units,
'cost': cost, 'book_value': round(cost * units, 3),
'market_value': round(latest_price*units, 3),
'gain_loss': round(latest_price*units-book_value, 3),
'change': round(((latest_price*units)-book_value)/book_value, 3)}
updates.append(new_data)
# Check for invalid symbols
for row in csv_target:
check_symbol = "'"+row['symbol']+"'"
if check_symbol not in str(api_data):
print("- "+check_symbol+" is an invalid api call, check source file.")
return updates
|
def time_string(t,precision=3):
"""Convert time given in seconds in more readable format
such as ps, ns, ms, s.
precision: number of digits"""
from numpy import isnan,isinf
if t is None: return "off"
if t == "off": return "off"
try: t=float(t)
except: return "off"
if isnan(t): return "off"
if isinf(t) and t>0: return "inf"
if isinf(t) and t<0: return "-inf"
if t == 0: return "0"
if abs(t) < 0.5e-12: return "0"
if abs(t) < 999e-12: return "%.*gps" % (precision,t*1e12)
if abs(t) < 999e-9: return "%.*gns" % (precision,t*1e9)
if abs(t) < 999e-6: return "%.*gus" % (precision,t*1e6)
if abs(t) < 999e-3: return "%.*gms" % (precision,t*1e3)
if abs(t) < 60: return "%.*gs" % (precision,t)
if abs(t) < 60*60: return "%.*gmin" % (precision,t/60.)
if abs(t) < 24*60*60: return "%.*gh" % (precision,t/(60.*60))
return "%.*gd" % (precision,t/(24*60.*60))
|
def esc_control_characters(regex):
"""
Escape control characters in regular expressions.
"""
unescapes = [('\a', r'\a'), ('\b', r'\b'), ('\f', r'\f'), ('\n', r'\n'),
('\r', r'\r'), ('\t', r'\t'), ('\v', r'\v')]
for val, text in unescapes:
regex = regex.replace(val, text)
return regex
|
def parse_list_arg(args):
"""
Parse a list of newline-delimited arguments, returning a list of strings with leading and
trailing whitespace stripped.
Parameters
----------
args : str
the arguments
Returns
-------
list[str]
the parsed arguments
"""
return [u.strip() for u in args.split("\n") if u.strip()]
|
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
for line in board[1:-1]:
for element in line:
if element == '?':
return False
return True
|
def _special_indexes_from_metadata(metadata, transforms, vocabulary=False):
"""Return list of SQLAlchemy index objects for the transformed metadata.
Given the stock metadata, for each transform `T` we invoke:
new_metadata = T.modify_metadata(metadata)
and at the end, we extract the indexes.
:param metadata: SQLAlchemy metadata for PEDSnet
:type: sqlalchemy.schema.MetaData
:param transforms: list of Transform classes
:type: list(type)
:param vocabulary: whether to return indexes for vocabulary tables or
non-vocabulary tables
:type: bool
:return: list of index objects
:rtype: list(sqlalchemy.Index)
"""
indexes = []
for t in transforms:
indexes.extend(t.modify_metadata(metadata))
return indexes
|
def is_valid(line):
"""
Checks if the content of an edge has a valid format.
<vertex vertex weight>
:param line: A line of the input text.
:type: String
:return: A list if edge is valid, None otherwise.
"""
edge = line.rsplit()
wrong_args_number = len(edge) != 3
is_comment = line.startswith("#")
if wrong_args_number or not edge or is_comment:
return None
try:
int(edge[0])
int(edge[1])
int(edge[2])
except ValueError:
return None
return edge
|
def stringToBool(s):
"""
Convert a string (True/true/1) to bool
s -- string/int value
return -- True/False
"""
return (s == "True" or s== "true" or s == "1" or s == 1)
|
def email_doner(name, amount):
"""Fill in a form thank-you email for a donation."""
email_string = """Thank you {0} for your donation of {1} goofy goober dollars.""".format(name, amount)
return email_string
|
def validation_metrics(ground_truth, bowtie2_prediction):
"""Calculates the recall and specificity
Find list instersection!!
parameters
----------
ground_truth
dict, contains the ground truth as obtained from the sim reads
bowtie2_prediction
dict, contains the predicted read mappings
returns
----------
metrics = {fastaheader : [truth, prediction, intersection, recall, precision]}
"""
metrics = {}
for fh, predicted_IDs in bowtie2_prediction.items():
true_IDs = ground_truth[fh]
set_predicted_IDs = set(predicted_IDs)
set_true_IDs = set(true_IDs)
intersection = set_predicted_IDs.intersection(set_true_IDs)
true_count = len(set_true_IDs)
predicted_count = len(set_predicted_IDs)
intersection_count = len(intersection)
# if ground_truth, prediction and intersection is 0, recall and precision are 1
if true_count == 0 and predicted_count == 0: # Implies intersection is also 0
true_count = 1e-99
predicted_count = 1e-99
intersection = 1e-99
try:
specificity = intersection_count/predicted_count
except(ZeroDivisionError):
specificity = "0 (ZeroDivision)"
try:
recall = intersection_count/true_count
except(ZeroDivisionError):
recall = "0 (ZeroDivision)"
#if not recall == "0 (ZeroDivision)":
metrics[fh] = [true_count, predicted_count, intersection_count, recall, specificity]
return(metrics)
|
def parse(argv):
"""Parse optional list of keyword arguments into a dict.
Parses a list of keyword arguments defined by a leading ``--`` and separated by ``=`` (for example, --key=value).
Args:
argv (listof str):
Keyword dict to use as an update.
Examples::
# Import the kwconfig module
import kwconfig
# Create a sample list of keyword arguments
argv = ['--key1=value1', '--key2=value2']
# Parse into a keyword dict
kwdict = kwconfig.parse(argv)
# View the values of key1 and key2
print('key1: ' + kwdict['key1'])
print('key2: ' + kwdict['key2'])
"""
kwdict = {}
for kv in argv:
k, v = kv.split('=', 1)
kwdict[k.strip('-')] = v
return(kwdict)
|
def convert_to_bool(value):
"""Check if the value of an environment variable is truthy."""
return value.lower() in ("true", "yes", "1")
|
def two_column(left, right, col1_length=65, col2_length=1):
"""Two column layout for printouts.
Example:
I did this thing done!
"""
tmp = '%-{}s%-{}s'.format(col1_length, col2_length)
# The space in front of the right column add minimal padding in case
# lefts content is very long (>col1_length)
return tmp % (left, ' ' + right)
|
def parse_config_dicts(INPUT_CONFIG, CROSS_VALID_CONFIG,
LABEL_VALID_CONFIG,DATA_VALID_CONFIG,
LABEL_ACTOR_CONFIG, DATA_ACTOR_CONFIG):
""" Parse configs into kwargs for librarian.create()
Args:
INPUT_CONFIG (dict):
CROSS_VALID_CONFIG (dict):
LABEL_VALID_CONFIG (dict):
DATA_VALID_CONFIG (dict):
LABEL_ACTOR_CONFIG (dict):
DATA_ACTOR_CONFIG (dict):
Returns (dict):
Kwargs needed to create a librarian instance
Raises:
KeyError: if a needed tag was not found in config dict
"""
return {
# INPUT: These define which type of data is expected
"DATA_TYPE": INPUT_CONFIG["type"],
"DATA_TAG": INPUT_CONFIG["tag"],
# CROSS: these define validations for each label-data combination obtained
"CROSS_VALID_TYPE": CROSS_VALID_CONFIG["validator"],
"CROSS_VALID_ARGS": CROSS_VALID_CONFIG["args"],
# LABEL: these define validations for each label object obtained
"LABEL_VALID_TYPE": LABEL_VALID_CONFIG["validator"],
"LABEL_VALID_ARGS": LABEL_VALID_CONFIG["args"],
# DATA: these define validations for each data object obtained
"DATA_VALID_TYPE": DATA_VALID_CONFIG["validator"],
"DATA_VALID_ARGS": DATA_VALID_CONFIG["args"],
# LABEL: these define actions for each label object obtained
"LABEL_ACTOR_TYPE": LABEL_ACTOR_CONFIG["actor"],
"LABEL_ACTOR_ARGS": LABEL_ACTOR_CONFIG["args"],
# DATA: these define actions for each data object obtained
"DATA_ACTOR_TYPE": DATA_ACTOR_CONFIG["actor"],
"DATA_ACTOR_ARGS": DATA_ACTOR_CONFIG["args"],
}
|
def removeIntInxString(txt, sep = '.'):
""" removeIntInxString(txt, sep)
From text writen like "1. Text what u need"
transform that to "Text what u need"
Parameters
----------
txt : String
String what you want to be transformed
sep : Char
Separation between you don't need and
text
Returns
-------
String
Returns string with real info you need
"""
s = txt.split(sep)
rettxt = ''
if len(s) > 1:
for t in s[1: len(s) -1]:
rettxt = rettxt + t.strip() + sep
rettxt = rettxt + s[-1].strip()
return rettxt
else:
return txt.strip()
|
def debytes(string):
"""
Decode string if it is a bytes object.
This is necessary since Neovim, correctly, gives strings as a str, but regular
Vim leaves them encoded as bytes.
"""
try:
return string.decode()
except AttributeError:
return string
|
def normalize_url(url):
""" ensure a url is "properly" constructed
Remove trailing slashes
Add http if http or https is not specified
Parameters
----------
url: string
A string to return as a url
"""
if url.endswith('/'):
url = url[:-1]
if not url.startswith('http://') and not url.startswith('https://'):
url = "http://{}".format(url)
return url
|
def is_fixed_line_number(number):
"""
Fixed lines start with an area code enclosed in brackets. The area
codes vary in length but always begin with 0.
"""
if len(number) < 3:
return False
return number.find("(") != -1 and number.find(")") != -1 and number[1] == '0'
|
def extract_paths(actions):
"""
<Purpose>
Given a list of actions, it extracts all the absolute and relative paths
from all the actions.
<Arguments>
actions: A list of actions from a parsed trace
<Returns>
absolute_paths: a list with all absolute paths extracted from the actions
relative_paths: a list with all relative paths extracted from the actions
"""
absolute_paths = []
relative_paths = []
actions_with_path = ['open', 'creat', 'statfs', 'access', 'stat',
'link', 'unlink', 'chdir', 'rmdir', 'mkdir']
for action in actions:
# get the name of the syscall and remove the "_syscall" part at the end.
action_name = action[0][:action[0].find("_syscall")]
# we only care about actions containing paths
if action_name not in actions_with_path:
continue
# we only care about paths that exist
action_result = action[2]
if action_result == (-1, 'ENOENT'):
continue
path = action[1][0]
if path.startswith("/"):
if path not in absolute_paths:
absolute_paths.append(path)
else:
if path not in relative_paths:
relative_paths.append(path)
# get the second path of link
if action_name == "link":
path = action[1][1]
if path.startswith("/"):
if path not in absolute_paths:
absolute_paths.append(path)
else:
if path not in relative_paths:
relative_paths.append(path)
return absolute_paths, relative_paths
|
def build_minio_url(minio_host, minio_port=9000):
"""
Purpose:
Create the Minio URL from host and port
Args:
minio_host (String): Host of Minio
minio_host (Int): Port of Minio (Defaults to 9000)
Returns:
minio_url (String): URL of Minio
"""
return f"{minio_host}:{minio_port}"
|
def get_input(desc):
"""get input values"""
value = desc.get('value', None)
return value if value is not None else desc['tensor_name']
|
def _merge_json_dicts(from_dict, to_dict):
"""Merges the json elements of from_dict into to_dict. Only works for json dicts
converted from proto messages
"""
for key, value in from_dict.items():
if isinstance(key, int) and str(key) in to_dict:
# When the key (i.e. the proto field name) is an integer, it must be a proto map field
# with integer as the key. For example:
# from_dict is {'field_map': {1: '2', 3: '4'}}
# to_dict is {'field_map': {'1': '2', '3': '4'}}
# So we need to replace the str keys with int keys in to_dict.
to_dict[key] = to_dict[str(key)]
del to_dict[str(key)]
if key not in to_dict:
continue
if isinstance(value, dict):
_merge_json_dicts(from_dict[key], to_dict[key])
elif isinstance(value, list):
for i, v in enumerate(value):
if isinstance(v, dict):
_merge_json_dicts(v, to_dict[key][i])
else:
to_dict[key][i] = v
else:
to_dict[key] = from_dict[key]
return to_dict
|
def dos_list_request_to_gdc(dos_list):
"""
Takes a dos ListDataObjects request and converts it into a GDC request.
:param gdc:
:return: A request against GDC as a dictionary.
"""
mreq = {}
mreq['size'] = dos_list.get('page_size', None)
mreq['from'] = dos_list.get('page_token', None)
return mreq
|
def parse_cores(core_str):
"""Parse core list passed through command line"""
cores = []
# remove spaces
core_str.replace(" ", "")
# check if not a range
if '-' not in core_str:
return list(map(int, core_str.strip().split(',')))
# parse range e.g. 2-8
core_str = core_str.strip().split('-')
for i in range(int(core_str[0]), int(core_str[1]) + 1):
cores.append(i)
return cores
|
def multi(a, b, c):
""" performs arithmetic operations this is the docstring of multi() """
return a * b - c
|
def to_ver32(version):
"""
Converts version in Redfish format (e.g. v1_0_0) to a PLDM ver32
Args:
version: The Redfish version to convert
Returns:
The version in ver32 format
"""
# The last item in result will have the latest version
if version != 'v0_0_0': # This is a versioned namespace
ver_array = version[1:].split('_') # skip the 'v' and split the major, minor and errata
ver_number = ((int(ver_array[0]) | 0xF0) << 24) | ((int(ver_array[1]) | 0xF0) << 16) | ((int(ver_array[2])
| 0xF0) << 8)
return ver_number
else: # This is an un-versioned entity, return v0_0_0
return 0xFFFFFFFF
|
def _make_reflected_gradient(X, Y, angle):
"""Generates index map for reflected gradients."""
import numpy as np
theta = np.radians(angle % 360)
Z = np.abs((np.cos(theta) * X - np.sin(theta) * Y))
return Z
|
def _strip_region_tags(sample_text):
"""Remove blank lines and region tags from sample text"""
magic_lines = [
line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line
]
return "\n".join(magic_lines)
|
def mapattr(value, arg):
"""
Maps an attribute from a list into a new list.
e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}]
arg = 'a'
result = [1, 2, 3]
"""
if len(value) > 0:
res = [getattr(o, arg) for o in value]
return res
else:
return []
|
def pair_sum(arr, target):
"""
:param: arr - input array
:param: target - target value
Find two numbers such that their sum is equal to the target
Return the two numbers in the form of a sorted list
"""
sorted_arr = sorted(arr, reverse=True)
n = len(arr)
for larger_el in range(n - 1): # 0 -> n-2
for smaller_el in range(n - 1, larger_el, -1): # n <- larger_el
if sorted_arr[larger_el] + sorted_arr[smaller_el] == target:
return [sorted_arr[smaller_el], sorted_arr[larger_el]]
if sorted_arr[larger_el] + sorted_arr[smaller_el] > target:
break
return [None, None]
|
def potential_temperature(temperature_k, pressure_hpa, pressure_reference_hpa=1000.0):
"""
Convert temperature to potential temperature based on the available pressure. Potential temperature is at a
reference pressure of 1000 mb.
Args:
temperature_k: The air temperature in units K
pressure_hpa: The atmospheric pressure in units hPa
pressure_reference_hpa: The reference atmospheric pressure for the potential temperature in hPa;
default 1000 hPa
Returns:
The potential temperature in units K
"""
return temperature_k * (pressure_reference_hpa / pressure_hpa) ** (2.0 / 7.0)
|
def euler_step(u, f, dt):
"""Returns the solution at the next time-step using Euler's method.
Parameters
----------
u : array of float
solution at the previous time-step.
f : function
function to compute the right hand-side of the system of equation.
dt : float
time-increment.
Returns
-------
u_n_plus_1 : array of float
approximate solution at the next time step.
"""
return u + dt * f(u)
|
def _strip_external_workspace_prefix(path):
"""Either 'external/workspace_name/' or '../workspace_name/'."""
# Label.EXTERNAL_PATH_PREFIX is due to change from 'external' to '..' in Bazel 0.4.5.
# This code is for forwards and backwards compatibility.
# Remove the 'external/' check when Bazel 0.4.4 and earlier no longer need to be supported.
if path.startswith("../") or path.startswith("external/"):
return "/".join(path.split("/")[2:])
return path
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.