content
stringlengths
42
6.51k
def isSameTree(p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p and q: return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right) return p is q
def external_pressure(rho, g, d): """Return the external pressure [Pa] at water depth. :param float rho: Water density [kg/m^3] :param float g: Acceleration of gravity [m/s/s] :param float d: Water depth [m] """ return rho * g * d
def to_aws_tags(tags): """ Convert tags from dictionary to a format expected by AWS: [{'Key': key, 'Value': value}] :param tags :return: """ return [{'Key': k, 'Value': v} for k, v in tags.items()]
def is_valid_mysql_connection(cnx): """Check if it is a valid MySQL connection. """ if cnx is not None and cnx.is_connected(): return True return False
def generate_machine_states(service_configs): """ Generate list of all possible configurations of service and compromised status for a single machine. Config = (compromised, [s0, s1, ..., sn]) where: compromised = True/False sn = True/False """ machine_states = [] for cfg in service_configs: machine_states.append((True, cfg)) machine_states.append((False, cfg)) return machine_states
def high(string): """function takes in a string, splits it, and finds one with largest value.""" word_list = string.split() letters = [] word_dict = {} for word in word_list: string_list = [x for x in word] word_sum = 0 for letter in string_list: word_sum += ord(letter) - 97 word_dict[word] = word_sum return max(word_dict, key=lambda key: word_dict[key])
def check_indicators_all_false(indicators): """ Input: indicators: (num_regions,) list Return: True if all indicators are False, False if any indicator is True """ for indicator in indicators: if indicator: return False return True
def IsSubset(l, s): """ Check if list s is a subset of nested list l """ result = False for i in s: if set(i).issubset(set(l)): result = True return result
def dot_product(u, v): """ compute the dot product of u and v """ return sum((a*b for a, b in zip(u, v)));
def insert_sort(data): """Sort a list of unique numbers in ascending order using insert sort. O(n^2). The process includes iterating through a list and ordering elements as they're visited. Args: data: data to sort (list of int) Returns: sorted list """ sorted_data = data[:] # visit new elements for i, value in enumerate(sorted_data): # compare each new element with previously visited elements for j in range(i, -1, -1): # swap if needed if sorted_data[j] > value: sorted_data[j + 1] = sorted_data[j] sorted_data[j] = value return sorted_data
def analysis_max(x, y): """Maximum of two integers.""" result = max(x, y) return result
def convert_hex_to_255(hex_color): """ hex_color = '#6A5AFFAF' """ assert hex_color.startswith('#'), 'not a hex string %r' % (hex_color,) parts = hex_color[1:].strip() color255 = tuple(int(parts[i : i + 2], 16) for i in range(0, len(parts), 2)) assert len(color255) in [3, 4], 'must be length 3 or 4' # # color = mcolors.hex2color(hex_color[0:7]) # if len(hex_color) > 8: # alpha_hex = hex_color[7:9] # alpha_float = int(alpha_hex, 16) / 255.0 # color = color + (alpha_float,) return color255
def merge_partial_elements(element_list): """ Merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list: list List of all the elements. Returns ------- list: List of merged elements. """ outs = dict() # output data structure for element in element_list: if element["py_expr"] != "None": # for name = element["py_name"] if name not in outs: # Use 'expr' for Vensim models, and 'eqn' for Xmile # (This makes the Vensim equation prettier.) eqn = element["expr"] if "expr" in element else element["eqn"] outs[name] = { "py_name": element["py_name"], "real_name": element["real_name"], "doc": element["doc"], "py_expr": [element["py_expr"]], # in a list "unit": element["unit"], "subs": [element["subs"]], "merge_subs": element["merge_subs"] if "merge_subs" in element else None, "lims": element["lims"], "eqn": [eqn.replace(r"\ ", "")], "kind": element["kind"], "arguments": element["arguments"], } else: eqn = element["expr"] if "expr" in element else element["eqn"] outs[name]["doc"] = outs[name]["doc"] or element["doc"] outs[name]["unit"] = outs[name]["unit"] or element["unit"] outs[name]["lims"] = outs[name]["lims"] or element["lims"] outs[name]["eqn"] += [eqn.replace(r"\ ", "")] outs[name]["py_expr"] += [element["py_expr"]] outs[name]["subs"] += [element["subs"]] outs[name]["arguments"] = element["arguments"] return list(outs.values())
def prepare_nodelist(lists): """ Combine lists of nodes into a single master list for use by nmf_pathway and other functions that accept a nodelist as input """ set_all = set() for ll in lists: for item in ll: set_all.add(item) rv = sorted(set_all) return rv
def else_while(n, numbers): """ A function illustrating the use of else with a loop. This function will determine if n is in the iterable numbers. :param n: The thing to search for. :param numbers: An iterable to search over. :return: True if the thing is in the iterable, false otherwise. """ # Loop over the numbers for e in numbers: # If we've found it, break out of the loop. if e == n: break else: # The else clause runs if we exited the loop normally (ie, didn't break) return False # Otherwise, if we execute break, then we get to here. return True
def R(units): """Universal molar gas constant, R Parameters ---------- units : str Units for R. Supported units ============= =============================================== ============ Unit Description Value ============= =============================================== ============ J/mol/K Joule per mole per kelvin 8.3144598 kJ/mol/K kiloJoule per mole per kelvin 8.3144598e-3 L kPa/mol/K Liter kilopascal per mole per kelvin 8.3144598 cm3 kPa/mol/K Cubic centimeter kilopascal per mole per kelvin 8.3144598e3 m3 Pa/mol/K Cubic meter pascal per mole per kelvin 8.3144598 cm3 MPa/mol/K Cubic centimeter megapascal per mole per kelvin 8.3144598 m3 bar/mol/K Cubic meters bar per mole per kelvin 8.3144598e-5 L bar/mol/K Liter bar per mole per kelvin 8.3144598e-2 L torr/mol/K Liter torr per mole per kelvin 62.363577 cal/mol/K Calorie per mole per kelvin 1.9872036 kcal/mol/K Kilocalorie per mole per kevin 1.9872036e-3 L atm/mol/K Liter atmosphere per mole per kelvin 0.082057338 cm3 atm/mol/K Cubic centimeter atmosphere per mole per kelvin 82.057338 eV/K Electron volt per molecule per kelvin 8.6173303e-5 Eh/K Hartree per molecule per kelvin 3.1668105e-6 Ha/K Hartree per molecule per kelvin 3.1668105e-6 ============= =============================================== ============ Returns ------- R : float Universal molar gas constant in appropriate units Raises ------ KeyError If units is not supported. """ R_dict = { 'J/mol/K': 8.3144598, 'kJ/mol/K': 8.3144598e-3, 'L kPa/mol/K': 8.3144598, 'cm3 kPa/mol/K': 8.3144598e3, 'm3 Pa/mol/K': 8.3144598, 'cm3 MPa/mol/K': 8.3144598, 'm3 bar/mol/K': 8.3144598e-5, 'L bar/mol/K': 8.3144598e-2, 'L torr/mol/K': 62.363577, 'cal/mol/K': 1.9872036, 'kcal/mol/K': 1.9872036e-3, 'L atm/mol/K': 0.082057338, 'cm3 atm/mol/K': 82.057338, 'eV/K': 8.6173303e-5, 'Eh/K': 3.1668105e-06, 'Ha/K': 3.1668105e-06, } try: return R_dict[units] except KeyError: err_msg = ('Invalid unit for R: {}. Use help(pmutt.constants.R) ' 'for accepted units.'.format(units)) raise KeyError(err_msg)
def int2str(n, length=-1): """Convert an integer to a byte string. @param n: positive integer to convert @param length: minimum length @return: converted bytestring, of at least the minimum length if it was specified """ assert n >= 0 r = bytearray() while length < 0 or len(r) < length: r.append(n & 0xff) n >>= 8 if length < 0 and n == 0: break r.reverse() assert length < 0 or len(r) == length return r
def _extract_contractions(sent): """ Args: sent - a single sentence split up into (word, pos) tuples. Returns: List with the indices in the sentence where the contraction starts. Or None if no contractions are in the sentence. Based on the POS-tags and the existence of an apostrophe or not, extract the existing contractions. """ idx_lst = [] for i, word_pos in enumerate(sent): # If the word in the word_pos tuple begins with an apostrophe, # add the index to idx_list. if word_pos[0][0] == "'": if word_pos[1] != 'POS': # POS stands for possessive pronoun idx_lst.append(i) elif word_pos[0] == "n't": # n't is treated extraordinarily and added explicitly idx_lst.append(i) if idx_lst: return idx_lst
def linear(x, a, b): """ Input: x - given point for which background is calculated (floats) a, b - coeffitients for linear background function a * x + b Return: value of function with desired parameters in x (float) Descr.: Calculate linear function for given x and parameters""" return a * x + b
def short_version(version): """Get a shorter version, only with the major and minor version. :param version: The version. :type version: str :return 'major.minor' version number. :rtype float """ return float('.'.join(version.split('.')[0:2]))
def translate_version(iana_version: str) -> str: """Translates from an IANA version to a PEP 440 version string. E.g. 2020a -> 2020.1 """ if ( len(iana_version) < 5 or not iana_version[0:4].isdigit() or not iana_version[4:].isalpha() ): raise ValueError( "IANA version string must be of the format YYYYx where YYYY represents the " f"year and x is in [a-z], found: {iana_version}" ) version_year = iana_version[0:4] patch_letters = iana_version[4:] # From tz-link.html: # # Since 1996, each version has been a four-digit year followed by # lower-case letter (a through z, then za through zz, then zza through zzz, # and so on). if len(patch_letters) > 1 and not all(c == "z" for c in patch_letters[0:-1]): raise ValueError( f"Invalid IANA version number (only the last character may be a letter " f"other than z), found: {iana_version}" ) final_patch_number = ord(patch_letters[-1]) - ord("a") + 1 patch_number = (26 * (len(patch_letters) - 1)) + final_patch_number return f"{version_year}.{patch_number:d}"
def build_controllers(controller_definitions): """ loop through the list of controller definitions creating them. """ c_list = [] for controller_definition in controller_definitions: c_list.append(controller_definition()) return c_list
def compute_cell_next_state(current, neighbours): """Return the next state of the cell on position (i, j) in alive_matrix. Parameters ---------- current: int The state of the cell, 1 or 0 (live or dead) neighbours: array The number of alive cells around the cell. Returns ------- new_state: int The new state of the cell, 1 or 0 (live or dead) """ new_state = 0 if current > 0: if neighbours == 2 or neighbours == 3: new_state = 1 elif neighbours == 3: new_state = 1 return new_state
def slot_by_car_number(parkingLot, number): """ prints the slot number of the cars for the given number ARGS: parkingLot(ParkingLot Object) number(str) - given registration number """ returnString = '' if parkingLot: if not parkingLot.get_parked_cars(): returnString = 'Sorry, parking lot is empty' else: flag = False parkingSlot = parkingLot.get_slots() for parkedCar in parkingSlot.values(): if parkedCar is not None: if parkedCar.get_registration_number() == number: flag = True returnString += str(parkedCar.get_slot()) + ', ' # assuming that for the cars, there is one and only one registration number exits break if not flag: returnString = 'Not found' else: returnString = 'Parking lot is not defined' return returnString
def value_in_range(rule, value): """ Checks if a value is in range of a given tuple. :param rule: [(a, b), (c, d)] :param value: value :return: boolean """ return value in range(rule[0][0], rule[0][1] + 1) or \ value in range(rule[1][0], rule[1][1] + 1)
def power_law(deg_sep, ALPHA=1.0): """ Applies a power law model. WEIGHT = DEG_SEP^(-ALPHA) ALPHA: Parameter to control power law decay rate. """ return (deg_sep + 1) ** (- ALPHA)
def FilterInteger(param, value): """ Filter: Assert integral number. """ if value.isnumeric () == False: return "parameter --" + param.name + " expectes an integer as value" return None
def action_not_implemented(*args, **kwargs) -> dict: """ Default function if no action function is found :return: OpenC2 response message - dict """ return dict( status=501, status_text="Action not implemented" )
def _get_year(obj): """ Get the year of the entry. :param obj: year string object :return: entry year or none if not valid value """ year = obj[0:4] try: year = int(year) except ValueError: year = None return year
def isxdigit(znak): """Provjerava je li znak hex znamenka""" return znak != '' and (znak.isdigit() or znak in 'ABCDEFabcdef')
def get_heat_required_input(data): """Returns Heat required user input fields.""" heat_params = [] heat_param_dict = data["parameters"] for key, heat_param in heat_param_dict.items(): heat_params.append([key, heat_param.get("type"), heat_param.get("default"), heat_param.get("description")]) return sorted(heat_params)
def evaluate_postfix(postfix): """ Evaluates a postfix expression. Precondition: postfix is a valid postfix expression (no extra numbers, extra operators, etc.) :param postfix: Postfix expression to be evaluated :return: Result of the postfix expression, or error if unsupported operators used """ stack = [] postfix_tokens = postfix.split() for token in postfix_tokens: if token in "1234567890": stack.append(int(token)) # If number, push to stack else: num2 = stack.pop() # If operator then pop last num1 = stack.pop() # two numbers in stack # Do the calculation if token is "*": result = num1 * num2 elif token is "/": result = num1 / num2 elif token is "+": result = num1 + num2 elif token is "-": result = num1 - num2 else: return "Invalid operator detected." stack.append(result) # Add calculation to stack return stack.pop()
def _get_package_version(package): """Get the version for a package (if any).""" return package["version"] or "None"
def invert_dict(dict_in, append_list=False): """ Invert the key:values of a dict :param dict_in: dict to invert :param append_list: append to a list? (for non-uniqueness) :return: inverted dict """ if not append_list: return {val:key for key,val in dict_in.items()} else: dict_out = {val:[] for key,val in dict_in.items()} for key, val in dict_in.items(): dict_out[val].append(key) return dict_out
def _grab_newline(position, string, direction): """ Boundary can be preceded by `\r\n` or `\n` and can end with `\r\n` or `\n` this function scans the line to locate these cases. """ while 0 < position < len(string): if string[position] == '\n': if direction < 0: if position - 1 > 0 and string[position-1] == '\r': return position - 1 return position position += direction return position
def return_xs_unique(xs, ys): """ merge sorted lists xs and ys. Return only those items that are present in the first list, but not in the second. """ result = [] xi = 0 while True: if xi >= len(xs): # If xs list is finished, return result # We're done. if xs[xi] not in ys: # this time it just checks the reverse condition compared to exercise 1 result.append(xs[xi]) xi += 1 else: xi += 1
def format_nav_item(url: str, title: str) -> str: """Format a single entry for the navigation bar (navbar).""" return '<li class="nav-item"><a class="nav-link" href="{}">{}</a></li>'.format(url, title)
def select_bucket_region( custom_bucket, hook_region, cfngin_bucket_region, provider_region ): """Return the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (Optional[str]): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. cfngin_bucket_region (str): The contents of the ``cfngin_bucket_region`` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string. """ region = None if custom_bucket: region = hook_region else: region = cfngin_bucket_region return region or provider_region
def isleapyear(year): """Given a year as an integer (e.g. 2004) it returns True if the year is a leap year, and False if it isn't.""" if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 == 0: return True else: return False
def mpl_process_lbl(lbl, math=False): """ Process a (plotly-compatible) text label `lbl` to matplotlb text. Parameters ---------- lbl : str A text label to process. math : bool, optional Whether math-formatting (latex) should be used. Returns ------- str """ if not isinstance(lbl, str): lbl = str(lbl) # just force as a string math = math or ('<sup>' in lbl) or ('<sub>' in lbl) or \ ('_' in lbl) or ('|' in lbl) or (len(lbl) == 1) try: float(lbl) math = True except: pass l = lbl l = l.replace("<i>", "").replace("</i>", "") l = l.replace("<sup>", "^{").replace("</sup>", "}") l = l.replace("<sub>", "_{").replace("</sub>", "}") l = l.replace("<br>", "\n") if math: l = l.replace("alpha", "\\alpha") l = l.replace("beta", "\\beta") l = l.replace("sigma", "\\sigma") if math or (len(l) == 1): l = "$" + l + "$" return l
def get_frame(env_observation, info): """Searches for a rendered frame in 'info', fallbacks to the env obs.""" info_frame = info.get('frame') if info_frame is not None: return info_frame return env_observation
def for_each_du_in_mcu(mcu, func): """ Helper function that iterates over all DU's in an MCU and runs "func" on it """ return [map(func, comp) for comp in mcu]
def vrtc_center(viewport_size, cursor_size): """Puts the cursor at the center of the viewport""" return int((viewport_size - cursor_size) / -2)
def calcMemUsage(counters): """ Calculate system memory usage :param counters: dict, output of readMemInfo() :return: system memory usage """ used = counters['total'] - counters['free'] - \ counters['buffers'] - counters['cached'] total = counters['total'] # return used*100 / total return used / total
def point_not_below_center(p, c): """Return True if a point lies not below (y-value) a circle's center point. Parameters ---------- p : Point that should be checked c : Center point of the circle Returns ------- bool True or False """ return p[1] >= c[1] - 1e-9
def get_environment(health_event): """Get the environment setting from the source event Normalise to prod|test to match index names """ try: event_env = health_event.get("Environment", "prod") except (TypeError): event_env = "prod" env = "prod" if event_env in ("prod", "production", "live") else "test" return env
def _convert(t): """Convert feature and value to appropriate types""" return int(t[0]), float(t[1])
def validate_http_request(request): """Check if request is a valid HTTP request and returns True or False along with the requested URL :param request: The HTTP Request :type request: bytes :return: Whether the request is valid or not and the requested path :rtype: tuple """ headers = [header for header in request.decode().split("\r\n")] basic_info = headers[0].split(" ") if basic_info[0] == "GET" and basic_info[1].startswith("/") and basic_info[2] == "HTTP/1.1": return True, basic_info[1] return False, None
def is_bit_k_set(int_val, k): """Tests if the value of bit at offset k in an integer is set""" return (int_val & (1 << k)) != 0
def dictChoice(invalue, dictionary): """ Return the key of a dictionary designated by a given value, where the value is a ponderation to be consumed. """ value = invalue for key in dictionary.keys(): value -= dictionary[key] if value < 0: return key raise Exception("The value asked is out of the dictionary.")
def compare_command(commands): """check if the commands is valid""" if len(commands) < 3: return True if commands[0] != 'sys' or commands[1] != 'undo ip route-static default-bfd' \ or commands[2] != 'commit': return True
def kelvinToFahrenheit(kelvin:float, ndigits = 2)->float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit """ return round(((float(kelvin) - 273.15)* 9 / 5)+32,ndigits)
def get_dictkey(In, k, dtype): """ returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command: get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats. """ Out = [] for d in In: if dtype == '': Out.append(d[k]) if dtype == 'f': if d[k] == "": Out.append(0) elif d[k] == None: Out.append(0) else: Out.append(float(d[k])) if dtype == 'int': if d[k] == "": Out.append(0) elif d[k] == None: Out.append(0) else: Out.append(int(d[k])) return Out
def lowercase_keys(d: dict): """Map keys to lowercase, e.g. it will map a dict with a MODELS key into {"models": "MODELS"}. This allows for a unified way of naming custom-case keys. """ out = {} for k in d.keys(): out[k.lower()] = k return out
def validate_frequencies(frequencies, p_floor, p_ceil, max_p_factor): """Given a sequence of frequencies, [f1, f2, ..., fn], a minimum period, maximum period, and maximum period factor, first remove all frequencies computed as 0. Then, if periods are the inverse frequencies, this function returns True if the sequence of periods satisfies the conditions, otherwise returns False. In order to satisfy the maximum period factor, the periods have to satisfy pi / pi+1 < max_p_factor and pi+1 / pi < max_p_factor. Args: frequencies (sequence, eg list, of floats): sequence of frequencies == 1 / period. p_floor (float): minimum acceptable period. p_ceil (float): maximum acceptable period. max_p_factor (float): value to use for the period factor principle Returns: bool: True if the conditions are met, False otherwise. """ for freq in frequencies: if freq == 0: return False periods = [1 / f for f in frequencies] for period in periods: if period < p_floor or period > p_ceil: return False if len(periods) > 1 and max_p_factor is not None: for period1, period2 in zip(periods[:-1], periods[1:]): if period1 / period2 > max_p_factor or period2 / period1 > max_p_factor: return False return True
def an_example_plugin(qrcode): """\ This is a Segno converter plugin used by the next test case. """ assert qrcode return 'works'
def is_eval_epoch(eval_period, cur_epoch, num_epochs): """ Determine if the model should be evaluated at the current epoch. """ return ( cur_epoch + 1 ) % eval_period == 0 or cur_epoch + 1 == num_epochs
def pad(sequences, pad_int, max_length=None): """ ARGUMENTS: sequences : list of sequences (list of word ids) RETURNS: padded_sequences : list with padded sequences """ # if max length is not defined, set length to the longest sequence, # then return the padded sequences if max_length is None: length = max([len(sequence) for sequence in sequences]) return [sequence + [pad_int]*(length-len(sequence)) for sequence in sequences] # else, padded_sequences = [] for sequence in sequences: if len(sequence) >= max_length: padded_sequences.append(sequence[:max_length]) else: padded_sequences.append(sequence+[pad_int]*(max_length-len(sequence))) return padded_sequences
def string_rotate(line: str, num_of_symbol: int) -> str: """ Function make left rotate for string :param line: Line to rotate :param num_of_symbol: Number of symbol to rotate :return: Rotating line """ return line[num_of_symbol:] + line[:num_of_symbol]
def update_episodes_per_oracles(episodes_per_oracle, played_policies_indexes): """Updates the current episode count per policy. Args: episodes_per_oracle: List of list of number of episodes played per policy. One list per player. played_policies_indexes: List with structure (player_index, policy_index) of played policies whose count needs updating. Returns: Updated count. """ for player_index, policy_index in played_policies_indexes: episodes_per_oracle[player_index][policy_index] += 1 return episodes_per_oracle
def get_strawberry_type(name, description, directives): """ Create strawberry type field as a string """ strawberry_type = "" deprecated = [d for d in directives if d.name.value == "deprecated"] deprecated = deprecated[0] if deprecated else None if name or description is not None or directives or deprecated: strawberry_type = " = strawberry.field({}{}{} )".format( f"\n name='{name}'," if name else "", f"\n description='''{description.value}''',\n" if description is not None else "", f"\n derpecation_reason='{deprecated.arguments[0].value.value}',\n" if deprecated else "", ) return strawberry_type
def _parse_ports(ports_text): """ Handle the case where the entry represents a range of ports. Parameters ---------- ports_text: str The text of the given port table entry. Returns ------- tuple A tuple of all ports the text represents. """ ports = ports_text.split('-') try: if len(ports) == 2: ports = tuple(range(int(ports[0]), int(ports[1]) + 1)) else: ports = (int(ports[0]),) except ValueError: return () return ports
def prepare_data(data, xn, yn): """Change format from (algo, instance, dict) to (algo, instance, x, y).""" res = [] for algo, algo_name, result in data: res.append((algo, algo_name, result[xn], result[yn])) return res
def ERR_calc(ACC): """ Calculate error rate. :param ACC: accuracy :type ACC: float :return: error rate as float """ try: return 1 - ACC except Exception: return "None"
def grid_search(g, p): """ :type g: list[list[int]] :type p: list[list[int]] :rtype: bool """ pattern_found = False for i in range(0, len(g) - len(p) + 1): for j in range(0, len(g[i]) - len(p[0]) + 1): for p_i in range(len(p)): row_pattern_found = False for p_j in range(len(p[p_i])): if g[i + p_i][j + p_j] != p[p_i][p_j]: break else: row_pattern_found = True if not row_pattern_found: break else: pattern_found = True if pattern_found: break if pattern_found: break return pattern_found
def mult_mat_vec(a, b): """Multiply matrix times vector for any indexable types.""" return [sum(ae*be for ae, be in zip(a_row, b)) for a_row in a]
def inc(i): """Increments number. Simple types like int, str are passed to function by value (value is copied to new memory slot). Class instances and e.g. lists are passed by reference.""" i += 1 return i
def convert_pyte_buffer_to_colormap(buffer, lines): """ Convert a pyte buffer to a simple colors """ color_map = {} for line_index in lines: # There may be lines outside the buffer after terminal was resized. # These are considered blank. if line_index > len(buffer) - 1: break # Get line and process all colors on that. If there are multiple # continuous fields with same color we want to combine them for # optimization and because it looks better when rendered in ST3. line = buffer[line_index] line_len = len(line) if line_len == 0: continue # Initialize vars to keep track of continuous colors last_bg = line[0].bg if last_bg == "default": last_bg = "black" last_fg = line[0].fg if last_fg == "default": last_fg = "white" if line[0].reverse: last_color = (last_fg, last_bg) else: last_color = (last_bg, last_fg) last_index = 0 field_length = 0 char_index = 0 for char in line: # Default bg is black if char.bg is "default": bg = "black" else: bg = char.bg # Default fg is white if char.fg is "default": fg = "white" else: fg = char.fg if char.reverse: color = (fg, bg) else: color = (bg, fg) if last_color == color: field_length = field_length + 1 else: color_dict = {"color": last_color, "field_length": field_length} if last_color != ("black", "white"): if line_index not in color_map: color_map[line_index] = {} color_map[line_index][last_index] = color_dict last_color = color last_index = char_index field_length = 1 # Check if last color was active to the end of screen if last_color != ("black", "white"): color_dict = {"color": last_color, "field_length": field_length} if line_index not in color_map: color_map[line_index] = {} color_map[line_index][last_index] = color_dict char_index = char_index + 1 return color_map
def mod(a,b): """ Function that return the modulus of two numbers (a%b) Takes arguments mod(a,b) """ i = 1 if float(a/b) - int(a/b) != 0.0: while True: if b*i < a: i +=1 else: return a - b * (i-1) break elif b > a: return a else: return 0
def vec_dot(a, b): """Compute the dot product of two vectors given in lists.""" return sum([va * vb for va, vb in zip(a, b)])
def label_decoder(zmin): """figure friendly labels for the redshift bins """ zmax, zs = zmin + 0.1, zmin + 0.2 label = "{0:.1f}< {3:s} <{1:.1f}, {4:s}>{2:.1f}".format(zmin, zmax, zs, r"$z_{\rm H\alpha}$", r"$z_{\rm s}$") return label
def Make_Sequential(sents): """ Make sequential parses (each word simply linked to the next one), to use as baseline """ sequential_parses = [] for sent in sents: parse = [["0", "###LEFT-WALL###", "1", sent[0]]] # include left-wall for i in range(1, len(sent)): parse.append([str(i), sent[i - 1], str(i + 1), sent[i]]) #parse.append([str(i), sent[i - 1], str(i + 1), sent[i]] for i in range(1, len(sent))) sequential_parses.append(parse) return sequential_parses
def default_dev_objective(metrics): """ Objective used for picking the best model on development sets """ if "eval_mnli/acc" in metrics: return metrics["eval_mnli/acc"] elif "eval_mnli-mm/acc" in metrics: return metrics["eval_mnli-mm/acc"] elif "eval_f1" in metrics: return metrics["eval_f1"] elif "eval_mcc" in metrics: return metrics["eval_mcc"] elif "eval_pearson" in metrics: return metrics["eval_pearson"] elif "eval_acc" in metrics: return metrics["eval_acc"] raise Exception("No metric founded for {}".format(metrics))
def init_icon_state_dict(icon_names): """Initialise the icon state for icon_names.""" return {k: False for k in icon_names}
def d2(dx, fc, i): """ second-order centered derivative at index i """ D = fc[i+1] - fc[i-1] D = D/(2.0*dx) return D
def destring(value): """ Strip quotes from string args: value (str) returns: str """ return value.strip('"\'')
def print_path(path): """Assumes path is a list of nodes""" result = '' for i in range(len(path)): result = result + str(path[i]) if i != len(path) - 1: result = result + '->' return result
def baseline_from_names(names_list): """Given a list of ifg names in the form YYYYMMDD_YYYYMMDD, find the temporal baselines in days_elapsed (e.g. 12, 6, 12, 24, 6 etc. ) Inputs: names_list | list | in form YYYYMMDD_YYYYMMDD Returns: baselines | list of ints | baselines in days History: 2020/02/16 | MEG | Documented """ from datetime import datetime, timedelta baselines = [] for file in names_list: master = datetime.strptime(file.split('_')[-2], '%Y%m%d') slave = datetime.strptime(file.split('_')[-1][:8], '%Y%m%d') baselines.append(-1 *(master - slave).days) return baselines
def strip_quotes(t): """ Run replace_diacritics first -- this routine only attempts to remove normal quotes ~ ', " """ return t.strip('"').strip("'")
def licor_correction(exp_signal, control_signal): """ """ # Make sure all of the inputs are numbers assert all([type(item) == float or type(item) == int for item in exp_signal]), "Signal should be provided as a float." assert all([type(item) == float or type(item) == int for item in control_signal]), "Signal should be provided as a float." assert len(exp_signal) == len(control_signal), "The exp_signal and control_signal should be index paired lists of the same size." # Make the correction factors using the max signal corr_facts = [signal / max(control_signal) for signal in control_signal] # Correct the experimental signals using the controls return [exp_signal[i]/corr_facts[i] for i in range(len(exp_signal))]
def parseAlphabetNotation(userInput): """ Replaces any valid coordinate character with a number """ userInput = userInput.lower() userInput = userInput.replace("a", "1") userInput = userInput.replace("b", "2") userInput = userInput.replace("c", "3") userInput = userInput.replace("d", "4") userInput = userInput.replace("e", "5") userInput = userInput.replace("f", "6") userInput = userInput.replace("g", "7") return userInput
def keys_with_max_val(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) nbMax = v.count(max(v)) k=list(d.keys()) if nbMax == 1: return k[v.index(max(v))] else: keys = [] for i in range(nbMax): v=list(d.values()) k=list(d.keys()) firstKey = k[v.index(max(v))] keys.append(firstKey) del d[firstKey] return keys
def underline(line, character="-"): """Return the line underlined. """ return line + "\n" + character * len(line)
def compute_exact_R_P(final_patterns, centones_tab): """ Function tha computes Recall and Precision with exact matches """ true = 0 for tab in final_patterns: for centon in centones_tab[tab]: check = False for p in final_patterns[tab]: if centon == p: check = True if check: true += 1 all_centones = len([x for y in centones_tab.values() for x in y]) all_ours = len([x for y in final_patterns.values() for x in y]) overall_recall = true / all_centones overall_precision = true / all_ours return overall_recall, overall_precision
def split_array(a): """ split a list into two lists :param a: list of integers :return: two sub-list of integers """ n = len(a) if n == 1: return a index = n // 2 b = a[:index] c = a[index:] return b, c
def compare_adapters(adapters): """Part 1""" jolt1 = 0 jolt3 = 0 for i in range(len(adapters) - 1): diff = adapters[i+1] - adapters[i] if diff == 1: jolt1 += 1 if diff == 3: jolt3 += 1 print(f"Found {jolt1} jolt1 and {jolt3} jolt3") return jolt1 * jolt3
def identify(payload): """If we are here, token verification was successful. Do not load actual user model from mongo, as it's not always required. This can help us save few RPS on mongo reads. """ return payload['identity']
def any_not_none(*args): """ Returns a boolean indicating if any argument is not None. """ return any(arg is not None for arg in args)
def se_beta_formatter(value: str) -> str: """ SE Beta formatter. This formats SE beta values. A valid SE beta values is a positive float. @param value: @return: """ try: se_beta = float(value) if se_beta >= 0: result = str(se_beta) else: raise ValueError(f'position expected positive float "{value}"') except ValueError as value_error: raise ValueError( f'position could not be parsed as integer "{value}" details : {value_error}', ) from value_error return result
def iterative_topological_sort(graph, start): """doesn't return some nodes""" seen = set() stack = [] # path variable is gone, stack and order are new order = [] # order will be in reverse order at first queue = [start] while queue: node = queue.pop() if node not in seen: seen.add(node) # no need to append to path any more queue.extend(graph[node]) while stack and node not in graph[stack[-1]]: # new stuff here! order.append(stack.pop()) stack.append(node) return stack + order[::-1]
def flip_nums(text): """ flips numbers on string to the end (so 2019_est --> est_2019)""" if not text: return '' i = 0 s = text + '_' while text[i].isnumeric(): s += text[i] i += 1 if text[i] == '_': i += 1 return s[i:]
def is_json_string(text: str) -> bool: """ Given an input text, is_json_string returns `True` if it is a valid JSON string, or False otherwise. The definition of a valid JSON string is set out in the JSON specification available at https://json.org/. Specifically, the section on strings defines them as: "A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes." """ # Valid state machine states empty_state = "EMPTY" inside_string_state = "INSIDE_STRING" start_escape_state = "START_ESCAPE" end_string_state = "END_STRING" state = empty_state for char in text: if state == empty_state: # EMPTY state is the start of the JSON string, the current character must be a double-quote character: " if char == "\"": state = inside_string_state else: return False elif state == inside_string_state: # INSIDE_STRING state is any characters inside the body of the string. # The inside of a string can be any Unicode character other than \ and " # - \ signifies the begin of an escape sequence # - " signifies the end of the JSON string if char == "\\": state = start_escape_state elif char == "\"": state = end_string_state elif state == start_escape_state: # START_ESCAPE state is entered when a \ was the previous character. The next character # must be one of ", \, /, b, f, b, r, t, or u to define a valid escape sequence. if char in ["\"", "\\", "/", "b", "f", "n", "r", "t", "u"]: state = inside_string_state else: return False elif state == end_string_state: # END_STRING is entered if the previous character we parsed was the string closing # double-quote. If there are still more characters to process text is not a valid JSON string. return False else: # If we don't enter a valid state branch, somehow we've gotten into an invalid state and we cannot continue raise Exception("Invalid state machine state: {}".format(state)) # If we managed to parse the entire string without error, we know we have a JSON string return True
def hex2rgb(h): """ Convert hex colors to RGB tuples Parameters ---------- h : str String hex color value >>> hex2rgb("#ff0033") '255,0,51' """ if not h.startswith('#') or len(h) != 7: raise ValueError("Does not look like a hex color: '{0}'".format(h)) return ','.join(map(str, ( int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16), )))
def fix_hypenation (foo): """ fix hyphenation in the word list for a parsed sentence """ i = 0 bar = [] while i < len(foo): text, lemma, pos, tag = foo[i] if (tag == "HYPH") and (i > 0) and (i < len(foo) - 1): prev_tok = bar[-1] next_tok = foo[i + 1] prev_tok[0] += "-" + next_tok[0] prev_tok[1] += "-" + next_tok[1] bar[-1] = prev_tok i += 2 else: bar.append(foo[i]) i += 1 return bar
def can_reach(adj, start, end): """ Searches in a graph represented by an adjacency list to determine if there is a path from a start vertex to an end vertex. """ vis = [False] * len(adj) def dfs(src): if vis[src]: return False vis[src] = True return src == end or any(dfs(dest) for dest in adj[src]) return dfs(start)
def paritysort_list(arr): """Move all even numbers to the left and all odd numbers to the right Args: arr (list[int]): a list of integers to be sorted in place Returns: (int): number of exchanges needed to complete the sorting """ larr = len(arr) parr = [[i[0] % 2, i] for i in arr] swap_count = 0 for i in range(larr): swapped = False for j in range(0, larr - i - 1): if parr[j][0] > parr[j + 1][0]: parr[j], parr[j + 1] = parr[j + 1], parr[j] swapped = True swap_count += 1 if not swapped: break for indx, val in enumerate(parr): arr[indx] = list(val[1]) return swap_count, arr
def sample_b1_fib(x): """Calculate fibonacci numbers.""" if x == 0 or x == 1: return 1 return sample_b1_fib(x - 1) + sample_b1_fib(x - 2)
def single_sort_by(queryset, params): """ Orders and returns the queryset using the GET parameters of a request The function takes care of checking if the "sort_by" key exists in the dict :param queryset queryset: A queryset object from a django model :param dict params: Dict containing the request params :return: The sorted and updated queryset :rtype: queryset """ sort_by = params.get("sort_by", None) if sort_by: ascending = params.get("ascending", False) if ascending != "true": sort_by = "-" + sort_by queryset = queryset.order_by(sort_by) return queryset
def calc_angle_speed(omega: float, ang_speed_max: float) -> float: """ Calculation of angular speed :param omega: normalized angular speed [-1 1] :param ang_speed_max: angular speed maximum value, deg/s :return: Angular speed [0 360] grad/s """ if abs(omega) < 0.15: return 0.0 return omega * ang_speed_max
def find_unsaticefied(recipe, likes): """ Find an unsaticefied customer index (0-based). Returns -1 if all customers can be saticefied. """ for i,like in enumerate(likes): for x in like: if recipe[x[0]-1] == x[1]: break else: return i return -1