content stringlengths 42 6.51k |
|---|
def assert_model_predictions_correct(
y_pred: float,
y_pred_perturb: float,
):
"""Assert that model predictions are the same."""
if y_pred == y_pred_perturb:
return True
else:
return False |
def filter_modules(model_state_dict, modules):
"""Filter non-matched modules in module_state_dict.
Args:
model_state_dict (OrderedDict): trained model state_dict
modules (list): specified module list for transfer
Return:
new_mods (list): the update module list
"""
new_mods = []
incorrect_mods = []
mods_model = list(model_state_dict.keys())
for mod in modules:
if any(key.startswith(mod) for key in mods_model):
new_mods += [mod]
else:
incorrect_mods += [mod]
if incorrect_mods:
print(
"module(s) %s don't match or (partially match) "
"available modules in model.",
incorrect_mods,
)
print("for information, the existing modules in model are:")
print("%s", mods_model)
return new_mods |
def mb_to_hgt(Psta, mslp=1013.25): # METERS
"""Convert millibars to expected altitude, in meters."""
return (1-(Psta/mslp)**0.190284)*44307.69396 |
def F_to_C(Tf):
"""convertit une temperature de Fahrenheit en Celsius"""
Tc = (Tf-32)*5/9
return Tc |
def _spark_filter_successive_chunks(chunk_1, chunk_2):
"""
Return the chunk having the highest 'chunk_index' between chunk X and Y
inputs are a tuple composed of (current chunk index, last point of current chunk, first point of previous chunk)
:param chunk_1: first chunk to compare
:type chunk_1: tuple
:param chunk_2: second chunk to compare
:type chunk_2: tuple
:return: the chunk with highest chunk_index
:rtype: tuple
"""
if max(chunk_1[0], chunk_2[0]) == chunk_1[0]:
return chunk_1
return chunk_2 |
def process_medians(helst, shelst, authlst):
"""
>>> medians_he = [12, 130, 0, 12, 314, 18, 15, 12, 123]
>>> medians_she = [123, 52, 12, 345, 0, 13, 214, 12, 23]
>>> books = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> process_medians(helst=medians_he, shelst=medians_she, authlst=books)
{'he': [0, 2.5, 0, 1.3846153846153846, 0, 1.0, 5.3478260869565215], 'she': [10.25, 0, 28.75,
0, 14.266666666666667, 0, 0], 'book': ['a', 'b', 'd', 'f', 'g', 'h', 'i']}
:param helst:
:param shelst:
:param authlst:
:return: a dictionary sorted as so {
"he":[ratio of he to she if >= 1, else 0],
"she":[ratio of she to he if > 1, else 0]
"book":[lst of book authors]
}
"""
d = {"he": [], "she": [], "book": []}
for num in range(len(helst)):
if helst[num] > 0 and shelst[num] > 0:
res = helst[num] - shelst[num]
if res >= 0:
d["he"].append(helst[num] / shelst[num])
d["she"].append(0)
d["book"].append(authlst[num])
else:
d["he"].append(0)
d["she"].append(shelst[num] / helst[num])
d["book"].append(authlst[num])
else:
if helst == 0:
print("ERR: no MALE values: " + authlst[num])
if shelst == 0:
print("ERR: no FEMALE values: " + authlst[num])
return d |
def filter_OD(origins, destinations):
"""
takes lists of origins and destinations in (1D notation)
and returns list of tuples with OD coorinates
"""
if len(origins) == len(destinations):
return list(zip(origins, destinations))
else:
return [] |
def get_english_chapter_count(book):
"""
A helper function to return the number of chapters in a given book in the English version of the Bible.
:param book: Name of the book
:type book: str
:return: Number of chapters in the book. 0 usually means an invalid book or unsupported translation.
:rtype: int
>>> get_english_chapter_count('Ecclesiastes')
12
>>> get_english_chapter_count('Barnabas')
0
>>> get_english_chapter_count('Song of Solomon')
8
>>> get_english_chapter_count('Psalms')
150
>>> get_english_chapter_count('Philippians')
4
"""
# Standardise letter casing to help find the key easier
book_name = book.title()
if book_name == 'Song Of Solomon':
# Song Of Songs has an alternate name
book_name = 'Song Of Songs'
elif book_name == 'Psalms':
# Psalm and its plural variation are basically the same book, but prefer the singular variant
book_name = 'Psalm'
elif book_name == 'Philippians':
# Prefer the spelling variation with two L's, partly for backwards compatibility with previous versions
book_name = 'Phillippians'
# This is the default mapping of books to their chapter counts
chapter_count_mappings = {
'Genesis': 50,
'Exodus': 40,
'Leviticus': 27,
'Numbers': 36,
'Deuteronomy': 34,
'Joshua': 24,
'Judges': 21,
'Ruth': 4,
'1 Samuel': 31,
'2 Samuel': 24,
'1 Kings': 22,
'2 Kings': 25,
'1 Chronicles': 29,
'2 Chronicles': 36,
'Ezra': 10,
'Nehemiah': 13,
'Esther': 10,
'Job': 42,
'Psalm': 150,
'Proverbs': 31,
'Ecclesiastes': 12,
'Song Of Songs': 8,
'Isaiah': 66,
'Jeremiah': 52,
'Lamentations': 5,
'Ezekiel': 48,
'Daniel': 12,
'Hosea': 14,
'Joel': 3,
'Amos': 9,
'Obadiah': 1,
'Jonah': 4,
'Micah': 7,
'Nahum': 3,
'Habakkuk': 3,
'Zephaniah': 3,
'Haggai': 2,
'Zechariah': 14,
'Malachi': 4,
'Matthew': 28,
'Mark': 16,
'Luke': 24,
'John': 21,
'Acts': 28,
'Romans': 16,
'1 Corinthians': 16,
'2 Corinthians': 13,
'Galatians': 6,
'Ephesians': 6,
'Phillippians': 4,
'Colossians': 4,
'1 Thessalonians': 5,
'2 Thessalonians': 3,
'1 Timothy': 6,
'2 Timothy': 4,
'Titus': 3,
'Philemon': 1,
'Hebrews': 13,
'James': 5,
'1 Peter': 5,
'2 Peter': 3,
'1 John': 5,
'2 John': 1,
'3 John': 1,
'Jude': 1,
'Revelation': 22
}
if book_name not in chapter_count_mappings.keys():
return 0
return chapter_count_mappings[book_name] |
def format_error_code(errorCode: int, descriptions: list) -> str:
"""Emergency error code -> description.
Args:
errorCode: Error code to check.
descriptions: Description table with (code, mask, description) entries.
Returns:
Text error description.
"""
description = 'Unknown emergency error'
for code, mask, desc in descriptions:
if errorCode & mask == code:
description = desc
return f'{description} (error code {errorCode:#04x})' |
def getHTMLOf(url):
"""
@param url a valid URL string
@return HTML of page at given URL
"""
import urllib
from urllib import request
return request.urlopen(request.Request(url)).read() |
def create_report(info):
"""Create a report with a list of auto included zcml."""
if not info:
# Return a comment. Maybe someone wants to automatically include this
# in a zcml file, so make it a proper xml comment.
return ["<!-- No zcml files found to include. -->"]
report = []
# Try to report meta.zcml first.
filenames = list(info)
meta = "meta.zcml"
if meta in filenames:
filenames.remove(meta)
filenames.insert(0, meta)
for filename in filenames:
dotted_names = info[filename]
for dotted_name in dotted_names:
if filename == "overrides.zcml":
line = ' <includeOverrides package="%s" file="%s" />' % (dotted_name, filename)
elif filename == "configure.zcml":
line = ' <include package="%s" />'% dotted_name
else:
line = ' <include package="%s" file="%s" />'% (dotted_name, filename)
report.append(line)
return report |
def diwt2do(Di, WT):
"""Calculate pipe outer diameter from inner diameter and wall thickness.
"""
return Di + 2 * WT |
def getPairedPaths(cur_path, time2path, path2time, same_time=True):
"""
Get edges from the same time or (closed time if same_time = False).
Parameters
----------
cur_path: integer
name of the current edge / path
time2path: dictionary
time as key and list of edges / paths as value
path2time: dictionary
edge / path as key and time as value
same_time: boolean
if only select edge / path belonging to the same time
Returns
-------
paired_paths: list
edge / paths closed in time to the current edge / path
"""
time = path2time[cur_path]
paired_paths = []
for k, v in time2path.items():
if same_time:
if k == time:
paired_paths += time2path[k]
else:
if k <= time + 1 and k >= time - 1: # include 1 sampling time before and after
paired_paths += time2path[k]
return paired_paths |
def genotype(gt: tuple) -> int:
"""Convert genotype tuple to dosage (0/1/2)"""
return None if gt == (None, None) else gt[0] + gt[1] |
def clean_action_name(action: str) -> str:
"""Cleans the given action to be used in the texts"""
return action.replace("-", " ").capitalize() |
def is_ends_with_underscore(value: str):
"""Does value end with underscore."""
if value == "":
return False
else:
return value[-1] == '_' |
def adding_odds(range1, range2):
"""
Function that sums all ods numbers between range 1 and range 2 (both inclusive)
Args:
range1(int): first range
range2(int): second range
Returns:
sum of all ods numbers between two ranges
"""
some_list = []
for i in range(range1, range2+1):
if i % 2 == 0:
some_list.append(i)
return sum(some_list) |
def lerp(value1=0.0, value2=1.0, parameter=0.5):
"""
Linearly interpolates between value1 and value2 according to a parameter.
Args:
value1: First interpolation value
value2: Second interpolation value
parameter: Parameter of interpolation
Returns:
The linear intepolation between value 1 and value 2
"""
return value1 + parameter * (value2 - value1) |
def get_xpath_for_possible_available_time_element(day_index: int) -> str:
"""
The element showing potential available times displayed in the results are found in divs having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[3]/div/div[2]/div[N]/div[1]/a'
^
where N is the day of the week from 2 to 8. So, div[2] is Mon, div[3] is Tue. and so on.
"""
return f'/html/body/div[4]/div[2]/div/div[5]/div/div[3]/div/div[2]/div[{day_index}]/div[1]/a' |
def error_rate(error_count, total):
"""
Calculate the error rate, given the error count and the total number
of words.
Args:
error_count (int): Number of errors.
total (int): Total number of words (of the same type).
Returns:
tuple (int, int, float): The error count, the total number
of words, and the calculated error rate.
"""
if total == 0:
return error_count, total, 0.0
return error_count, total, (error_count/total)*100 |
def convert_link(link, idx):
"""Convert the D3 JSON link data into a Multinet-style record."""
return {
"_key": str(idx),
"_from": f"""people/{link["source"]}""",
"_to": f"""people/{link["target"]}""",
} |
def translate_priority(priority: str) -> str:
"""Translate to new Jira priority types.
Jira changed how their priority names, so some translation is
necessary if migrating from an older Jira.
Args:
priority: A ticket priority.
Returns:
A valid Jira priority.
"""
if priority in ("Blocker", "Critical"):
return "Highest"
elif priority == "Major":
return "High"
elif priority == "Minor":
return "Low"
elif priority == "Trivial":
return "Lowest"
return priority |
def colorFromAngle(angle):
"""
Converts numbers into colors for shading effects.
"""
return (int(230*(angle/450)), int(230*(angle/450)), 250) |
def read_template(file_name):
"""reads the tex content from a file and returns it as a string"""
# open file
with open(file_name, 'r') as file:
# skip lines until we read a latex comment marker
for line in file:
if len(line) > 0 and line[0] == '%': break
# add lines to the template until we read a python docstring marker
template = ""
for line in file:
if len(line) >= 3 and line[0:3] == '"""': break
template += line
# return template
return template |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
"""
if values:
v = values[0]
if isinstance(v, dict):
v = v.get('value', '')
if strip:
v = v.strip()
return v |
def make_twin(indices):
"""
Swaps to interfaces to give the tuple with opposite orientation. That is given a triangle with orientation
(i,j,k) this function return the same triangle with orientation (j,i,k)
:param indices:
:return:
"""
return indices[1], indices[0], indices[2] |
def grounding_dict_to_list(groundings):
"""Transform the webservice response into a flat list."""
all_grounding_lists = []
for entry in groundings:
grounding_list = []
for grounding_dict in entry:
grounding_list.append((grounding_dict['grounding'],
grounding_dict['score']))
grounding_list = sorted(grounding_list, key=lambda x: x[1],
reverse=True)
all_grounding_lists.append(grounding_list)
return all_grounding_lists |
def p_dict_has_key( dct, key ):
""" If `dct` is a dictionary AND has the `key`, then return True, Otherwise return False """
return ( isinstance( dct, dict ) and (key in dct) ) |
def strip_suffix(string_in, suffix):
"""
Strip a suffix from a string
"""
if string_in.endswith(suffix):
return string_in[:-len(suffix)]
return string_in |
def get_side(a, b, p):
"""Get which side cone is on relative to vehicle absolute coordinates"""
return (p[0]-a[0])*(b[1]-a[1]) - (p[1]-a[1])*(b[0]-a[0]) |
def check_list(in_lst, dtype=str):
"""Helper function to ensure input is a list of correct data type."""
assert isinstance(in_lst, (list, dtype, tuple))
if isinstance(in_lst, list):
for itm in in_lst:
assert isinstance(itm, dtype)
else:
in_lst = [in_lst]
return in_lst |
def infer_records(columns):
""" inferring all entity records of a sentence
Args:
columns: columns of a sentence in iob2 format
Returns:
entity record in gave sentence
"""
records = dict()
for col in columns:
start = 0
while start < len(col):
end = start + 1
if col[start][0] == 'B':
while end < len(col) and col[end][0] == 'I':
end += 1
records[(start, end)] = col[start][2:]
start = end
return records |
def zero_pad_value(value: int) -> str:
"""
Zero pad the provided value and return string.
"""
return "0" + str(value) if value < 10 else str(value) |
def Interpolator(X, Y, TimeleftIndex, TimeRightIndex,YValue):
"""
Interpolate exact time Y == YValue using 4 points around closest data point to YValue
Returns a tuple with time and error associated.
"""
Y1 = Y[TimeleftIndex]
Y2 = Y[TimeRightIndex]
X2 = X[TimeRightIndex]
X1 = X[TimeleftIndex]
slope = (Y2 - Y1) / (X2 - X1)
if slope != 0:
X0 = (YValue - Y1) / slope + X1
return X0
else:
return 0 |
def clean_bath_text(x):
"""
Cleanes the bathrooms_text field from AirBnB datasource.
This has only been tested for data obtained from Washington DC. For a new city you may need to update the list.
x = is the input of the bathroom_text field.
"""
if isinstance(x, str):
return(x.replace("shared", '').replace("private", "").replace("baths", "").replace("bath", "").replace("Half-", "").replace("Shared half-", "").replace("Private half-", ""))
return(x) |
def SplitRange(regression):
"""Splits a range as retrieved from clusterfuzz.
Args:
regression: A string in format 'r1234:r5678'.
Returns:
A list containing two numbers represented in string, for example
['1234','5678'].
"""
if not regression:
return None
revisions = regression.split(':')
# If regression information is not available, return none.
if len(revisions) != 2:
return None
range_start = revisions[0]
range_end = revisions[1]
# Strip 'r' off the range start/end. Not using lstrip to avoid the case when
# the range is in git hash and it starts with 'r'.
if range_start.startswith('r'):
range_start = range_start[1:]
if range_end.startswith('r'):
range_end = range_end[1:]
return [range_start, range_end] |
def predict_species_orig(sepal_width=None,
petal_length=None,
petal_width=None):
""" Predictor for species from model/52952081035d07727e01d836
Predictive model by BigML - Machine Learning Made Easy
"""
if (petal_width is None):
return u'Iris-virginica'
if (petal_width > 0.8):
if (petal_width <= 1.75):
if (petal_length is None):
return u'Iris-versicolor'
if (petal_length > 4.95):
if (petal_width <= 1.55):
return u'Iris-virginica'
if (petal_width > 1.55):
if (petal_length > 5.45):
return u'Iris-virginica'
if (petal_length <= 5.45):
return u'Iris-versicolor'
if (petal_length <= 4.95):
if (petal_width <= 1.65):
return u'Iris-versicolor'
if (petal_width > 1.65):
return u'Iris-virginica'
if (petal_width > 1.75):
if (petal_length is None):
return u'Iris-virginica'
if (petal_length > 4.85):
return u'Iris-virginica'
if (petal_length <= 4.85):
if (sepal_width is None):
return u'Iris-virginica'
if (sepal_width <= 3.1):
return u'Iris-virginica'
if (sepal_width > 3.1):
return u'Iris-versicolor'
if (petal_width <= 0.8):
return u'Iris-setosa' |
def skip_if(cursor, offset, date_key):
"""Return True if we want to skip a particular date"""
# Useful to skip work that already has been done
return int(date_key) < 20191228 |
def repr_format(obj, *args, **kwargs):
"""
Helper function to format objects into strings in the format of:
ClassName(param1=value1, param2=value2, ...)
:param obj: Object to get the class name from
:param args: Optional tuples of (param_name, value) which will ensure ordering during format
:param kwargs: Other keyword args to populate with
:return: String which represents the object
"""
items = args + tuple(kwargs.items())
inner = ", ".join("{}={!r}".format(k, v) for k, v in items)
return "{}({})".format(obj.__class__.__name__, inner) |
def clamp(value, range_min, range_max):
"""Clamp a value within a range."""
return min(max(value, range_min), range_max) |
def myfunction(x):
"""Return the square of the value."""
if isinstance(x, int):
xx = x * x
else:
xx = None
return xx |
def group_episodes_by_writer(episodes):
"""Utilizes a dictionary to group individual episodes by a contributing writer. The writer's
name comprises the key and the associated value comprises a list of one or more episode
dictionaries. Duplicate keys are NOT permitted.
Format:
{
< writer name >: [{< episode_01 >}, {< episode_02 >}, ...],
< writer name >: [{< episode_01 >}, {< episode_02 >}, ...],
...
}
Parameters:
episodes (list): nested episode dictionaries
Returns:
dict: a dictionary that groups episodes by a contributing writer
"""
result = {}
for ep in range(len(episodes)):
print(episodes[ep]['episode_writers'])
for write in episodes[ep]['episode_writers']:
if write in result:
result[write] += [(episodes[ep])]
else:
result[write] = [(episodes[ep])]
return result |
def base_name(name):
"""Returns name without overload index.
"""
i = name.find('_')
if i != -1:
return name[:i]
return name |
def isequal(angle, X, dx):
"""isequal function. Is angle equal X?"""
try:
if float(angle) == X:
return True
else:
return False
except ValueError:
return False |
def calculate_relative_enrichments(results, total_pathways_by_resource):
"""Calculate relative enrichment of pathways (enriched pathways/total pathways).
:param dict results: result enrichment
:param dict total_pathways_by_resource: resource to number of pathways
:rtype: dict
"""
return {
resource: len(enriched_pathways) / total_pathways_by_resource[resource]
for resource, enriched_pathways in results.items()
} |
def get_source_location_by_offset(source: str, offset: int) -> int:
"""Retrieve the Solidity source code location based on the source map
offset.
:param source: The Solidity source to analyze
:param offset: The source map's offset
:return: The offset's source line number equivalent
"""
return source.encode("utf-8")[0:offset].count("\n".encode("utf-8")) + 1 |
def get_val(d, keys):
"""Helper for getting nested values from a dict based on a list of keys."""
for key in keys:
d = d[key]
return d |
def mysql_stat(server, args_array, **kwargs):
"""Method: mysql_stat
Description: Function stub holder for mysql_perf.mysql_stat.
Arguments:
(input) server -> Server instance.
(input) args_array -> Stub holder for dictionary of args.
(input) **kwargs
class_cfg -> Stub holder for Mongo configuration.
"""
status = True
mongo_cfg = kwargs.get("class_cfg", None)
if server and args_array and mongo_cfg:
status = True
return status |
def isinstancetype(__type, type_class):
"""Recursive isinstance for types."""
__t = __type
while __t is not None:
if isinstance(__t, type_class):
return True
__t = __t.parent
return False |
def _search_for_existing_group(user, group):
"""Test if a group with a given source tag that the user is a member of already exists in the organization.
This is used to determine if the group has already been created and if new maps and apps that belong to the same group should be shared to the same group.
Keyword arguments:
user - The gis.User to search through their group membership.
group - The original group used to determine if it has already been cloned in the organization."""
existing_group = None
if 'groups' in user and user['groups'] is not None:
groups = [g for g in user['groups'] if "source-{0}".format(group['id']) in g['tags']]
if len(groups) > 0:
existing_group = max(groups, key=lambda x: x['created'])
return existing_group |
def slash_escape(err):
""" codecs error handler. err is UnicodeDecode instance. return
a tuple with a replacement for the unencodable part of the input
and a position where encoding should continue"""
# print err, dir(err), err.start, err.end, err.object[:err.start]
thebyte = err.object[err.start:err.end]
repl = u'\\x' + hex(ord(thebyte))[2:]
return (repl, err.end) |
def add_scores ( sumscores, scores ):
"""Calculate the avg scores for each positions in a width window.
"""
n = len(scores)
for score_win in scores:
for (p,s) in score_win:
sumscores[p-1] += s
return True |
def filter_candidates(text, candidates):
"""
Filters completion candidates by the text being entered.
"""
return [x for x in candidates if x.startswith(text)] |
def countWords(text:str)->dict:
"""Prototype of a function counting number of appeareances of words in a text."""
word_count = {}
text = text.lower() # to prevent counting We and we as different words
skips = [".",",",";",":","'"]
for character in skips:
text = text.replace(character,"")
for word in text.split(" "):
if word in word_count.keys(): # the parenthesis are necessary!
word_count[word] += 1
else:
word_count[word] = 1
return word_count |
def string_from_ids(ids):
"""
Concatenates the ids with ',' to do only one request for all ids
@:return
A concatenated string
"""
return ','.join(ids) |
def format_template(template: str, values: dict) -> str:
"""
Function to process `for` loops in our own simple
template language. Use for loops as so:
{{ for item in list }}
...
{{ endfor }}
"""
loop = ""
loop_elem = ""
loop_iter = ""
in_loop = False
output = ""
for line in template.splitlines(keepends=True):
# Check if starting a loop.
if line.strip().startswith(r"{{ for"):
in_loop = True
# Strip spaces and braces, and parse the `for` statement.
parsed = line.strip("}{ \t\r\n").lstrip("for").split("in")
loop_elem = parsed[0].strip()
loop_iter = parsed[1].strip()
continue
# Check if done with a loop.
if line.strip().startswith(r"{{ endfor }}"):
# Render the contents of the loop now.
for x in values[loop_iter]:
output += loop.format(**{loop_elem: x})
# Reset and then exit the loop.
in_loop = False
loop = ""
continue
# Format the current line or load it into a loop.
if in_loop:
loop += line
else:
output += line.format(**values)
return output |
def _method_info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keyword args:
a foo=bar -> method('a', foo='bar')
- using more of the above
1234 'extras=["r2"]' -> method(1234, extras=["r2"])
@param argv {list} Command line arg list. Defaults to `sys.argv`.
@returns (<method-name>, <args>, <kwargs>)
Reference: http://code.activestate.com/recipes/577122-transform-command-line-arguments-to-args-and-kwarg/
"""
import json
import sys
if argv is None:
argv = sys.argv
method_name, arg_strs = argv[0], argv[1:]
args = []
kwargs = {}
for s in arg_strs:
if s.count('=') == 1:
key, value = s.split('=', 1)
else:
key, value = None, s
try:
value = json.loads(value)
except ValueError:
pass
if key:
kwargs[key] = value
else:
args.append(value)
return method_name, args, kwargs |
def splitFilename(filename):
"""
Pass in a standard style rpm fullname
Return a name, version, release, epoch, arch, e.g.::
foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
"""
if filename[-4:] == '.rpm':
filename = filename[:-4]
archIndex = filename.rfind('.')
arch = filename[archIndex+1:]
relIndex = filename[:archIndex].rfind('-')
rel = filename[relIndex+1:archIndex]
verIndex = filename[:relIndex].rfind('-')
ver = filename[verIndex+1:relIndex]
epochIndex = filename.find(':')
if epochIndex == -1:
epoch = ''
else:
epoch = filename[:epochIndex]
name = filename[epochIndex + 1:verIndex]
return name, ver, rel, epoch, arch |
def asFloatOrNone(val):
"""Converts floats, integers and string representations of either to floats.
If val is "NaN" (case irrelevant) or "?" returns None.
Raises ValueError or TypeError for all other values
"""
# check for NaN first in case ieee floating point is in use
# (in which case float(val) would return something instead of failing)
if hasattr(val, "lower") and val.lower() in ("nan", "?"):
return None
else:
return float(val) |
def adjust_cluster_indices(clusters, subtoken_map, sent_start, sent_end):
"""
Adjust cluster indices to reflect their position within an individual sentence.
"""
adjusted_clusters = []
for cluster in clusters:
for span in cluster:
if span[0] >= sent_start and span[1] <= sent_end:
adjusted_start = subtoken_map[span[0]] - subtoken_map[sent_start]
adjusted_end = subtoken_map[span[1]] - subtoken_map[sent_start]
adjusted_clusters.append((adjusted_start, adjusted_end))
return adjusted_clusters |
def parse_int(s):
"""
trim alphabets
"""
return int(float(''.join(i for i in s if (not i.isalpha())))) |
def from_python(value):
"""
Returns value prepared for storage. This is required for search because
some Python types cannot be converted to string and back without changes
in semantics, e.g. bools (True-->"True"-->True and False-->"False"-->True)
and NoneType (None-->"None"-->"None")::
>>> from pyrant.utils import from_python
>>> bool(None) == bool(str(from_python(None)))
True
>>> bool(True) == bool(str(from_python(True)))
True
>>> bool(False) == bool(str(from_python(False)))
True
Such behaviour is achieved this way::
>>> from_python('text')
'text'
>>> from_python(0)
0
>>> from_python(123)
123
>>> from_python(True)
1
>>> from_python(False)
''
>>> from_python(None)
''
Note that we don't convert the value to bytes here, it's done by
pyrant.protocol._pack.
"""
if value is None:
return ''
if isinstance(value, bool):
return 1 if value else ''
return value |
def type_unpack(type):
""" return the struct and the len of a particular type """
type = type.lower()
s = None
l = None
if type == 'short':
s = 'h'
l = 2
elif type == 'ushort':
s = 'H'
l = 2
elif type == 'int':
s = 'i'
l = 4
elif type == 'uint':
s = 'I'
l = 4
elif type == 'long':
s = 'l'
l = 4
elif type == 'ulong':
s = 'L'
l = 4
elif type == 'float':
s = 'f'
l = 4
elif type == 'double':
s = 'd'
l = 8
else:
raise TypeError('Unknown type %s' % type)
return ('<' + s, l) |
def _unique_paths(m: int, n: int, memo = {}):
"""
@ref https://leetcode.com/problems/unique-paths/
@ref https://youtu.be/oBt53YbR9Kk Dynamic Programming - Learn to Solve
Algorithmic Problems & Coding Challenges. freeCodeCamp.com
@details 62. Unique Paths.
How many possible unique paths are there?
08/12/2021 00:18 Accepted 32 ms 14.3 MB python3
"""
if (m < 0 or n < 0):
return 0
if (m == 1 or n == 1):
return 1
if (m, n) in memo:
return memo[(m, n)]
memo[(m, n)] = _unique_paths(m - 1, n, memo) + _unique_paths(m, n - 1, memo)
return memo[(m, n)] |
def parse_float(n):
"""
Securely converts a non-numeric value to float.
"""
try:
return float(n)
except ValueError:
return float("nan") |
def tapcodeConvert(sentence: str, tap: str = " ", sep: str = ".", outputSep: str = " ") -> str:
"""
Convert TapCode to decimal values
Args:
Sentence (String): Tapcode to convert
Tap (String): Tap string ("." by default)
Sep (String): Separator (" " by default)
OutputSep (String): Output separator (" " by default)
Return:
String. Enciphered sentences.
Example:
>>> tapcodeConvert(".. ... . ..... ... . ... . ... ....")
"23 15 31 31 34"
>>> tapcodeConvert("--_---_-_-----_---_-_---_-_---_----", "-", "_")
"23 15 31 31 34"
>>> tapcodeConvert(".. ... . ..... ... . ... . ... ....", outputSep="_")
"23_15_31_31_34"
"""
converted = []
cleaned = ""
# Clean the sentence to just taps and separators
for i in sentence:
if i == tap:
cleaned += i
if i == sep:
cleaned += sep
splited = cleaned.split(sep) # split the cleaned sentence to list of taps
for i in range(1, len(splited), 2):
converted.append(str(len(splited[i - 1])))
converted.append(str(len(splited[i])))
converted.append(outputSep)
# Just like encipher function
if outputSep:
return "".join(converted)[:-(len(sep))]
else:
return "".join(converted) |
def format_number(n, max_length):
"""
Get number in String, in a format fitting in the max_length specified
:param n: number to transform in String
:param max_length: maximum length authorized to display that number
:return: a String representing this number fitting in the desired size
"""
# First, we round the number
s = str(int(n + 0.5))
if len(s) > max_length or abs(n) < 1:
# If the String of the rounded number is bigger than max_length,
# or of the absolute value is < 1, then we return the number using an exponent
return format(n, str(max_length - 3) + ".2G")
else:
# otherwise, we return the rounded number in text
return s |
def distance_helper(initial_velocity, acceleration, time):
"""
Calculates the distance traveled given the initial velocity, acceleration, and time, Helper function to the distance
function.
:param initial_velocity: Integer initial velocity
:param acceleration: Integer acceleration
:param time: Integer time
:return: Integer distance traveled
"""
dist = initial_velocity * time + 0.5 * (acceleration * time ** 2)
return dist |
def get_domain(url):
""" Return the domain part of an url """
# Taken from https://www.quora.com/How-do-I-extract-only-the-domain-name-from-an-URL
if url is None:
return None
return url.split('//')[-1].split('/')[0] |
def compute_energy(moon):
"""
>>> compute_energy([[8,-12,-9], [-7,3,0]])
290
>>> compute_energy([[13,16,-3],[3,11,5]])
608
"""
kin_energy = 0
pot_energy = 0
for i in range(3):
kin_energy += abs(moon[1][i])
pot_energy += abs(moon[0][i])
return kin_energy*pot_energy |
def RemoveNullTokens(in_ptkns):
"""This function just gets rid of useless empty tokens in the path ('', '.')
(However if '' appears at the beginning of a path, we leave it alone.)
"""
out_ptkns = []
for i in range(0, len(in_ptkns)):
if ((in_ptkns[i] != '.') and
((in_ptkns[i] != '') or (i == 0))):
out_ptkns.append(in_ptkns[i])
# (I'm sure there are ways to write this in python
# using fewer lines of code. Sigh.)
return out_ptkns |
def circulate(n):
"""
n: an int or a str of int
output: a set of "circulations" of n, including n itself
note: for definition of circulations, see question
"""
numSet = set()
numStr = str(n)
numLen = len(numStr)
if numLen is 1:
numSet.add(n)
return numSet
for i in range(numLen):
numStr = numStr[1:] + numStr[0]
numSet.add(int(numStr))
return numSet |
def run_length_encode(n):
"""Generates the run-length encoded version of `n`
https://en.wikipedia.org/wiki/Run-length_encoding
"""
prev = None
count = 0
output = []
for d in str(n):
if prev is None:
count = 1
prev = d
elif d == prev:
count += 1
else:
output.extend([str(count), prev])
prev = d
count = 1
if count > 0 and prev is not None:
output.extend([str(count), prev])
encoded = ''.join(output)
return encoded |
def image_name(src):
"""
:param src: path
:return: file name
"""
return src.split('/')[-1] |
def solution(string):
"""Returns a reversed string with built in splice function."""
return(string[::-1]) |
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode("utf-8")
except AttributeError:
return value |
def firewall_rule_group_update_payload(passed_keywords: dict) -> dict:
"""Create a properly formatted firewall rule group payload.
{
"diff_operations": [
{
"from": "string",
"op": "string",
"path": "string"
}
],
"diff_type": "string",
"id": "string",
"rule_ids": [
"string"
],
"rule_versions": [
0
],
"tracking": "string"
}
"""
returned_payload = {}
keys = ["diff_type", "id", "tracking"]
for key in keys:
if passed_keywords.get(key, None):
returned_payload[key] = passed_keywords.get(key, None)
if passed_keywords.get("rule_ids", None):
returned_payload["rule_ids"] = passed_keywords.get("rule_ids", None)
if passed_keywords.get("rule_versions", None):
returned_payload["rule_versions"] = passed_keywords.get("rule_versions", None)
diffs = passed_keywords.get("diff_operations", None)
if diffs:
if isinstance(diffs, list):
returned_payload["diff_operations"] = diffs
else:
returned_payload["diff_operations"] = [diffs]
return returned_payload |
def format_isolate_name(isolate):
"""
Take a complete or partial isolate ``dict`` and return a readable isolate name.
:param isolate: a complete or partial isolate ``dict`` containing ``source_type`` and ``source_name`` fields.
:type isolate: dict
:return: an isolate name
:rtype: str
"""
if not isolate["source_type"] or not isolate["source_name"]:
return "Unnamed Isolate"
return " ".join((isolate["source_type"].capitalize(), isolate["source_name"])) |
def is_wrapped(transformer):
"""Check if a transformer is wrapped.
Args:
transformer: A transformer instance
Returns:
bool: True if transformer is wrapped, otherwise False.
"""
return hasattr(transformer, "is_wrapped") |
def get_cos_theta(s, d):
"""Calculate the cosine of the contact angle.
Args:
s: A float (or numpy array): the spreading coefficient.
d: A float (or numpy array): the drying coefficient.
Returns:
The cosine of the contact angle as a float or numpy array.
"""
return -(s - d) / (s + d) |
def code_snippet(snippet):
"""Change a string-typed code snippet into Markdown-style code fence.
# Argument
snippet: `str`. A code snippet.
# Return
`str`: Markdown-style code fence.
"""
return '```python\n{}\n```'.format(snippet) |
def check_for_victory(board):
"""
the function analyzes the board status in order to check if
the player using 'O's or 'X's has won the game
"""
row_len = len(board)
col_len = len(board[0])
#Row check
for row_list in board:
result = len(row_list) > 0 and all(elem == row_list[0] for elem in row_list)
if result:
return (True, row_list[0])
#Column check
for col_index in range(col_len):
column_lst = []
column_lst.clear()
for row_index in range(row_len):
column_lst.append(board[row_index][col_index])
result = len(column_lst) > 0 and all(elem == column_lst[0] for elem in column_lst)
if result:
return (True, column_lst[0])
#Diagonal check from top-left to bottom right
diag_lst = []
for diag_index in range(row_len):
diag_lst.append(board[diag_index][diag_index])
result = len(diag_lst) > 0 and all(elem == diag_lst[0] for elem in diag_lst)
if result:
return (True, diag_lst[0])
diag_lst.clear()
#Diagonal check from bottom-left to top-right
min_val, max_val = 0, col_len-1
while min_val < col_len-1:
diag_lst.append(board[min_val][max_val])
min_val += 1
max_val -= 1
result = len(diag_lst) > 0 and all(elem == diag_lst[0] for elem in diag_lst)
if result:
return (True, diag_lst[0])
#no one success yet
return (False, " ") |
def dcs_caption_from_id(dcs_id,dcs_json_data):
"""
Find Caption from an DataCore Id
"""
for item in dcs_json_data:
if item["Id"] == dcs_id:
return str(item["Caption"]) |
def boobies(text):
"""- prints boobies!"""
boob = "\u2299"
out = text.strip()
out = out.replace('o', boob).replace('O', boob).replace('0', boob)
if out == text.strip():
return "Sorry I couldn't turn anything in '{}' into boobs for you.".format(out)
return out |
def result_format(task, clf, ftype, fscope, token, partition, res):
"""
Helper function to produce result dictionary (for use in dataframe)
"""
return {
"task": task,
"classifier": clf,
"feature_type": ftype,
"feature_scope": fscope,
"token": token,
"partition": str(int(partition) + 1),
"results": res,
} |
def takeids(cblist, rows_var):
""" Take check button list and returns Employee ids for continue operation.
Show warning message if selected 'all' button for critical operation (flag warning).
Return tuples of (id, rownum) of check button
"""
rowsnum = tuple([i-1 for (i, var) in enumerate(cblist) if var.get()])
ids = tuple([(int(rows_var[i][0].get()), i+1) for i in rowsnum])
return ids |
def map_geometries(func, obj):
"""
Returns the result of passing every geometry in the given geojson object
through func.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: GeoJSON
:return: The result of applying the function to each geometry
:rtype: list
:raises ValueError: if the provided object is not geojson.
"""
simple_types = [
'Point',
'LineString',
'MultiPoint',
'MultiLineString',
'Polygon',
'MultiPolygon',
]
if obj['type'] in simple_types:
return func(obj)
elif obj['type'] == 'GeometryCollection':
geoms = [func(geom) if geom else None for geom in obj['geometries']]
return {'type': obj['type'], 'geometries': geoms}
elif obj['type'] == 'Feature':
geom = func(obj['geometry']) if obj['geometry'] else None
return {
'type': obj['type'],
'geometry': geom,
'properties': obj['properties'],
}
elif obj['type'] == 'FeatureCollection':
feats = [map_geometries(func, feat) for feat in obj['features']]
return {'type': obj['type'], 'features': feats}
else:
raise ValueError("Invalid GeoJSON object %s" % repr(obj)) |
def dlist(src):
"""
Convert dicts with numeric keys to lists
:param src: {"a": {"b": {"0":"red", "1":"blue"}, "c": "foo"}}
:return: {"a": {"b": ["red", "blue"], "c": "foo"}}
"""
if isinstance(src, dict):
for k in src:
src[k] = dlist(src[k])
if set(src) == set([str(k) for k in range(len(src))]):
src = [src[str(k)] for k in range(len(src))]
return src |
def contains_digits(input_str):
"""Receives input string and checks if it contains
one or more digits."""
digi_range = [str(i) for i in range(10)]
return any(c in digi_range for c in list(input_str.lower())) |
def get_remote_file_name(url):
"""Create a file name from the url
Args:
url: file location
Returns:
String representing the filename
"""
array = url.split('/')
name = url
if len(array) > 0:
name = array[-1]
return name |
def _get_docstring_type_name(var_doc: str) -> str:
"""
Get the string of argument or return value type's description
from docstring.
Parameters
----------
var_doc : str
Docstring's part of argument or return value.
Returns
-------
type_name : str
Argument or return value's type description.
"""
type_name: str = var_doc.split('\n')[0]
colon_exists: bool = ':' in type_name
if not colon_exists:
return ''
type_name = type_name.split(':')[1]
type_name = type_name.split(',')[0]
type_name = type_name.strip()
return type_name |
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n**2) As it loops through the whole array for each element
Memory usage: O(1) Sorting is done in place on the array
"""
# Loop through each index
for i in range(len(items)):
# Find the smallest unsorted value
ind = items.index(min(items[i:]), i)
# Switch it with the current index
items[ind], items[i] = items[i], items[ind]
return items |
def show_g(t):
"""[(g,p),[lst]]"""
return (t[0] [0]) |
def abbreviation(a, b):
"""https://www.hackerrank.com/challenges/abbr"""
n = len(b)
m = len(a)
memo = [[False]*(m + 1) for _ in range(n + 1)]
memo[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j > 0:
memo[i][j] = a[j - 1].islower() and memo[i][j - 1]
elif i > 0 and j > 0:
if a[j - 1] == b[i - 1]:
memo[i][j] = memo[i - 1][j - 1]
elif a[j - 1].upper() == b[i - 1]:
memo[i][j] = memo[i - 1][j - 1] or memo[i][j - 1]
elif a[j - 1].islower():
memo[i][j] = memo[i][j - 1]
else:
memo[i][j] = False
return "YES" if memo[n][m] else "NO" |
def escape(s, quote=None):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated."""
s = s.replace('&', '&')
s = s.replace('<', '<')
s = s.replace('>', '>')
if quote:
s = s.replace('"', '"')
return s |
def line_and_column(text, position):
"""Return the line number and column of a position in a string."""
position_counter = 0
for idx_line, line in enumerate(text.splitlines(True)):
if (position_counter + len(line.rstrip())) >= position:
return (idx_line, position - position_counter)
else:
position_counter += len(line) |
def format_size(size: int) -> str:
"""Formats the size of a file into MB
Input:
- size: size of a file in bytes
Output:
- formatted string showing the size of the file in MB
"""
return "%3.1f MB" % (size/1000000) if size is not None else size |
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (1, 5)
elif nyears < 100:
(min_spacing, maj_spacing) = (5, 10)
elif nyears < 200:
(min_spacing, maj_spacing) = (5, 25)
elif nyears < 600:
(min_spacing, maj_spacing) = (10, 50)
else:
factor = nyears // 1000 + 1
(min_spacing, maj_spacing) = (factor * 20, factor * 100)
return (min_spacing, maj_spacing) |
def sortbylength(data, lang_ids, maxlen=500):
"""
:param data: List of tuples of source sentences and morph tags
:param lang_ids: List of lang IDs for each sentence
:param maxlen: Maximum sentence length permitted
:return: Sorted data and sorted langIDs
"""
src = [elem[0] for elem in data]
tgt = [elem[1] for elem in data]
indexed_src = [(i,src[i]) for i in range(len(src))]
sorted_indexed_src = sorted(indexed_src, key=lambda x: -len(x[1]))
sorted_src = [item[1] for item in sorted_indexed_src if len(item[1])<maxlen]
sort_order = [item[0] for item in sorted_indexed_src if len(item[1])<maxlen]
sorted_tgt = [tgt[i] for i in sort_order]
sorted_lang_ids = [lang_ids[i] for i in sort_order]
sorted_data = [(src, tgt) for src, tgt in zip(sorted_src, sorted_tgt)]
return sorted_data, sorted_lang_ids |
def sqlInsertStrFromList (table,aList,dbType='postgres'):
"""Take a list and make an insert string.
This works with dictionaries too. Here is a quick example:
>>> aList = [('one',1),('2','two'),('threepoint',3.)]
>>> sqlInsertStrFromList('myTable',aList,dbType='sqlite')
"insert into myTable (one,2,threepoint) values (1,'two',3.0);"
>>> sqlInsertStrFromList('myTable',aList)
"insert into mytable (one,2,threepoint) values (1,'two',3.0);"
@param table: Which table to insert into
@type table: str
@param aList: list of tubles pairs to insert - (name, value)
@type aList(list)
@return: complete SQL insert command
@rtype: str
"""
if 'postgres'==dbType: table = table.lower()
ins = "insert into " + table + " ("
first = []
if 'postgres'==dbType: first = [f[0].lower() for f in aList]
else: first = [f[0] for f in aList]
ins += ','.join(first) + ") values ("
first=True
for pair in aList:
value = pair[1]
if first: first=False
else: ins+=","
# Make sure to quote all strings and timestamps
# print type(value)
# <type 'DateTime'>
# What way is better to handle this?
#if type(value) == str or type(value) == type(datetime()): ins+="'"
if type(value)!=int and type(value)!=float: ins+="'"
ins+=str(value)
if type(value)!=int and type(value)!=float: ins+="'"
ins += ");"
return ins |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.