content
stringlengths
42
6.51k
def eng_to_i18n(string, mapping): """Convert English to i18n.""" i18n = None for k, v in mapping.items(): if v == string: i18n = k break return i18n
def _escape_specification(specification): # type: (str) -> str """ Escapes the interface string: replaces slashes '/' by '%2F' :param specification: Specification name :return: The escaped name """ return specification.replace("/", "%2F")
def main1(nums, k): """ Find compliment of each number in the remaining list. Time: O(n^2) Space: O(1) """ for i, num in enumerate(nums): compliment = k - num if compliment in nums[i + 1:]: return True return False
def n(src): """ Normalize the link. Very basic implementation :param src: :return: """ if src.startswith('//'): src = 'http:' + src return src
def _build_line(entry): """ Create a define statement in a single line. Args: - entry(Dictionary(String:String)): Dictionary containing a description of the target define statement using the Keys: 'Module', 'Address/Value', 'Function', 'Submodule' (opt), 'Comment' (opt) Returns: - (String): Define statement of the form: #define Module_Submodule_Function Address/Value // Comment """ line = '#define ' line += '{}_'.format(entry['Module']) if entry['Submodule']: line += '{}_'.format(entry['Submodule']) line += entry['Function'] line += ' {} '.format(entry['Address/Value']) if entry['Comment']: line += '// {}'.format(entry['Comment']) line += '\n' return line
def decode_base64(data): """Decodes a base64 string to binary.""" import base64 data = data.replace("\n", "") data = data.replace(" ", "") data = base64.b64decode(data) return data
def char_contains(str1, str2): """ check whether str2 cotains all characters of str1 """ if set(str1).issubset(set(str2)): return True return False
def axial_dispersion_coeff(Dm, dp, ui): """ Estimate the axial dispersion coefficient using Edwards and Richardson correlation. .. math:: D_{ax} = 0.73 D_m + 0.5 d_p u_i Parameters ---------- Dm : float Molecular diffusion coefficient [m^2/s] dp : float Particle diameter [m] ui : float Interstitial velocity [m/s] Returns ------- Dax : float Axial dispersion coefficient [m^2/s] Example ------- >>> axial_dispersion_coeff(4.7e-9, 5.0e-6, 3.0e-3) 1.0931e-8 References ---------- M.F. Edwards and J.F. Richardson. Correlation of axial dispersion data. J. Chem. Eng., 1970, 48 (4) 466, 1970. """ Dax = 0.73 * Dm + 0.5 * dp * ui return Dax
def is_command_yes(cmd: str): """Check if user agree with current command. Args: cmd (str): Command input value. Returns: bool: True if command value is match "yes" or "y" (case insensitive.). """ lower_cmd = cmd.lower() return lower_cmd == "yes" or lower_cmd == "y"
def vector_subtract(u, v): """returns the difference (vector) of vectors u and v""" return (u[0]-v[0], u[1]-v[1], u[2]-v[2])
def dict_of_integrals_until(num): """ Question3: print dict of integrals from 0 to 'num' containing pairs {num: num*num} """ return {i : i*i for i in range(1,num+1)}
def optiWage(A,k,alpha): """Compute the optimal wage Args: A (float): technology level k (float): capital level alpha (float): Cobb Douglas parameter Returns: (float): optimal wage """ return A*(1-alpha)*k**alpha
def parse_youtube_time(yt_time: str) -> str: """ Parse the Youtube time format to the hh:mm:ss format params : - yt_time: str = The youtube time string return -> str = The youtube time formatted in a cooler format """ # Remove the PT at the start yt_time = yt_time[2:len(yt_time)] # Prepare the result hour: int = 0 minute: int = 0 second: int = 0 # Extract time from the string buffer: str = "" for c in yt_time: if c == "H": hour = int(buffer) buffer = "" elif c == "M": minute = int(buffer) buffer = "" elif c == "S": second = int(buffer) buffer = "" else: buffer += c # Prepare the result res: str = "" if hour > 0: res += "{:02d}".format(hour) + ":" res += "{:02d}".format(minute) + ":" res += "{:02d}".format(second) # Return the string result return res
def _transpose_list_of_lists(lol): """Transpose a list of equally-sized python lists. Args: lol: a list of lists Returns: a list of lists """ assert lol, "cannot pass the empty list" return [list(x) for x in zip(*lol)]
def is_float(value): """ Checks value if it can be converted to float. Args: value (string): value to check if can be converted to float Returns: bool: True if float, False if not """ try: float(value) return True except ValueError: return False
def check_separation(values, distance_threshold): """Checks that the separation among the values is close enough about distance_threshold. :param values: array of values to check, assumed to be sorted from low to high :param distance_threshold: threshold :returns: success :rtype: bool """ for i in range(len(values) - 1): x = values[i] y = values[i + 1] assert x < y, '`values` assumed to be sorted' if y < x + distance_threshold / 2.: # print('check_separation(): not long enough for idx: {}'.format(i)) return False if y - x > distance_threshold: # print('check_separation(): too far apart') return False return True
def _matches2str(matches): """ Get matches into a multi-line string :param matches: matches to convert :return: multi-line string containing matches """ output_text = '' for match in matches: output_text += f"{match[0]} - {match[1]}\n" return output_text
def rule_to_expression(filtering_rule): """ Single filtering rule to expression :param filtering_rule: :return: expression """ column = filtering_rule["column"] filter_type = filtering_rule["type"] filter_params = filtering_rule["value"] if filter_type == "range": sdt = "to_timestamp(\"{}-{}-{}\",\"yyyy-MM-dd\")".format(filter_params[0][0], filter_params[0][1], filter_params[0][2]) edt = "to_timestamp(\"{}-{}-{}\",\"yyyy-MM-dd\")".format(filter_params[1][0], filter_params[1][1], filter_params[1][2]) return "{} >= {} and {} <= {}".format(column, sdt, column, edt) elif filter_type == "date": return "date_format({},\"yyyy-MM-dd\") == \"{}-{}-{}\"".format(column, filter_params[0],filter_params[1],filter_params[2]) elif filter_type == "year-month": return "year({}) == {} and month({}) == {}".format(column, filter_params[0], column, filter_params[1]) elif filter_type == "year": return "year({}) == {}".format(column, filter_params)
def move_player_backward(player_pos, current_move): """ move pos by current move in circular field from 1 to 10 backward """ player_pos = (player_pos - current_move) % 10 if player_pos == 0: return 10 return player_pos
def mean_(data): """Mean of the values""" return sum(data) / len(data)
def InducedSubgraph(V, G, adjacency_list_type=set): """ The subgraph consisting of all edges between pairs of vertices in V. """ return {x: adjacency_list_type(y for y in G[x] if y in V) for x in G if x in V}
def make_video_spec_dict(video_specs): """ convert video_specs from list to dictionary, key is thee video name w/o extentions """ video_specs_dict = {} for v_spec in video_specs: video_specs_dict[''.join(v_spec['filename'].split('.')[:-1])] = v_spec return video_specs_dict
def rpmul(a,b): """Russian peasant multiplication. Simple multiplication on shifters, taken from "Ten Little Algorithms" by Jason Sachs. Args: a (int): the first variable, b (int): the second vairable. Returns: x (int): result of multiplication a*b. """ result = 0 while b != 0: if b & 1: result += a b >>= 1 a <<= 1 return result
def filter(p, xs): """Takes a predicate and a Filterable, and returns a new filterable of the same type containing the members of the given filterable which satisfy the given predicate. Filterable objects include plain objects or any object that has a filter method such as Array. Dispatches to the filter method of the second argument, if present. Acts as a transducer if a transformer is given in list position""" if not hasattr(xs, "__iter__"): return [] if hasattr(xs, "values"): out = {} for k, v in xs.items(): if p(v): out[k] = v return out return [x for x in xs if p(x)]
def foo_3(x, y, z): """ test >>> foo_3(1,2,3) [1, 2, 3] >>> foo_3(2,1,3) [1, 2, 3] >>> foo_3(3,1,2) [1, 2, 3] >>> foo_3(3,2,1) [1, 2, 3] """ if x > y: tmp=y y=x x=tmp if y > z: tmp=z z=y y=tmp return [x, y, z]
def find_integer(array, target): """ :params array: [[]] :params target: int :return bool """ if not array: return False for i in array: if i[0] <= target <= i[len(i)-1]: if target in i: return True else: if i[0] > target: break return False
def code(doc: str) -> str: """Escape Markdown charters from inline code.""" doc = doc.replace('|', '&#124;') if '&' in doc: return f"<code>{doc}</code>" elif doc: return f"`{doc}`" else: return " "
def add_ap_record(aps, classes, record=None, mean=True): """ ap values in aps and there must be the same length of classes and same order """ if record is None: record = {} sum_ap = 0 for cid, c in enumerate(classes): ap = aps[cid] name_ap = 'ap_' + c.lower() record[name_ap] = ap if mean: sum_ap += ap if mean: record['ap_mean'] = float(sum_ap / len(aps)) return record
def get_app_module_name_list(modules): """ Returns the list of module name from a Ghost App >>> modules = [{ ... "name" : "symfony2", ... "post_deploy" : "Y29tcG9zZXIgaW5zdGFsbCAtLW5vLWludGVyYWN0aW9u", ... "pre_deploy" : "ZXhpdCAx", ... "scope" : "code", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... }] >>> get_app_module_name_list(modules) ['symfony2'] >>> modules = [{ ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... }] >>> get_app_module_name_list(modules) [] >>> modules = [{ ... "name" : "mod1", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... },{ ... "name" : "mod-name2", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... }] >>> get_app_module_name_list(modules) ['mod1', 'mod-name2'] >>> modules = [{ ... "name" : "mod1", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... },{ ... "noname" : "mod-name2", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... },{ ... "name" : "mod3", ... "initialized" : False, ... "path" : "/var/www", ... "git_repo" : "https://github.com/symfony/symfony-demo" ... }] >>> get_app_module_name_list(modules) ['mod1', 'mod3'] """ return [app_module['name'] for app_module in modules if 'name' in app_module]
def format_dword(i): """Format an integer to 32-bit hex.""" return '{0:#010x}'.format(i)
def generate_sql_q1(sql_i1, tb1): """ sql = {'sel': 5, 'agg': 4, 'conds': [[3, 0, '59']]} agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg'] cond_ops = ['=', '>', '<', 'OP'] Temporal as it can show only one-time conditioned case. sql_query: real sql_query sql_plus_query: More redable sql_query "PLUS" indicates, it deals with the some of db specific facts like PCODE <-> NAME """ agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg'] cond_ops = ['=', '>', '<', 'OP'] headers = tb1["header"] # select_header = headers[sql['sel']].lower() # try: # select_table = tb1["name"] # except: # print(f"No table name while headers are {headers}") select_table = tb1["id"] select_agg = agg_ops[sql_i1['agg']] select_header = headers[sql_i1['sel']] sql_query_part1 = f'SELECT {select_agg}({select_header}) ' where_num = len(sql_i1['conds']) if where_num == 0: sql_query_part2 = f'FROM {select_table}' # sql_plus_query_part2 = f'FROM {select_table}' else: sql_query_part2 = f'FROM {select_table} WHERE' # sql_plus_query_part2 = f'FROM {select_table_refined} WHERE' # ---------------------------------------------------------------------------------------------------------- for i in range(where_num): # check 'OR' # number_of_sub_conds = len(sql['conds'][i]) where_header_idx, where_op_idx, where_str = sql_i1['conds'][i] where_header = headers[where_header_idx] where_op = cond_ops[where_op_idx] if i > 0: sql_query_part2 += ' AND' # sql_plus_query_part2 += ' AND' sql_query_part2 += f" {where_header} {where_op} {where_str}" sql_query = sql_query_part1 + sql_query_part2 # sql_plus_query = sql_plus_query_part1 + sql_plus_query_part2 return sql_query
def _extract_format(fmt): """ Returns: a list of tuples: each tuple is a ex: [('H', 6)] """ correspond_fmt = [] start = 0 for i, ch in enumerate(fmt): if not ch.isdigit(): end = i times = int(fmt[start:end]) if start != end else 1 correspond_fmt.append((ch, times)) start = end + 1 return correspond_fmt
def get_bucket_name_from_path(path_input): """ >>> get_bucket_name_from_path('gs://my-bucket/path') 'my-bucket' """ path = str(path_input) if not path.startswith('gs://'): raise ValueError(f'path does not start with gs://: {path}') return path[len('gs://') :].split('/', maxsplit=1)[0]
def diff_flair(left, right): """returns: (modifications, deletions)""" left_users = frozenset(left) right_users = frozenset(right) common_users = left_users & right_users added_users = right_users - left_users removed_users = left_users - right_users modifications = [(u, right[u][0], right[u][1]) for u in common_users if left[u] != right[u]] modifications.extend((u, right[u][0], right[u][1]) for u in added_users) return modifications, removed_users
def extract_kwargs(kwargs_tuple): """ Converts a tuple of kwarg tokens to a dictionary. Expects in format (--key1, value1, --key2, value2) Args: kwargs_tuple (tuple(str)) tuple of list """ if len(kwargs_tuple) == 0: return {} assert kwargs_tuple[0][:2] == "--", f"No key for first kwarg {kwargs_tuple[0]}" curr_key = None kwargs_dict = {} for token in kwargs_tuple: if token[:2] == "--": curr_key = token[2:] else: kwargs_dict[curr_key] = token return kwargs_dict
def ABS(expression): """ Returns the absolute value of a number. See https://docs.mongodb.com/manual/reference/operator/aggregation/abs/ for more details :param expression: The number or field of number :return: Aggregation operator """ return {'$abs': expression}
def db_error_needs_new_session(driver, code): """some errors justify a new database connection. In that case return true""" if code in ("1001", "57P01"): return True return False
def dict_is_all_none(dict_item: dict) -> bool: """ Tests if all dictionary items are None. :param dict_item: A dictionary object to be testes. :return bool: True if all keys have None as value, False otherwise """ for _key, _value in dict_item.items(): if _value is not None: return False return True
def positives(nums): """Positives: Given a list of numbers, write a list comprehension that produces a list of only the positive numbers in that list. >>> positives([-2, -1, 0, 1, 2]) [1, 2] """ lst = [a for a in nums if a > 0] return lst pass
def _remove_trailing_nones(array): """ Trim any trailing Nones from a list """ while array and array[-1] is None: array.pop() return array
def _getLogHandlers(logToFile=True, logToStderr=True): """Get the appropriate list of log handlers. :param bool logToFile: If ``True``, add a logfile handler. :param bool logToStderr: If ``True``, add a stream handler to stderr. :rtype: list :returns: A list containing the appropriate log handler names from the :class:`logging.config.dictConfigClass`. """ logHandlers = [] if logToFile: logHandlers.append('rotating') if logToStderr: logHandlers.append('console') return logHandlers
def sformat(text, args): """ sformat """ for key in args: text = text.replace("{%s}" % key, "%s" % (args[key])) return text
def size_to_bytes(size): """ Returns a number of bytes if given a reasonably formatted string with the size """ # Assume input in bytes if we can convert directly to an int try: return int(size) except Exception: return -1 # Otherwise it must have non-numeric characters size_re = re.compile('([\d\.]+)\s*([tgmk]b?|b|bytes?)$') size_match = re.match(size_re, size.lower()) assert size_match is not None size = float(size_match.group(1)) multiple = size_match.group(2) if multiple.startswith('t'): return int(size * 1024 ** 4) elif multiple.startswith('g'): return int(size * 1024 ** 3) elif multiple.startswith('m'): return int(size * 1024 ** 2) elif multiple.startswith('k'): return int(size * 1024) elif multiple.startswith('b'): return int(size)
def find(s, sub, i = 0, last=None): """find(s, sub [,start [,end]]) -> in Return the lowest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ Slen = len(s) # cache this value, for speed if last is None: last = Slen elif last < 0: last = max(0, last + Slen) elif last > Slen: last = Slen if i < 0: i = max(0, i + Slen) n = len(sub) m = last + 1 - n while i < m: if sub == s[i:i+n]: return i i = i+1 return -1
def build_increments(start, stop, increment): """ Build a range of years from start to stop, given a specific increment Args: start (int): starting year stop (int): ending year increment (int): number of years in one time series Returns: year_increments (list): list of tuples, each containing one time series """ year_increments = [] start_increment = start stop_increment = start + increment - 1 #keep increment-range (not increment + 1) while stop_increment <= stop: year_increments.append((start_increment, stop_increment)) start_increment += increment stop_increment += increment return year_increments
def stripquotes(s): """Replace explicit quotes in a string. >>> from sympy.physics.quantum.qasm import stripquotes >>> stripquotes("'S'") == 'S' True >>> stripquotes('"S"') == 'S' True >>> stripquotes('S') == 'S' True """ s = s.replace('"', '') # Remove second set of quotes? s = s.replace("'", '') return s
def searchers_start_together(m: int, v): """Place all searchers are one vertex :param m : number of searchers :param v : integer or list""" if isinstance(v, int): my_v = v else: my_v = v[0] v_searchers = [] for i in range(m): v_searchers.append(my_v) return v_searchers
def nfc_normalize(iri): """ Normalizes the given unicode string according to Unicode Normalization Form C (NFC) so that it can be used as an IRI or IRI reference. """ from unicodedata import normalize return normalize('NFC', iri)
def constrain_rgb(r, g, b): """ If the requested RGB shade contains a negative weight for one of the primaries, it lies outside the colour gamut accessible from the given triple of primaries. Desaturate it by adding white, equal quantities of R, G, and B, enough to make RGB all positive. The function returns 1 if the components were modified, zero otherwise. """ # Amount of white needed is w = - min(0, *r, *g, *b) w = -min([0, r, g, b]) # I think? # Add just enough white to make r, g, b all positive. if w > 0: r += w g += w b += w return(r,g,b)
def turn_weight_function_distance(v, u, e, pred_node): """ Weight function used in modified version of Dijkstra path algorithm. Weight is calculated as the sum of edge length weight and turn length weight (turn length weight keyed by predecessor node) This version of the function takes edge lengths keyed with 'distance' Args: v (var): edge start node u (var): edge end node e (dict): edge attribute dictionary with keys pred_node (var): predecessor node Returns: calculated edge weight (float) """ if pred_node == None: weight = e[0]['distance'] else: weight = e[0]['distance'] + e[0]['turn_length'][pred_node] return(weight)
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None): """Generate a horizontal line. Args: lineLength (int): The length of the line or how many characters the line will have. lineWidth (int, optional): The width of the line or how many lines of text the line will take space. Defaults to 1. lineCharacter (str, optional): The string, character, or number the line will use as a single character. Defaults to '-'. printOut (bool, optional): Print out the generated dummy text. Defaults to False. Returns: The horizontal line created. """ meaningless_text = "" lineGenerated = "" # check if lineWidth is none if lineWidth is None: # if lineWidth is none, set it to default of 1 width = 1 else: # if line wdith is not none, set it to the given value width = lineWidth # check if lineCharacter is none if lineCharacter is None: # if lineCharacter is none, set it to default "-" character = "-" else: # if line character is not none, then use the user specified character character = lineCharacter for i in range(width): # generate a line for char in range(lineLength): lineGenerated += character if width > 1: # if line width is greater than 1, append a new line character lineGenerated += "\n" meaningless_text += lineGenerated # check if printOut is not none if printOut is not None: # print out is not none and is true so print out the generated text. if printOut == True: print(meaningless_text) # print out is not none and is false so only return the generated text. return meaningless_text
def type_getattr_construct(ls, **kwargs): """Utility to build a type_getattr_table entry. Used only at module load time. """ map = dict.fromkeys(ls, True) map.update(kwargs) return map
def computeRatio(indicator1, indicator2): """Computation of ratio of 2 inidcators. Parameters: ----------- indicator1 : float indicator1 : float Returns: -------- Either None (division by zero) Or the computed ratio (float) """ try: ratio = indicator1 / indicator2 except ZeroDivisionError: return None else: return ratio
def arePermsEqualParity(perm0, perm1): """Check if 2 permutations are of equal parity. Assume that both permutation lists are of equal length and have the same elements. No need to check for these conditions. :param perm0: A list. :param perm1: Another list with same elements. :return: True if even parity, False if odd parity. """ perm1 = perm1[:] ## copy this list so we don't mutate the original transCount = 0 for loc in range(len(perm0) - 1): # Do (len - 1) transpositions p0 = perm0[loc] p1 = perm1[loc] if p0 != p1: sloc = perm1[loc:].index(p0)+loc # Find position in perm1 perm1[loc], perm1[sloc] = p0, p1 # Swap in perm1 transCount += 1 # Even number of transpositions means equal parity if (transCount % 2) == 0: return True else: return False
def name_value(name): """ Compute name value for a name """ return sum([ord(c) - ord('A') + 1 for c in name])
def convert_pos(pos): """ Method to convert part of speech from nltk form to WordNet form """ # dictionary of pos tags (keys are in nltk form, values are wordnet form) pos_conversions = dict.fromkeys(['NN', 'NNS'], 'n') pos_conversions.update(dict.fromkeys(['VB', 'VBD', 'VBN', 'VBP', 'VBZ'], 'v')) pos_conversions.update(dict.fromkeys(['JJ'], 'a')) pos_conversions.update(dict.fromkeys(['RB'], 'r')) new_pos = pos_conversions[pos] return new_pos
def _retrieve_yearly_data(yearly_data): """Auxiliary function to collect yearly data. Returns list of lists in the form [mergedstatname, stat], where mergedstatname - dictionary key joined with associated period. """ out = [] for t in yearly_data: for key in t: if key not in ('@year', '@_fa'): out.append([f"{key}_{t['@year']}", t[key]]) return out or None
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 """ # new strat: since Euclid's algorithm swaps the numbers' places for every call to gcd, # eventually 'b' will have no remainder, making 'a' the final answer return a if b == 0 else gcd(b, a % b) """ old strat: - try to get a and b to be the bigger and smaller number, respectively - if a == b, then a and b are divisible by themselves, which is the gcd - whichever is the bigger number, if the bigger number isn't cleanly divisible by the smaller one call the gcp function with the new bigger number as 'a' and the smaller number as b, which is the remainder of the bigger divided by the smaller - however, if the bigger number is cleanly divisible by the smaller one, return b, which is the gcd """ """ old solution if a > b and a % b != 0: return gcd(b, a % b) elif b > a and b % a != 0: return gcd(a, b % a) # this is here to swap the bigger and smaller number role else: return b """
def data_corners(data, data_filter = None): """! @brief Finds maximum and minimum corner in each dimension of the specified data. @param[in] data (list): List of points that should be analysed. @param[in] data_filter (list): List of indexes of the data that should be analysed, if it is 'None' then whole 'data' is analysed to obtain corners. @return (list) Tuple of two points that corresponds to minimum and maximum corner (min_corner, max_corner). """ dimensions = len(data[0]) bypass = data_filter if bypass is None: bypass = range(len(data)) maximum_corner = list(data[bypass[0]][:]) minimum_corner = list(data[bypass[0]][:]) for index_point in bypass: for index_dimension in range(dimensions): if data[index_point][index_dimension] > maximum_corner[index_dimension]: maximum_corner[index_dimension] = data[index_point][index_dimension] if data[index_point][index_dimension] < minimum_corner[index_dimension]: minimum_corner[index_dimension] = data[index_point][index_dimension] return minimum_corner, maximum_corner
def line(x1, y1, x2, y2): """Returns a list of points in a line between the given points. Uses the Bresenham line algorithm. More info at: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm""" points = [] isSteep = abs(y2-y1) > abs(x2-x1) if isSteep: x1, y1 = y1, x1 x2, y2 = y2, x2 isReversed = x1 > x2 if isReversed: x1, x2 = x2, x1 y1, y2 = y2, y1 deltax = x2 - x1 deltay = abs(y2-y1) error = int(deltax / 2) y = y2 ystep = None if y1 < y2: ystep = 1 else: ystep = -1 for x in range(x2, x1 - 1, -1): if isSteep: points.append((y, x)) else: points.append((x, y)) error -= deltay if error <= 0: y -= ystep error += deltax else: deltax = x2 - x1 deltay = abs(y2-y1) error = int(deltax / 2) y = y1 ystep = None if y1 < y2: ystep = 1 else: ystep = -1 for x in range(x1, x2 + 1): if isSteep: points.append((y, x)) else: points.append((x, y)) error -= deltay if error < 0: y += ystep error += deltax return points
def _GenerateDeviceHVInfoStr(hvinfo): """Construct the -device option string for hvinfo dict PV disk: virtio-blk-pci,id=disk-1234,bus=pci.0,addr=0x9 PV NIC: virtio-net-pci,id=nic-1234,bus=pci.0,addr=0x9 SG disk: scsi-generic,id=disk-1234,bus=scsi.0,channel=0,scsi-id=1,lun=0 @type hvinfo: dict @param hvinfo: dictionary created by _GenerateDeviceHVInfo() @rtype: string @return: The constructed string to be passed along with a -device option """ # work on a copy d = dict(hvinfo) hvinfo_str = d.pop("driver") for k, v in d.items(): hvinfo_str += ",%s=%s" % (k, v) return hvinfo_str
def hasNumbers(inputString): """ Returns True if the string contains a number, False otherwise :param inputString: String to check for number :return: Boolean: whether string contains a number """ return any(char.isdigit() for char in inputString)
def replace_duplicate_words(word_list): """ input: list of words output: new list where words that appear more than once in the input are replaced by 'word ' used due to react-autoselect UI of the app """ new_list = [] for word in word_list: occurences = word_list.count(word) if occurences > 1: for i in range(occurences): suffix = " "*i new_list += [word+suffix] else: new_list += [word] return new_list
def dict_or_list_2_tuple_2_str(inp): """ dict_or_list_2_tuple_2_str Args: inp: dict or list of 2-tuple Returns: formatted string """ if isinstance(inp, dict): inp = sorted(list(inp.items()), key=lambda x: x[0]) else: inp = sorted(inp, key=lambda x: x[0]) out_str = "\n" for k, v in inp: one_line = "{} ----> {}\n".format(k, v) out_str += one_line return out_str
def default_entry_point(name): """Generate a default entry point for package `name`.""" return "{name}.__main__:main".format(name=name)
def upper_diag_self_prodx(list_): """ upper diagnoal of cartesian product of self and self. Weird name. fixme Args: list_ (list): Returns: list: CommandLine: python -m utool.util_alg --exec-upper_diag_self_prodx Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> list_ = [1, 2, 3] >>> result = upper_diag_self_prodx(list_) >>> print(result) [(1, 2), (1, 3), (2, 3)] """ return [(item1, item2) for n1, item1 in enumerate(list_) for n2, item2 in enumerate(list_) if n1 < n2]
def _getfield(history, field): """ Return the last value in the trace, or None if there is no last value or no trace. """ trace = getattr(history, field, []) try: return trace[0] except IndexError: return None
def _get_single_wdr_with_qw_sel(asm_str): """returns a single register from string with quad word select and check proper formatting (e.g "w5.2")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in reg reference') if not asm_str.lower().startswith('w'): raise SyntaxError('Missing \'w\' character at start of reg reference') if not (asm_str.lower().endswith('.0') or asm_str.lower().endswith('.1') or asm_str.lower().endswith('.2') or asm_str.lower().endswith('.3')): raise SyntaxError('Missing quad word selection (\'.0\', \'.1\', \'.2\' or \'.3\') at end of reg reference') if not asm_str[1:-2].isdigit(): raise SyntaxError('reg reference not a number') qw_sel = int(asm_str[-1]) return int(asm_str[1:-2]), qw_sel
def text2idx(text, max_seq_length, word2idx): """ Converts a single text into a list of ids with mask. This function consider annotaiton of z1, z2, z3 are provided """ input_ids = [] text_ = text.strip().split(" ") if len(text_) > max_seq_length: text_ = text_[0:max_seq_length] for word in text_: word = word.strip() try: input_ids.append(word2idx[word]) except: # if the word is not exist in word2idx, use <unknown> token input_ids.append(1) # The mask has 1 for real tokens and 0 for padding tokens. input_mask = [1] * len(input_ids) # zero-pad up to the max_seq_length. while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length return input_ids, input_mask
def digitsaverage(d): """Return the average of the digits until number is one digit. input = integer output = integer, single digit ex. 246 = 4 i.e. avg of 2 and 4 is 3, average of 4 and 6 is 5 so after first iteration 246 => 35 avg of 3 and 5 is 4 so digitsAverage(246) returns 4 """ if not d: return d res = '' if d < 10: return d else: st_d = str(d) for x in range(len(st_d) - 1): z = st_d[x] y = st_d[x + 1] float = (int(z) + int(y)) % len(z + y) avg = ((int(z) + int(y)) // len(z + y)) + float res += str(avg) recurs = int(res) return digitsaverage(recurs)
def _validate_window_size(k): """ Check if k is a positive integer """ if not isinstance(k, int): raise TypeError( "window_size must be integer type, got {}".format(type(k).__name__) ) if k <= 0: raise ValueError("window_size must be positive") return k
def no_bracketed(st): """ Remove bracketed substrings from a string -- used to convert to a one letter sequence: acgu[URA:VirtualPhosphate]acgu ==> acguacgu """ ret = "" incl = True for c in st: if incl: if c == '[': incl = False else: ret += c else: if c == ']': incl = True else: pass return ret
def temperature_rise(H, Eff, U): """ Func to provide temperature rise versus pump capacity. TR (deg F) = H(1.0-E)/(778.0*U*E) Where: -TR is temp rise -H is total head in ft. -E efficiency as a decimal -U specific heat ( BTU/lb/Deg F) """ TR = (H*(1.0-Eff))/(778.0*U*Eff) print('Temp. Rise @ {} total ft of Head = {} deg F'.format(H,TR)) return TR
def is_in_pi(param_name, pi_exp): """ Parameters ---------- param_name Name of a particular physical parameter pi_exp Pi expression Returns True if the parameter is in pi_exp ------- """ _vars = pi_exp.split('*') raw_vars = [] for _var in _vars: raw_vars += _var.split('/') vars = [] for raw_var in raw_vars: var = raw_var.strip() var = var.replace('(', '') var = var.replace(')', '') vars.append(var) for var in vars: if var == param_name: return True return False
def max_sum(triangle_matrix): """Finds maximum sum of path from top of triangle down to bottom. Input: Matrix of triangle e.g. 1 3 5 7 8 4 becomes [[1], [3, 5], [7, 8, 4]] Uses memoization from the bottom layer up to work quickly Output: maximum value """ max_depth = len(triangle_matrix) - 1 # Set bottom row for memoization depth = max_depth result = {} for i, entry in enumerate(triangle_matrix[depth]): result[(i, max_depth - depth)] = entry depth -= 1 # Set each row moving up the triangle based on # the results one low below while depth >= 0: for i, entry in enumerate(triangle_matrix[depth]): val_left = result[(i, max_depth - depth - 1)] val_right = result[(i + 1, max_depth - depth - 1)] result[(i, max_depth - depth)] = entry + max(val_left, val_right) depth -= 1 return result[(0, max_depth - depth - 1)]
def _nval(val): """convert value to byte array""" if val < 0: raise ValueError buf = b'' while val >> 7: m = val & 0xFF | 0x80 buf += m.to_bytes(1, 'big') val >>= 7 buf += val.to_bytes(1, 'big') return buf
def align_cells(lines): """ Correct the problem of some cells not being aligned in successive columns, when belonging to the same fragment sequence """ previous_line, output_lines = None, ['molecule,nres,mod,mod_ext,matches\n'] for line in lines: output_nts = [] if previous_line: current_nts, previous_nts = line.split(",")[4:], previous_line.split(",")[4:] output_nts = current_nts pairs = [] for j, previous_nt in reversed(list(enumerate(previous_nts))): for i, current_nt in enumerate(current_nts): if "_".join(current_nt.split('_')[:-2]) in previous_nt and i != j and (i, j) not in pairs and ( j, i) not in pairs: pairs.extend([(i, j), (j, i)]) if len(output_nts) < len(previous_nts): output_nts = current_nts + [''] * (len(previous_nts) - len(current_nts)) output_nts[j], output_nts[i] = "_".join(current_nt.split('_')), output_nts[j] break output_nts[:] = [s.replace('\n', '') for s in output_nts] output_nts[-1] = output_nts[-1] + "\n" output_lines.append(",".join(line.split(",")[:4] + output_nts)) previous_line = ",".join(line.split(",")[:4] + output_nts) else: previous_line = line return output_lines
def cobs_encode(data): """ COBS-encode DATA. """ output = bytearray() curr_block = bytearray() for byte in data: if byte: curr_block.append(byte) if len(curr_block) == 254: output.append(1 + len(curr_block)) output.extend(curr_block) curr_block = bytearray() else: output.append(1 + len(curr_block)) output.extend(curr_block) curr_block = bytearray() output.append(1 + len(curr_block)) output.extend(curr_block) return output
def get_next(currentHead, nextMove): """ return the coordinate of the head if our snake goes that way """ futureHead = currentHead.copy() if nextMove == 'left': futureHead['x'] = currentHead['x'] - 1 if nextMove == 'right': futureHead['x'] = currentHead['x'] + 1 if nextMove == 'up': futureHead['y'] = currentHead['y'] + 1 if nextMove == 'down': futureHead['y'] = currentHead['y'] - 1 return futureHead
def calculate(triangle): """Returns the maximum total from top to bottom by starting at the top of the specified triangle and moving to adjacent numbers on the row below""" def calculate_helper(row, col): """Returns the maximum path value of a specified cell in the triangle""" if row == len(triangle): return 0 return triangle[row][col] + max( calculate_helper(row + 1, col), calculate_helper(row + 1, col + 1) ) return calculate_helper(0, 0)
def cross_map(iter_mapper, iterable): """Maps each map in iter_mapper on each iterable""" return [list(map(im, iterable)) for im in iter_mapper]
def getmodestring_( I, callingRoutine ) : """For internal use only.""" if ( I in [ 0, 7, 9, 10, 11, 12, 13, 30, 32, 80, 89, 90, 91, 92, 941, 942, 951 ] ) : s = "2" elif ( I in [ 1, 21, 22, 81, 84, 952 ] ) : s = "3" elif ( I in [ 3, 4, 20 ] ) : s = "4" else : raise Exception( "\nError in %s: unsupported I-value = %d" % ( callingRoutine, I ) ) return s
def _normalize_percent_rgb(value): """ Normalize ``value`` for use in a percentage ``rgb()`` triplet, as follows: * If ``value`` is less than 0%, convert to 0%. * If ``value`` is greater than 100%, convert to 100%. Examples: >>> _normalize_percent_rgb('0%') '0%' >>> _normalize_percent_rgb('100%') '100%' >>> _normalize_percent_rgb('62%') '62%' >>> _normalize_percent_rgb('-5%') '0%' >>> _normalize_percent_rgb('250%') '100%' >>> _normalize_percent_rgb('85.49%') '85.49%' """ percent = value.split('%')[0] percent = float(percent) if '.' in percent else int(percent) if 0 <= percent <= 100: return '%s%%' % percent if percent < 0: return '0%' if percent > 100: return '100%'
def extend_matches(value, choices, direction): """ Extends the value by anything in choices the 1) ends in the same 2 digits that value begins with 2) has remaining digit(s) unique from those in value """ value_digits = set(value) if direction == 'right': first_two_match = [choice for choice in choices if choice[:2] == value[-2:]] matches = [choice for choice in first_two_match if value_digits.intersection(choice[2:]) == set()] return [value + choice[2:] for choice in matches] elif direction == 'left': last_two_match = [choice for choice in choices if choice[-2:] == value[:2]] matches = [choice for choice in last_two_match if value_digits.intersection(choice[:-2]) == set()] return [choice[:-2] + value for choice in matches] else: raise ValueError("%s not a valid direction." % direction)
def polynomiale_2(a: float, b: float, c: float, d: float, x: float) -> float: """Retourne la valeur de a*x^3 + b*x^2 + c*x + d """ return ((((a*x + b) * x) + c) * x) + d
def TSKVsPartGetNumberOfSectors(tsk_vs_part): """Retrieves the number of sectors of a TSK volume system part object. Args: tsk_vs_part (pytsk3.TSK_VS_PART_INFO): TSK volume system part information. Returns: int: number of sectors or None. """ # Note that because pytsk3.TSK_VS_PART_INFO does not explicitly defines # len we need to check if the attribute exists. return getattr(tsk_vs_part, 'len', None)
def subset_to_str_list(subset_sol): """From a subset solution (e.g.: [[0,1],[0,0]]) returns a list with the rows string and the columns string (e.g.: ['0 1', '0 0']) or NO_SOL""" return [' '.join([str(e) for e in subset_sol[0]]), \ ' '.join([str(e) for e in subset_sol[1]])]
def cut_strokes(strokes, n_points): """ Reduce a drawing to its n first points. """ result_strokes = [] current_n_points = 0 for xs, ys in strokes: stroke_size = len(xs) n_points_remaining = max(0, n_points - current_n_points) result_strokes.append((xs[:n_points_remaining], ys[:n_points_remaining])) current_n_points += stroke_size return result_strokes
def computescale(population): """ Computes appropriate scale to show locations with specific population """ if population == '': population = 0 population = int(population) if population < 20000: return 15 if population < 40000: return 14.5 if population < 60000: return 14 if population < 80000: return 13.5 if population < 100000: return 13 if population < 200000: return 12.5 if population < 400000: return 12 if population < 600000: return 11.5 if population < 800000: return 11 if population < 1000000: return 10.5 return 10
def _starsToPercentage (numStars): """ Converts a given number of stars to its percentage :param numStars: teh number of stars as an integer or float :return: the percentage is the number is valid or None if it's not. """ if numStars == 0: return 1 elif numStars == 1: return 1.05 elif numStars == 2 or numStars == 3: return 1.1 elif numStars == 4 or numStars == 5: return 1.15 elif numStars == 6 or numStars == 7: return 1.2 else: return None
def find_stop(seq): """ :param seq: a translated amino acid sequence :return: the position of the first stop codon (*) inside - if none, return length of whole sequence """ if '*' in seq: return seq.index('*') else: return len(seq)
def dict_repr_html(dictionary): """ Jupyter Notebook magic repr function. """ rows = '' s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>' for k, v in dictionary.items(): rows += s.format(k=k, v=v) html = '<table>{}</table>'.format(rows) return html
def get_token_update(count, token): """ Estrae i token uno alla volta dal dizionario di count """ old_value = count[token] count[token] -= min(count[token], 1) return min(old_value, 1)
def parse_fsx_backups(backups, tag_key, tag_val): """Parse backups by tag.""" tmp_backups = [] for bkup in backups: for tag in bkup['Tags']: if ((tag['Key'] == tag_key) and (tag['Value'] == tag_val)): tmp_backups.append(bkup) break return tmp_backups
def paired(coords): """Return a list of pairs from a flat list of coordinates.""" assert len(coords) % 2 == 0, 'Coordinates are not paired.' points = [] x = None for elem in coords: if x is None: x = elem else: points.append((x, elem)) x = None return points
def return_(value = None): """Create a return statement.""" if value is not None: return [['return', value]] else: return [['return']]
def multisigfig(X, sigfigs=5): """ Return a string representation of variable x with sigfigs number of significant figures """ from numpy import log10, floor output = [] try: n=len(X) islist = True except: X = [X] n = 1 islist = False for i in range(n): x = X[i] try: if x==0: output.append('0') else: magnitude = floor(log10(abs(x))) factor = 10**(sigfigs-magnitude-1) x = round(x*factor)/float(factor) digits = int(abs(magnitude) + max(0, sigfigs - max(0,magnitude) - 1) + 1 + (x<0) + (abs(x)<1)) # one because, one for decimal, one for minus decimals = int(max(0,-magnitude+sigfigs-1)) strformat = '%' + '%i.%i' % (digits, decimals) + 'f' string = strformat % x output.append(string) except: output.append(str(x)) if islist: return tuple(output) else: return output[0]
def st_rowfreq(row,srate,length): """ for a row in a stockwell transform, give what frequency (Hz) it corresponds to, given the sampling rate srate and the length of the original array """ return row*srate/length
def listify(*args): """ Given a set of parameters where some of them are given as lists and the others as values, put brackets around the values to make lists of 1 element so that we can use a for loop on all parameters in run_synthetic_exps. For instance, the tuple of parameters (n=500, k=[10, 15, 20], dim=10, ampl=[0, 1, 2]) is changed into (n=[500], k=[10, 15, 20], dim=[10], ampl = [0, 1, 2]) by this function. """ listed_args = () for arg in args: if type(arg) == list: listed_args += (arg, ) else: listed_args += ([arg], ) return(listed_args)
def get_input(fn_str): """ Get input var to `fn_str` """ # parse to innermost inputs if "(" not in fn_str: return {fn_str} else: inner_fns = [] parens_stack = [] for c, char in enumerate(fn_str): if char == '(': parens_stack.append(c) elif char == ')': start_idx = parens_stack.pop() if len(parens_stack) == 0: inner_fns.append(fn_str[start_idx+1:c]) # find matching closing # segment inner_fns all_inputs = set() for inner_fn in inner_fns: all_inputs = all_inputs.union(get_input(inner_fn)) return all_inputs