content
stringlengths
42
6.51k
def parseData(_dict): """ transform type """ for key in _dict: if key == 'init_num' or key == 'iter_max': _dict[key] = int(_dict[key]) else: _dict[key] = float(_dict[key]) return _dict
def task_next_bucket(iterator, partition_num): """ Get the next partition of incoming data depending on its size and number of total partitions to be created left. After adding elements to new partitions, they are deleted from the source in order to ease data transfer. :param iterator: :param partition_num: :return: """ ret = list() chunk_size = max(1, len(iterator) // partition_num) for index, key in enumerate(iterator.keys()): ret.extend(iterator[key]) del iterator[key] if index == chunk_size-1: break return ret
def intToID(idnum): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return rid
def spell_sql(*args,**kwargs): """ list=[] """ if len(args[0])<=0: return None sql="SELECT * from `emotion_data` WHERE id ={}".format(args[0][0]) for index in args[0][1:]: sql +=" or id ={}".format(index) return sql
def convert_to_uint256(value): """ Convert an int value to a 16 bytes binary string value. Note: the return value is not really 256 bits, nor is it of the neo.Core.UInt256 type Args: value (int): number to convert. Returns: str: """ return bin(value + 2 ** 32)[-32:]
def _parse_arguments(*args): """Because I'm not particularly Pythonic.""" formula = None if len(args) == 1: date = args[0] elif len(args) == 2: date, formula = args else: date = args return date, formula
def test_if_reassign(obj1, obj2): """ >>> test_if_reassign(*values[:2]) (4.0, 5.0) >>> sig, syms = infer(test_if_reassign.py_func, ... functype(None, [object_] * 2)) >>> types(syms, 'obj1', 'obj2') (double, object_) """ x = 4.0 y = 5.0 z = 6.0 if int(obj1) < int(obj2): obj1 = x obj2 = y else: obj1 = z return obj1, obj2
def split_list(s): """Split a comma-separated list, with out breaking up list elements enclosed in backets or parentheses""" start = 0 level = 0 elements = [] for i in range(0,len(s)): if s[i] in ["(","[",'{']: level += 1 if s[i] in [")","]",'}']: level -= 1 if s[i] == "," and level == 0: end = i element = s[start:end].strip() if element: elements += [element] start = i+1 end = len(s) element = s[start:end].strip() if element: elements += [element] return elements
def listit(t): """Format deep tuples into deep list Args: t (tuple of tuples): deep tuples Returns: list[list]: deep list """ return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
def _default_scale(bound, objective): """`max{1.0,|objective|}`""" # avoid using abs() as it uses the same logic, but adds # additional function call overhead if objective > 1.0: return objective elif objective < -1.0: return -objective else: return 1.0
def is_timestamp_ms(timestamp): """ :param timestamp: :return: """ timestamp = int(timestamp) timestamp_length = len(str(timestamp)) if timestamp_length != 13: raise TypeError('timestamp:({}) is not int or len({}) < 13'.format( type(timestamp), timestamp_length)) return True
def _is_float(string_inp: str) -> bool: """Method to check if the given string input can be parsed as a float""" try: float(string_inp) return True except ValueError: return False
def check_config(config, warnings, errors): """Checks the config for consistency, returns (config, warnings, errors)""" if 'server' not in config: errors.append("No server specified.") if 'user' not in config: errors.append("No username specified.") if ('keyfilename' in config) ^ ('certfilename' in config): errors.append("Please specify both key and cert or neither.") if 'keyfilename' in config and not config['usessl']: errors.append("Key specified without SSL. Please use -e or --ssl.") if 'certfilename' in config and not config['usessl']: errors.append( "Certificate specified without SSL. Please use -e or --ssl.") if 'server' in config and ':' in config['server']: # get host and port strings bits = config['server'].split(':', 1) config['server'] = bits[0] # port specified, convert it to int if len(bits) > 1 and len(bits[1]) > 0: try: port = int(bits[1]) if port > 65535 or port < 0: raise ValueError config['port'] = port except ValueError: errors.append( "Invalid port. Port must be an integer between 0 and 65535.") if 'timeout' in config: try: timeout = int(config['timeout']) if timeout <= 0: raise ValueError config['timeout'] = timeout except ValueError: errors.append( "Invalid timeout value. Must be an integer greater than 0.") return config, warnings, errors
def RoundupPow2(a): """ Round an integer up to the nearest power of 2. @return integer """ if type(a) != type(0): raise RuntimeError("Only works for ints!") if a <= 0: raise RuntimeError("Oops, doesn't handle negative values") next_one_up = 1 while (next_one_up < a): next_one_up = next_one_up << 1 return next_one_up
def device_name(device): """Generate a string name for the device fixture.""" name = device[0] if device[1] is None: name += '(all)' else: name += '(' + str(device[1]) + ')' return name
def trim(string, trim_chars = None): """ Strips all whitespace characters from the beginning and end of the `string`. If `trim_chars` is set, instead of whitespace, will replace only those characters. """ return string.strip(trim_chars)
def split_at(collection, index, to_list): """:yaql:splitAt Splits collection into two lists by index. :signature: collection.splitAt(index) :receiverArg collection: input collection :argType collection: iterable :arg index: the index of collection to be delimiter for splitting :argType index: integer :returnType: list .. code:: yaql> [1, 2, 3, 4].splitAt(1) [[1], [2, 3, 4]] yaql> [1, 2, 3, 4].splitAt(0) [[], [1, 2, 3, 4]] """ lst = to_list(collection) return [lst[:index], lst[index:]]
def merge(a, b): """ Function to merge two arrays / separated lists :param a: Array 1 :param b: Array 2 :return: merged arrays """ c = [] while len(a) != 0 and len(b) != 0: if a[0] < b[0]: c.append(a[0]) a.remove(a[0]) else: c.append(b[0]) b.remove(b[0]) if len(a) == 0: c += b else: c += a return c
def akaike_ic(lnl, k): """Akaike information criterion""" return 2 * k - 2 * lnl
def split_list(n,ls): """Split input list into n chunks, remainder of division by n goes into last chunk. If input list is empty, returns list of n empty lists. Parameters ---------- n : int Number of chunks. ls : list List to split. Returns ------- list List of n chunks of input list. """ if len(ls) == 0: return [[] for i in range(n)] m = int(len(ls)/n) chunks = [] for i in range(0,len(ls),m): if i == (n - 1)*m: chunks.append(ls[i:]) break chunks.append(ls[i:(i + m)]) return chunks
def int16(c): """ Parse a string as a hexadecimal number """ return int(c, 16)
def is_function(name): # type: (str) -> bool """ Return True if a serializer/deserializer is function. A function is prefixed with '::' so that the IDL generated code calls it as a function instead of as a class method. """ return name.startswith("::")
def map_value(x_value, in_min, in_max, out_min, out_max): """Maps value of the temperature to color""" return (x_value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def is_list(annotation): """Returns True if annotation is a typing.List""" annotation_origin = getattr(annotation, "__origin__", None) return annotation_origin == list
def should_display_email(email: str) -> bool: """ Returns true if the given email is not associated with the CCDL suers """ if not email: return False return not ( email.startswith("cansav09") or email.startswith("arielsvn") or email.startswith("jaclyn.n.taroni") or email.startswith("kurt.wheeler") or email.startswith("greenescientist") or "@alexslemonade.org" not in email or email.startswith("miserlou") or email.startswith("d.prasad") or email is ("daniel.himmelstein@gmail.com") or email is ("dv.prasad991@gmail.com") )
def distribute(included_targets_as_list_size, total_scan_engines_in_pool): """Distribute targets to scan engines as evenly as possible. Generates a list of targets per engine. For example, if there are 13 targets and 3 scan engines, this function will return [5, 4 ,4] - 5 targets for engine1, 4 targets for engine2, and 4 targets for engine3. https://stackanswers.net/questions/distribute-an-integer-amount-by-a-set-of-slots-as-evenly-as-possible """ base, extra = divmod(included_targets_as_list_size, total_scan_engines_in_pool) return [base + (i < extra) for i in range(total_scan_engines_in_pool)]
def solidsFluxPembNose(dp, db, emf, umf, us): """ Calculates the solids entrainment flux for the surface of a bubbling bed with the bubble nose ejection model of Pemberton and Davidsion (Chem. Eng. Sci., 1986, 41, pp. 243-251). This model is suitable if there is a single bubble in the bed. Parameters ---------- dp : float Particle diameter [m] db : float Bubble diameter [m] emf : float Void fraction at minimum fluidization [-] umf : float Minimum fluidization velocity [m/s] us : float Superficial gas velocity [m/s] Returns ------- F0 : float Solids entrainment flux at the top of the bed [kg/m^2/s] """ F0 = 3.0 * dp / db * (1 - emf) * (us - umf) return F0
def color_to_rgb(c): """Convert a 24 bit color to RGB triplets.""" return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)
def n_sigdigs_str(x, n): """Return a string representation of float x with n significant digits, where n > 0 is an integer. """ format = "%." + str(int(n)) + "g" s = "%s" % float(format % x) if "." in s: # handle trailing ".0" when not one of the sig. digits pt_idx = s.index(".") if s[0] == "-": # pt_idx is one too large if pt_idx - 1 >= n: return s[:pt_idx] else: if pt_idx >= n: return s[:pt_idx] return s
def _get_dp_bin(dp): """Returns lower bin width for the given depth. Bin width - 0..19: 1bp - 20..49: 5bp - 50..199: 10bp - 200..: = 200 """ if dp < 20: return dp elif dp < 50: return (dp // 2) * 2 elif dp < 200: return (dp // 5) * 5 else: return 200
def bbox_intersection_over_union(bbox_a, bbox_b) -> float: """Compute intersection over union for two bounding boxes Args: bbox_a -- format is (xmin, ymin, xmin+width, ymin+height) bbox_b -- format is (xmin, ymin, xmin+width, ymin+height) """ assert (bbox_a[0] <= bbox_a[2] and bbox_a[1] <= bbox_a[3] ), f"Please make sure arg bbox_a is in format (xmin,ymin,xmin+w,ymin+h): {bbox_a}" assert (bbox_b[0] <= bbox_b[2] and bbox_b[1] <= bbox_b[3] ), f"Please make sure arg bbox_b is in in format (xmin,ymin,xmin+w,ymin+h): {bbox_b}" # determine the (x, y)-coordinates of the intersection rectangle x_upper_left = max(bbox_a[0], bbox_b[0]) # xcoords y_upper_left = max(bbox_a[1], bbox_b[1]) # ycoords x_lower_right = min(bbox_a[2], bbox_b[2]) # xcoords plus w y_lower_right = min(bbox_a[3], bbox_b[3]) # ycoords plus h # compute the area of intersection rectangle inter_area = abs(max((x_lower_right - x_upper_left, 0)) * max((y_lower_right - y_upper_left), 0)) if inter_area == 0: return 0 # compute the area of both the prediction and ground-truth # rectangles bbox_a_area = abs((bbox_a[2] - bbox_a[0]) * (bbox_a[3] - bbox_a[1])) bbox_b_area = abs((bbox_b[2] - bbox_b[0]) * (bbox_b[3] - bbox_b[1])) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou = inter_area / float(bbox_a_area + bbox_b_area - inter_area) # return the intersection over union value return iou
def polevl(x, coef): """evaluates a polynomial y = C_0 + C_1x + C_2x^2 + ... + C_Nx^N Coefficients are stored in reverse order, i.e. coef[0] = C_N """ result = 0 for c in coef: result = result * x + c return result
def sanitize_string(string, size=80): """ Remplazamos los caracteres especiales y truncamos las cadenas largas """ string = string.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")[:size] string = string.strip() return string
def is_list_unknow_type(type_name): """Check if the type is a list of unknow type (Frozen or ndarray or python) "[]" Parameters ---------- type_name : str Type of the property Returns ------- is_list : bool True if the type is a list of unknow type """ return type_name == "[]"
def clean_value(value): """ Trims values """ return value.replace("''", "'").strip().rstrip("\0").strip()
def _to_frac(timestamp, n=32): """Return the fractional part of a timestamp. Parameters: timestamp -- NTP timestamp n -- number of bits of the fractional part Retuns: fractional part """ return int(abs(timestamp - int(timestamp)) * 2**n)
def _ppbv_to_kg_conversion(GHG): """ Convert the radiative efficiency from ppbv normalization to kg normalization. References -------------- IPCC 2013. AR5, WG1, Chapter 8 Supplementary Material. p. 8SM-15. https://www.ipcc.ch/report/ar5/wg1/ """ # kg per kmol molecular_weight = {"co2": 44.01, "ch4": 16.04, "n2o": 44.013} total_mass_atmosphere = 5.1352e18 # kg mean_molecular_weight_air = 28.97 # kg per kmol molecular_weight_ghg = molecular_weight[GHG] mass_ratio = mean_molecular_weight_air/molecular_weight_ghg return mass_ratio * (1e9/total_mass_atmosphere)
def delete_row(a, rownumber): """ Return the matrix a without row rownumber If rownumber is not correct (between 0 et len(a)-1) the function return the a matrix without modification :param a: a 2 dimensional array :param rownumber: an int between 0 et len(a)-1 :return: a 2 dimensional array """ return [[a[i][j] for j in range(len(a[i]))] for i in range(len(a)) if i != rownumber]
def dict_get(d, *args): """Get the values corresponding to the given keys in the provided dict.""" return [d[arg] for arg in args]
def dict_bool(x): """Implementation of `dict_bool`.""" return len(x) != 0
def even_occuring_element(arr): """Returns the even occuring element within a list of integers""" dict = {} for num in arr: if num in dict: dict[num] += 1 else: dict[num] = 1 for num in dict: if not dict[num] & 1: # bitwise check for parity. return num
def index_of_coincidence(frequencies, n): """ Calculate the index of coincidence of a frequency distribution relative to the text length. Args: frequencies: the target frequencies to compare the text to. n: length of the text that the IC should be calculated for. Returns: the index of coincidence of a text of length n with the frequency distribution frequencies. """ combinations = sum([f * (f - 1) for f in frequencies.values()]) pairs = n * (n - 1) return float(combinations) / float(pairs) if pairs > 0 else 0
def _make_list_of_str(arg): """ Convert a str to list of str or ensure a list is a list of str :param list[str] | str arg: string or a list of strings to listify :return list: list of strings :raise TypeError: if a fault argument was provided """ def _raise_faulty_arg(): raise TypeError("Provided argument has to be a list[str] or a str, got '{}'".format(arg.__class__.__name__)) if isinstance(arg, str): return [arg] elif isinstance(arg, list): if not all(isinstance(i, str) for i in arg): _raise_faulty_arg() else: return arg else: _raise_faulty_arg()
def fix_string(string): """ remove first line (asserts it empty)""" lines = string.splitlines() assert not lines[0] return "\n".join(lines[1:])
def concat(*args): """:yaql:concat Returns concatenated args. :signature: concat([args]) :arg [args]: values to be joined :argType [args]: string :returnType: string .. code:: yaql> concat("abc", "de", "f") "abcdef" """ return ''.join(args)
def mapif(predicate, function, list): """ """ result = list.copy() for i, x in enumerate(list): if predicate(x): result[i] = function(x) return result
def calculate_order(params, xc, yc): """ Calculate spectral order centre. Calculate a spectral order centre given the corresponding coefficients and the centre of the zeroth-order image. Parameters ---------- params : dict Dictionary of coefficients. Contains 6 coefficients labeled as a, b, c, d, e, f, which correspond to a constant (a), linear terms in x (b) and y (c), and quadratic terms in x (d), xy (e), and y (f) xc : float Central x pixel of spectrum. yc : float Central y pixel of spectrum. Returns ------- result : float The result of the calculation. """ result = params['a'] + params['b']*xc + params['c']*yc result += params['d']*xc*xc + params['e']*xc*yc + params['f']*yc*yc return result
def swap_16b(val): """ Swap 16b val :param val: 16b value :return: swapped 16b """ tmp = (val << 8) | (val >> 8) return tmp & 0xFFFF
def prune_dict(my_dict): """ Remove all keys associated to a null value. Args: my_dict (dict): any dictionary Returns: pruned_dict (dict): pruned dictionary """ # Start from empty dict pruned_dict = dict() # Add all entry of dict1 that does not have a null value for key in my_dict.keys(): if my_dict[key] != 0: pruned_dict[key] = my_dict[key] # Return pruned dict return pruned_dict
def getStatusCode(statusWord): """Returns the status code from the status word. """ try: return ['ordered', 'wished', 'owned'].index(statusWord) except ValueError: return -1
def counting_sort(items, key=None, max_key=None, min_key=None): """ Sorts an array of items by their integer keys, using counting_sort. Implemented as a stable sort. This is a modified version of the code described on Wikipedia: https://en.wikipedia.org/wiki/Counting_sort Parameters ---------- items: list of items key: function mapping each item to an integer key max_key: the maximum possible key min_key: the minimum possible key """ #If no key functions is passed, assume items #are integers in the range 0,1,2,...,max_key if key is None: key = lambda x: x #If the maximum key wasn't specified, find it. if max_key is None: #If min_key is also none, find both simultaneously. if min_key is None: max_key = min_key = key(items[0]) for item in items[1:]: next_key = key(item) if next_key < min_key: min_key = next_key elif next_key > max_key: max_key = next_key else: #(Takes time n if max_key was not specified) max_key = max(key(item) for item in items) #If None was passed for the minimum key, find the minimum. elif min_key is None: #(Takes time n if min_key was set to None) min_key = min(key(item) for item in items) #Initialize an array to count the occurrances of keys. #The index is the key, and counts[key] is the count of that key. #(Takes time K) counts = [0 for k in range(max_key-min_key+1)] #In case the minimum key is not 0, redefine the key function to return #values from 0 to max_key-min_key, in order to index into the #counts array. shifted_key = lambda x: key(x) - min_key #Iterate through items, to count how many times each key occurs #(Takes time n) for item in items: counts[shifted_key(item)] += 1 #Rename the counts array because we will be overwriting it to store indices #of keys instead of counts of keys. index_of = counts #Create the index_of array as the cumulative sum of the counts array. #When the loop finishes, we will have #index_of[k] = counts[0] + counts[1] + ... + counts[k-1], #but we can do it in place, replacing count[k] with index_of[k]. # #The value index_of[k] is the start index of the items with key(item) = k. #In the final loop, we will increment index_of[k] each time we place an #item with key(item) = k, so that the next time k is encountered, we'll #have the new correct index for that key. index=0 #Store the current index (cumulative sum of counts) #(Takes time K) for k, count in enumerate(counts): #k is the shifted key, count is its count. index_of[k] = index #Note that index_of = counts index += count #Create a new array for output. We can't modify the input in place #if we want a stable sort. #(Takes time n) output = [None for _ in range(len(items))] #Iterate through items, putting each item in the correct place in output. #The index for the first item with each key k is stored in index_of[k] #(Takes time n) for item in items: #Put the item in the correct index for its key. output[index_of[shifted_key(item)]] = item #Increment the index for the next time we encounter the key. index_of[shifted_key(item)] += 1 #Total runtime in iterations is 2k + 3n, plus another n if max_key or min_key #is not specified. return output
def validate_byr(value: str) -> bool: """Birth year must be 1920-2002""" try: return int(value) in range(1920, 2003) except (TypeError, ValueError): return False
def get_both_marks(record, course_code): """ (str, str) -> str Return a string containing the course mark and final mark respectively, separated by a single space, corresponding to a particular course code from the record. If the course code is absent from the record then return an empty string. >>> get_both_marks('Jacqueline Smith,Fort McMurray Composite High,2015,MAT,90,94,ENG,92,88,CHM,80,85,BArts', 'MAT') '90 94' >>> get_both_marks('Jacqueline Smith,Fort McMurray Composite High,2015,MAT,90,94,ENG,92,88,CHM,80,85,BArts', 'CAT') '' >>> get_both_marks('Paul Gries,Ithaca High School,1986,BIO,60,70,CHM,80,NE,CAT,10,20,BEng', 'CHM') '80 NE' """ if course_code in record: i = record.index(course_code) return record[(i + 4):(i + 6)] + " " + record[(i + 7):(i + 9)] else: return ''
def fibonacci_iterative(n): """ Args: n (int): Returns: int: the n-th fibonacci number References: http://stackoverflow.com/questions/15047116/iterative-alg-fib CommandLine: python -m utool.util_alg fibonacci_iterative Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> import utool as ut >>> with ut.Timer('fib iter'): >>> series = [fibonacci_iterative(n) for n in range(20)] >>> result = ('series = %s' % (str(series[0:10]),)) >>> print(result) series = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] """ a, b = 0, 1 for _ in range(0, n): a, b = b, a + b return a
def pretty_print_shortcut(raw_string): """ A custom Jinja 2 filter that formats the list.toString that we get in the frontent for the keyboard shortcut for the buttons. Is registered for Jinja in __main__ :param raw_string: the list.toString() string form js :return: a beautified version of the string """ pretty_string = str(raw_string) # raw string is a list a this point... pretty_string = pretty_string.replace("[", "") pretty_string = pretty_string.replace("]", "") pretty_string = pretty_string.replace("'", "") pretty_string = pretty_string.replace(",", "") pretty_string = pretty_string.replace(" ", " + ") return pretty_string
def med_product(l): """Takes a list of numbers and returns their product. A list of length 1 should return its sole element, and a list of length 0 should return 1.""" return 1 if not l else l[0] * med_product(l[1:])
def get_pos(i): """ return key positions in N253 (1..10) from Meier's Table 2: 0 = blank, if you want to use the peak in the cube 11 = map center, the reference position of N253 """ pos = [ [], # 0 = blank ['00h47m33.041s', '-25d17m26.61s' ], # pos 1 ['00h47m32.290s', '-25d17m19.10s' ], # 2 ['00h47m31.936s', '-25d17m29.10s' ], # 3 ['00h47m32.792s', '-25d17m21.10s' ], # 4 ['00h47m32.969s', '-25d17m19.50s' ], # 5 ['00h47m33.159s', '-25d17m17.41s' ], # 6 ['00h47m33.323s', '-25d17m15.50s' ], # 7 ['00h47m33.647s', '-25d17m13.10s' ], # 8 ['00h47m33.942s', '-25d17m11.10s' ], # 9 ['00h47m34.148s', '-25d17m12.30s' ], # pos 10 ['00h47m33.100s', '-25d17m17.50s' ], # map reference ] return pos[i]
def Length(expr): """ Returns number of elements in the expression just as SymPy's len. Examples ======== >>> from sympy.integrals.rubi.utility_function import Length >>> from sympy.abc import x, a, b >>> from sympy import cos, sin >>> Length(a + b) 2 >>> Length(sin(a)*cos(a)) 2 """ if isinstance(expr, list): return len(expr) return len(expr.args)
def num_to_str(num, precision=2): """ Converts num into a string with `precision` number of decimal places. Args: num (float or int) precision (int) Returns: a string """ return '%.{0}f'.format(str(precision)) % num
def is_multiple(x, y): """Determine if the two values passed are multiples/divisors""" # There were many cases that had to be checked # If both x and y are 1, they are multiples, but if only 1 coefficient # is the value 1, then they are not truly multiples. if x == 1 and y == 1: return True if x == 1: return False if y == 1: return False # 0 cannot be a multiple of something and must be caught here, lest # we end up with a divide by zero error. if x == 0 or y == 0: return False # Test, by the modulo operator, if the values are even multiples. x, y = abs(x), abs(y) if x > y: return x % y == 0 else: return y % x == 0
def num_from_str(s): """Return a num computed from a string.""" try: return int(s) except ValueError: try: return float(s) except ValueError: raise ValueError("Can not convert the string into a numeric value.")
def create_ref(*parts): """Create a reference from `parts` For example: assert create_ref("#", "definitions", "foo") == "#/definitions/foo" :param Tuple[str] parts: :rtype: str """ return "/".join(parts)
def count_some_palindromes(n, word): """ list all substrings which are palindromes repeating the same character like 'aaa' and not 'abcba' palindromes of uneven length like 'aacaa' and not 'abba' it is sufficient to look at the last 3 letters read from the string (l0, l1, l2) l0 = repeat_letter l1 = last_letter l2 = current_letter """ count = n last_letter = '' repeat_letter = '' left_repeat = 0 right_repeat = 1 has_middle = False DEBUG = False if DEBUG: print(count) for ix, letter in enumerate(word): if DEBUG: print(word[:ix+1]) if letter != last_letter: if right_repeat > 1: count += (right_repeat * (right_repeat-1)) // 2 if DEBUG: print(count) if has_middle: count += max(0, min(right_repeat-1, left_repeat-1)) has_middle = False if DEBUG: print(count) left_repeat = right_repeat right_repeat = 1 else: if letter == repeat_letter: count += 1 if has_middle: has_middle = False else: if left_repeat > 1: has_middle = True if DEBUG: print(count) else: left_repeat = 0 has_middle = False else: right_repeat += 1 repeat_letter = last_letter last_letter = letter count += (right_repeat * (right_repeat-1)) // 2 if has_middle: count += max(0, min(right_repeat-1, left_repeat-1)) return count
def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the importance of the style cost Returns: J -- total cost """ J_total = alpha*J_content+beta*J_style return J_total
def _cleanup_non_fields(terms): """Removes unwanted fields and empty terms from final json""" to_delete = 'closure' tids2delete = [] for termid, term in terms.items(): if not term: tids2delete.append(termid) else: if to_delete in term: del term[to_delete] for tid in tids2delete: del terms[tid] return terms
def intersect(a,b): """Intersect two lists""" return [val for val in a if val in b]
def fibonacci1(n): """ Recursive descendant version. """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacci1(n - 1) + fibonacci1(n - 2)
def tokenize_phoneme(phoneme): """ tokenizer for phoneme """ return phoneme.split()
def logistic(x, r): """Logistic map, with parameter r.""" return r * x * (1 - x)
def show_post(post_id): """ show the post with the given id, the id is an integer @param post_id: @return: """ return 'Post %d' % post_id
def parse_exclude_patterns(raw_pattern_list): """ :param list[str] raw_pattern_list: :return: """ if not raw_pattern_list: return [] # line no cast to int. because comparing easily. return [(x.split(":")[0], int(x.split(":")[1])) for x in raw_pattern_list]
def isNumber(txt): """ >>> isNumber('1 2 3') False >>> isNumber('- 156.3') False >>> isNumber(' 29.99999999 ') True >>> isNumber(' 5.9999x ') False """ # use for loop to search if not isinstance(txt, str) or len(txt) == 0: return "error: isNumber" # --- YOU CODE STARTS HERE # try the float if correct return else return false try: float(txt) return True except ValueError: pass return False
def string_from_arsdkxml(_input): """ This is an utility function that convert any string (or object) coming from arsdkparser to a unicode string where ascii escape sequences have been processed (ex:"\\n" -> "\n"). """ if not _input: # Handles empty string and None (we don't actually handle boolean type) return u'' errors = 'strict' if isinstance(_input, bytes): # str input must be decoded to unicode first output = _input.decode('utf-8', errors=errors) elif isinstance(_input, str): output = _input elif callable(_input): output = _input() else: # try to serialize the object to unicode output = bytes(_input).decode('utf-8', errors=errors) output = output.replace(r'\n', '\n') # Finally return a unicode 'string_escaped' string return output
def find_ips_supporting(ips, support_check): """Find IPs fulfilling support_check function.""" return [ip for ip in ips if support_check(ip)]
def ortho_line_cf(a, b, x0, y0): """ get orthogonal line to y = ax * b """ if a is None: # x=const a2 = 0 b2 = y0 elif abs(a - 0.0) < 1e-6: # y=const a2 = None b2 = x0 else: a2 = -1.0 / a b2 = y0 - a2 * x0 return a2, b2
def saddle_points(matrix): """ Return coordinates of all saddle points """ if len({len(row) for row in matrix}) > 1: raise ValueError("irregular matrix") result = [] for i, row in enumerate(matrix): for j, cell in enumerate(row): if cell == max(row): if cell == min([matrix[r][j] for r in range(len(matrix))]): result.append({"row": i + 1, "column": j + 1}) return result
def int_to_hex(value): """Convert integer to two digit hex.""" hex = '{0:02x}'.format(int(value)) return hex
def category(char): """Classify `char` into: punctuation, digit, non-digit.""" if char in ('.', '-'): return 0 if char in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'): return 1 return 2
def is_profile_flag(flag): """ return true if provided profile flag is valid """ return flag in ('cpu', 'mem', 'block', 'trace')
def list_has_duplicates(values): """ https://www.dotnetperls.com/duplicates-python """ # For each element, check all following elements for a duplicate. for i in range(0, len(values)): for x in range(i + 1, len(values)): if values[i] == values[x]: return True return False
def _correct_url_number(text): """Checks that the schema definition contains only one url definition. Args: text (str): The schema definition. Returns: bool: Whether only one url is defined. """ url_count = text.count("@url") return url_count == 1
def any_of(*args): """ Matches to any of the specified arguments with == operator """ class AnyOfMatcher: def __init__(self, values): self.values = values def __eq__(self, other): return any(map(lambda v: v == other, self.values)) def __ne__(self, other): return all(map(lambda v: v != other, self.values)) if not args: raise ValueError( "at least one argument should be provided for any_of matcher") return AnyOfMatcher(args)
def linear_map(xs, palette, low=None, high=None): """Map (linearly) a sequence of real values to the given palette. Parameters: xs - A list of numbers, in the range [low, high] palette - A list of colors Returns: A list of the same size of xs, with the color of each sample """ if xs == []: return [] if low == None: low = min(xs) if high == None: high = max(xs) idx = lambda x: int( (float(x) - low) / (high - low) * (len(palette)-1) ) clamped = [ max(low, min(high, x)) for x in xs ] return [ palette[ idx(x) ] for x in clamped ]
def _is_not_empty(value): """Check if value is empty value or a tuple of empty values.""" if isinstance(value, tuple): return any(bool(elem) for elem in value) return bool(value)
def is_list_of_list(value): """ Check if all elements in a list are tuples :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, list) for elem in value)
def _extract_feature_values(eopatches, feature): """ A helper function that extracts a feature values from those EOPatches where a feature exists. """ feature_type, feature_name = feature return [eopatch[feature] for eopatch in eopatches if feature_name in eopatch[feature_type]]
def set_defaults(lvm_data): """dict: Sets all existing null string values to None.""" for l in lvm_data: for k, v in lvm_data[l].items(): if v == '': lvm_data[l][k] = None return lvm_data
def image_proc_desaturate( image ): """ Desaturate the image. The function uses Rec. 709 luma component factors: OUT = 0.2989 R + 0.587 G + 0.114 B """ output_image = [] for row in image: output_row = [] for pixel in row: output_row.append( 0.2989 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2] ) output_image.append( output_row ) return output_image
def percent_of(value, arg): """Removes all values of arg from the given string""" return round(value/arg *100)
def get_base_venv_path(pyversion: str) -> str: """Return the base virtual environment path relative to the current directory.""" pyversion = str(pyversion).replace(".", "") return f".riot/.venv_py{pyversion}"
def _get_job_dir(jenkins_directory, job_name): """ Returns the directory for a job configuration file relative to the jenkins home directory. """ return jenkins_directory + '/jobs/' + job_name
def make_full_endpoint(endpoint, url_param_names, fn_args): """ Args: - endpoint: (str) e.g. "/survey/{survey_id}" - url_param_names: (list of str) e.g. ["survey_id"] - fn_args: (list) e.g. ["id_1"] Returns: (str) the endpoint interpolated with the given args e.g. "/survey/id_1" """ url_params = { param_name: fn_args[index] for index, param_name in enumerate(url_param_names) } return endpoint.format(**url_params)
def join(*paths): """Like os.path.join but doesn't treat absolute RHS specially""" import os.path return os.path.normpath("/".join(paths))
def _calculate_parcel_grain_diameter_post_abrasion( starting_diameter, pre_abrasion_volume, post_abrasion_volume ): """Calculate parcel grain diameters after abrasion, according to Sternberg exponential abrasion. Parameters ---------- starting_diameter : float or array Starting volume of each parcel. pre_abrasion_volume: float or array Parcel volume before abrasion. post_abrasion_volume: float or array Parcel volume after abrasion. Examples -------- >>> from landlab.components.network_sediment_transporter.network_sediment_transporter import _calculate_parcel_grain_diameter_post_abrasion >>> import numpy as np >>> from numpy.testing import assert_almost_equal If no abrasion happens, we should get the same value. >>> _calculate_parcel_grain_diameter_post_abrasion(10, 1, 1) 10.0 If some abrasion happens, test the value. >>> starting_diameter = 10 >>> pre_abrasion_volume = 2 >>> post_abrasion_volume = 1 >>> expected_value = ( ... starting_diameter * ... ( post_abrasion_volume / pre_abrasion_volume) ** (1. / 3.)) >>> print(np.round(expected_value, decimals=3)) 7.937 >>> assert_almost_equal( ... _calculate_parcel_grain_diameter_post_abrasion(10, 2, 1), ... expected_value) """ abraded_grain_diameter = starting_diameter * ( post_abrasion_volume / pre_abrasion_volume ) ** (1.0 / 3.0) return abraded_grain_diameter
def convertDBZtoGranizo(dbz): """ Funcion para convertir el valor de dbz a granizo param: dbz : valor """ if dbz >= 55: granizo = ((10**(dbz/10))/200)**(5/8) if granizo <= 1: return 0 else: return granizo else: return 0
def split_host_and_port(host): """ Splits a string into its host and port components :param host: a string matching the following patern: <host name | ip address>[:port] :return: a Dictionary containing 'host' and 'port' entries for the input value """ if host is None: host_and_port = None else: host_and_port = {} parts = host.split(":") if parts is not None: length = len(parts) if length > 0: host_and_port['host'] = parts[0] if length > 1: host_and_port['port'] = int(parts[1]) return host_and_port
def list_scanner(array_list, index=0): """ scanner list. :param array_list: <tuple> :param index: <int> the index to search the array list from. :return: <tuple> array of 3 tuples of XYZ values. """ if index == 0: return array_list[index], array_list[index], array_list[index + 1], if index == len(array_list) - 1: return array_list[index - 1], array_list[index], array_list[index], return array_list[index - 1], array_list[index], array_list[index + 1]
def flatten_path(path): """Returns the file name in the path without the directory before""" return path.split("/")[-1]
def remove_special_characters(value, remove_spaces=True): """ Removes all special characters from a string, so only [a-Z] and [0-9] stay. :param value: The value where the characters need to be removed from. :type value: str :param remove_spaces: If true the spaces are also going to be removed. :type remove_spaces: bool :return: The value in without special characters :rtype: str """ return ''.join( character for character in value if character.isalnum() or (character == ' ' and not remove_spaces) )
def get_resource_suffix(params): """ This function generates the part of suffix of result folders that pertains to resource cap(s). Parameters ---------- params : dict Parameters that are needed to run the indp optimization. Returns ------- out_dir_suffix_res : str The part of suffix of result folders that pertains to resource cap(s). """ out_dir_suffix_res = '' for rc, val in params["V"].items(): if isinstance(val, int): if rc != '': out_dir_suffix_res += rc[0] + str(val) else: out_dir_suffix_res += str(val) else: out_dir_suffix_res += rc[0] + str(sum([lval for _, lval in val.items()])) + '_fixed_layer_Cap' return out_dir_suffix_res