content
stringlengths
42
6.51k
def accelerator_ipaddresstype(type): """ Property: Accelerator.IpAddressType """ valid_types = ["IPV4"] if type not in valid_types: raise ValueError( 'IpAddressType must be one of: "%s"' % (", ".join(valid_types)) ) return type
def ideal_efficiency(induced_velocity, velocity): """Given the effective area, momentum theory ideal efficiency.""" return velocity / (velocity + induced_velocity)
def toBytes(text): """Convert string (unicode) to bytes.""" try: if type(text) != bytes: text = bytes(text, 'UTF-8') except TypeError: text = "\n[WARNING] : Failed to encode unicode!\n" return text
def round_exp(x,n): """Round floating point number to *n* decimal digits in the mantissa""" return float(("%."+str(n)+"g") % x)
def round_filters(filters, width_coefficient, depth_divisor): """ Round number of filters based on width multiplier. """ filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor new_filters = max(depth_divisor, new_filters) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters: new_filters += depth_divisor return int(new_filters)
def default_density(depth, vp): """Default rule for density as a function of Vp. Args: depth (float) Depth of location in m. vp (float) P wave speed in m/s. Returns: Density in kg/m**3. """ return 1.74e+3 * (vp*1.0e-3)**0.25
def is_header(bounds_list, position, font_size, i): """Determines whether a piece of text is considered header or not. Args: bounds_list ([(int, int)]): text position bounds for each page in the document. position (int): pixel position of a piece of text. font_size (int): font size of a piece of text. i (int): number of page to look at in bounds_list. Returns: (bool, int): a tuple containing a boolean that indicates if the piece of text is a header or not, and an integer that represents the document page where text is located. """ if(font_size >= 18): # If text is big, it isn't a header return False, i else: # If text is not big found = False it_is_header = True while(not found): if(position >= bounds_list[i][0] and position <= bounds_list[i][1]): # OK found = True it_is_header = False elif(position > bounds_list[i][1]): # Higher than upper bound i += 1 if(i == len(bounds_list)): # end of the bounds lists found = True # Restore i, maybe there are more headers in the last page i -= 1 else: # Lower than lower bound found = True # Decrease i, because text might not be in the right order i -= 2 if(i < 0): i = 0 return it_is_header, i
def list_string(alist, key=lambda a: a): """Given items a, b, ..., x, y, z in an array, this will print "a, b, ..., x, y and z" """ if len(alist) == 0: return "[empty]" elif len(alist) < 2: return str(key(alist[0])) elif len(alist) == 2: return "{} and {}".format(str(key(alist[0])), str(key(alist[1]))) alist = list(map(str, map(key, alist))) return ", and ".join([", ".join(alist[:-1]), alist[-1]])
def get_value(obj): """ Extract value from obj. "Description": { "value": "application/epub+zip", "memberOf": null } """ if obj is None or isinstance(obj, str): return obj return obj['Description']['value']
def is_convertible_to_float(value): """Returns True if value is convertible to float""" try: float(value) except ValueError: return False else: return True
def signed_number(number, precision=2): """ Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise. """ prefix = '' if number <= 0 else '+' number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision) return number_str
def parse_string_list_from_string(a_string): """ This just parses a comma separated string and returns either a float or an int. Will return a float if there is a decimal in any of the data entries Args: a_string (str): The string to be parsed Returns: A list of integers Author: SMM Date: 18/11/2019 """ print("Hey pardner, I'm a gonna parse a string into a list. Yeehaw.") if len(a_string) == 0: print("No items found, I am returning and empty list.") return_list = [] else: return_list = [item for item in a_string.split(',')] print("The parsed string is:") print(return_list) return return_list
def known_mismatch(hashes1, hashes2): """Returns a string if this is a known mismatch.""" def frame_0_dup_(h1, h2): # asymmetric version return ((h1[0] == h2[0]) and (h1[2:] == h2[2:]) and (h1[1] != h2[1] and h2[1] == h1[0])) def frame_0_dup(h1, h2): return frame_0_dup_(h1, h2) or frame_0_dup_(h2, h1) def frame_0_missing(h1, h2): return (h1[1:] == h2[:-1]) or (h2[:1] == h1[:-1]) for func in [frame_0_dup, frame_0_missing]: if func(hashes1, hashes2): return func.__name__ return None
def shape_attr_name(name, length=6, keep_layer=False): """ Function for to format an array name to a maximum of 10 characters to conform with ESRI shapefile maximum attribute name length Parameters ---------- name : string data array name length : int maximum length of string to return. Value passed to function is overridden and set to 10 if keep_layer=True. (default is 6) keep_layer : bool Boolean that determines if layer number in name should be retained. (default is False) Returns ------- String Examples -------- >>> import flopy >>> name = flopy.utils.shape_attr_name('averylongstring') >>> name >>> 'averyl' """ # replace spaces with "_" n = name.lower().replace(' ', '_') # exclude "_layer_X" portion of string if keep_layer: length = 10 n = n.replace('_layer', '_') else: try: idx = n.index('_layer') n = n[:idx] except: pass if len(n) > length: n = n[:length] return n
def find_brackets(s): """Get indices of matching square brackets in a string.""" # Source: https://stackoverflow.com/questions/29991917/indices-of-matching-parentheses-in-python toret = {} pstack = [] for i, c in enumerate(s): if c == '[': pstack.append(i) elif c == ']': if len(pstack) == 0: raise IndexError("No matching closing parens ']' at: " + str(i)) toret[pstack.pop()] = i if len(pstack) > 0: raise IndexError("No matching opening parens '[' at: " + str(pstack.pop())) return toret
def _SkipOmitted(line): """ Skip lines that are to be intentionally omitted from the expectations file. This is required when the file to be compared against expectations contains a line that changes from build to build because - for instance - it contains version information. """ if line.endswith('# OMIT FROM EXPECTATIONS\n'): return '# THIS LINE WAS OMITTED\n' return line
def tuple_sort_key(values): """ Key for sorting tuples of integer values. First sort according to the first value, then second ... :param values: tuple of positive integers :return: positive integer that can be used as sort key """ key = 0 max_value, multi = 100000000, 1 for value in values[::-1]: key += multi + value max_value *= multi return key
def get_metadata_path_value(map_value): """ Get raw metadata path without converter """ return map_value[1] if isinstance(map_value, list) else map_value
def quicksort(lyst): """This is a quicksort """ def partition_helper(lyst, first, last): pivot = lyst[first] left = (first + 1) right = last done = False while not done: while left <= right and lyst[left] <= pivot: left += 1 while right >= left and lyst[right] >= pivot: right -= 1 if right < left: done = True else: lyst[left], lyst[right] = lyst[right], lyst[left] lyst[first], lyst[right] = lyst[right], lyst[first] return right def quicksort_helper(lyst, first, last): if first < last: splitpoint = partition_helper(lyst, first, last) quicksort_helper(lyst, first, (splitpoint-1)) quicksort_helper(lyst, (splitpoint+1), last) return lyst quicksort_helper(lyst, 0, (len(lyst)-1)) return lyst
def statusInvoiceObject(account_data: dict, order_reference: str) -> dict: """ example: https://wiki.wayforpay.com/view/852526 param: account_data: dict merchant_account: str merchant_password: str param: order_reference : str """ return { "requestType": "STATUS", "merchantAccount": account_data['merchant_account'], "merchantPassword": account_data['merchant_password'], "orderReference": order_reference, }
def save(file_name, content): """Save content to a file""" with open(file_name, "w", encoding="utf-8") as output_file: output_file.write(content) return output_file.name
def normalize(vector): """ Returns a 3-element vector as a unit vector. """ magnitude = vector[0] + vector[1] + vector[2] + 0.0 return vector[0] / magnitude, vector[1] / magnitude, vector[2] / magnitude
def listize(item): """Create a listlike object from an item Args: item (dict): The object to convert Returns: Seq: Item as a listlike object Examples: >>> listize(x for x in range(3)) # doctest: +ELLIPSIS <generator object <genexpr> at 0x...> >>> listize([x for x in range(3)]) [0, 1, 2] >>> listize(iter(x for x in range(3))) # doctest: +ELLIPSIS <generator object <genexpr> at 0x...> >>> listize(range(3)) range(0, 3) """ if hasattr(item, "keys"): listlike = False else: attrs = {"append", "next", "__reversed__", "__next__"} listlike = attrs.intersection(dir(item)) return item if listlike else [item]
def JavaFileForUnitTest(test): """Returns the Java file name for a unit test.""" return 'UT_{}.java'.format(test)
def zero_plentiful4(arr): """.""" four_zero = 0 count = 0 if arr == [0]: return 0 elif len(arr) == arr.count(0): return 1 else: for el in arr: if el == 0: count += 1 if count >= 4: four_zero += 1 count = 0 if el != 0 and count < 4: four_zero = 0 return 0 if el != 0 and count > 0: four_zero = 0 return 0 if el != 0: count = 0 if four_zero > 0: return four_zero else: return 0
def width(s): """ Calculates the width of a string. .. note:: The string passed to this function is expected to have been :attr:`normalized <normalize>`. Parameters ---------- s: :class:`str` The string to calculate the width of. Returns ------- :class:`int` The calculated width of the string. """ return max(len(s) for s in s.split("\n"))
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate """ lr = 1e-5 if epoch > 80: lr *= 0.5e-3 elif epoch > 60: lr *= 1e-3 elif epoch > 40: lr *= 1e-2 elif epoch > 20: lr *= 1e-1 print('Learning rate: ', lr) return lr
def R_minus(x): """ Negative restriction of variable (x if x<0 else 0) """ return 0.5 * (x - abs(x))
def padding_zero(int_to_pad, lim): """ Adds a leading, or padding, zero to an integer if needed. Returns the int as a str Parameters ------------ int_to_pad : int The integer to add padding/leading zero to, if needed lim : int Used to check to see if the param int needs a padding zero added to it. Ex: int_to_pad = 11, lim = 10 -> no padding needed, '11' is returned int_to_pad = 9, lim = 10 -> padding needed, '09' is returned Returns ------------ result : str int_to_pad cast as a string, regardless if a padding 0 was added to it """ str_2_pad = str(int_to_pad) str_lim = str(lim) while (len(str_2_pad) < len(str_lim)): str_2_pad = '0' + str_2_pad return str_2_pad
def _onegroup(it, n): """Return the next size-n group from the given iterable.""" toret = [] for _ in range(n): try: toret.append(next(it)) except StopIteration: break if toret: return toret else: raise StopIteration
def displayRangeToBricon(dataRange, displayRange): """Converts the given brightness/contrast values to a display range, given the data range. :arg dataRange: The full range of the data being displayed, a (min, max) tuple. :arg displayRange: A (min, max) tuple containing the display range. """ dmin, dmax = dataRange dlo, dhi = displayRange drange = dmax - dmin dmid = dmin + 0.5 * drange if drange == 0: return 0, 0 # These are inversions of the equations in # the briconToScaleOffset function above, # which calculate the display ranges from # the bricon offset/scale offset = dlo + 0.5 * (dhi - dlo) - dmid scale = (dhi - dlo) / drange brightness = 0.5 * (offset / drange + 1) if scale <= 1: contrast = scale / 2.0 else: contrast = ((scale + 0.25) / 20.0) ** 0.25 brightness = 1.0 - brightness contrast = 1.0 - contrast return brightness, contrast
def checkmark(value, show_false=True, true='Yes', false='No'): """ Display either a green checkmark or red X to indicate a boolean value. Args: value: True or False show_false: Show false values true: Text label for true values false: Text label for false values """ return { 'value': bool(value), 'show_false': show_false, 'true_label': true, 'false_label': false, }
def tree_height(t): """ Returns the height of a tree. """ if t is None or not t.left and not t.right: return 0 else: return 1 + max(tree_height(t.left), tree_height(t.right))
def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step)
def get_min_bbox(box_1, box_2): """Get the minimal bounding box around two boxes. Args: box_1: First box of coordinates (x1, y1, x2, y2). May be None. box_2: Second box of coordinates (x1, y1, x2, y2). May be None. """ if box_1 is None: return box_2 if box_2 is None: return box_1 b1_x1, b1_y1, b1_x2, b1_y2 = box_1 b2_x1, b2_y1, b2_x2, b2_y2 = box_2 x1 = min(b1_x1, b2_x1) y1 = min(b1_y1, b2_y1) x2 = max(b1_x2, b2_x2) y2 = max(b1_y2, b2_y2) return x1, y1, x2, y2
def message(s) -> str: """Function to convert OPTIONS description to present tense""" if s == 'Exit program': return 'Shutting down' return s.replace('Parse', 'Parsing').replace('eXport', 'Exporting').replace('Find', 'Finding').replace('build', 'Building').replace('Index', 'index')
def listify(dct, key): """Make sure a key in this dct is a list""" if key not in dct: dct[key] = [] elif not isinstance(dct[key], list): dct[key] = [dct[key]] return dct[key]
def op_abs(x): """Returns the absolute value of a mathematical object.""" if isinstance(x, list): return [op_abs(a) for a in x] else: return abs(x)
def strip_brackets(string): """ Strips brackets from a string. """ return string.replace('[', '').replace(']', '')
def create_histogram_dict(words_list): """Return a dictionary representing a histogram of words in a list. Parameters: words_list(list): list of strings representing words Returns: histogram(dict): each key a unique word, values are number of word appearances """ histogram = dict() words = histogram.keys() for word in words_list: if word.lower() not in words: histogram[word.lower()] = 1 else: histogram[word.lower()] += 1 return histogram
def _add_aligned_message(s1: str, s2: str, error_message: str) -> str: """Align s1 and s2 so that the their first difference is highlighted. For example, if s1 is 'foobar' and s2 is 'fobar', display the following lines: E: foobar A: fobar ^ If s1 and s2 are long, only display a fragment of the strings around the first difference. If s1 is very short, do nothing. """ # Seeing what went wrong is trivial even without alignment if the expected # string is very short. In this case do nothing to simplify output. if len(s1) < 4: return error_message maxw = 72 # Maximum number of characters shown error_message += "Alignment of first line difference:\n" trunc = False while s1[:30] == s2[:30]: s1 = s1[10:] s2 = s2[10:] trunc = True if trunc: s1 = "..." + s1 s2 = "..." + s2 max_len = max(len(s1), len(s2)) extra = "" if max_len > maxw: extra = "..." # Write a chunk of both lines, aligned. error_message += " E: {}{}\n".format(s1[:maxw], extra) error_message += " A: {}{}\n".format(s2[:maxw], extra) # Write an indicator character under the different columns. error_message += " " # sys.stderr.write(' ') for j in range(min(maxw, max(len(s1), len(s2)))): if s1[j : j + 1] != s2[j : j + 1]: error_message += "^" break else: error_message += " " error_message += "\n" return error_message
def has_cycle(head): """" boolean function to identify a cycle in a linked list """ print('\nIn has_cycle') count = {} if head != None: while head: if head.next in count: return True else: count[head] = 1 head = head.next return False # space complexity is O(n)
def chunks(l, n): """Yield successive n-sized chunks from l.""" return [l[i : i + n] for i in range(0, len(l), n)]
def cat_cmd(last_output, expected_output): """Command to convert or concat files. >>> cat_cmd('file1.osm', 'file2.osm.pbf') ('osmium cat file1.osm -o file2.osm.pbf', None) >>> cat_cmd('file1.osm file2.osm.pbf', 'file3.osm.gz') ('osmium cat file1.osm file2.osm.pbf -o file3.osm.gz', None) >>> cat_cmd('file1.osm file2.osm.pbf', 'file3.osm.gz') ('osmium cat file1.osm file2.osm.pbf -o file3.osm.gz', None) """ return f'osmium cat {last_output} -o {expected_output}', None
def flatten_(items, seqtypes=(list, tuple)): """Flattten an arbitrarily nested list IN PLACE""" for i, x in enumerate(items): while i < len(items) and isinstance(items[i], seqtypes): items[i:i+1] = items[i] return items
def response_ssml_text(output, endsession): """ create a simple json plain text response """ return { 'outputSpeech': { 'type': 'SSML', 'ssml': "<speak>" +output +"</speak>" }, 'shouldEndSession': endsession }
def is_valid_dataset_dict(data): """Validate passed data (must be dictionary of sets)""" if not (hasattr(data, "keys") and hasattr(data, "values")): return False for dataset in data.values(): if not isinstance(dataset, set): return False else: return True
def _find_error_code(e): """Gets the approriate error code for an exception e, see http://tldp.org/LDP/abs/html/exitcodes.html for exit codes. """ if isinstance(e, PermissionError): code = 126 elif isinstance(e, FileNotFoundError): code = 127 else: code = 1 return code
def fortran_int(s, blank_value = 0): """Returns float of a string written by Fortran. Its behaviour is different from the float() function in the following ways: - a blank string will return the specified blank value (default zero) - embedded spaces are ignored If any other errors are encountered, None is returned.""" try: return int(s) except ValueError: s = s.strip() if not s: return blank_value else: try: s = s.replace(' ', '') return int(s) except: return None
def _ensure_iterable(item): """Ensure item is a non-string iterable (wrap in a list if not)""" try: len(item) has_len = True except TypeError: has_len = False if isinstance(item, str) or not has_len: return [item] return item
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, list_path, path
def dict_set(_dict, keys, values): """Set dict values by keys.""" for key, value in zip(keys, values): _dict[key] = value return _dict
def set_element(base, index, value): """Implementation of perl = on an array element""" base[index] = value return value
def isclose(actual, desired, rtol=1e-7, atol=0): """ rigourously evaluates closeness of values. https://www.python.org/dev/peps/pep-0485/#proposed-implementation """ return abs(actual-desired) <= max(rtol * max(abs(actual), abs(desired)), atol)
def splitFilename(fn) : """Split filename into base and extension (base+ext = filename).""" if '.' in fn : base,ext = fn.rsplit('.', 1) #ext = '.' + _ext else : ext = '' base = fn return base,ext
def get_tag(blocks): """ Template tag to get the html tag. Search for every block and return the first block with block_type 'tag' """ for block in blocks: if block.block_type == 'tag': return block return ''
def _create_shifted_copy(arrays, arrays_index, index, delta): """Creates a copy of the arrays with one element shifted.""" A = arrays[arrays_index] A_shifted = A.copy() A_shifted[index] += delta arrays_shifted = list(arrays) arrays_shifted[arrays_index] = A_shifted return arrays_shifted
def is_valid_url(url): """ Check if the href URL is valid """ return ( url != "#" and url != "" and url[0] != "?" and url[0] != "#" and not url.startswith("tel:") and not url.startswith("javascript:") and not url.startswith("mailto:") )
def url_path_join(*pieces): """Join components of url into a relative url Use to prevent double slash when joining subpath. This will leave the initial and final / in place """ initial = pieces[0].startswith("/") final = pieces[-1].endswith("/") stripped = [s.strip("/") for s in pieces] result = "/".join(s for s in stripped if s) if initial: result = "/" + result if final: result = result + "/" if result == "//": result = "/" return result
def ms_to_mph(ms): """Input: wind speed in meters/second, Returns a human friendly string in mph. """ try: mph = float(ms) * 2.236936 if mph<1: ws = "wind speed: calm" else: ws = "wind speed: %d mph" % round(mph,0) except Exception as e: ws = '' # Don't report anything if there is no wind speed reading available pass return ws
def get_bbox(x_start, y_start, x_end, y_end): """ This method returns the bounding box of a face. Parameters: ------------- x_start: the x value of top-left corner of bounding box y_start: the y value of top-left corner of bounding box width : the x value of bottom-right corner of bounding box height: the y value of bottom-right corner of bounding box returns: -------------- [x1, y1, x2, y2, x3, y3, x4, y4] the list of x and y values starting from the top-left corner and going clock, or counter-clock wise """ x1 = x_start y1 = y_start x2 = x_end y2 = y_start x3 = x_end y3 = y_end x4 = x_start y4 = y_end return [x1, y1, x2, y2, x3, y3, x4, y4]
def _constructSingleSummonerURL(name): """Takes a summonername and returns its op.gg profile.""" return "https://euw.op.gg/summoner/userName=" + name.lower()
def _SedPairsToString(pairs): """Convert a list of sed pairs to a string for the sed command. Args: pairs: a list of pairs, indicating the replacement requests Returns: a string to supply to the sed command """ sed_str = '; '.join(['s/%s/%s/g' % pair for pair in pairs]) if pairs: sed_str += ';' return sed_str
def clean_dict(d): """ remove the keys with None values. """ ktd = list() for k, v in d.items(): if not v: ktd.append(k) elif type(v) is dict: d[k] = clean_dict(v) for k in ktd: d.pop(k) return d
def tar_entry_size(filesize): """Get the space a file of the given size will actually require in a TAR. The entry has a 512-byte header followd by the actual file data, padded to a multiple of 512 bytes if necessary. Args: filesize (int): File size in bytes Returns: int: Bytes consumed in a TAR archive by this file. Examples: :: >>> tar_entry_size(1) 1024 >>> tar_entry_size(511) 1024 >>> tar_entry_size(512) 1024 >>> tar_entry_size(513) 1536 """ # round up to next multiple of 512 return 512 + filesize + ((512 - filesize) % 512)
def checkIfDuplicates_2(listOfElems): """ Check if given list contains any duplicates """ setOfElems = set() for elem in listOfElems: if elem in setOfElems: return True else: setOfElems.add(elem) return False
def contacts_to_list_items(contacts) -> str: """ A module helper function to convert a list of contacts to a string of HTML unordered list items ... Parameters ---------- contacts : [Contact] a list of contact objects to transform ... Returns ------- str a string containing the formatted items """ # Generate a list of HTML <li> items and join them as a string return "\n\t\t\t".join([f'<li>{contact}</li>' for contact in contacts])
def get_item_hash(terms, i): """ Computes the hash of the `terms`, based on its index `i`. :param terms: the terms :type terms: List[Term] :param i: the index of the term :type i: int :return: the hash :rtype: int """ if terms[i] is None: return 0 if terms[i].is_constant(): return hash(terms[i]) return i + 1
def strip_term(term, collation): """Strip out undefined letters from a term.""" return ''.join(c for c in term if c in collation)
def apply_backward_euler(Delta_t, u): """ Apply the backward Euler (fully implicit, first order) time discretization method. """ u_t = (u[0] - u[1])/Delta_t return u_t
def minWithNone(a, b): """ Returns minimal value from two values, if any of them is None, returns other one. :param a: int, float or None value :param b: int, float or None value :return: class instance with given properties >>> minWithNone(None, 1) 1 """ if a == None: return b elif b == None: return a else: return min(a, b)
def make_hash(obj, hash_func=hash): """ Return the hash value for the given object. :param obj: The object which to calculate the hash. :param hash_func: Hash function to use. :return: The hash value. """ if isinstance(obj, (tuple, list)): return hash_func((type(obj), tuple(make_hash(e, hash_func) for e in obj))) elif isinstance(obj, (set, frozenset)): return hash_func((type(obj), tuple(make_hash(e, hash_func) for e in sorted(obj)))) elif isinstance(obj, dict): return hash_func((type(obj), tuple((k, make_hash(obj[k]), hash_func) for k in sorted(obj)))) return hash_func(obj)
def clean_file_record(raw_record_string): # type: (str) -> str """ Performs some basic cleansing of the provided string, and returns it """ return raw_record_string.replace('\x00', '')
def table_name(obj): """ Return table name of given target, declarative class or the table name where the declarative attribute is bound to. """ class_ = getattr(obj, 'class_', obj) try: return class_.__tablename__ except AttributeError: pass try: return class_.__table__.name except AttributeError: pass
def get_idx_scores_mapping(scores): """Get mat index to scores mapping.""" return {i: score for i, score in enumerate(scores)}
def strip_string_to_integer(string): """ :param string: :return: """ return int("".join(filter(lambda x: x.isdigit(), string)))
def yper(p): """Calculates the y position for a given amount of peroxide.""" return 100 + (p - 12) * -10
def isnamedtuple(x): """Returns whether x is a namedtuple.""" # from https://bit.ly/2SkthFu t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n)==str for n in f)
def get_utxos(tx, address): """ Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format tx - <Dictionary> in bitcoind core format address - <string> """ utxos = [] for output in tx["vout"]: if "addresses" not in output["scriptPubKey"]: # In Bitcoin Core versions older than v0.16, native segwit outputs have no address decoded continue out_addresses = output["scriptPubKey"]["addresses"] amount_btc = output["value"] if address in out_addresses: utxos.append(output) return utxos
def build_kwargs_for_template_rendering(module): """This method receives a process chain for an actinia module, isolates the received values and returns them so they can be filled into the process chain template. """ kwargs = {} inOrOutputs = [] if module.get('inputs') is not None: inOrOutputs += module.get('inputs') if module.get('outputs') is not None: inOrOutputs += module.get('outputs') for item in inOrOutputs: if (item.get('param') is None) or (item.get('value') is None): return None key = item['param'] val = item['value'] kwargs[key] = val return kwargs
def count_circle_lattice_points(cx: int, cy: int, r: int, k: int) -> int: """ count up integer point (x, y) in the circle or on it. centered at (cx, cy) with radius r. and both x and y are multiple of k. """ assert r >= 0 and k >= 0 cx %= k cy %= k def is_ok(dx: int, dy: int) -> bool: return dx * dx + dy * dy <= r * r def count_right(cx: int, cy: int, x0: int) -> int: assert x0 == 0 or x0 == k y0, y1 = 0, 1 count = 0 for x in range((cx + r) // k * k, x0 - 1, -k): while is_ok(x - cx, y0 * k - cy): y0 -= 1 while is_ok(x - cx, y1 * k - cy): y1 += 1 count += y1 - y0 - 1 return count return count_right(cx, cy, k) + count_right(-cx, cy, 0)
def add_lists(a, b): """ >>> add_lists([1, 1], [1, 1]) [2, 2] >>> add_lists([1, 2], [1, 4]) [2, 6] >>> add_lists([1, 2, 1], [1, 4, 3]) [2, 6, 4] >>> list1 = [1, 2, 1] >>> list2 = [1, 4, 3] >>> sum = add_lists(list1, list2) >>> list1 == [1, 2, 1] True >>> list2 == [1, 4, 3] True """ len_a = len(a) -1 len_b = len(b) -1 sum_list = [] i=0 if len_a == len_b: while i <= len_a: sum_list.append(a[i]+b[i]) i += 1 # import pdb # pdb.set_trace() # print(sum_list) return sum_list
def get_directive_type(directive): """Given a dict containing a directive, return the directive type Directives have the form {'<directive type>' : <dict of stuff>} Example: {'#requirement': {...}} --> '#requirement' """ keys = list(directive.keys()) if len(keys) != 1: raise ValueError('Expected directive dict to contain a single key: {}'.format(directive)) return keys[0]
def build_success_response(result, status="success"): """Make Success Response based on the result""" return dict(status=status, success=True, result=result)
def merge_sort(aList): """Sort a list of integers from least to greatest""" n = len(aList) # Check for base case if n <= 1: return aList # Split the list into two halves and call recursively first = merge_sort(aList[0:int(n/2)]) second = merge_sort(aList[int(n/2):n]) #pdb.set_trace() # Perform Merge of two sorted lists # Initialize counters, lengths and the newly sorted array i, j = 0, 0 firstLen = len(first) secondLen = len(second) sortedList = [] # Populate the sorted list with the lesser of each half-list for k in range(n): # Make sure we won't try to access past the end of a list # If we've reached the end of the first array, then # add the element from the second array. if i == firstLen: sortedList.append(second[j]) j += 1 # If we've reached the end of the second array, add # the element from the first array elif j == secondLen: sortedList.append(first[i]) i += 1 # The normal case (before we've reached the end of either array) elif first[i] < second[j]: sortedList.append(first[i]) i += 1 else: sortedList.append(second[j]) j += 1 return sortedList
def alpha1(Te): """[cm^3 / s]""" return 1.95e-7 * (Te / 300.)**(-0.7)
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(\ ['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(\ ['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(\ ['***21**', '412453*', '423145*', '*553215', '*35214*', '*41532*', '*2*1***']) False """ for i in board: if i[0] != '*': for k in i: if k != '*': if i[1:].count(k) > 1: return False if i[0] == '*': for k in i: if k != '*': if i[:-1].count(k) > 1: return False return True
def is_greek_or_latin(name): """ This function determins if one name is of latin or greek origin. Note that this function only applies to concepts in CUB dataset, and should not be regarded as a universal judgement """ if name.endswith('dae') or name.endswith('formes'): _is = True else: _is = False return _is
def check_two_box_is_overlap(a_box, b_box): """ :param a_box: :param b_box: :return: """ in_h = min(a_box[2], b_box[2]) - max(a_box[0], b_box[0]) in_w = min(a_box[3], b_box[3]) - max(a_box[1], b_box[1]) inter = 0 if in_h < 0 or in_w < 0 else in_h * in_w return inter > 0
def extendListNoDuplicates(listToBeExtended, newItems): """Extend list with items without duplicities. :param list listToBeExtended: list to be extended :param list newItems: new items :return: extended list :rtype: list >>> extendListNoDuplicates([1, 2, 3, 4], [4, 5, 6]) [1, 2, 3, 4, 5, 6] """ for item in newItems: if not item in listToBeExtended: listToBeExtended.append(item) return listToBeExtended
def extrakey(key): """Return True if key is not a boring standard FITS keyword. To make the data model more human readable, we don't overwhelm the output with required keywords which are required by the FITS standard anyway, or cases where the number of headers might change over time. This list isn't exhaustive. Parameters ---------- key : :class:`str` A FITS keyword. Returns ------- :class:`bool` ``True`` if the keyword is not boring. Examples -------- >>> extrakey('SIMPLE') False >>> extrakey('DEPNAM01') False >>> extrakey('BZERO') True """ from re import match # don't drop NAXIS1 and NAXIS2 since we want to document which is which if key in ('BITPIX', 'NAXIS', 'PCOUNT', 'GCOUNT', 'TFIELDS', 'XTENSION', 'SIMPLE', 'EXTEND', 'COMMENT', 'HISTORY', 'EXTNAME', ''): return False # Table-specific keywords if match(r'T(TYPE|FORM|UNIT|COMM|DIM)\d+', key) is not None: return False # Compression-specific keywords if match(r'Z(IMAGE|TENSION|BITPIX|NAXIS|NAXIS1|NAXIS2|PCOUNT|GCOUNT|TILE1|TILE2|CMPTYPE|NAME1|VAL1|NAME2|VAL2|HECKSUM|DATASUM)', key) is not None: return False # Dependency list if match(r'DEP(NAM|VER)\d+', key) is not None: return False return True
def get_time_groupby_name(time_groups): """Return a name reflecting the temporal groupby operation.""" # Define time groupby name time_groups_list = [] for k, v in time_groups.items(): if v == 1: time_groups_list.append(k) else: time_groups_list.append(str(v) + k) time_groupby_name = "Time_GroupBy " + '-'.join(time_groups_list) return time_groupby_name
def multi_label_f_score(y_true, y_pred): """ Reference: https://www.kaggle.com/onodera/multilabel-fscore https://github.com/KazukiOnodera/Instacart :return: Examples -------- >>> y_true, y_pred = [1, 2, 3], [2, 3] >>> multi_label_f_score(y_true, y_pred) 0.8 >>> y_true, y_pred = [None], [2, None] >>> round(multi_label_f_score(y_true, y_pred), 3) 0.667 >>> y_true, y_pred = [4, 5, 6, 7], [2, 4, 8, 9] >>> multi_label_f_score(y_true, y_pred) 0.25 """ y_true, y_pred = set(y_true), set(y_pred) precision = sum([1 for i in y_pred if i in y_true]) / len(y_pred) recall = sum([1 for i in y_true if i in y_pred]) / len(y_true) if precision + recall == 0: return 0 return (2 * precision * recall) / (precision + recall)
def _indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters. """ if predicate is None: predicate = lambda line: line.strip() def prefixed_lines(): for line in text.splitlines(True): yield prefix + line if predicate(line) else line return ''.join(prefixed_lines())
def _call_args_kwargs(func_arg1, call_arg1, func_mult, call_mult): """Test utility for args and kwargs case where values passed from call site""" return (func_arg1 + call_arg1) * func_mult * call_mult
def joinString(str1, list): """This method joins a list of strings to a input string.\n returns a string object. """ for i in list: str1 += i str1 + " " str1 + " " return str1
def jaccard_similarity(b1, b2): """Jaccard similarity between two set b1 and b2 :param b1: set of index if there is a rate for business b1 :param b2: set of index if there is a rate for business b2 :return: jaccard similarity of two sets """ return len(b1.intersection(b2))/len(b1.union(b2))
def tamiz3(m): """Algoritmo alternativo""" found, numbers, i = [], [], 2 while (i <= m): if i not in numbers: found.append(i) for j in range(i, m+1, i): numbers.append(j) i += 1 return found
def yp_raw_competitors(data_path): """ The file contains the list of business objects. File Type: JSON """ return f'{data_path}/yp_competitors.json'
def doc_or_uid_to_uid(doc_or_uid): """Given Document or uid return the uid Parameters ---------- doc_or_uid : dict or str If str, then assume uid and pass through, if not, return the 'uid' field Returns ------- uid : str A string version of the uid of the given document """ try: return str(doc_or_uid['uid']) except TypeError: return doc_or_uid