content
stringlengths
42
6.51k
def _extract_url_and_sha_from_deps_entry(entry): """Split a DEPS file entry into a URL and git sha.""" assert 'url' in entry and 'rev' in entry, 'Unexpected format: %s' % entry url = entry['url'] sha = entry['rev'] # Strip unnecessary ".git" from the URL where applicable. if url.endswith('.git'): url = url[:-len('.git')] return url, sha
def all_filled(board): """ Returns True if all board is filled, False otherwise. """ for i in range(len(board)): if board[i].count(None): return False return True
def hours_minutes_seconds( time_spec ): """ Interprets a string argument as a time of day specification and returns a string "hh:mm:ss" in 24 hour clock. The string can contain am, pm, and colons, such as "3pm" or "21:30". If the interpretation fails, an exception is raised. """ orig = time_spec try: assert '-' not in time_spec ampm = None time_spec = time_spec.strip() if time_spec[-2:].lower() == 'am': ampm = "am" time_spec = time_spec[:-2] elif time_spec[-2:].lower() == 'pm': ampm = "pm" time_spec = time_spec[:-2] elif time_spec[-1:].lower() == 'a': ampm = "am" time_spec = time_spec[:-1] elif time_spec[-1:].lower() == 'p': ampm = "pm" time_spec = time_spec[:-1] L = [ s.strip() for s in time_spec.split(':') ] assert len(L) == 1 or len(L) == 2 or len(L) == 3 L2 = [ int(i) for i in L ] hr = L2[0] if ampm: if ampm == 'am': if hr == 12: hr = 0 else: assert hr < 12 else: if hr == 12: hr = 12 else: assert hr < 12 hr += 12 else: assert hr < 24 mn = 0 if len(L2) > 1: mn = L2[1] assert mn < 60 sc = 0 if len(L2) > 2: sc = L2[2] assert sc < 60 except Exception: raise Exception( "invalid time-of-day specification: "+str(orig) ) return hr,mn,sc
def get_box_coordinates(box,img_shape): """#convert model coordinates format to (xmin,ymin,width,height) Args: box ((xmin,xmax,ymin,ymax)): the coordinates are relative [0,1] img_shape ((height,width,channels)): the frame size Returns: (xmin,ymin,width,height): (xmin,ymin,width,height): converted coordinates """ height,width, = img_shape[:2] xmin=max(int(box[0]*width),0) ymin=max(0,int(box[1]*height)) xmax=min(int(box[2]*width),width-1) ymax=min(int(box[3]*height),height-1) return ( xmin,#xmin ymin,#ymin xmax-xmin,#box width ymax-ymin#box height )
def flipx(tile): """ Return a copy of the tile, flipped horizontally """ return list(reversed(tile))
def is_iterable(obj): """ Returns True if 'obj' is iterable and False otherwise. We check for __iter__ and for __getitem__ here because an iterable type must, by definition, define one of these attributes but is not required or guarenteed to define both of them. For more information on iterable types see: http://docs.python.org/2/glossary.html#term-iterable http://docs.python.org/2/library/functions.html#iter """ return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__')
def get_ext(file): """Return the extension of the given filename.""" return file.split('.')[-1]
def factorial(n): """ returns factorial of n """ if n < 0: return None if n < 2: return 1 return n * factorial(n - 1)
def Fibonacci(n): """ Returns the nth term of the Fibonacci Sequence n is zero based indexed """ if n < 0: raise Exception("Invalid Argument") elif n < 2: return n else: return Fibonacci(n-1) + Fibonacci(n-2)
def unpackLine(string, separator="|"): """ Unpacks a string that was packed by packLine. """ result = [] token = None escaped = False for char in string: if token is None: token = "" if escaped and char in ('\\', separator): token += char escaped = False continue escaped = (char == '\\') if escaped: continue if char == separator: result.append(token) token = "" else: token += char if token is not None: result.append(token) return result
def convert_iob_to_bio(seq): """Convert a sequence of IOB tags to BIO tags. The difference between IOB and BIO (also called IOB2) is that in IOB the B- prefix is only used to separate two chunks of the same type while in BIO the B- prefix is used to start every chunk. :param seq: `List[str]` The list of IOB tags. :returns: `List[str] The list of BIO tags. """ new = [] prev = 'O' for token in seq: # Only I- needs to be changed if token.startswith('I-'): # If last was O or last was a different type force B if prev == 'O' or token[2:] != prev[2:]: token = 'B-' + token[2:] new.append(token) prev = token return new
def get_iou(bboxes1, bboxes2): """ Adapted from https://gist.github.com/zacharybell/8d9b1b25749fe6494511f843361bb167 Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. Returns: int: intersection-over-onion of bbox1, bbox2 """ ious = [] for bbox1, bbox2 in zip(bboxes1, bboxes2): bbox1 = [float(x) for x in bbox1] bbox2 = [float(x) for x in bbox2] (x0_1, y0_1, x1_1, y1_1) = bbox1 (x0_2, y0_2, x1_2, y1_2) = bbox2 # get the overlap rectangle overlap_x0 = max(x0_1, x0_2) overlap_y0 = max(y0_1, y0_2) overlap_x1 = min(x1_1, x1_2) overlap_y1 = min(y1_1, y1_2) # check if there is an overlap if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0: ious.append(0) continue # if yes, calculate the ratio of the overlap to each ROI size and the unified size size_1 = (x1_1 - x0_1) * (y1_1 - y0_1) size_2 = (x1_2 - x0_2) * (y1_2 - y0_2) size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0) size_union = size_1 + size_2 - size_intersection iou = size_intersection / size_union ious.append(iou) return ious
def get_usa_veh_id(acc_id, vehicle_index): """ Returns global vehicle id for USA, year and index of accident. The id is constructed as <Acc_id><Vehicle_index> where Vehicle_index is three digits max. """ veh_id = acc_id * 1000 veh_id += vehicle_index return veh_id
def thresholdClassify(sim_vec_dict, sim_thres): """Method to classify the given similarity vector dictionary with regard to a given similarity threshold (in the range 0.0 to 1.0), where record pairs with an average similarity of at least this threshold are classified as matches and all others as non-matches. Parameter Description: sim_vec_dict : Dictionary of record pairs with their identifiers as as keys and their corresponding similarity vectors as values. sim_thres : The classification similarity threshold. """ assert sim_thres >= 0.0 and sim_thres <= 1.0, sim_thres print('Similarity threshold based classification of %d record pairs' % \ (len(sim_vec_dict))) print(' Classification similarity threshold: %.3f' % (sim_thres)) class_match_set = set() class_nonmatch_set = set() # Iterate over all record pairs # for (rec_id_tuple, sim_vec) in sim_vec_dict.items(): sim_sum = float(sum(sim_vec)) # Sum all attribute similarities avr_sim = sim_sum / len(sim_vec) if avr_sim >= sim_thres: # Average similarity is high enough class_match_set.add(rec_id_tuple) else: class_nonmatch_set.add(rec_id_tuple) print(' Classified %d record pairs as matches and %d as non-matches' % \ (len(class_match_set), len(class_nonmatch_set))) print('') return class_match_set, class_nonmatch_set
def is_gerrit_issue(issue): """Returns true, if the issue is likely legacy Gerrit issue. Doesn't do database requests and guesses based purely on issue. """ # Gerrit CQ used to post urls for Gerrit users usign same code as Rietveld. # The only easy way to distinguish Rietveld from Gerrit issue, is that # all Gerrit instances used numbers (so far) < 1M, while Rietveld issues are # >10M. Since March 2016, CQ started sending extra codereview_hostname # metadata explicitely, so guessing isn't necessary, and we can safely support # Gerrit issues >1M. try: issue = int(issue) return 0 < issue and issue < 10**6 except (ValueError, TypeError): return False
def max_clique(dic): """Return the maximum clique in the given graph represented by dic. See readme for detailed description. Args: dic: dictionary{int : {'name' : str, 'edges' : a set of int}} Returns: list of int """ max_c = [] V = dic.keys() for vi in V: # pruning vertices that have fewer neighbours than the size of the maximum clique already computed if len(dic[vi]['edges']) >= len(max_c): # only considers this vertex if it is able to span a clique that is maximal U = {vi} # list of neighbours who can potentially be part of the clique # pruning neighbors of vi that cannot form a clique of size larger than current maximum clique for vj in dic[vi]['edges']: if len(dic[vj]['edges']) >= len(max_c): U.add(vj) size = 0 temp_max_c = [] while len(U) != 0: # keep adding nghs of vi as long as there are potential nghs. # break if current U is impossible to form a larger clique than current maximum clique # i.e if the maximal size of the clique that we are trying to create ( = nodes already in the clique + potential nodes which are still # possible to be added). This is the limes superior. if size+len(U) <= len(max_c): break # choose a random element u in U and add it. u = U.pop() temp_max_c.append(u) N_u = dic[u]['edges'] # nghs of u U = U.intersection(N_u) # restrict the potential nodes in U considering that u is now in the clique size += 1 # if the size of this maximal clique created by starting with vi exceeds the size of so far globally biggest clique, # redefine the new globally largest clique. if size > len(max_c): max_c = temp_max_c # sort the result and return it! max_c.sort() return max_c
def find_infinite_loop(instructions: list) -> tuple: """Find the infinite loop in the program, and return the accumulator :param instructions: List of instructions in the program :return: Value of the accumulator, and a flag """ accumulator = 0 line = 0 line_history = [] flag = -1 while line not in line_history: try: operation, argument = instructions[line] except IndexError: flag = 0 return accumulator, flag if operation == 'acc': accumulator += argument line_history.append(line) line += 1 elif operation == 'jmp': line_history.append(line) line += argument elif operation == 'nop': line_history.append(line) line += 1 return accumulator, flag
def decimal_to_hexadecimal(decimal: int)-> str: """Convert a Decimal Number to a Hexadecimal Number.""" if not isinstance(decimal , int): raise TypeError("You must enter integer value") if decimal == 0: return '0x0' is_negative = '-' if decimal < 0 else '' decimal = abs(decimal) chars = '0123456789abcdef' hex: list[str] = [] while decimal > 0: hex.insert(0 , chars[decimal % 16]) decimal //= 16 return f'{is_negative}0x{"".join(hex)}'
def human_format(num): """Returns a formated number depending on digits (e.g., 30K instead of 30,000)""" num = float("{:.2g}".format(num)) magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return "{}{}".format( "{:f}".format(num).rstrip("0").rstrip("."), ["", "K", "M", "B", "T"][magnitude], )
def kelvin(value: float, target_unit: str) -> float: """ Utility function for Kelvin conversion in Celsius or in Fahrenheit :param value: temperature :param target_unit: Celsius, Kelvin or Fahrenheit :return: value converted in the right scale """ if target_unit == "C": # Convert in Celsius return value - 273.15 else: # Convert in Fahrenheit return (value - 273.15) * 1.8 + 32
def _decode(x): """ Decoding input, if needed """ try: x = x.decode('utf-8') except AttributeError: pass return x
def uniquify(lst): """ Make the elements of a list unique by inserting them into a dictionary. This must not change the order of the input lst. """ dct = {} result = [] for k in lst: if k not in dct: result.append(k) dct[k] = 1 return result
def lifo_pre_sequencing(dataset, *args, **kwargs): """ Generates an initial job sequence based on the last-in-first-out dispatching strategy. The job sequence will be feed to the model. """ sequence = [] for job in dataset.values(): sequence.insert(0, job) return sequence
def derive_queue_id_from_dscp(dscp): """ Derive queue id form DSCP using following mapping DSCP -> Queue mapping 8 0 5 2 3 3 4 4 46 5 48 6 Rest 1 """ dscp_to_queue = { 8 : 0, 5 : 2, 3 : 3, 4 : 4, 46 : 5, 48 : 6} return dscp_to_queue.get(dscp, 1)
def is_match(item, pattern): """implements DP algorithm for string matching""" length = len(item) if len(pattern) - pattern.count('*') > length: return False matches = [True] + [False] * length for i in pattern: if i != '*': for index in reversed(range(length)): matches[index + 1] = matches[index] and (i == item[index] or i == '?') else: for index in range(1, length + 1): matches[index] = matches[index - 1] or matches[index] matches[0] = matches[0] and i == '*' return matches[-1]
def bit_count(int_no): """Computes Hamming weight of a number.""" c = 0 while int_no: int_no &= int_no - 1 c += 1 return c
def _get_data(title, func, dest): """Populate dest with data from the given function. Args: title: The name of the data func: The function which will return the data dest: a dict which will store the data Returns: dest: The modified destination dict """ # Get interface data dest[title] = func() return dest
def duration_string(duration: float) -> str: """Convert duration in seconds to human readable string. Parameters ---------- duration : float duration in seconds Returns ------- str human readable duration string """ if duration < 60: return f"{duration:.1f} seconds" elif duration < 3600: return f"{duration / 60:.1f} minutes" elif duration < 86400: return f"{duration / 3600:.1f} hours" return f"{duration / 86400:.1f} days"
def multi_getattr(obj, attr, default=None): """ Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is equivalent to x.a.b.c.d. When a default argument is given, it is returned when any attribute in the chain doesn't exist; without it, an exception is raised when a missing attribute is encountered. From http://code.activestate.com/recipes/577346-getattr-with-arbitrary-depth/ Deprecated, does not work with dictionaries. Use resolve_with_default() instead. """ attributes = attr.split(".") for i in attributes: try: obj = getattr(obj, i) except AttributeError: if default is not None: return default else: raise return obj
def _asciiz_to_bytestr(a_bytestring): """Transform a null-terminated string of any length into a Python str. Returns a normal Python str that has been terminated. """ i = a_bytestring.find(b'\0') if i > -1: a_bytestring = a_bytestring[0:i] return a_bytestring
def build_response(session_attributes, speechlet_response): """ Build the Response :param session_attributes: :param speechlet_response: :return: """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
def calculate_chksum(buffer): """ Calculate simple checksum by XOR'ing each byte in the buffer Returns the checksum """ checksum = 0 for b in buffer: if not b == '\n': checksum ^= int(b, 16) return checksum
def splitPgpassLine(a): """ If the user has specified a .pgpass file, we'll have to parse it. We simply split the string into arrays at :. We could just use a native python function but we need to escape the ':' character. """ b = [] escape = False d = '' for c in a: if not escape and c=='\\': escape = True elif not escape and c==':': b.append(d) d = '' else: d += c escape = False if escape: d += '\\' b.append(d) return b
def _input_key_to_id(model_id: str, key: str) -> str: """Gets the name of the feature accumulator resource.""" # Escape the commas that are used to separate the column resource id. # Those IDs have not impact to the final model, but they should be unique and # not contain commas. # # Turn the character '|' into an escape symbol. input_id = model_id + "_" + key.replace("|", "||").replace(",", "|c") if "," in input_id: raise ValueError(f"Internal error: Found comma in input_id {input_id}") return input_id
def _nint(str): """Nearest integer, internal use.""" x = float(str) if x >= 0: return int(x+0.5) else: return int(x-0.5)
def month_passed(date): """ Get the month from a date, month should be between 0 and 11 :date: a date in format YYYY/MM/DD :return: integer between 0 and 11 """ return 0 if date.split('/')[0] == '2010' else int(date.split('/')[1])
def creditcard_auth(customer, order_total): """Test function to approve/denigh an authorization request""" # Always fails Joan's auth if customer.upper() == "JOAN": return False else: return True
def frozenset_repr(iterable): """ Return a repr() of frozenset compatible with Python 2.6. Python 2.6 doesn't have set literals, and newer versions of Python use set literals in the ``frozenset()`` ``__repr__()``. """ return "frozenset(({0}))".format( ", ".join(map(repr, iterable)) )
def samplenamer(listofdata, indexposition=0): """Tries to replicate the Illumina rules to create file names from 'Sample_Name' :param listofdata: a list of data extracted from a file :param indexposition: """ samplename = listofdata[indexposition].rstrip().replace(" ", "-").replace(".", "-").replace("=", "-")\ .replace("+", "").replace("/", "-").replace("#", "").replace("---", "-").replace("--", "-") return samplename
def print_issues(issues): """ Append each of the issues to the release notes string in a form suitable for HTML output. """ text = '' for issue in issues: text += '<li>' text += '[<a href="{}">{}</a>] - {}'\ .format(issue.permalink(), issue.key, issue.fields.summary) text += '</li>\n' return text
def downcast(var_specs): """ Cast python scalars down to most common type of arrays used. Right now, focus on complex and float types. Ignore int types. Require all arrays to have same type before forcing downcasts. Note: var_specs are currently altered in place (horrors...!) """ numeric_types = [] #grab all the numeric types associated with a variables. for var in var_specs: if hasattr(var,'numeric_type'): numeric_types.append(var.numeric_type) # if arrays are present, but none of them are double precision, # make all numeric types float or complex(float) if (('f' in numeric_types or 'F' in numeric_types) and not ( 'd' in numeric_types or 'D' in numeric_types)): for var in var_specs: if hasattr(var,'numeric_type'): if issubclass(var.numeric_type, complex): var.numeric_type = 'F' elif issubclass(var.numeric_type, float): var.numeric_type = 'f' return var_specs
def generate_pin(color, coordinate): """ generates a pin for the stops :param color: the color of the pin :param coordinate: the coordinate of the pin :return: the string to write to the KML file """ output = "" # output string description = "" # description of pin image_url = "" # the image of the pin if color == 'yellow': description = "Stop For Errand" image_url = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png' if color == 'pink': description = "Stop/rolling stop for sign or light" image_url = "http://maps.google.com/mapfiles/kml/pushpin/pink-pushpin.png" output = """ # use KML syntax to make a placemark(the pin) <Placemark> <description>%s</description> <Style id="normalPlacemark"> <IconStyle> <scale>1.5</scale> <Icon><href>%s</href></Icon> </IconStyle> </Style> <Point><coordinates>%s</coordinates></Point> </Placemark> """ % (description, image_url, coordinate) return output
def if_else(condition, a, b): """ It's helper for lambda functions. """ if condition: return a else: return b
def _convert_to_str(value): """Ensure that a value is converted to a string. This ensure proper XML build. """ if type(value) in [int, float]: return str(value) elif type(value) == bool: return str(int(value)) return value
def cars_cross_path(car_lane, car_intention, other_car_lane, other_car_intention): """ Check if the path of one car crosses tih the path o f another. It is true if the other car is the same lane or if the other car is in one of the perpendicular lanes. :param car_lane: lane of the car :param car_intention: intention of a car :param other_car_intention: the intention of way of the other car :param other_car_lane: the lane at which the other car star its way. :return: True if the paths does not crosses, False otherwise. """ lane_to_int_dict = {"l": 0, "s": 1, "r": 2} table0 = [[True, True, True], [True, True, True], [True, True, True]] table1 = [[True, True, False], [True, True, False], [False, True, False]] table2 = [[True, True, True], [True, False, False], [True, False, False]] table3 = [[True, True, False], [True, True, True], [False, False, False]] all_tables = [table0, table1, table2, table3] return all_tables[(car_lane - other_car_lane) % 4][lane_to_int_dict[car_intention]][ lane_to_int_dict[other_car_intention]]
def get_epoch_from_header(sig_header: str)-> str: """Extracts epoch timestamp from the X-Telnyx-Signature header value""" sig_key_value = dict(param.split("=", 1) for param in sig_header.split(",")) epoch = sig_key_value["t"] return epoch
def norm_rgb(r, g, b): """ Normalise RGB components so the most intense (unless all are zero) has a value of 1. """ greatest = max([r, g, b]) if greatest > 0: r /= greatest g /= greatest b /= greatest return(r, g, b)
def repeated(t, k): """Return the first value in iterator T that appears K times in a row. Iterate through the items such that if the same iterator is passed into the function twice, it continues in the second call at the point it left off in the first. >>> s = iter([10, 9, 10, 9, 9, 10, 8, 8, 8, 7]) >>> repeated(s, 2) 9 >>> s2 = iter([10, 9, 10, 9, 9, 10, 8, 8, 8, 7]) >>> repeated(s2, 3) 8 >>> s = iter([3, 2, 2, 2, 1, 2, 1, 4, 4, 5, 5, 5]) >>> repeated(s, 3) 2 >>> repeated(s, 3) 5 >>> s2 = iter([4, 1, 6, 6, 7, 7, 8, 8, 2, 2, 2, 5]) >>> repeated(s2, 3) 2 """ assert k > 1 "*** YOUR CODE HERE ***" cur = next(t) count = 1 while True: temp = next(t) if temp == cur: count += 1 else: cur = temp count = 1 if count == k: return cur
def safe_eval(expression, value, names=None): """ Safely evaluates expression given value and names. Supposed to be used to parse string parameters and allow dependencies between parameters (e.g. number of channels) in subsequent layers. Parameters ---------- expression : str Valid Python expression. Each element of the `names` will be swapped with `value`. value : object Value to use instead of elements of `names`. names : sequence of str Names inside `expression` to be interpreted as `value`. Default names are `same`, `S`. Examples -------- Add 5 to the value:: safe_eval('same + 5', 10) Increase number of channels of tensor by the factor of two:: new_channels = safe_eval('same * 2', old_channels) """ #pylint: disable=eval-used names = names or ['S', 'same'] return eval(expression, {}, {name: value for name in names})
def class_decode(b): """Decode the data type from a byte. Parameters: b (byte): Byte with the encoded type Returns: str: Name of the decoded data type """ if b == b'\x00': cls = 'float64' elif b == b'\x01': cls = 'float32' elif b == b'\x02': cls = 'bool' elif b == b'\x03': cls = 'str' elif b == b'\x04': cls = 'int8' elif b == b'\x05': cls = 'uint8' elif b == b'\x08': cls = 'int32' elif b == b'\x09': cls = 'uint32' elif b == b'\x0a': cls = 'int64' elif b == b'\x0b': cls = 'uint64' elif b == b'\x0c': cls = 'dict' else: raise TypeError('invalid data type') return cls
def incremental_mean(mu_i, n, x): """ Calculates the mean after adding x to a vector with given mean and size. :param mu_i: Mean before adding x. :param n: Number of elements before adding x. :param x: Element to be added. :return: New mean. """ delta = (x - mu_i) / float(n + 1) mu_f = mu_i + delta return mu_f
def ResolveForwardingRuleURI(project, region, forwarding_rule, resource_parser): """Resolves the URI of a forwarding rule.""" if project and region and forwarding_rule and resource_parser: return str( resource_parser.Parse( forwarding_rule, collection='compute.forwardingRules', params={ 'project': project, 'region': region })) return None
def formatRs(Rs): """ :param Rs: list of triplet (multiplicity, representation order, [parity]) :return: simplified version of the same list with the parity """ d = { 0: "", 1: "+", -1: "-", } return ",".join("{}{}{}".format("{}x".format(mul) if mul > 1 else "", l, d[p]) for mul, l, p in Rs)
def insertion_sort(t_input): """ Insertion Sort Algorithm Simple, stable algorithm with in-place sorting http://en.wikipedia.org/wiki/Insertion_sort Best case performance: O(n) - when array is already sorted Worst case performance: O(n^2) - when array sorted in reverse order Worst Case Auxiliary Space Complexity: O(n) :param t_input: [list] of numbers :return: [list] - sorted list of numbers """ # copy input to array that will be sorted array = t_input[:] for i in range(1, len(t_input)): j = i while 0 < j and array[j] < array[j - 1]: # swap elements array[j], array[j - 1] = array[j - 1], array[j] j -= 1 return array
def get_scale(W, H, scale): """ Computes the scales for bird-eye view image Parameters ---------- W : int Polygon ROI width H : int Polygon ROI height scale: list [height, width] """ dis_w = int(scale[1]) dis_h = int(scale[0]) return float(dis_w/W),float(dis_h/H)
def build_mu(mut, grid, full_levels=False): """Build 3D mu on full or half-levels from 2D mu and grid constants.""" if full_levels: mu = grid["C1F"] * mut + grid["C2F"] else: mu = grid["C1H"] * mut + grid["C2H"] return mu
def mean(data): """Returns the average of a list of numbers Args: data: a list of numbers returns: a float that is the average of the list of numbers """ if len(data)==0: return 0 return sum(data) / float(len(data))
def get_host_id(item): """ get id of the device """ return int(item.split(" ")[0])
def get_timestamps(frames, fps, offset=0.0): """Returns timestamps for frames in a video.""" return [offset + x/float(fps) for x in range(len(frames))]
def to_lower_camel_case(snake_case_str): """Converts snake_case to lowerCamelCase. Example: foo_bar -> fooBar fooBar -> foobar """ words = snake_case_str.split("_") if len(words) > 1: capitalized = [w.title() for w in words] capitalized[0] = words[0] return "".join(capitalized) else: return snake_case_str
def get_model_name(param): """ name = vector_name + num_epochs + rnn_number_of_layers + rnn_dropout + GRU/LSTM separated by underscore :param param: :return: """ if param['pretrained_vectors'] == None: model_name = f"own" else: model_name = f"{param['pretrained_vectors'].split('.')[0]}" if param['RNN_USE_GRU']: model_name += f"_GRU" else: model_name += f"_LSTM" model_name += f"_{param['RNN_EPOCHS']}_epochs" \ f"_{param['RNN_N_LAYERS']}" print(f"model name is {model_name}") return model_name
def size_seq(seq1, seq2): """identify the largest and smallest sequence. Output tuple of big and sequence. """ if len(seq1) >= len(seq2): big, little = seq1, seq2 else: big, little = seq2, seq1 return big, little
def getver(value): """Return pair of integers that represent version. >>> getver('2.5') (2, 5) >>> getver('2.6.4') (2, 6) >>> getver(None) '' """ if not value: return '' return tuple(int(i) for i in value.split('.', 2))[:2]
def _get_chan_from_name(nm): """Extract channel number from filename. Given a ABI filename, extract the channel number. Args: nm (str): Filename / path to ABI file Returns: int: channel number """ return int(nm.split("/")[-1].split("-")[3][3:5])
def RowXorCol(xy1, xy2): """ Evaluates to true if the given positions are in the same row / column but are in different columns / rows """ return (xy1[0] == xy2[0]) != (xy1[1] == xy2[1])
def f(x): """ Helper function to determine number on a Gann square at coords: x, 0. If x = 0 -> 1 If x < 0 -> f(-x) - 4 * (-x) Else -> f(x-1) + 8 * x - 3 :param x: x position :return: value """ return 1 if x == 0 else (f(-x) - 4 * (-x) if x < 0 else f(x-1) + 8 * x - 3)
def preprocess(raw): """ Basic text formatting e.g. BOM at start of file """ ## 1. Remove byte order marks if necessary if raw[0]=='\ufeff': raw = raw[1:] # if raw[0] == '\xef': # raw = raw[1:] # if raw[0] == '\xbb': # raw = raw[1:] # if raw[0] == '\xbf': # raw = raw[1:] return raw
def stubs(nodes, relns): """Return the list of stub nodes.""" # start from every node, drop any node that is ever a peer or a provider stubs = set(range(0, nodes)) for ((u, v), relp) in relns.items(): if relp == "cust_prov": stubs.discard(v) elif relp == "peer_peer": stubs.discard(u) stubs.discard(v) elif relp == "prov_cust": stubs.discard(u) return list(stubs)
def get_atmos_url(year:int, variable ="PM25") -> str: """ Constructs URL to download data from the Atmospheric Composition Analysis Group given a year and a band :param year: year :param variable: Gridmet band (variable) :return: URL for download """ base = "http://fizz.phys.dal.ca/~atmos/datasets/V4NA03/" pattern = base + "V4NA03_{}_NA_{:d}01_{:d}12-RH35.nc" return pattern.format(variable, year, year)
def ping(host, silent=False): """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ import platform # For getting the operating system name import subprocess # For executing a shell command # Option for the number of packets as a function of param = "-n" if platform.system().lower() == "windows" else "-c" # Building the command. Ex: "ping -c 1 google.com" command = ["ping", param, "1", host] if silent: return ( subprocess.run( command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) == 0 ) else: return subprocess.run(command) == 0
def get_jid(log_name): """Strip path and file type from the log name to return the jid as int""" return int(log_name.split('/')[-1].split('.')[0])
def split_by_predicate(iterable, predicate): """Split an iterable into two lists the according to a predicate Return a tuple of two lists: The first has the values for which `predicate` returned True The second has the values for which `predicate` returned False :param iterable: An Iterable[T] :param predicate: A function from T to bool """ true, false = [], [] for item in iterable: if predicate(item): true.append(item) else: false.append(item) return true, false
def _check_detector(detector, **kwargs): """ checks to see if detector is in right format. """ detector_numbers = [str(i) for i in range(12)] detector_list = ['n' + i for i in detector_numbers] if detector.lower() in detector_list: return detector elif detector in detector_numbers: return 'n' + detector else: raise ValueError('Detector number needs to be a string. Available detectors are n0-n11')
def merge(left, right, lt): """Assumes left and right are sorted lists. lt defines an ordering on the elements of the lists. Returns a new sorted(by lt) list containing the same elements as (left + right) would contain.""" result = [] i,j = 0, 0 while i < len(left) and j < len(right): if lt(left[i], right[j]): result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while (i < len(left)): result.append(left[i]) i += 1 while (j < len(right)): result.append(right[j]) j += 1 return result
def fully_qualified_name(type_: type) -> str: """Construct the fully qualified name of a type.""" return getattr(type_, '__module__', '') + '.' + getattr(type_, '__qualname__', '')
def get_dlons_from_case(case: dict): """pull list of latitudes from test case""" dlons = [geo[1] for geo in case["destinations"]] return dlons
def uniform_pdf(x: float) -> float: """Uniform probability density function (PDF)""" return 1 if 0 <= x < 1 else 0
def roi_center(roi): """Return center point of an ``roi``.""" def slice_center(s): return (s.start + s.stop) * 0.5 if isinstance(roi, slice): return slice_center(roi) return tuple(slice_center(s) for s in roi)
def depth_sort(files): """Sort a list of files by folder depth.""" return sorted(files, key=lambda x: x.count('/'), reverse=True)
def example_function_with_default_args( positional_arg: int, default_arg: str = "optional" ) -> str: """Return a string that tells what args you passed in. Args: positional_arg: any number to print default_arg: any string to print Returns: A success message that includes the given arguments. """ return f"success! args: {positional_arg}, {default_arg}"
def heatCapacity(T, hCP): """ heatCapacity(T, hCP) heatCapacity = A + B*T + C*T^2 Parameters T, temperature in Kelvin hCP, A=hCP[0], B=hCP[1], C=hCP[2] A, B, and C are regression coefficients Returns heat capacity at T """ return hCP[0] + hCP[1]*T + hCP[2]*T**2
def different_delimiter_chars(one: int, two: int, three: int): """I am a sneaky function. Args: one -- this one is a no brainer even with dashes three -- noticed you're missing docstring for two and I'm multiline too! Returns: the first string argument concatenated with itself 'two' times and the last parameters multiplied by itself """ return one * two, three * three
def align(axes:str): """ axes:str -> Updates the command's execution position, aligning to its current block position "x", "xz", "xyz", "yz", "y", "z", "xy" """ if not isinstance(axes, str): return "" h = ["x", "y", "z"] b = [] for i in axes: if (not i in h) or i in b: return "" b.append(i) return f"align {axes}"
def remove_text_inside_brackets(s, brackets="()[]"): """ From http://stackoverflow.com/a/14603508/610569 """ count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in s: for i, b in enumerate(brackets): if character == b: # found bracket kind, is_close = divmod(i, 2) count[kind] += (-1)**is_close # `+1`: open, `-1`: close if count[kind] < 0: # unbalanced bracket count[kind] = 0 break else: # character is not a bracket if not any(count): # outside brackets saved_chars.append(character) return ''.join(saved_chars)
def delete(sentence, mainword, **kwargs): #Done with testing """Delete entire sentence if <mainword> is present""" if mainword not in sentence: return False, sentence else: return True, ''
def falling_factorial( x, n ): """ Calculate falling factorial of x. [https://en.wikipedia.org/wiki/Falling_and_rising_factorials] """ c = 1 for k in range(n): c *= x-k return c
def prepare_results(results): """ Prepare a given set of results and return a dict structure that contains, for each size of words, a dict structure that contains, for each number of states, a list of words that have this size and this number of states. """ words = dict() for word, size in results: length = len(word) number_of_states = words.setdefault(length, dict()) list_of_words = number_of_states.setdefault(size, []) if word not in list_of_words: list_of_words.append(word) return words
def makeGray(rgb, factor, maskColor): """ Make a pixel grayed-out. If the pixel matches the maskColor, it won't be changed. :param tuple `rgb`: a tuple of red, green, blue integers, defining the pixel :class:`wx.Colour`; :param float `factor`: the amount for which we want to grey out a pixel colour; :param `maskColor`: the mask colour. :type `maskColor`: tuple or :class:`wx.Colour`. :rtype: tuple :returns: An RGB tuple with the greyed out pixel colour. """ if rgb != maskColor: return tuple([int((230 - x)*factor) + x for x in rgb]) else: return rgb
def get_activation_details(name, layer_type, layer, keyword_arguments): """ Creates the layer details data for the activation function """ return { 'layer_details': None, 'name': name, 'type': layer_type, 'layer': layer, "keyword_arguments": keyword_arguments }
def confirm_feature_relationships(feature, feature_list_name, feature_id_sets_dict): """ Pass in a feature and the list that the feature came from, it then verifies if all feature ids in the relationships are present Note it does not check if a relationship field is present as some features will not have determined relationships. returns dict of types as keys and ids that were not found. An empty dict means all declared relationships were found """ not_found_relationships = dict() if len(feature_id_sets_dict) == 0: raise ValueError('feature_id_sets_dict is empty') if feature_list_name == "features": # means protein encoding gene may have mRNA and chidren relationships, should have CDS relationships. not_found_cdss = list() for cds in feature['cdss']: if cds not in feature_id_sets_dict['cdss']: not_found_cdss.append(cds) if len(not_found_cdss) > 0: not_found_relationships['cdss'] = not_found_cdss if "mrnas" in feature: not_found_mrnas = list() for mrna in feature['mrnas']: if mrna not in feature_id_sets_dict['mrnas']: not_found_mrnas.append(mrna) if len(not_found_mrnas) > 0: not_found_relationships['mrnas'] = not_found_mrnas if "children" in feature: not_found_children = list() for child in feature['children']: if child not in feature_id_sets_dict['non_coding_features']: not_found_children.append(child) if len(not_found_children) > 0: not_found_relationships['children'] = not_found_children elif feature_list_name == "cdss": # means will have parent_gene relationship, may have parent_mrna relationship. if "parent_gene" in feature: if feature['parent_gene'] not in feature_id_sets_dict['features']: not_found_relationships['parent_gene'] = [feature['parent_gene']] if "parent_mrna" in feature: if feature['parent_mrna'] not in feature_id_sets_dict['mrnas']: not_found_relationships['mrnas'] = [feature['parent_mrna']] elif feature_list_name == "mrnas": # means will have parent_gene relationship, may have CDS relationship. if "parent_gene" in feature: if feature['parent_gene'] not in feature_id_sets_dict['features']: not_found_relationships['parent_gene'] = [feature['parent_gene']] if "cds" in feature: if feature['cds'] not in feature_id_sets_dict['cdss']: not_found_relationships['cds'] = [feature['cds']] elif feature_list_name == "non_coding_features": # NEED TO CHECK BOTH FEATURES AND NON_CODING_FEATURES FOR PARENT_GENE # Children will only be NON_CODING_FEATURES # Do parent could be in either feature or non_coding_features (Only 1 parent) if "parent_gene" in feature: if feature['parent_gene'] not in feature_id_sets_dict['features'] and \ feature['parent_gene'] not in feature_id_sets_dict['non_coding_features']: not_found_relationships['parent_gene'] = [feature['parent_gene']] if "children" in feature: not_found_children = list() for child in feature['children']: if child not in feature_id_sets_dict['non_coding_features']: not_found_children.append(child) if len(not_found_children) > 0: not_found_relationships['children'] = not_found_children else: # Raise an error the searched for feature does not exist in any of the 4 lists. raise ValueError('Feature List Name : ' + feature_list_name + ' was not one of the expected 4 types.') return not_found_relationships
def string_to_format(value, target_format): """Convert string to specified format""" if target_format == float: try: ret = float(value) except ValueError: ret = value elif target_format == int: try: ret = float(value) ret = int(ret) except ValueError: ret = value else: ret = value return ret
def disemvowel(string): """Return string with vowels removed""" vowels = 'aeiouAEIOU' return "".join([c for c in string if c not in vowels])
def flat_list(_list): """[(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in _list], [])
def create_tag(name): """create a viewer tag from a class name.""" model_name = '%s_model' % name.lower() tag = { 'name': model_name, 'x-displayName': name, 'description': '<SchemaDefinition schemaRef=\"#/components/schemas/%s\" />\n' % name } return model_name, tag
def update_cse(cse_subs_tup_list, new_subs): """ :param cse_subs_tup_list: list of tuples: [(x1, a+b), (x2, x1*b**2)] :param new_subs: list of tuples: [(a, b + 5), (b, 3)] :return: list of tuples [(x1, 11), (x2, 99)] useful to substitute values in a collection returned by sympy.cse (common subexpressions) """ res = [] for e1, e2 in cse_subs_tup_list: new_tup = (e1, e2.subs(res + new_subs)) res.append(new_tup) return res
def transform_is_ascii( is_ascii ): """ what it says ... currently list is manual make auto ?? auto now in test """ if is_ascii == 1: return "Yes" else: return "No"
def get_conversion(img_height, leftx_base, rightx_base): """ Get the conversion factors for pixel/meters """ # y-direction: # the lane lines are about 30 m long # in the perspective transform we take about half of that # and project it to the warped image ym_per_pix = 15/img_height # the lane is about 3.7 m wide # in the warped image that corresponds to the number of pixels between # the left and right lane xm_per_pix = 3.7/(rightx_base - leftx_base) return ym_per_pix, xm_per_pix
def unescape_json_str(st): """ Unescape Monero json encoded string /monero/external/rapidjson/reader.h :param st: :return: """ c = 0 ln = len(st) escape_chmap = { b'b': b'\b', b'f': b'\f', b'n': b'\n', b'r': b'\r', b't': b'\t', b'\\': b'\\', b'"': b'\"', b'/': b'\/' } ret = [] def at(i): return st[i:i+1] while c < ln: if at(c) == b'\\': if at(c+1) == b'u': ret.append(bytes([int(st[c+2:c+6], 16)])) # ret.append(st[c:c+6].decode('unicode_escape').encode('utf8')) c += 6 else: ret.append(escape_chmap[at(c+1)]) c += 2 else: ret.append(at(c)) c += 1 df = (b''.join(ret)) return df
def constant_series(z): """ returns 1 + z + z ** 2 + ... """ return 1 / (1 - z)
def find_next_perfect_square(sq): """ sq: a number that is the square of an integer (perfect square) return: -1 if sq is not a perfect square and the square of the square root of sq + 1 if sq is a perfect square """ if (sq**0.5)*10 == int(sq**0.5)*10: return int(((sq**0.5)+1)**2) return -1