content
stringlengths
42
6.51k
def _clean_annotated_text(text): """Cleans text from the format that it was presented to annotators in the S.M.A.R.T data annotation tool. Splits the title from the abstract text and strips any trailing whitespace. Returns: title (str): The project title text (str): The project abstract """ text = text.split('=====') title = text[1].strip() abstract = text[-1].strip() return title, abstract
def populate_item_object_ref_paths(set_items, obj_selector): """ Called when include_set_item_ref_paths is set. Add a field ref_path to each item in set """ for set_item in set_items: set_item["ref_path"] = obj_selector['ref'] + ';' + set_item['ref'] return set_items
def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) [2, 8] >>> solution(15) [2, 8] >>> solution(2) [2] >>> solution(1) [] >>> solution(34) [2, 8, 34] """ ls = [] a, b = 0, 1 while b <= n: if b % 2 == 0: ls.append(b) a, b = b, a + b return ls
def repeat(s, exclaim): """ Repeat the String 's' three times, If the exclaim is true, it will add ! at the end """ result = s * 3 #append s back to back three times. if exclaim: result = result + '!!!' return result
def dtd_correction(params): """ When normalizing DTDs to 1 sometimes a correction factor is needed, caused by the uncertainty in the value of the integral of the DTD for the whole mass range """ if "dtd_correction_factor" in params: return params["dtd_correction_factor"] return 1.0
def fib_dp(n): """ An optimized dynamic programming solution to find a single number of the Fibonacci sequence. It runs in O(n) time with O(1) space complexity. """ if not isinstance(n, int): raise TypeError("n must be an int") if n < 0: raise ValueError("n must be non-negative") f0, f1 = 0, 1 for _ in range(n): f0, f1 = f1, f0 + f1 return f0
def file_contents(filename): """Return the contents of filename.""" f = open(filename, 'r') contents = f.read() f.close() return contents
def bitCount(int_type): """ Count bits set in integer """ count = 0 while(int_type): int_type &= int_type - 1 count += 1 return(count)
def encode_boolean(value): """ Returns 1 or 0 if the value is True or False. None gets interpreted as False. Otherwise, the original value is returned. """ if value is True: return 1 if value is False or value is None: return 0 return value
def get_full_class_name(object_instance): """ Returns full class name :param object_instance: object instance """ return object_instance.__module__ + "." + object_instance.__name__
def derivative_nk(nkb_average, nkt): """Gera d_nk""" return (nkb_average - nkt) / nkt
def is_256_bit_imm(n): """Is n a 256-bit number?""" return type(n) == int and n >= 0 and 1 << 256 > n
def _set_loc_key(d, k, value): """Set key ``k`` in ``d`` to ``value```.""" if not value: return None if k in d: try: d[k].union(value.copy()) except KeyError as e: raise KeyError('Problem at location {}: {}'.format(k, str(e))) else: d[k] = value.copy()
def strip_comments(s): """Strips comment lines and docstring from Python source string.""" o = '' in_docstring = False for l in s.split('\n'): if l.strip().startswith(('#', '"', "'")) or in_docstring: in_docstring = l.strip().startswith(('"""', "'''")) + in_docstring == 1 continue o += l + '\n' return o
def data_to_rows(data): """Unzip column-wise data from doc._.data into rows""" col_data = [data[key] for key in data.keys()] row_data = list(zip(*col_data)) return row_data
def get_unique_mask_name(task_type: str, mask_name: str) -> str: """Prepends the task name to the mask name to ensure uniqueness. Args: task_type: Name of the task for which the masks are being modified. mask_name: Name of the mask e.g. base_eval. Returns: A mask name that has the task name prepended. Example: los_base_eval. """ unique_mask_name = mask_name if task_type not in mask_name: unique_mask_name = "_".join([task_type, mask_name]) return unique_mask_name
def ok(message, data=None, http_status_code=200, **kwargs): """ used when no error :param message: some message :param data: data for return :param http_status_code: http status code :param kwargs: other data for return :return: """ return {"message": message, "data": data, **kwargs}, http_status_code
def average_above_zero (items): """ Compute the average of an given array only for positive values. @type items: list @param items: List of positive values @rtype: float @return: Return the average of the list """ # Don't compute if items isn't an List (array) if type(items) is not list: raise TypeError('Type of items param need to be \'list\' and not ' + str(type(items))) average = -1 sum = 0 items_length = len(items) # Don't compute if items is empty if items_length > 0: for item in items: if (type(item) is float or type(item) is int) and item >= 0: sum += float(item) else: # Remove 1 to items_length if item isn't an positive value items_length -= 1 average = sum / items_length else: raise ValueError('Items list must not be empty') return average
def date_weekday_excel(x) : """function date_weekday_excel Args: x: Returns: """ import datetime date = datetime.datetime.strptime(x,"%Y%m%d") wday = date.weekday() if wday != 7 : return wday+1 else : return 1
def _ds(s): """Decode a bytestring for printing""" return s.decode("utf-8", "backslashreplace")
def return_repeating_word(values): """A helper function for read_line(). Address issues where word has repeating chargers, return them as a single word. :param values: values, a line of embedding text data :return: A string of repeating characters. """ word = [] first_char = values[0] counter = 1 word.append(first_char) # while values: for idx, char in enumerate(values[1:]): counter += 1 curr_char = char if curr_char == first_char: word.append(curr_char) else: break word = ''.join(map(str, word)) return word, counter
def is_label_or_synonym(labels, provided_label): """Determine if a user-provided ontology label is a valid label or synonymn :param labels: cached ontology label/synonyms from retriever.retrieve_ontology_term_label_and_synonyms :param provided_label: user-provided label from metadata file :return: True/False on match for label or synonym """ label = labels.get('label') synonyms = labels.get('synonyms') if label.casefold() == provided_label.casefold(): return True elif synonyms: if next((t for t in synonyms if t.casefold() == provided_label.casefold()), ''): return True else: return False else: return False
def _get_persons(event): """Get string of persons from event""" persons = [] for person in event['persons']: persons.append(person['public_name']) return ', '.join(persons)
def trim_data(data, xy, p = 0.1): """ RIGHT FROM iREP remove data from ends of sorted list """ if xy is False: length = len(data) num = int(length * (p/2)) return data[num:length - num] X, Y = data length = len(X) num = int(length * (p/2)) return X[num:length - num], Y[num:length - num]
def randSeed(val): """ validates the range of random seed""" if type(val) == int and 0 <= val < 2**32: return val else: raise ValueError("0 <= random seed < 2^32 is the correct range")
def is_valid_hour(seconds): """Check if the provided seconds is a valid hour. :seconds: provided seconds value """ if seconds % 3600 == 0: return True return False
def map_llc_result_to_dictionary_list(land_charge_result): """Produce a list of jsonable dictionaries of an alchemy result set """ if not isinstance(land_charge_result, list): return list(map(lambda land_charge: land_charge.to_dict(), [land_charge_result])) else: return list(map(lambda land_charge: land_charge.to_dict(), land_charge_result))
def bboxArea(a): """ box area :param a: :return: """ return (a[2] - a[0]) * (a[3] - a[1])
def tf_idf_vector(term_frequency, idf): """Calculates tf/idf vector""" try: return term_frequency * idf except ZeroDivisionError: return 0
def format_variable_name(name): """ Format Python variable name to LaTeX variable name Remove underscores and case the first letter of each word. """ return name.replace("_", " ").title().replace(" ", "")
def error(*_): """ System method :return: dict """ return {'type': 'error', 'data': 'Bad request'}
def folder( path ): """Extracts the resource folder.""" return path[:1+path.rfind('/')]
def mock_valid_dropbox_config(): """Mock valid Dropbox config.""" return {"access_token": "XXXXXXX", "upload_directory": "/home/dropbox_user/Documents/"}
def wuyts_line_Av(Acont): """ Wuyts prescription for extra extinction towards nebular emission """ return Acont + 0.9*Acont - 0.15*Acont**2
def _as_list(list_str, delimiter=','): """Return a list of items from a delimited string (after stripping whitespace). :param list_str: string to turn into a list :type list_str: str :param delimiter: split the string on this :type delimiter: str :return: string converted to a list :rtype: list """ return [str.strip(item).rstrip() for item in list_str.split(delimiter)]
def _word_to_bool(word): """convert a string to boolean according the first 2 characters.""" _accepted_bool_prefixes = ("T", ".T") return word.upper().startswith(_accepted_bool_prefixes)
def all_same(L): """Check if all elements in list are equal. Parameters ---------- L : array-like, shape (n,) List of objects of any type. Returns ------- y : bool True if all elements are equal. """ y = len(L) == 0 or all(x == L[0] for x in L) return y
def dt_dosage(value, member_id=None): """ Format Dosage Complex data type :param value: :return: f_value """ f_value = "" for v in value: if isinstance(v, int) or isinstance(v, float): if v == 0: pass else: f_value += str(v) + " " elif isinstance(v, str): if 'http' in v.lower(): pass else: f_value += str(v) + " " elif isinstance(v, dict): for d, vv in v.items(): if isinstance(vv, int) or isinstance(vv, float): if vv == 0: pass else: f_value += str(vv) + " " elif isinstance(vv, str): if 'http' in vv.lower(): pass else: f_value += str(vv) + " " return f_value
def prime_check(n): """Return True if n is a prime number Else return False. ##------------------------------------------------------------------- """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 return True
def rem(x, a): """ Parameters ---------- x : a non-negative integer argument a : a positive integer argument Returns ------- integer, the remainder when x is divided by a """ if x == a: return 0 elif x < a: return x else: return rem(x-a, a)
def shake_shake_eval(xa, xb): """Shake-shake regularization: evaluation. Args: xa: input, branch A xb: input, branch B Returns: Mix of input branches """ # Blend between inputs A and B 50%-50%. return (xa + xb) * 0.5
def expand_year(year): """Convert 2-digit year to 4-digit year.""" if year < 80: return 2000 + year else: return 1900 + year
def __get_pod_service_list(pod_items): """ Returns a set of pod service_account names from the pod_list parameter :param pod_items: the list of pod_items from which to extract the name :return: set of pod names """ out_names = set() for pod_item in pod_items: if pod_item.spec.service_account: out_names.add(pod_item.spec.service_account) else: out_names.add(pod_item.metadata.name) return out_names
def insert_at(alist, i, x): """This function returns a new list, with x inserted at location i """ # CHANGE OR REMOVE THE LINE BELOW return alist[:i] + [x] + alist[(i+1):]
def shift_list(array, s): """Shifts the elements of a list to the left or right.""" s %= len(array) s *= -1 shifted_array = array[s:] + array[:s] return shifted_array
def arg01_to_bool(args, argName): """ This function takes {request.args} and check if the argName is 1 or 0.\n If argName is "1", it returns True.\n If argname is "0", it returns False.\n And if it is anything else, or if it does not exist, it returns False aswell. """ if str(argName) in args: if str(args[str(argName)]) == "1": return True if str(args[str(argName)]) == "0": return False return False
def _check_dof(dof): """Check the user provided 'dofs'. Parameters ---------- dofs : array-like, shape (n_components,) The degrees-of-freedom of each mixture. n_components : int Number of components. Returns ------- weights : array, shape (n_components,) """ # check range if dof < 2: raise ValueError("The parameter 'dof' should be in the range " "[2, inf), but got min value %.5f" % dof) return dof
def checkForTextHavingOnlyGivenChars(text, ws=None): """Checks whether text contains only whitespace (or other chars). Does the given text contain anything other than the ws characters? Return true if text is only ws characters. """ if ws is None: return text.isspace() else: for char in text: if char not in ws: return False else: return True
def getElevations(trackSegments): """returns array of elevations in metres from trackSegments""" elevations = [] for seg in trackSegments: elevations.append([float(item.get("ele")) for item in seg]) return elevations
def latex_format_e(num, pre=2): """Format a number for nice latex presentation, the number will *not* be enclosed in $""" s = ("{:." + "{:d}".format(pre) + "e}").format(num) fp, xp = s.split("e+") return "{} \\times 10^{{{}}}".format(fp, int(xp))
def replace_prefix(text, find, replace): """Replace all leading instances of a string with another string. Args: text (str): Text to screw with find (str): Characters to replace replace (str): Characters to replace with Returns: str: `text` with all leading instances of `find` replaced with `replace` """ leading_count = len(text) - len(text.lstrip(find)) return replace*leading_count + text.lstrip(find)
def is_freq(*args): """Determine if input args require FreqPart""" is_freq = False if len(args) == 1 and type(args[0]) == tuple: args = args[0] # if called from another script with *args for arg in args: if "freqs" in arg or "wavenumber" in arg: is_freq = True break return is_freq
def isnumber(x): """Returns True, if x is a number (i.e. can be converted to float).""" if x is None: return False try: float(x) return True except ValueError: return False
def one_list_to_val(val, convert_tuple=False): """ Convert a single list element to val :param val: :return: """ if isinstance(val, (list, tuple) if convert_tuple else (list,)) and len(val) == 1: result = val[0] else: result = val return result
def urlify(string, length): """ Replace single spaces with %20 and remove trailing spaces Time complexity: O(N) Space complexity: O(1): in-place """ new_index = len(string) # This is the actual length including trailing spaces to hold the additional character for i in reversed(range(length)): # It's easiest to modify strings by going from the end of the string to the beginning if string[i] != ' ': string[new_index - 1] = string[i] # Shift character to the end of string new_index -= 1 else: string[new_index - 3:new_index] = '%20' # Replace spaces new_index -= 3 return string
def to_int(rating_count): """ Return rating count as an int """ rating_count = rating_count.split()[0] if ',' in rating_count: return int(rating_count.replace(',', '')) return int(rating_count)
def space_separated_elements(array): """Converts the question_tags array to a space delimited string.""" string = "" for element in array: string = string + element + " " return string
def dot_product(vector1, vector2): """ Computes the dot product. param list vector1, vector2: input vectors """ result = sum([x*y for x, y in zip(vector1, vector2)]) return result
def wind_vref_5vave(vave, factor=5): """ It calculates the 50 year return expected maximum wind speed as 5 times the long term average wind speed. It uses 10-minute wind speeds to obtain the 50-year return period extreme wind speed. **Parameters** vave : float or int Long term mean wind speed factor : float or int Factor used to obtain vref. Default value is 5. **Returns** vref : float vref wind speed, i.e., 50 years expected maximum wind speed in the same units used by the vave input parameter. """ return float(factor) * vave
def xyz_to_XYZ(v): """ convert xyz to XYZ """ V = [(1.0/v[1])*v[0], 1.0,(1.0/v[1])*v[2]] #print "XYZ val:",V return V
def solution(power): """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2 ** power r = 0 while n: r, n = r + n % 10, n // 10 return r
def check_all_rows(A): """ Check if all rows in 2-dimensional matrix don't have more than one queen """ for row_inx in range(len(A)): # compute sum of row row_inx if sum(A[row_inx]) > 1: return False return True
def add_to_sparse_tuple(tpl, index, new_value): """ Return a new tuple based on tpl with new_value added at the given index. The tuple is either expanded with ``None`` values to match the new size required or the value is replaced. :: >>> t = add_to_sparse_tuple(('a', 'b'), 5, 'f') >>> print(t) ('a', 'b', None, None, None, 'f') >>> t = add_to_sparse_tuple(('a', 'b'), 3, 'd') >>> print(t) ('a', 'b', None, 'd', None, 'f') This function does not replace existing values in the tuple. :: >>> t = add_to_sparse_tuple(('a', 'b'), 0, 'A') AssertionError blah blah """ l = [None] * max(len(tpl), index + 1) for i, v in enumerate(tpl): l[i] = v assert l[index] is None l[index] = new_value return tuple(l)
def _allocation_type(action) -> tuple: """Get details of child policy""" allocation = '---' action_type = '---' if action.get("action-type",{}) == 'shape': if 'bit-rate' in action.get('shape',{}).get('average',{}): allocation = str(round(int(action.get("shape",{}).get("average",{}).get("bit-rate",{})) / 1e+6)) + " Mbps" elif 'percent' in action.get('shape',{}).get('average'): allocation = str(action.get("shape",{}).get("average",{}).get("percent",{})) + "%" elif action.get("action-type",{}) == 'bandwidth': if 'kilo-bits' in action.get('bandwidth', {}): allocation = str(round(int(action.get("bandwidth",{}).get("kilo-bits",{})) * 1000 / 1e+6)) + " Mbps" elif 'percent' in action.get('bandwidth', {}): allocation = str(action.get("bandwidth",{}).get("percent",{})) + '%' elif action.get("action-type",{}) == 'priority': if 'kilo-bits' in action.get('priority', {}): allocation = str(round(int(action.get("priority",{}).get("kilo-bits",{})) * 1000 / 1e+6)) + " Mbps" elif 'percent' in action.get('priority', {}): allocation = str(action.get("priority",{}).get("percent",{})) + '%' elif action.get("action-type",{}) == 'set': if 'dscp-val' in action.get('set', {}).get('dscp', {}): allocation = action.get('set', {}).get('dscp', {}).get('dscp-val') if action.get("action-type",{}) == 'service-policy': action_type = 'service-policy' elif action.get("action-type",{}) == 'random-detect': action_type = 'fair-queue' elif action.get("action-type",{}) == 'fair-queue': action_type = 'fair-queue' return allocation, action_type
def validate_input(cents: int, exceptions_on: bool=True): """Validates user input cents. Checks to make sure input is an integer and is a valid cents value. If it is, the value is returned. If it isn't, an exception is raised and None is returned. Parameters: cents (int): The cents input to validate. exceptions_on: Whether to raise exceptions on error. Defaults to True. Returns: (int): The cents input if valid. None if not. Exceptions: ValueError: If value does not pass validation checks. TypeError: If value is not an integer. Examples: >>> validate_input(100, False) 100 >>> validate_input("100", False) >>> validate_input("-1", False) >>> validate_input("abcdefg", False) """ # Checking for integer value should happen during function call, # thanks to type hinting. However, just to be absolutely sure, and # to facilitate doctesting, check the types here explicitly. if not (isinstance(cents, int)): if exceptions_on: raise TypeError("Cents must be integers.") return None # Integer must be positive or zero if not cents >= 0: if exceptions_on: raise ValueError("Negative cents values are invalid.") return None return cents
def get_boolean(value): """ Return a bool from value. Args: value: A string or bool representing a boolean. Returns: If value is a bool, value is returned without modification. If value is a string this will convert 'true' and 'false' (ignoring case) to their associated values. Raises: ValueError if value does not match one of the string tests and is not a bool. """ if type(value) is not bool: value = value.lower() if value == 'true': value = True elif value == 'false': value = False else: raise ValueError("Boolean value was not valid") return value
def transliterate(trans, item): """Transliterates string, list of strings and list of list of strings""" if isinstance(item, str): return trans.get(item, item) if isinstance(item, list) and len(item) > 0: if isinstance(item[0], str): return [trans.get(i, i) for i in item] if isinstance(item[0], list): return [[trans.get(i, i) for i in first] for first in item] return item
def parse_filename(filename): """Returns the separate directory, basename, and file suffix for the given filename. Parameters ---------- filename : str Name of a file. Returns ------- directory : str Directory containing the file. basename : str Name of file, without any suffix. suffix : str Suffix of the file, normally the file type (e.g. txt, tgz, wav) """ directory = "" suffix = "" basename = "" data = filename.split('/') data = [x for x in data if x] if len(data) > 1: directory = "/".join(data[:-1]) directory = directory + "/" if filename.startswith("/"): directory = "/" + directory data = data[-1].split('.') basename = data[0] if len(data) > 1: suffix = ".".join(data[1:]) return directory, basename, suffix
def _set_cache_value(key, value): """ Sets or updates the value for a cache key """ with open(key, 'w') as f: f.seek(0) f.write(str(value)) return value
def prime_out(num): """prime_out: A user-friendly tool to evaluate whether or not a number is prime. Args: num (int): Number to be evaluated as prime Returns: Prints whether or not the number is prime and how long it took to evaluate. """ import time t1_start = time.perf_counter() t2_start = time.process_time() strnum = str(num) count = num - 1 print("Calculating whether " + strnum + " is prime...") def remain (div): strdiv = str(div) foo = num % div if foo == 0: print (strnum +" is divisible by " + strdiv) return True else: return False while count > 1: if remain (count): t1_stop = time.perf_counter() t2_stop = time.process_time() print(strnum + " isn't Prime. Done! ") print("--------------------------------------------------") print("Elapsed time: %.1f [sec]" % ((t1_stop-t1_start))) print("or %.1f [min]" % ((t1_stop-t1_start)/60)) print("CPU process time: %.1f [sec]" % ((t2_stop-t2_start))) print("or %.1f [min]" % ((t1_stop-t1_start)/60)) print("--------------------------------------------------") return else: count = count - 1 t1_stop = time.perf_counter() t2_stop = time.process_time() print (strnum + " is prime! Done! ") print("--------------------------------------------------") print("Elapsed time: %.1f [sec]" % ((t1_stop-t1_start))) print("or %.1f [min]" % ((t1_stop-t1_start)/60)) print("CPU process time: %.1f [sec]" % ((t2_stop-t2_start))) print("or %.1f [min]" % ((t1_stop-t1_start)/60)) print("--------------------------------------------------") return
def capStrLen(string, length): """ Truncates a string to a certain length. Adds '...' if it's too long. Parameters ---------- string : str The string to cap at length l. length : int The maximum length of the string s. """ if length <= 2: raise Exception("l must be at least 3 in utils.capStrLen") if len(string) <= length: return string return string[0 : length - 3] + "..."
def fill(array, value, start=0, end=None): """Fills elements of array with value from start up to, but not including, end. Args: array (list): List to fill. value (mixed): Value to fill with. start (int, optional): Index to start filling. Defaults to ``0``. end (int, optional): Index to end filling. Defaults to ``len(array)``. Returns: list: Filled `array`. Example: >>> fill([1, 2, 3, 4, 5], 0) [0, 0, 0, 0, 0] >>> fill([1, 2, 3, 4, 5], 0, 1, 3) [1, 0, 0, 4, 5] >>> fill([1, 2, 3, 4, 5], 0, 0, 100) [0, 0, 0, 0, 0] Warning: `array` is modified in place. .. versionadded:: 3.1.0 """ if end is None: end = len(array) else: end = min([end, len(array)]) # Use this style of assignment so that `array` is mutated. array[:] = array[:start] + [value] * len(array[start:end]) + array[end:] return array
def is_legal_filename(name): """ Function that returns true if the given name can be used as a filename """ if name == "": return False if " " in name: return False if "/" in name: return False if "\\" in name: return False return True
def apply_basic_padding(text, blocksize=16): """just fill with null bytes at the end""" _p = len(text)%blocksize # padding length return text + (_p > 0 and bytes(blocksize - _p) or b'\0') # = # return text + (bytes(blocksize - _p) if _p > 0 else b'')
def _num_two_factors(x): """return number of times x is divideable for 2""" if x <= 0: return 0 num_twos = 0 while x % 2 == 0: num_twos += 1 x //= 2 return num_twos
def dollarify(value): """Filter to convert int to dollar value""" return '${:,.2f}'.format(value)
def encode_int(i, nbytes, encoding='little'): """ encode integer i into nbytes bytes using a given byte ordering """ return i.to_bytes(nbytes, encoding)
def _swapxy(data): """Helper function to swap x and y coordinates""" return [(y, x) for (x, y) in data]
def __parse_cookies(headers): """ @type headers dict @return dict Parses cookies from response headers. """ cookies = {} if 'Set-Cookie' in headers: raw_cookies = headers['Set-Cookie'].split(';') for cookie in raw_cookies: cookie = cookie.split('=', 1) if cookie[0].strip() and len(cookie) > 1: cookies.update({cookie[0]: cookie[1]}) return cookies
def obscure_mpinstaller_deployment_test_failure(text): """ Returns 'Apex Test Failure' as the error text if the text contains a test failure message. """ if "Apex Test Failure: " in text: return "Apex Test Failure" return text
def ispalindrome(no)->bool: """ If number is palindrome function return true else false. """ if type(no)==list: if no==no[::-1]: return True else: return False else: no=str(no) rev=no[::-1] if no==rev: return True else: return False
def remove_empty_lines(text): """remove empty lines""" assert(len(text)>0) assert(isinstance(text, list)) text = [t.strip() for t in text] if "" in text: text.remove("") return text
def isn(parameter, value): """ usage: k = isn(k, 'default') alternative: if k is not None: k = 'default' :param parameter: :param value: :return: """ # if parameter is None: # return value # else: # return parameter return parameter or value
def get_call_uri(ad, call_id): """Get call's uri field. Get Uri for call_id in ad. Args: ad: android device object. call_id: the call id to get Uri from. Returns: call's Uri if call is active and have uri field. None otherwise. """ try: call_detail = ad.droid.telecomCallGetDetails(call_id) return call_detail["Handle"]["Uri"] except: return None
def as_seq(x, seq_type=None): """ If x is not a sequence, returns it as one. The seq_type argument allows the output type to be specified (defaults to list). If x is a sequence and seq_type is provided, then x is converted to seq_type. Arguments --------- x : seq or object seq_type : output sequence type If None, then if x is already a sequence, no change is made. If x is not a sequence, a list is returned. """ if x is None: # None represents an empty sequence x = [] elif not isinstance(x, (list, tuple, set, frozenset, dict)): # if x is not already a sequence (including dict), then make it one x = [x] if seq_type is not None and not isinstance(x, seq_type): # if necessary, convert x to the sequence type x = seq_type(x) return x
def ppm_to_dalton(mass:float, prec_tol:int)->float: """Function to convert ppm tolerances to Dalton. Args: mass (float): Base mass. prec_tol (int): Tolerance. Returns: float: Tolerance in Dalton. """ return mass / 1e6 * prec_tol
def rtsip_to_tag(rel_type, rel_sense, rel_id, rel_part): """Convert relation type, sense, id, and part to tag.""" rel_tag = ":".join([rel_type, rel_sense, str(rel_id), rel_part]) return rel_tag
def missing_param(param): """Sets param to 'dummy_data'""" out = {param: 'dummy_data'} return out
def partitionCtr(nums): """Compute sumCounter for partition""" sumCount = [0, 0] for num in nums: sumCount[0] += num sumCount[1] += 1 return [sumCount]
def to_string(nodes): """ Serialise a forest of DOM nodes to text, using the data fields of text nodes. :param nodes: the forest of DOM nodes :return: a concatenation of string representations. """ result = [] for node in nodes: if node.nodeType == node.TEXT_NODE: result.append(node.data) else: result.append(to_string(node.childNodes)) return ''.join(result)
def search_key_for_scene(scene): """Generate a string search key for a scene""" elements = [] elements.append(scene['sceneName']) # name of scene return u' '.join(elements)
def time_diff(t0, t1): """ Args: :t0: start time in seconds :t1: end time in seconds Returns: string with time difference (i.e. t1-t0) """ minutes, seconds = divmod(t1 - t0, 60) hours, minutes = divmod(minutes, 60) return "%d hours, %d minutes, %d seconds" % (hours, minutes, seconds)
def list_profiles(profilejson): """ expecting big json chunk containing all profiles applied to the virtual server. returns a string listing profile names """ listofprofiles = '' for nextprofile in profilejson['items']: if listofprofiles == '' : listofprofiles = nextprofile['name'] else: listofprofiles = listofprofiles + "; " + nextprofile['name'] return(listofprofiles)
def point_in_polygon(point, polygon): """ Checks if a point is inside a polygon. :param point: point :param polygon: polygon :return: point is inside polygon """ px, py = point size = len(polygon) for i in range(size): p1x, p1y = polygon[i] p2x, p2y = polygon[(i + 1) % size] if min(p1x, p2x) < px <= max(p1x, p2x): p = p1y - p2y q = p1x - p2x y = (px - p1x) * p / q + p1y if y < py: return True return False
def get_auth_token_url(host: str) -> str: """ Generate URL that creates an authentication token for the user. :return: URL to generate the token. """ return f"{host}/api/token-auth/"
def Hk(X, k): """ Calculate Hk for Sk(x) Parameters ---------- X : list list of x values k : int index from X Returns ------- float Hk from cubic spline """ return X[k] - X[k - 1]
def config_from_onnx_model(model, granularity='model', default_precision='ap_fixed<16,6>', default_reuse_factor=1): """Generate configuration dictionary from an ONNX model. Parameters ---------- model : ONNX model object. Model to be converted to hls model object. granularity : string, optional How granular you want the configuration to be. default_precision : string, optional Defines the precsion of your inputs, outputs, weights and biases. It is denoted by ap_fixed<X,Y>, where Y is the number of bits representing the signed number above the binary point (i.e. the integer part), and X is the total number of bits. Additionally, integers in fixed precision data type (ap_int<N>, where N is a bit-size from 1 to 1024) can also be used. default_reuse_factor : int, optional Reuse factor for hls model Returns ------- config : dict configuration dictionary to be used in ONNX converter. See Also -------- hls4ml.config_from_keras_model, hls4ml.convert_from_pytorch_model Examples -------- >>> import hls4ml >>> config = hls4ml.utils.config_from_keras_model(model, granularity='model') >>> hls_model = hls4ml.converters.convert_from_keras_model(model, hls_config=config) """ config = {} model_config = {} model_config['Precision'] = default_precision model_config['ReuseFactor'] = default_reuse_factor model_config['Strategy'] = 'Latency' config['Model'] = model_config return config
def generate_placeholder(length, width): """ Generate "(%s, %s, %s, ...), ..." for placing parameters. """ return ','.join('(' + ','.join(['%s'] * width) + ')' for _ in range(length))
def camel_to_underscore(string): """Translates amazon Camelcased strings to lowercased underscored strings""" res = [] for index, char in enumerate(string): if index != 0 and char.isupper(): res.extend(['_', char.lower()]) else: res.extend([char.lower()]) return ''.join(res)
def cauchy(wvl, A, *args): """Cauchy's equation for the (real) index of refraction of transparent materials. Parameters ---------- wvl : `number` wavelength of light, microns A : `number` the first term in Cauchy's equation args : `number` B, C, ... terms in Cauchy's equation Returns ------- `numpy.ndarray` array of refractive indices of the same shape as wvl """ seed = A for idx, arg in enumerate(args): # compute the power from the index, want to map: # 0 -> 2 # 1 -> 4 # 2 -> 6 # ... power = 2*idx + 2 seed = seed + arg / wvl ** power return seed