content
stringlengths
42
6.51k
def is_marked(name): """Returns True if the input file contains either a header or a Quran quote The file name is used to determine whether the file contains a header or a Quran quote. """ if 'header' in name: return True if 'QQuote' in name or 'HQuote' in name: return True return False
def get_1st_ck_line_from_line( line ): """ A check line may contain more than 1 check. Here we get only the info(line aka string) from the 1st one. """ # return line # if there is only 1 check per line splited = line.split() ck1 = splited[:4] # in this case, 1st check info is in 1st 4 words of the line ck1 = ' '.join(ck1) # bc next functions expect lines to be strings return ck1
def compare_verbose(gt, out): """ function that compares two lists of edges ex: ground truth list and list of discovered edges and returns precision and recall with explanations """ print("Number of ground truth edges: " +str(len(gt))) print("Number of discovered edges: " +str(len(out))) print(" ") correct = list(set(gt) & set(out)) print("\tCorrectly discovered: " +str(len(correct))) addit = list(set(out) - set(correct)) print("\tAdditionally discovered: " +str(len(addit))) precision = len(correct) / len(out) recall = len(correct) / len(gt) print(" ") print("Precision: " +str(precision)) print("Recall: " +str(recall)) return [precision, recall]
def get_iou(bb1, bb2): """ Calculate the Intersection over Union (IoU) of two bounding boxes. Parameters ---------- bb1 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x, y) position is at the top left corner, the (x2, y2) position is at the bottom right corner Returns ------- float in [0, 1] """ assert bb1['x1'] < bb1['x2'] assert bb1['y1'] < bb1['y2'] assert bb2['x1'] < bb2['x2'] assert bb2['y1'] < bb2['y2'] # determine the coordinates of the intersection rectangle x_left = max(bb1['x1'], bb2['x1']) y_top = max(bb1['y1'], bb2['y1']) x_right = min(bb1['x2'], bb2['x2']) y_bottom = min(bb1['y2'], bb2['y2']) if x_right < x_left or y_bottom < y_top: return 0, 0.0 # The intersection of two axis-aligned bounding boxes is always an # axis-aligned bounding box intersection_area = (x_right - x_left) * (y_bottom - y_top) # compute the area of both AABBs bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1']) bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1']) # 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 = intersection_area / float(bb1_area + bb2_area - intersection_area) assert iou >= 0.0 assert iou <= 1.0 return intersection_area, iou
def string_to_nat(b): """Given a binary string, converts it into a natural number. Do not modify this function.""" if b == "": return 0 else: return 2 * string_to_nat(b[:-1]) + int(b[-1])
def convert(number): """ Converts a number into string based on rain drops methodj Pling = if 3 is a factor Plang = if 5 is a factor Plong = if 7 is a factor the number itself if none of the above are factors. """ raindrops = '' r_3 = divmod(number, 3)[1] r_5 = divmod(number, 5)[1] r_7 = divmod(number, 7)[1] if r_3 != 0 and r_5 != 0 and r_7 != 0: return str(number) if r_3 == 0: raindrops += 'Pling' if r_5 == 0: raindrops += 'Plang' if r_7 == 0: raindrops += 'Plong' return raindrops
def _r_count_num_m(n, factors_d, i): """Count of numbers coprime to d less than end; sum( gcd(m, d) == 1 for m in range(n, n+i) ) Uses inclusion exclusion on prime factorization of d """ if n == 0: return 0 if i < 0: return n return _r_count_num_m(n, factors_d, i-1) - _r_count_num_m(n // factors_d[i], factors_d, i-1)
def getCDXJLineClosestTo(datetimeTarget, cdxjLines): """ Get the closest CDXJ entry for a datetime and URI-R """ smallestDiff = float('inf') # math.inf is only py3 bestLine = None datetimeTarget = int(datetimeTarget) for cdxjLine in cdxjLines: dt = int(cdxjLine.split(' ')[1]) diff = abs(dt - datetimeTarget) if diff < smallestDiff: smallestDiff = diff bestLine = cdxjLine return bestLine
def _MarkupDescriptionLineOnInput(line, tmpl_lines): """Markup one line of an issue description that was just entered. Args: line: string containing one line of the user-entered comment. tmpl_lines: list of strings for the text of the template lines. Returns: The same user-entered line, or that line highlighted to indicate that it came from the issue template. """ for tmpl_line in tmpl_lines: if line.startswith(tmpl_line): return '<b>' + tmpl_line + '</b>' + line[len(tmpl_line):] return line
def _pixel_to_coords(col, row, transform): """Returns the geographic coordinate pair (lon, lat) for the given col, row, and geotransform.""" lon = transform[0] + (col * transform[1]) + (row * transform[2]) lat = transform[3] + (col * transform[4]) + (row * transform[2]) return lon, lat
def strip_and_replace_backslashes(path: str) -> str: """ >>> strip_and_replace_backslashes('c:\\\\test') 'c:/test' >>> strip_and_replace_backslashes('\\\\\\\\main\\\\install') '//main/install' """ path = path.strip().replace('\\', '/') return path
def interval_to_col_name(interval): """ Queries the proper name of the column for timespans given an interval. """ interval = interval.lower() if interval == "yearly": return "year" elif interval == "monthly": return "month" elif interval == "weekly": return "week" elif interval == "daily": return "day"
def _get_image_lib_name_from_object(obj): """ Hackish way to determine from which image lib 'obj' come from without importing each lib module individually. """ result = () if obj is not None: # PIL/Pillow Image if hasattr(obj, "_close_exclusive_fp_after_loading"): result = ("pil", "PIL/Pillow") # wxPython Image elif hasattr(obj, "FindFirstUnusedColour") and hasattr( obj, "GetImageExtWildcard" ): result = ("wx", "wxPython") # PyQt4, PyQt5 or PySide QImage elif hasattr(obj, "createHeuristicMask") and hasattr(obj, "setDotsPerMeterX"): result = ("qt", "PyQt(4-5)/PySide(1.x)") # OpenCV Image (NumPy ndarray) elif hasattr(obj, "argpartition") and hasattr(obj, "newbyteorder"): result = ("cv", "OpenCV") return result
def merge_dicts(x, y): """ Given two dicts, merge them into a new dict as a shallow copy. """ # python 3.5 provides a more elegant way of doing this, # but at the cost of backwards compatibility z = x.copy() z.update(y) return z
def parse(input): """ parse an input string into token/tree. For now only return a list of tokens """ tokens = [] for l in input.splitlines(): tokens.extend(l.split(" ")) return tokens
def nondiscrete_relative_likelihood(p, k, k0): """given binomial probability (p,k,n) => p^k*(1-p)^(n-k), return binom_prob(p,k,n) / binom_prob(p,k0,n) note that n isn't actually needed! this is because we're calculating a per-configuration weight, and in a true binomial distribution we'd then multiply by (n choose k) configurations; however, we've effectively done that already with the enumeration/tallying phase """ if p < 0. or p > 1.: raise ValueError('p must be [0., 1.]') return float((p / (1 - p))**(k - k0))
def get_first(objs, default=""): """get the first element in a list or get blank""" if len(objs) > 0: return objs[0] return default
def strip_metadata(posts, blacklist): """Return the post list stripped of specific metadata keys.""" formatted = [] for post in posts: core_post = {} for field in post.keys(): if field in blacklist: continue core_post[field] = post[field] formatted.append(core_post) return formatted
def generate_schedule_event(region): """ Generates a Scheduled Event :param str region: AWS Region :return dict: Dictionary representing the Schedule Event """ return { "version": "0", "account": "123456789012", "region": region, "detail": {}, "detail-type": "Scheduled Event", "source": "aws.events", "time": "1970-01-01T00:00:00Z", "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", "resources": [ "arn:aws:events:us-east-1:123456789012:rule/my-schedule" ] }
def clamp(minimum, value, maximum): """ Clamp the passed `value` to be between `minimum` and `maximum`, including. """ return max(minimum, min(maximum, value))
def set_value(value_index, value): """ API for operator's control. :param value_name: global variable in main.py :param value: notuse2 value :return: flag: True indicates sucess while False means failure """ global f_show if value_index == 0: f_show = value return True else: return False
def autoBindEvents (sink, source, prefix='', weak=False, priority=None): """ Automatically set up listeners on sink for events raised by source. Often you have a "sink" object that is interested in multiple events raised by some other "source" object. This method makes setting that up easy. You name handler methods on the sink object in a special way. For example, lets say you have an object mySource which raises events of types FooEvent and BarEvent. You have an object mySink which wants to listen to these events. To do so, it names its handler methods "_handle_FooEvent" and "_handle_BarEvent". It can then simply call autoBindEvents(mySink, mySource), and the handlers are set up. You can also set a prefix which changes how the handlers are to be named. For example, autoBindEvents(mySink, mySource, "source1") would use a handler named "_handle_source1_FooEvent". "weak" has the same meaning as with addListener(). Returns the added listener IDs (so that you can remove them later). """ if len(prefix) > 0 and prefix[0] != '_': prefix = '_' + prefix if hasattr(source, '_eventMixin_events') is False: # If source does not declare that it raises any events, do nothing print("Warning: source class %s doesn't specify any events!" % ( source.__class__.__name__,)) return [] events = {} for e in source._eventMixin_events: if type(e) == str: events[e] = e else: events[e.__name__] = e listeners = [] # for each method in sink for m in dir(sink): # get the method object a = getattr(sink, m) if callable(a): # if it has the revent prefix signature, if m.startswith("_handle" + prefix + "_"): event = m[8+len(prefix):] # and it is one of the events our source triggers if event in events: # append the listener listeners.append(source.addListener(events[event], a, weak=weak, priority=priority)) #print("autoBind: ",source,m,"to",sink) elif len(prefix) > 0 and "_" not in event: print("Warning: %s found in %s, but %s not raised by %s" % (m, sink.__class__.__name__, event, source.__class__.__name__)) return listeners
def digitsToInt(digits, base=10): """ Convert list of digits (in specified base) to an integer """ # first get an iterator to digits if not hasattr(digits, 'next'): # digits is an iterator digits = iter(digits) # now loop through digits, updating num num = next(digits) for d in digits: num *= base num += d return num
def g(n): """Return the value of G(n), computed recursively. >>> g(1) 1 >>> g(2) 2 >>> g(3) 3 >>> g(4) 10 >>> g(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g', ['While', 'For']) True """ if n <= 3: return n return g(n-1) + 2*g(n-2) + 3*g(n-3)
def isprime(i): """ input: 1, a positive integer i > 1 returns True if i is a prime number, False otherwise """ if i > 1: count = 0 for z in range(2,i+1): if (i % z) == 0: count +=1 if count > 1: return False if count == 1: return True else: return False
def make_list(string): """Turn a binary string into a list of integers.""" return [int(x) for x in list(string)]
def grouped(s, mode): """ Takes a string and a mode. The mode is either "concatenate" or "star." Determines if the string needs parentheses around it before it gets concatenated or starred with something. Returns either the original string or the string with parentheses around it. """ if len(s) == 1: # If you are looking at a, you can concatenate or star that already. return s elif len(s) > 1 and s[0] == "(" and s[-1] == ")": # If you are looking at (a+b+c*), you can concatenate or star that already. return s elif len(s) == 0: # If you have the empty string, that's ready. return "" elif mode is "concatenate": if s[-1] is "*": # Whether you are looking at abc* or (a+b+c)*, you can concatenate that already. return s for (index,char) in enumerate(s): # If you have abababab or a(a+b)b, that is concatenate ready, but not star ready. Check whether the +s are all inside parentheses. if char is "+": # Each + needs to be inside parentheses for this to be concatenate-ready. if s[:index].count("(") <= s[:index].count(")"): # We're not ready; this + has fewer (s before it than )s. return "("+s+")" return s elif mode is "star": # If you are looking at a+b+c*, you need parentheses first no matter what: (a+b+c*) return "("+s+")"
def get_response(action, next): """Returns a fairly standard Twilio response template.""" response = """<?xml version="1.0" encoding="UTF-8"?> <Response> {action}<Redirect method="GET">{next}</Redirect> </Response>""" return response.format(action=action, next=next)
def get_loop_segments(loop): """returns a list of segments in a loop""" segments = [] last_point = None for this_point in loop: if last_point is not None: new_segment = [last_point, this_point] segments.append(new_segment) last_point = this_point return segments
def has_next(seq, index): """ Returns true if there is at least one more item after the current index in the sequence """ next_index = index + 1 return len(seq) > next_index
def b2mb(num): """ convert Bs to MBs and round down """ return int(num/2**20)
def _convert_value_to_eo3_type(key: str, value): """ Convert return type as per EO3 specification. Return type is String for "instrument" field in EO3 metadata. """ if key == "instruments": if len(value) > 0: return "_".join([i.upper() for i in value]) else: return None else: return value
def f(a:int,b:int)->int: """ Retourne la somme de a et b""" x:int x:int return a+b
def _mai(a: int, n: int) -> int: """ Modular Additive Inverse (MAI) of a mod n. """ return (n - a) % n
def serverparse(server): """serverparse(serverpart) Parses a server part and returns a 4-tuple (user, password, host, port). """ user = password = host = port = None server = server.split("@", 1) if len(server) == 2: userinfo, hostport = server userinfo = userinfo.split(":",1) if len(userinfo) == 2: user, password = userinfo else: user = userinfo[0] server = server[1] else: server = server[0] server = server.split(":", 1) if len(server) == 2: host, port = server else: host = server[0] return user, password, host, port
def scalar_multiplication(first_vector, second_vector): """ >>> scalar_multiplication([2, 3, 4], [3, 4, 6]) 42 """ return sum([first_vector[i]*second_vector[i] for i in range(len(first_vector))])
def related_domain_annotation(sample, domain, relatedness): """Create a string for the summary annotation of related samples""" if sample in relatedness: if relatedness[sample] == domain: rv = ":Y" else: rv = ":Y:%s" % relatedness[sample] else: rv = "" return rv
def rands(n): """Generates a random alphanumeric string of length *n*""" from random import Random import string return ''.join(Random().sample(string.ascii_letters+string.digits, n))
def assume_in_vitro_based_enzyme_modification_assertions(ac): """ write a JTMS assumption specifying that in vitro-based evidence is acceptable @param ac:bool True if action is to assert!, False if action is to retract!, None to get the representation of the assumption @returns: a string representation of the appropriate JTMS assumption """ rep = "(accept-in-vitro-based-enzyme-modulation-assertions)" if ac == True: return "(assume! '%s 'dikb-inference-assumption)" % rep elif ac == False: return "(retract! '%s 'dikb-inference-assumption)" % rep else: return rep
def is_county(puma): """This function takes a string input and checks if it is in King County or South King County. It returns a 0 for the greater washinton area, 1 for King County areas that are NOT south king county and 2 for South King County. It is meant to use as apart of a .map(lambda) style syntax to apply across a Pandas Datafram. puma_arg can be a single puma id number or a list. It must be a string.""" king_counties = [ "11601", "11602", "11603", "11606", "11607", "11608", "11609", "11610", "11611", "11612", "11613", "11614", "11615", "11616", ] s_king_counties = [ "11610", "11613", "11614", "11615", "11611", "11612", "11604", "11605", ] if puma in s_king_counties: return 2 elif puma in king_counties: return 1 else: return 0
def set_wanted_position(ra, dec, prefix='', rconn=None): """Sets the wanted Telescope RA, DEC - given as two floats in degrees Return True on success, False on failure""" if rconn is None: return False try: result_ra = rconn.set(prefix+'wanted_ra', str(ra)) result_dec = rconn.set(prefix+'wanted_dec', str(dec)) except Exception: return False if result_ra and result_dec: return True return False
def matrix_power(M, n): """Returns M**n for a symmetric square matrix M for n > 0.""" def symmetric_matmul(A, B): """Matrix multiplication of NxN symmetric matrices.""" N = len(A) C = [[0] * N for _ in range(N)] for i in range(N): for j in range(N): C[i][j] = sum([a*b for a, b in zip(A[i], B[j])]) return C if n == 1: return M else: P = matrix_power(M, n//2) C = symmetric_matmul(P, P) if n % 2 == 0: return C else: return symmetric_matmul(C, M)
def counting_sort(array: list) -> list: """ Implementation of the linear O(n) Counting Sort algorithm Arguments: array - array of integers to be sorted Returns: Contents of array argument """ # Number of items to be sorted n: int = len(array) # Get maximum value in array - represented by k in textbook max_val: int = max(array) # Create resultant sorting array, reserving space for n items sorted_arr: list = [None] * n # Count array is "temporary working storage" of max_val # of items count: list = [0] * (max_val + 1) # Set count[val] to contain number of elements equal to val in array for val in array: count[val] += 1 # Set count[i] equal to number of elements <= i for i in range(len(count)): # Avoid attempting to access count[-1] if on first iteration count[i] += count[i - 1] if i != 0 else 0 # Do sorting from end of array down for i in range(len(array) - 1, -1, -1): sorted_arr[count[array[i]] - 1] = array[i] count[array[i]] -= 1 return sorted_arr
def bytestring_to_integer(bytes): """Return the integral representation of a bytestring.""" n = 0 for (i, byte) in enumerate(bytes): n += ord(byte) << (8 * i) return n
def validate_geometry(screen_geometry): """Raise ValueError if 'screen_geometry' does not conform to <integer>x<integer> format""" columns, rows = [int(value) for value in screen_geometry.lower().split('x')] if columns <= 0 or rows <= 0: raise ValueError('Invalid value for screen-geometry option: "{}"'.format(screen_geometry)) return columns, rows
def combine_blocks(*groups): """Combine several blocks of commands into one. This means that blank lines are inserted between them. """ combined = [] for i, group in groups: if i != 0: combined.append("") combined.extend(group) return combined
def get_or_else_empty_list(map_to_check, key): """ Use map.get to handle missing keys for list values """ return map_to_check.get(key, [])
def parse_percent(size): """parses string percent value to float, ignores -- as 0""" if size == '--': return 0 number = size[:-1] return float(number) / 100
def convert_empty_value_to_none(event, key_name): """ Changes an empty string of "" or " ", and empty list of [] or an empty dictionary of {} to None so it will be NULL in the database :param event: A dictionary :param key_name: The key for which to check for empty strings :return: An altered dictionary Examples: .. code-block:: python # Example #1 event = {'a_field': ' '} event = convert_empty_value_to_none(event, key_name='a_field') event = {'a_field': None} # Example #2 event = {'a_field': '{}'} event = convert_empty_value_to_none(event, key_name='a_field') event = {'a_field': None} # Example #3 event = {'a_field': {}} event = convert_empty_value_to_none(event, key_name='a_field') event = {'a_field': None} """ if key_name in event: if type(event[key_name]) == str and (event[key_name] == '' or event[key_name].strip() == '' or event[key_name] == '{}' or event[key_name] == '[]'): event[key_name] = None # Converts an empty list or dictionary to None if not event[key_name]: event[key_name] = None return event
def _strip_or_pad_version(version, num_components): """Strips or pads a version string to the given number of components. If the version string contains fewer than the requested number of components, it will be padded with zeros. Args: version: The version string. num_components: The desired number of components. Returns: The version, stripped or padded to the requested number of components. """ version_string = str(version) components = version_string.split(".") if num_components <= len(components): return ".".join(components[:num_components]) return version_string + (".0" * (num_components - len(components)))
def filter_values(item): """ Returns last element of the tuple or ``item`` itself. :param object item: It can be tuple, list or just an object. >>> filter_values(1) ... 1 >>> filter_values((1, 2)) ... 2 """ if isinstance(item, tuple): return item[-1] return item
def is_url(path): """ Check if given path is an url path. Arguments: path (string): Ressource path. Returns: bool: True if url path, else False. """ if path.startswith("http://") or path.startswith("https://"): return True return False
def sort_into_sections(events, categories): """Separates events into their distinct (already-defined) categories.""" categorized = {} for c in categories: categorized[c] = [] for e in events: categorized[e["category"]].append(e) return categorized
def to_bool(value): """ Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle. Case is ignored for strings. These string values are handled: True: 'True', "1", "TRue", "yes", "y", "t" False: "", "0", "faLse", "no", "n", "f" Non-string values are passed to bool. """ if type(value) == type(''): if value.lower() in ("yes", "y", "true", "t", "1"): return True if value.lower() in ("no", "n", "false", "f", "0", ""): return False raise Exception('Invalid value for boolean conversion: ' + value) return bool(value)
def all_indexes (text,phrase): """Returns a list of all index positions for phrase in text""" returnlist = [] starting_from = 0 while text and phrase in text: position = text.index(phrase) returnlist.append(starting_from+position) text = text[position+len(phrase):] starting_from += position+len(phrase) return returnlist
def format_fasta_record(name, seq, wrap=80): """Fasta __str__ method. Convert fasta name and sequence into wrapped fasta format. Args: name (str): name of the record seq (str): sequence of the record wrap (int): length of sequence per line Yields: tuple: name, sequence >>> format_fasta_record("seq1", "ACTG") ">seq1\nACTG" """ record = ">" + name + "\n" if wrap: for i in range(0, len(seq), wrap): record += seq[i : i + wrap] + "\n" else: record += seq + "\n" return record.strip()
def align_up(value, align): """Align up int value Args: value:input data align: align data Return: aligned data """ return int(int((value + align - 1) / align) * align)
def get_redis_url(db, redis=None): """Returns redis url with format `redis://[arbitrary_username:password@]ipaddress:port/database_index` >>> get_redis_url(1) 'redis://redis:6379/1' >>> get_redis_url(1, {'host': 'localhost', 'password': 'password'}) 'redis://anonymous:password@localhost:6379/1' """ kwargs = { 'host': 'redis', 'port': 6379, 'password': '', } kwargs.update(redis or {}) kwargs['db'] = db if kwargs['password']: return "redis://anonymous:{password}@{host}:{port}/{db}".format(**kwargs) return "redis://{host}:{port}/{db}".format(**kwargs)
def default_thread_index (value, threads): """ find index in threads array value :param value: :param threads: :return: """ value_index = threads.index(value) return value_index
def clamp(value, min_=0., max_=1.): """Clip a value to a range [min, max]. :param value: The value to clip :param min_: The min edge of the range :param max_: The max edge of the range :return: The clipped value """ if value < min_: return min_ elif value > max_: return max_ else: return value
def gcd(a, b): """Returns the greatest common divisor of a and b. Should be implemented using recursion. >>> gcd(34, 19) 1 >>> gcd(39, 91) 13 >>> gcd(20, 30) 10 >>> gcd(40, 40) 40 """ if a < b: return gcd(b, a) if not a % b == 0: return gcd(b, a % b) return b
def get_slice(tensors, slicer): """Return slice from tensors. We handle case where tensors are just one tensor or dict of tensors. """ if isinstance(tensors, dict): tensors_sliced = {} for key, tens in tensors.items(): tensors_sliced[key] = tens[slicer] else: tensors_sliced = tensors[slicer] return tensors_sliced
def replace_all_str(x, pattern_list, repl_by): """Replace all patterns by a str""" for p in pattern_list: x = x.replace(p, repl_by) return x
def byte_pad(data: bytes, block_size: int) -> bytes: """ Pad data with 0x00 until its length is a multiple of block_size. Add a whole block of 0 if data lenght is already a multiple of block_size. """ padding = bytes(block_size - (len(data) % block_size)) return data + padding
def diff(x0, y0, z0, x1, y1, z1): """ Return the sum of the differences in related values. """ dx = abs(x0 - x1) dy = abs(y0 - y1) dz = abs(z0 - z1) return dx + dy + dz
def upper_bound(arr, value): """Python version of std::upper_bound.""" for index, elem in enumerate(arr): if elem > value: return index return len(arr)
def console_output(access_key_id, secret_access_key, session_token, verbose): """ Outputs STS credentials to console """ if verbose: print("Use these to set your environment variables:") exports = "\n".join([ "export AWS_ACCESS_KEY_ID=%s" % access_key_id, "export AWS_SECRET_ACCESS_KEY=%s" % secret_access_key, "export AWS_SESSION_TOKEN=%s" % session_token ]) print(exports) return exports
def is_pos_float(string): """Check if a string can be converted to a positive float. Parameters ---------- string : str The string to check for convertibility. Returns ------- bool True if the string can be converted, False if it cannot. """ try: return True if float(string) > 0 else False except ValueError: return False
def convert_slice(s, rev_lookup_table): """Convert slice to (start, stop, step).""" if s.start is None: start = 0 else: start = s.start if s.stop is None: stop = len(rev_lookup_table) else: stop = s.stop if s.step is None: step = 1 else: step = s.step def convert_negative(val): if val >= 0: return val else: return len(rev_lookup_table)+val start = convert_negative(start) stop = convert_negative(stop) return start, stop, step
def combinations(c, d): """ Compute all combinations possible between c and d and their derived values. """ c_list = [c - 0.1, c, c + 0.1] d_list = [d - 0.1, d, d + 0.1] possibilities = [] for cl in c_list: for dl in d_list: possibilities.append([cl, dl]) return possibilities
def extract_primitives(transitions): """ Extract all the primitives out of the possible transititions, which are defined by the user and make an list of unique primitives. Args: transitions (list): indicated start, end primitive and their transition probability Returns: list of all primitives """ primitives = set() for transition in transitions: primitives.add(transition[0]) # collect start primitive primitives.add(transition[1]) # collect end primitive return sorted(list(primitives))
def chunk_list(lst, n): """ Splits a list into n parts :param lst: list obj :param n: parts int :return: list of lists """ return [lst[i:i + n] for i in range(0, len(lst), n)]
def u2nt_time(epoch): """ Convert UNIX epoch time to NT filestamp quoting from spec: The FILETIME structure is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since January 1, 1601, Coordinated Universal Time """ return int(epoch*10000000.0)+116444736000000000
def LeakyReLU(v): """ Leaky ReLU activation function. """ return 0.01*v if v<0 else v
def exists_and_equal(dict1,key1,val1): """ Simple test to see if """ if key1 in dict1: if dict1[key1] == val1: return True else: return False else: return False
def find_shape(bottom_lines, max_len): """ Finds a shape of lowest horizontal lines with step=1 :param bottom_lines: :param max_len: :return: list of levels (row values), list indexes are columns """ shape = [1] * max_len for i in range(max_len): for line in bottom_lines: if line[0] <= i + 1 < line[2]: shape[i] = line[1] break return shape
def compare_structure(source, target, match_null=False): """Compare two structures against each other. If lists, only compare the first element""" # pylint: disable=R0911 if isinstance(source, (list, tuple)) and isinstance(target, (list, tuple)): if not source or not target: if match_null: return True return False return compare_structure(source[0], target[0], match_null=True) if source == target: return True if isinstance(source, dict) and isinstance(target, dict): # They must have the same keys if sorted(source.keys()) != sorted(target.keys()): return False for key in source: if not compare_structure(source[key], target[key], match_null=True): return False return True # OK, curveball -- we'll match 'null'/None as a wildcard match if match_null and (source is None or source == 'null' or target is None or target == 'null'): return True return False
def partition(A, start_idx, stop_idx, pivot_idx): """ FIRST >>> partition([3, 8 ,2, 5, 1, 4, 7, 6], 0, 8, 0) 2 >>> partition([3, 8 ,2, 5, 1, 4, 7, 6], 3, 8, 3) 5 >>> partition([2, 1], 0, 2, 0) 1 LAST >>> partition([3, 4, 2, 1, 6], 0, 5, 4) 4 >>> partition([3, 4, 2, 1, 6], 2, 5, 4) 4 >>> partition([6, 3], 0, 2, 0) 1 MEDIAN >>> partition([3, 4, 2, 1, 6], 0, 5, 2) 1 >>> partition([3, 4, 2, 1, 6], 1, 5, 3) 1 >>> partition([688, 117, 468, 885, 64, 419, 374, 645, 716, 75], 0, 10, 0) 7 """ A[start_idx], A[pivot_idx] = A[pivot_idx], A[start_idx] pivot = A[start_idx] initial_pivot_idx = start_idx final_pivot_idx = start_idx + 1 for item_idx in range(start_idx, stop_idx): if A[item_idx] < pivot: A[final_pivot_idx], A[item_idx] = A[item_idx], A[final_pivot_idx] final_pivot_idx += 1 A[initial_pivot_idx], A[final_pivot_idx - 1] = A[final_pivot_idx - 1], A[initial_pivot_idx] return final_pivot_idx - 1
def get_L_BB_k_d(L_HP_d, L_dashdash_d, L_dashdash_k_d): """ Args: L_HP_d: param L_dashdash_d: L_dashdash_k_d: L_dashdash_d: Returns: """ return L_dashdash_k_d - L_HP_d * (L_dashdash_k_d / L_dashdash_d)
def stand_alone_additional_dist_desc(lst_dist_name1, lst_dist_name2, lst_desc_name1, lst_desc_name2): """Return True if there is an additional distinctive or descriptive in the stand-alone name.""" if lst_dist_name1.__len__() != lst_dist_name2.__len__() or lst_desc_name1.__len__() != lst_desc_name2.__len__(): return True return False
def linear_interpolate_pdfs(sample, xvals, pdfs): """ Parameters ---------- sample xvals: Returns ------- PDF: np.ndarray The PDF at sample. """ x1, x2 = xvals pdf1, pdf2 = pdfs grad = (pdf2 - pdf1) / (x2 - x1) dist = sample - x1 return grad * dist + pdf1
def removeArgs(l,r): """ Used to remove specific parameters from the main function """ args=l[l.find("(")+1:l.rfind(")")] args=[x.strip() for x in args.split(',')] new_l=l[:l.find("(")+1] removeLastComma=False for idx,arg in enumerate(args): if r not in arg: new_l=new_l+args[idx]+", " removeLastComma=True if removeLastComma: new_l=new_l[:-2]+l[l.rfind(")"):] else: new_l=new_l+l[l.rfind(")"):] return new_l
def g(row): """helper function""" if row['prev_winner_runnerup'] == row['winner_name']: val = 1 else: val = 0 return val
def clone_list(lst: list) -> list: """Clone a List""" new_lst = lst.copy() return new_lst
def some_calculation(x, y, z=1): """Some arbitrary calculation with three numbers. Choose z smartly if you want a division by zero exception. """ return x * y / z
def intersectarea(p1,p2,size): """ Given 2 boxes, this function returns intersection area """ x1, y1 = p1 x2, y2 = p2 ix1, iy1 = max(x1,x2), max(y1,y2) ix2, iy2 = min(x1+size,x2+size), min(y1+size,y2+size) iarea = abs(ix2-ix1)*abs(iy2-iy1) if iy2 < iy1 or ix2 < ix1: iarea = 0 return iarea
def GetTypeAllocationCode(imei): """Returns the 'type allocation code' (TAC) from the IMEI.""" return imei[0:8]
def select(_, vectors): """ Any vector works, pick the first one """ return vectors[0] if vectors else None
def replace_range(new_content: str, target: str, start: int, end: int) -> str: """ Replace `target[start:end]` with `new_content`. """ if start > len(target): raise IndexError( f"start index {start} is too large for target string with length {len(target)}" ) return target[:start] + new_content + target[end + 1 :]
def remove_paren(token: str): """Remove ( and ) from the given token.""" return token.replace('(', '') \ .replace(')', '')
def remove_space_characters(field): """Remove every 28th character if it is a space character.""" if field is None: return None return u"".join(c for i, c in enumerate(field) if i % 28 != 27 or c != u' ')
def convert_seconds(seconds): """Convert seconds into """ seconds_in_day = 86400 seconds_in_hr = 3600 seconds_in_min = 60 days = seconds // seconds_in_day hrs = (seconds - (days*seconds_in_day)) // seconds_in_hr mins = (seconds - (days*seconds_in_day) - (hrs*seconds_in_hr)) // seconds_in_min secs = (seconds - (days*seconds_in_day) - (hrs*seconds_in_hr) - (mins*seconds_in_min)) // 1 return days, hrs, mins, secs
def make_album(artist, album, tracks=""): """Try it yourself 8-7. Album.""" if tracks: return {'artist': artist, 'album': album, 'tracks': tracks} return {'artist': artist, 'album': album}
def calc_db_cost_v2(db) -> float: """Returns a noise cost for given dB based on a linear scale (dB >= 45 & dB <= 75). """ if db <= 44: return 0.0 db_cost = (db-40) / (75-40) return round(db_cost, 3)
def search_binary_iter(xs, target): """ Find and return the index of key in sequence xs """ lb = 0 ub = len(xs) while True: if lb == ub: # If region of interest (ROI) becomes empty return -1 # Next probe should be in the middle of the ROI mid_index = (lb + ub) // 2 # # Fetch the item at that position item_at_mid = xs[mid_index] # print("ROI[{0}:{1}](size={2}), probed='{3}', target='{4}'" # .format(lb, ub, ub-lb, item_at_mid, target)) # How does the probed item compare to the target? if item_at_mid == target: return mid_index # Found it! if item_at_mid < target: lb = mid_index + 1 # Use upper half of ROI next time else: ub = mid_index # Use lower half of ROI next time
def getTitle(test:str) -> str: """ getting str like #test TITLE return TITLE """ return test[5:].strip()
def best_customer_record(new_record, top_record): """Find the best customer record. Compares the new_record to the current top_record to determine what's the best extra_dimension for the customer. Records are lists containing the following information in the specified position: 2: dimension_count 3: tot_sales 4: max_dimension_date Args: new_record: New record that we want to compare to the current top record. top_record: The current top record. Returns: The best record according to the logic. """ if new_record[2] > top_record[2] or \ new_record[2] == top_record[2] and new_record[4] > top_record[4] or \ new_record[2] == top_record[2] and new_record[4] == top_record[4] and \ new_record[3] > top_record[3]: return new_record return top_record
def _number_of_graphlets(size): """Number of all undirected graphlets of given size""" if size == 2: return 2 if size == 3: return 4 if size == 4: return 11 if size == 5: return 34
def find_all_paths(parents_to_children, start, end, path=[]): """Return a list of all paths through a graph from start to end. `parents_to_children` is a dict with parent nodes as keys and sets of child nodes as values. Based on https://www.python.org/doc/essays/graphs/ """ path = path + [start] if start == end: return [path] if start not in parents_to_children.keys(): return [] paths = [] for node in parents_to_children[start]: if node not in path: newpaths = find_all_paths(parents_to_children, node, end, path) for newpath in newpaths: paths.append(tuple(newpath)) return paths
def calc_f1_macro(y_true, y_pred): """ @param y_true: The true values @param y_pred: The predicted values @return the f1 macro results for true and predicted values """ tp1 = tn1 = fp1 = fn1 = 0 tp0 = tn0 = fp0 = fn0 = 0 for i, val in enumerate(y_pred): if y_true[i] == val: if val == 1: tp1 += 1 tn0 += 1 else: tn1 += 1 tp0 += 1 else: if val == 1: fp1 += 1 fn0 += 1 else: fn1 += 1 fp0 += 1 f1_1 = tp1 / (tp1 + 0.5 * (fp1 + fn1)) f1_0 = tp0 / (tp0 + 0.5 * (fp0 + fn0)) f1_macro = (f1_0 + f1_1) * 0.5 return f1_macro