content
stringlengths
42
6.51k
def _get_instance(resp): """ Get the one and only match for the instance list in the response. If there are more or less and one match, log errors and return None. """ instances = [i for r in resp['Reservations'] for i in r['Instances']] # return the one and only match if len(instances) == 1: return instances[0]
def center(coordinates): """ >>> [[0,0],[2, 2]] (1.0, 1.0) """ l = float(len(coordinates)) return (sum((c[0] for c in coordinates))/l, sum(c[1] for c in coordinates)/l)
def _bin2bcd(value): """Convert a binary value to binary coded decimal. Arguments: value - the binary value to convert to BCD. (required, no default) """ return value + 6 * (value // 10)
def stack_follow(deck_size, position, *_): """Get new position after stacking deck.""" return deck_size - position - 1
def int_set_null(int_value): """sql util function""" return "null" if int_value is None else str(int_value)
def rgb2hsv(c): """Convert an RGB color to HSV.""" r,g,b = c v = max(r,g,b) mn = min(r,g,b) range = v-mn if v == mn: h = 0 elif v == r: h = 60*(g-b)/range+(0 if g >= b else 360) elif v == g: h = 60*(b-r)/range+120 else: h = 60*(r-g)/range+240 s = 0 if v == 0 else 1-mn/v return (h,s,v)
def remove_spaces(s): """Returns a stripped string with all of the spaces removed. :param str s: String to remove spaces from """ return s.replace(' ', '')
def _get_bit_string(value): """INTERNAL. Get string representation of an int in binary""" return "{0:b}".format(value).zfill(8)
def bytes2human(size, *, unit="", precision=2, base=1024): """ Convert number in bytes to human format. Arguments: size (int): bytes to be converted Keyword arguments (opt): unit (str): If it will convert bytes to a specific unit 'KB', 'MB', 'GB', 'TB', 'PB', 'EB' precision (int): number of digits after the decimal point base (int): 1000 - for decimal base 1024 - for binary base (it is the default) Returns: (int): number (str): unit ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'] Example: >>> bytes2human(10) ('10.00', 'Bytes') >>> bytes2human(2048) ('2.00', 'KB') >>> bytes2human(27273042329) ('25.40', 'GB') >>> bytes2human(27273042329, precision=1) ('25.4', 'GB') >>> bytes2human(27273042329, unit='MB') ('26009.60', 'MB') """ # validate parameters if not isinstance(precision, int): raise ValueError("precision is not a number") if not isinstance(base, int): raise ValueError("base is not a number") try: num = float(size) except ValueError: raise ValueError("value is not a number") suffix = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"] # If it needs to convert bytes to a specific unit if unit: try: num = num / base ** suffix.index(unit) except ValueError: raise ValueError("Error: unit must be {}".format(", ".join(suffix[1:]))) return "{0:.{prec}f}".format(num, prec=precision), unit # Calculate the greatest unit for the that size for counter, suffix_unit in enumerate(suffix): if num < base: return "{0:.{prec}f}".format(num, prec=precision), suffix_unit if counter == len(suffix) - 1: raise ValueError("value greater than the highest unit") num /= base
def _Underride(d, **options): """Add key-value pairs to d only if key is not in d. If d is None, create a new dictionary. d: dictionary options: keyword args to add to d """ if d is None: d = {} for key, val in options.items(): d.setdefault(key, val) return d
def is_emtpy(struct): """ Checks wether the given struct is empty or not """ if struct: return False else: return True
def precision(overlap_count: int, guess_count: int) -> float: """Compute the precision in a zero safe way. :param overlap_count: `int` The number of true positives. :param guess_count: `int` The number of predicted positives (tp + fp) :returns: `float` The precision. """ if guess_count == 0: return 0.0 return 0.0 if guess_count == 0 else overlap_count / float(guess_count)
def run_plugin_action(path, block=False): """Create an action that can be run with xbmc.executebuiltin in order to run a Kodi plugin specified by path. If block is True (default=False), the execution of code will block until the called plugin has finished running.""" return 'RunPlugin({}, {})'.format(path, block)
def get_field_aggregation(field): """ i..e, 'field@{sum}' """ if field and '@{' in field and '}' in field: i = field.index('@{') j = field.index('}', i) cond = field[i + 2:j] try: if cond or cond == '': return (field[:i], cond) except Exception: return (field.replace('@{%s}' % cond, ''), False) return (field, False)
def split_using(text, quote, sep = '.', maxsplit = -1): """ split the string on the seperator ignoring the separator in quoted areas. This is only useful for simple quoted strings. Dollar quotes, and backslash escapes are not supported. """ escape = quote * 2 esclen = len(escape) offset = 0 tl = len(text) end = tl # Fast path: No quotes? Do a simple split. if quote not in text: return text.split(sep, maxsplit) l = [] while len(l) != maxsplit: # Look for the separator first nextsep = text.find(sep, offset) if nextsep == -1: # it's over. there are no more seps break else: # There's a sep ahead, but is there a quoted section before it? nextquote = text.find(quote, offset, nextsep) while nextquote != -1: # Yep, there's a quote before the sep; # need to eat the escaped portion. nextquote = text.find(quote, nextquote + 1,) while nextquote != -1: if text.find(escape, nextquote, nextquote+esclen) != nextquote: # Not an escape, so it's the end. break # Look for another quote past the escape quote. nextquote = text.find(quote, nextquote + 2) else: # the sep was located in the escape, and # the escape consumed the rest of the string. nextsep = -1 break nextsep = text.find(sep, nextquote + 1) if nextsep == -1: # it's over. there are no more seps # [likely they were consumed by the escape] break nextquote = text.find(quote, nextquote + 1, nextsep) if nextsep == -1: break l.append(text[offset:nextsep]) offset = nextsep + 1 l.append(text[offset:]) return l
def search_multiple_lines(stationList): """ search_multiple_lines: Searches the set of stations that have different lines. :param - stationList: LIST of the stations of the current cicty (-id, destinationDic, name, line, x, y -) :return: - multiplelines: DICTIONARY which relates the different stations with the same name and different id's (stations that have different metro lines) """ multipleLines = {} for i in stationList: for j in stationList: if i.id != j.id: if i.x == j.x and i.y == j.y: if i.id in multipleLines: if j.id not in multipleLines[i.id]: multipleLines[i.id].append(j.id) else: multipleLines[i.id] = [] multipleLines[i.id].append(j.id) if j.id in multipleLines: if j.id not in multipleLines[i.id]: multipleLines[j.id].append(i.id) else: multipleLines[j.id] = [] multipleLines[j.id].append(i.id) return multipleLines
def unitarity_decay(A, B, u, m): """Eq. (8) of Wallman et al. New J. Phys. 2015.""" return A + B * u ** m
def listAxes(axd): """ make a list of the axes from the dictionary """ if type(axd) is not dict: if type(axd) is list: return axd else: print('listAxes expects dictionary or list; type not known (fix the code)') raise axl = [axd[x] for x in axd] return axl
def append_terminal_token(dataset, terminal_token='<e>'): """Appends end-of-sequence token to each sequence. :param dataset - a 2-d array, contains sequences of tokens. :param terminal_token (Optional) which symbol to append. """ return [sample + [terminal_token] for sample in dataset]
def interpolation(x0: float, y0: float, x1: float, y1: float, x: float) -> float: """ Performs interpolation. Parameters ---------- x0 : float. The coordinate of the first point on the x axis. y0 : float. The coordinate of the first point on the y axis. x1 : float. The coordinate of the second point on the x axis. y1 : float. The coordinate of the second point on the y axis. x : float. A value in the interval (x0, x1). Returns ------- float. Is the interpolated or extrapolated value. Example ------- >>> from pymove.utils.math import interpolation >>> x0, y0, x1, y1, x = 2, 4, 3, 6, 3.5 >>> print(interpolation(x0,y0,x1,y1,x), type(interpolation(x0,y0,x1,y1,x))) 7.0 <class 'float'> """ return y0 + (y1 - y0) * ((x - x0) / (x1 - x0))
def searchPFAMmatch(list_pfamId_orga_A:list, list_pfamId_orga_B:list, dict_ddi_sources:dict): """ Combine all the pfam ids and check if they exist in the dictionary of ddi, if yes the tuple was add to an array and returned. This method check the id_pfam_A - id_pfam_B AND id_fam_B - id_pfam_A :param list_pfamId_orga_A: list of pfam ids in the organism A :param list_pfamId_orga_B: list of pfam ids in the organism B :param dict_ddi_sources: dictionary that contain all the pairs :type list_pfamId_orga_A: list :type list_pfamId_orga_B: list :type dict_ddi_sources: dictionary :return: array with the tuples of id ddi matches :rtype: array[(id_domain_a, id_domain_b)] """ array_tuples_match = [] for id_pfam_orga_a in list_pfamId_orga_A: for id_pfam_orga_b in list_pfamId_orga_B: if (id_pfam_orga_a, id_pfam_orga_b) in dict_ddi_sources: tuple_key = (id_pfam_orga_a, id_pfam_orga_b) array_tuples_match.append(tuple_key) continue elif (id_pfam_orga_b, id_pfam_orga_a) in dict_ddi_sources: tuple_key = (id_pfam_orga_b, id_pfam_orga_a) array_tuples_match.append(tuple_key) return array_tuples_match
def removesuffix(s, suffix): """ Remove the suffix from a string, if it exists. Avoid needing Python 3.9 just for this. """ return s[:-len(suffix)] if s.endswith(suffix) else s
def nighttime_view(request): """Display Imager Detail.""" message = "Hello" return {'message': message}
def encode_as_bytes(obj): """ Convert any type to bytes """ return str.encode(str(obj))
def get_scope(field): """For a single field get the scope variable Return a tuple with name:scope pairs""" name = field['name'] if 'scope' in field['field']: scope = field['field']['scope'] else: scope = '' return (name, scope)
def FixName(name, uri_prefixes): """Converts a Clark qualified name into a name with a namespace prefix.""" if name[0] == '{': uri, tag = name[1:].split('}') if uri in uri_prefixes: return uri_prefixes[uri] + ':' + tag return name
def get_unique_tokens(texts): """ Returns a set of unique tokens. >>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl']) {'oeffentl', 'ist'} """ unique_tokens = set() for text in texts: for token in text: unique_tokens.add(token) return unique_tokens
def containsAny(s, set): """Check whether 'str' contains ANY of the chars in 'set'""" return 1 in [c in str(s) for c in set]
def initNxtTrainsIdx(stationTimetbls): """ initialises nxtTrainsIdx """ nxtTrainsIdx = {}; for stnName,timeTbl in stationTimetbls.items(): index = []; for i in range(len(timeTbl)): index.append(0); nxtTrainsIdx[stnName] = index; index = None; return nxtTrainsIdx;
def preprocess(X, test_X, y, test_y, X_pipeline, y_pipeline, n_train, seed): """ Preprocessing using `sklearn` pipelines. """ if X_pipeline: X = X_pipeline.fit_transform(X) test_X = X_pipeline.transform(test_X) if y_pipeline: y = y_pipeline.fit_transform(y) test_y = y_pipeline.transform(y) return X, test_X, y, test_y
def get_reference_node_parents(ref): """Return all parent reference nodes of reference node Args: ref (str): reference node. Returns: list: The upstream parent reference nodes. """ parents = [] return parents
def even_control_policy(time): """Policy carrying out evenly distributed disease management.""" return [0.16]*6
def compound_interest(principle: int, rate_pp: float, years: int) -> float: """Returns compound interest.""" # print(principle, rate_pp, years) amount = principle * (pow((1 + rate_pp / 100), years)) # print("amount: ", amount) return amount - principle
def int2str( binstr, nbits ): """ converts an integer to a string containing the binary number in ascii form, without prefix '0b' and filled with leading zeros up to nbits """ return str(bin(binstr))[2:].zfill(nbits)
def prepare_config_uri(config_uri: str) -> str: """Make sure a configuration uri has the prefix ws://. :param config_uri: Configuration uri, i.e.: websauna/conf/development.ini :return: Configuration uri with the prefix ws://. """ if not config_uri.startswith('ws://'): config_uri = 'ws://{uri}'.format(uri=config_uri) return config_uri
def qtr_to_quarter(qtr): """Transform a quarter into the standard form Args: qtr (str): The initial quarter Returns: str: The standardized quarter """ qtr_dict = { 1: (1, "Autumn"), "AUT": (1, "Autumn"), "Autumn": (1, "Autumn"), 2: (2, "Winter"), "WIN": (2, "Winter"), "Winter": (2, "Winter"), 3: (3, "Spring"), "SPR": (3, "Spring"), "Spring": (3, "Spring"), 0: (4, "Summer"), "SUM": (4, "Summer"), "Summer": (4, "Summer"), } return qtr_dict[qtr]
def _get_kwargs(kwargs, testcase_method): """Compatibility with parametrization""" return dict(kwargs, **getattr(testcase_method, '_parametrization_kwargs', {}))
def text_to_words(the_text): """ return a list of words with all punctuation removed, and all in lowercase. """ my_substitutions = the_text.maketrans( # If you find any of these "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\", # Replace them by these "abcdefghijklmnopqrstuvwxyz ") # Translate the text now. cleaned_text = the_text.translate(my_substitutions) wds = cleaned_text.split() return wds
def jacobsthal(n): """Returns Jacobsthall number. Arguments: n -- The index of the desired number in the Jacobsthall sequence. Returns: The n-th Jacobsthall number. """ if not isinstance(n, int): raise TypeError('Parameter n must an integer') if n < 0: raise ValueError('Parameter n must be non-negative') if (n == 0): return 0 if (n == 1): return 1 # recursion applied return jacobsthal(n - 1) + 2 * jacobsthal(n - 2)
def fullscan_policy(obs): """ A policy function that generates only fullscan data. """ valid_actions = obs['valid_actions'] ms1_action = len(valid_actions) - 1 # last index is always the action for MS1 scan return ms1_action
def ext_s(variable, value, substitution): """Add a value v to variable x for the given substitution s""" new = {variable:value} return {**substitution, **new}
def database(database=None): """ Filters search results by database """ if database is None: return database = database.lower().split(" or ") for each in database: if each not in ("general", "astronomy", "physics"): return ValueError("database must be either general, astronomy, or physics") return " OR ".join(["database:{0}".format(each) for each in database])
def axis_letters(dim_list): """Convert dimension list to string. e.g. ['latitude', 'longitude', 'time'] -> 'yxt' """ dim_letters = {'latitude': 'y', 'longitude': 'x', 'time': 't', 'level': 'z'} letter_list = [] for dim in dim_list: assert dim in dim_letters.keys() letter_list.append(dim_letters[dim]) return "".join(letter_list)
def check_layer_filters(filters_name): """ Check layer names and retern filter layer class :param filters_name: Layer names :return: Layer Class list """ # Get not import layers non_target_layers = [fn for fn in filters_name if fn not in globals().keys()] for ln in non_target_layers: if ln not in globals().keys(): print('[Warning] "%s" is non-targeted layer' % ln) return [globals()[n] for n in filters_name if n not in non_target_layers]
def change_to_str(data, rowstr="<br>", count=4, origin_count=4): """ This function can turn a data which you give into a str which you can look easily. Like a dict {"text": 1, "id":2, "reply":3} call the function changeToStr(text) you will look follow data: dict(3) =>{ ["text"] => 1 ["id"] => 2 ["reply"] => 3 } :param data: data you give, it can be any type. :param rowstr: it's a str. Enter, if you want to show data in web, it's default, or you want to show data in console, you should set rowstr="\n" :param count: It's a int. spacing num(I'm so sorry, I have forget the parameter's meaning, but you can try changing it.) :param origin_count: It's a int. spacing num(I'm so sorry, I have forget the parameter's meaning) :return: str """ s = "" space1 = rowstr space2 = rowstr if count == 0: endstr = "}" else: endstr = "}" for i in range(count): space1 = space1 + " " if i >= origin_count: space2 = space2 + " " count = count + origin_count if isinstance(data, dict): length = len(data) s = s + "dict(" + str(length) + ") => {" for k, v in data.items(): s = s + space1 + "['" + str(k) + "'] => " + change_to_str(v, rowstr, count, origin_count) s = s + endstr if not length else s + space2 + endstr elif isinstance(data, (tuple)): length = len(data) s = s + "tuple(" + str(length) + ") => (" i = 0 for v in data: s = s + space1 + "[" + str(i) + "] => " + change_to_str(v, rowstr, count, origin_count) i = i + 1 s = s + ")" if not length else s + space2 + ")" elif isinstance(data, (list)): length = len(data) s = s + "list(" + str(length) + ") => [" i = 0 for v in data: s = s + space1 + "[" + str(i) + "] => " + change_to_str(v, rowstr, count, origin_count) i = i + 1 s = s + "]" if not length else s + space2 + "]" else: s = str(data) return s
def convert_to_fortran_bool(boolean): """ Converts a Boolean as string to the format defined in the input :param boolean: either a boolean or a string ('True', 'False', 'F', 'T') :return: a string (either 't' or 'f') """ if isinstance(boolean, bool): if boolean: return 'T' else: return 'F' elif isinstance(boolean, str): # basestring): if boolean in ('True', 't', 'T'): return 'T' elif boolean in ('False', 'f', 'F'): return 'F' else: raise ValueError(f"A string: {boolean} for a boolean was given, which is not 'True'," "'False', 't', 'T', 'F' or 'f'") raise TypeError('convert_to_fortran_bool accepts only a string or ' f'bool as argument, given {boolean} ')
def index_of(val, in_list): """Return index of value in in_list""" try: return in_list.index(val) except ValueError: return -1
def min_sum_first_attempt(arr): """ A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array. Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0 Correct problem description: task.md time complexity: O(n*sum) space complexity: O(n*sum) Parameters ---------- arr : int[] a list of int values Returns ------- x : int the minimum (absolute) difference between the sums of 2 arrays consisting of all the elements from the input array """ n = len(arr) if n == 0: return 0 if n == 1: return arr[0] sum_of_all = sum(arr) matrix = [[0 for _ in range(sum_of_all+1)] for _ in range(n)] matrix[0] = [abs(sum_of_all - i - i) for i in range(sum_of_all+1)] for i in range(1, n): for j in range(sum_of_all, -1, -1): matrix[i][j] = matrix[i-1][j] if j+arr[i] <= sum_of_all: if matrix[i-1][j+arr[i]] <= matrix[i][j]: matrix[i][j] = matrix[i-1][j+arr[i]] return matrix[n-1][0]
def revert_correct_V3SciYAngle(V3SciYAngle_deg): """Return corrected V3SciYAngle. Only correct if the original V3SciYAngle in [0,180) deg Parameters ---------- V3SciYAngle_deg : float angle in deg Returns ------- V3SciYAngle_deg : float Angle in deg """ if V3SciYAngle_deg < 0.: V3SciYAngle_deg += 180. return V3SciYAngle_deg
def isnumeric(x): """Test whether the value can be represented as a number""" try: float(x) return True except: return False
def extract_include_paths(args): """ Extract include paths from command-line arguments. Recognizes two argument "-I path" and one argument "-Ipath". """ prefixes = ["-I", "-isystem"] include_paths = [] prefix = "" for a in args: if a in prefixes: prefix = a elif prefix in prefixes: include_paths += [a] prefix = "" elif a[0:2] == "-I": include_paths += [a[2:]] return include_paths
def _RDSParseDBInstanceStatus(json_response): """Parses a JSON response from an RDS DB status query command. Args: json_response: The response from the DB status query command in JSON. Returns: A list of sample.Sample objects. """ status = '' # Sometimes you look for 'DBInstance', some times you need to look for # 'DBInstances' and then take the first element if 'DBInstance' in json_response: status = json_response['DBInstance']['DBInstanceStatus'] else: if 'DBInstances' in json_response: status = json_response['DBInstances'][0]['DBInstanceStatus'] return status
def gen_team(name): """Generate a dict to represent a soccer team """ return {'name': name, 'avg_height': 0, 'players': []}
def IsBinary(data): """Checks for a 0x00 byte as a proxy for 'binary-ness'.""" return '\x00' in data
def docstringTypemap(cpptype): """Translate a C++ type to Python for inclusion in the Python docstrings. This doesn't need to be perfectly accurate -- it's not used for generating the actual swig wrapper code. It's only used for generating the docstrings. """ pytype = cpptype if pytype.startswith('const '): pytype = pytype[6:] if pytype.startswith('std::'): pytype = pytype[5:] pytype = pytype.strip('&') return pytype.strip()
def counting_steps(t): """ :param t: int, starts from 0. :return: int, return times + 1. """ t += 1 return t
def areSetsIntersets(setA, setB): """ Check if intersection of sets is not empty """ return any(x in setA for x in setB)
def attr_flag(s): """ Parse attributes parameters. """ if s == "*": return s attr = s.split(',') assert len(attr) == len(set(attr)) attributes = [] for x in attr: if '.' not in x: attributes.append((x, 2)) else: split = x.split('.') assert len(split) == 2 and len(split[0]) > 0 assert split[1].isdigit() and int(split[1]) >= 2 attributes.append((split[0], int(split[1]))) return sorted(attributes, key=lambda x: (x[1], x[0]))
def hit_edge2d(out, r, c): """ Returns True if we hit the edge of a 2D grid while searching for cell neighbors. Author: Lekan Molu, September 05, 2021 """ return ((r<0) or (c<0) or (r>=out[0]) or (c>=out[1]))
def split_list(mylist, chunk_size): """Split list in chunks. Parameters ---------- my_list: list list to split. chunk_size: int size of the lists returned. Returns ------- chunked lists: list list of the chunked lists. See: https://stackoverflow.com/a/312466/5201771 """ return [ mylist[offs : offs + chunk_size] for offs in range(0, len(mylist), chunk_size) ]
def __write_rnx3_header_obsagency__(observer="unknown", agency="unknown"): """ """ TAIL = "OBSERVER / AGENCY" res = "{0:20s}{1:40s}{2}\n".format(observer, agency, TAIL) return res
def chunkIt(seq, num): """Seperate an array into equal lengths :param seq: The arrray to seperate :param num: The number of chunks to seperate the array into :type seq: list :type num: int :rtype: list :return: 2D list of chunks """ avg = len(seq) / float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out
def binAndMapHits(hitIter): """ return map of assignments to list of reads """ hits = {} hitMap = {} for (read, hit) in hitIter: hitMap[read] = hit if isinstance(hit, list): for h in hit: hits.setdefault(h, []).append(read) else: hits.setdefault(hit, []).append(read) return (hits, hitMap)
def merge(list1, list2): """ Merge two lists into a list of tuples """ return [(list1[i], list2[i]) for i in range(0, len(list1))]
def Total_Delims(str): """ Function to calculate the Total Number of Delimeters in a URL """ delim=['-','_','?','=','&'] count=0 for i in str: for j in delim: if i==j: count+=1 return count
def calc_velocity(dist_m, time_start, time_end): """Return 0 if time_start == time_end, avoid dividing by 0""" return dist_m / (time_end - time_start) if time_end > time_start else 0
def handler(event, context): """ function handler """ res = {} if isinstance(event, dict): if "err" in event: raise TypeError(event['err']) res = event elif isinstance(event, bytes): res['bytes'] = event.decode("utf-8") if 'messageQOS' in context: res['messageQOS'] = context['messageQOS'] if 'messageTopic' in context: res['messageTopic'] = context['messageTopic'] if 'messageTimestamp' in context: res['messageTimestamp'] = context['messageTimestamp'] if 'functionName' in context: res['functionName'] = context['functionName'] if 'functionInvokeID' in context: res['functionInvokeID'] = context['functionInvokeID'] res['Say'] = 'Hello Baetyl' return res
def get_original_order_from_reordered_list(L, ordering): """ Returns the original order from a reordered list. """ ret = [None] * len(ordering) for orig_idx, ordered_idx in enumerate(ordering): ret[ordered_idx] = L[orig_idx] return ret
def parse_orgs(org_json): """ Extract what we need from Github orgs listing response. """ return [{'login': org['login']} for org in org_json]
def rfind_str(text, sub, start=None, end=None): """ Finds the highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``]. Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However, the index returned is relative to the original string ``text`` and not the slice ``text[start:end]``. The function returns -1 if ``sub`` is not found. :param text: The string to search :type text: ``str`` :param sub: The substring to search for :type sub: ``str`` :param start: The start of the search range :type start: ``int`` :param end: The end of the search range :type end: ``int`` :return: The highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``]. :rtype: ``int`` """ assert isinstance(text,str), '%s is not a string' % text return text.rfind(sub,start,end)
def Cross(a,b): """Cross returns the cross product of 2 vectors of length 3, or a zero vector if the vectors are not both length 3.""" assert len(a) == len(b) == 3, "Cross was given a vector whose length is not 3. a: %s b: %s" % (a, b) c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c
def phone_number(number): """Convert a 10 character string into (xxx) xxx-xxxx.""" #print(number) #first = number[0:3] #second = number[3:6] #third = number[6:10] #return '(' + first + ')' + ' ' + second + '-' + third return number
def insetRect( rectangle, horInset, vertInset): """ """ x, y, w, h = rectangle dh = horInset / 2.0 dv = vertInset / 2.0 return x+dh, y+dv, w-horInset, h-vertInset
def escaped_call(fn, *args, **kwargs): """ NOTE: In its raw form, this function simply calls fn on the supplied arguments. Only when encountered by an Autodiff context object does that change as described below. Allows users to call functions which can not be recompiled by Autodiff. When an Autodiff context encounters an `escaped_call` function, it does not attempt to modify the called function `fn`. Instead, it calls escape on all the arguments and passes them to the unmodified function. This should be used only when necessary, as tracing will not be possible on the result (it will be treated as a constant value). """ return fn(*args, **kwargs)
def strings_differ(string1, string2): """Check whether two strings differ while avoiding timing attacks. This function returns True if the given strings differ and False if they are equal. It's careful not to leak information about *where* they differ as a result of its running time, which can be very important to avoid certain timing-related crypto attacks: http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf """ if len(string1) != len(string2): return True invalid_bits = 0 for a, b in zip(string1, string2): invalid_bits += a != b return invalid_bits != 0
def normalize_us_phone_number(number: str) -> str: """Clean phone number and convert is raw US phone number in international format. :param number: Hand typed US phone number like (555) 123-1234 :return: Raw phone number like +15551231234 """ assert type(number) == str digits = "+0123456789" number = "".join([digit for digit in number if digit in digits]) # International 00 prefix if number.startswith("00"): number = number[2:] # Assume US, with area code if not number.startswith("+"): if not number.startswith("1"): number = "1" + number number = "+" + number return number
def split(list): """ Divide the unsorted list at midpont into two sublists Returns two sublists - left and right half Runs in overall O(k log n) time """ mid = len(list)//2 left = list[:mid] right = list[mid:] return left, right
def iterable_str(iterable): """ Converts iterable collection into simple string representation. Returns: string with commans in between string representation of objects. """ return ', '.join((str(elem) for elem in iterable))
def numdiff(f, x, h=1E-5): """takes the first derivative of function f""" return (f(x + h) - f(x - h)) / (2 * float(h))
def _escape(message): """Escape some characters in a message. Make them HTML friendly. Params: ----- - message : (str) Text to process. Returns: - (str) Escaped string. """ translations = { '"': '&quot;', "'": '&#39;', '`': '&lsquo;', '\n': '<br>', } for k, v in translations.items(): message = message.replace(k, v) return message
def ms(value): """ Convert kilometers per hour to meters per second """ return round(value / 3.6, 1)
def _format_counters(counters, indent='\t'): """Convert a map from group -> counter name -> amount to a message similar to that printed by the Hadoop binary, with no trailing newline. """ num_counters = sum(len(counter_to_amount) for group, counter_to_amount in counters.items()) message = 'Counters: %d' % num_counters for group, group_counters in sorted(counters.items()): if group_counters: message += '\n%s%s' % (indent, group) for counter, amount in sorted(group_counters.items()): message += '\n%s%s%s=%d' % (indent, indent, counter, amount) return message
def extra(request): """ Add information to the json response """ return {'one': 123}
def title_getter(node): """Return the title of a node (or `None`).""" return node.get('title','')
def find_overlapping_cds_simple(v_start, v_stop, cds_begins, strand): """ Find overlapping CDS within an exon given a list of CDS starts """ # cds_start = cds_begin[0] if strand == '+': return list(filter(lambda x: x[0] >= v_start and x[0] < v_stop, cds_begins)) else: return list(filter(lambda x: x[0] > v_start and x[0] <= v_stop, cds_begins))
def is_left(point0, point1, point2): """ Tests if a point is Left|On|Right of an infinite line. Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point0: Point P0 :param point1: Point P1 :param point2: Point P2 :return: >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line """ return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1]))
def getCommunity(config): """Get the SNMPv1 community string from the config file Args: config (list[str]): The list generated from configparser.ConfigParser().read() Returns: str: The SNMPv1 community string with Write Access to the PDUs """ community = config["Credentials"]["community"] return community
def n_air(P,T,wavelength): """ The edlen equation for index of refraction of air with pressure INPUT: P - pressure in Torr T - Temperature in Celsius wavelength - wavelength in nm OUTPUT: (n-1)_tp - see equation 1, and 2 in REF below. REF: http://iopscience.iop.org/article/10.1088/0026-1394/30/3/004/pdf EXAMPLE: nn = n_air(763.,20.,500.)-n_air(760.,20.,500.) (nn/(nn + 1.))*3.e8 """ wavenum = 1000./wavelength # in 1/micron # refractivity is (n-1)_s for a standard air mixture refractivity = ( 8342.13 + 2406030./(130.-wavenum**2.) + 15997./(38.9-wavenum**2.))*1e-8 return ((P*refractivity)/720.775) * ( (1.+P*(0.817-0.0133*T)*1e-6) / (1. + 0.0036610*T) )
def __get_git_url(pkg_info): """ Get git repo url of package """ url = pkg_info["src_repo"] return url
def collect_powers(s,v): """ Collect repeated multiplications of string v in s and replace them by exponentiation. **Examples**:: >>> collect_powers('c*c','c') 'c**2' >>> collect_powers('c*c*c*c*c*c*c*c*c*c','c') 'c**10' >>> collect_powers('d*c*c','c') 'd*c**2' """ import re m=s.count(v) for i in range(m,0,-1): pattern=re.compile(v+'(\*'+v+'){'+str(i)+'}') s=pattern.sub(v+'**'+str(i+1),s) return s
def scale_ratio(src_width, src_height, dest_width, dest_height): """Return a size fitting into dest preserving src's aspect ratio.""" if src_height > dest_height: if src_width > dest_width: ratio = min(float(dest_width) / src_width, float(dest_height) / src_height) else: ratio = float(dest_height) / src_height elif src_width > dest_width: ratio = float(dest_width) / src_width else: ratio = 1 return int(ratio * src_width), int(ratio * src_height)
def str2kvdict(s, sep='@', dlm='::'): """Returns a key-value dict from the given string. Keys and values are assumed to be separated using `sep` [default '@']. Each key-value pair is delimited using `dlm` [default '::']. .. warning:: Silently skips any elements that don't have the separator in them or are blank. """ ret = dict([pair.split(sep,1) for pair in s.split(dlm) if pair and sep in pair]) return ret
def get_neighbor_address(ip): """Get the neighbor address in a subnet /30 Args: ip (`str`): Ip address to get the neighbor for Returns: None """ # Get the neighbor IP address ip_list = ip.split(".") last = int(ip_list[-1]) if last % 2 == 0: ip_list[-1] = str(last - 1) else: ip_list[-1] = str(last + 1) return ".".join(ip_list)
def find_anychar(string, chars, index=None, negate=0): """find_anychar(string, chars[, index]) -> index of a character or -1 Find a character in string. chars is a list of characters to look for. Return the index of the first occurrence of any of the characters, or -1 if not found. index is the index where the search should start. By default, I search from the beginning of the string. """ if index is None: index = 0 while index < len(string) and \ ((not negate and string[index] not in chars) or (negate and string[index] in chars)): index += 1 if index == len(string): return -1 return index
def bisect_right(a, x, lo=0, hi=None): """bisection search (right)""" if hi is None: hi = len(a) while lo < hi: mid = (lo + hi)//2 if a[mid] <= x: lo = mid + 1 else: hi = mid return lo
def framework_supports_e_signature(framework): """ :param framework: framework object :return: Boolean """ return framework['isESignatureSupported']
def get_name(idx2name, info): """ get name from idx2name """ idx = info.strip().split('_') if len(idx) == 1: if idx[0] in idx2name: return idx2name[idx[0]] else: return idx[0] elif len(idx) > 1: ret = [] for i in idx: if i in idx2name: ret.append(idx2name[i]) else: ret.append(i) return '#'.join(ret)
def find_in_sequence(predicate, seq): """ Returns the index of the first element that matches the given condition, or -1 if none found. """ idx = 0 for elem in seq: if predicate(elem): return idx idx += 1 return -1
def __py_def(statements,lineno): """returns a valid python function.""" function_name = statements.split()[1] function_name = function_name[:function_name.find('(')] function_parameters = statements[statements.find('(')+1:statements.find(')')] py_function = statements[:statements.find('function')]+'def {}:\n' if function_parameters: return py_function.format(f'{function_name}({function_parameters})') else: return py_function.format(f'{function_name}()')
def compute_crop(image_shape, crop_degree=0): """Compute padding space in an equirectangular images""" crop_h = 0 if crop_degree > 0: crop_h = image_shape[0] // (180 / crop_degree) return crop_h