content
stringlengths
42
6.51k
def combine_by_function(iterable, start_val, combine_func): """ An approximation of the reduce method. :param iterable: input list etc. :param start_val: a starting value :param combine_func: a function taking two arguments and returning a value. :return: combined value """ count = len(iterable) if count == 0: return start_val else: last_val = start_val index = 0 while index < count: curr_elem = iterable[index] last_val = combine_func(last_val, curr_elem) index += 1 return last_val
def get_web2_slack_url(host, service=None, web2_url=""): """ Return a Slack formatted hyperlink Parameters ---------- host: str host name to use for url. If service is None a hyperlink to a Icingaweb2 host page will be returned service : str, optional service name to use for url. A hyperlink to a Icingaweb2 service page will be returned web2_url: str url to icingaweb2 instance Returns ------- str: formatted url """ if host is None: return if service: url = "<{web2_url}/monitoring/service/show?host={host_name}&amp;service={service_name}|{service_name}>" else: url = "<{web2_url}/monitoring/host/show?host={host_name}|{host_name}>" url = url.format(web2_url=web2_url, host_name=host, service_name=service) return url
def rotate_2d_list(squares_list): """ http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python """ return [x for x in zip(*squares_list[::-1])]
def validate_periodicity(periodic): """Validate method params: periodic. Periodicity has a differnt validator format because it can be changed in set_periodicity, so we only validate it there """ # Chek if dict if not isinstance(periodic, dict): raise TypeError( "Periodicity: Argument must be a dictionary. " "Got instead type {}".format(type(periodic)) ) # If dict is empty means no periodicity, stop validation. if len(periodic) == 0: return None # Check if keys are valid for k in periodic.keys(): # Check if integer if not isinstance(k, int): raise TypeError( "Periodicity: Keys must be integers. " "Got instead type {}".format(type(k)) ) # Check if positive. No raise because negative values may work if k < 0: print( "WARNING: I got a negative periodic axis. " "Yo better know what you are doing." ) # Check if values are valid for v in periodic.values(): # Check if tuple or None if not (isinstance(v, tuple) or v is None): raise TypeError( "Periodicity: Values must be tuples. " "Got instead type {}".format(type(v)) ) if v is None: continue # Check if edges are valid numbers if not ( isinstance(v[0], (int, float)) and isinstance(v[1], (int, float)) ): raise TypeError( "Periodicity: Argument must be a tuple of " "2 real numbers as edge descriptors. " ) # Check that first number is lower than second if not v[0] < v[1]: raise ValueError( "Periodicity: First argument in tuple must be " "lower than second argument." ) return None
def coalesce(*args): """Returns the first not None item. :param args: list of items for checking :return the first not None item, or None """ try: return next((arg for arg in args if arg is not None)) except StopIteration: return None
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ next_pos_0 = 0 next_pos_2 = len(input_list) - 1 front_index = 0 while front_index <= next_pos_2: if input_list[front_index] == 0: input_list[front_index] = input_list[next_pos_0] input_list[next_pos_0] = 0 next_pos_0 += 1 front_index += 1 elif input_list[front_index] == 2: input_list[front_index] = input_list[next_pos_2] input_list[next_pos_2] = 2 next_pos_2 -= 1 else: front_index += 1 return input_list
def parse_torrent_id(arg): """Parse an torrent id or torrent hashString.""" torrent_id = None if isinstance(arg, int): # handle index torrent_id = int(arg) elif isinstance(arg, float): torrent_id = int(arg) if torrent_id != arg: torrent_id = None elif isinstance(arg, str): try: torrent_id = int(arg) if torrent_id >= 2**31: torrent_id = None except (ValueError, TypeError): pass if torrent_id is None: # handle hashes try: int(arg, 16) torrent_id = arg except (ValueError, TypeError): pass return torrent_id
def _compose_args(bloom_fn: str, gfa_fn: str) -> dict: """Compose a dict of args with two variables""" return { "kmer": 30, "bloom": bloom_fn, "bloom_size": "500M", "levels": 1, "fasta": "tests/correct/transcript.fa", "max_fp_bases": 5, "max_overlap": 10, "gfa1": gfa_fn, "threads": 4, "max_gap_size": 10, "reads": ["tests/correct/reads.fa"], }
def operatingexpenses(taxes, insurance, pmi, managementfee, hoafee): """Annual expenses occured through normal cost of business. :param taxes: Annual taxes. :type taxes: double :param insurance: Annual insurance. :type insurance: double :param pmi: Annual pmi payment. :type pmi: double :param managementfee: Annual management fee. :type managementfee: double :param hoafee: Annual homeowners association fee. :type hoafee: double :return: double """ return taxes + insurance + pmi + managementfee + hoafee
def intersection(lst1, lst2): """ Python program to illustrate the intersection of two lists using set() method """ return list(set(lst1).intersection(lst2))
def _fibonacci(n): """Fibonacci base function (naive recursive algorithm) Exponential Time Args: n: The nth number of the fibonacci sequence Returns: An integer of the nth number in the fibonacci sequence """ if n <= 2: # Base case f = 1 else: # Recursive call f = _fibonacci(n - 1) + _fibonacci(n - 2) return f
def _check_values(in_values): """ Check if values need to be converted before they get mogrify'd """ out_values = [] for value in in_values: # if isinstance(value, (dict, list)): # out_values.append(json.dumps(value)) # else: out_values.append(value) return tuple(out_values)
def split_on_attribute(index, value, dataset): """Separate a given dataset into two lists of rows. Args: index: the attribute index value: the split point of this attribute dataset: the list of instances the represent the dataset Returns: A tuple with the lists of instances according to the split, where left list has instances for which the value of the given attribute is less than split value, and the right list contains the other instances """ left, right = list(), list() for row in dataset: if row[index] < value: left.append(row) else: right.append(row) return left, right
def get_number_of_reviews(num_review: str) -> int: """ >>> get_number_of_reviews('172 reviews') 172 >>> get_number_of_reviews('1,822 reviews') 1822 """ num_str = num_review.split(' ')[0] num_str = ''.join([n for n in num_str if n != ',']) return int(num_str)
def fix_sanitizer_crash_type(crash_type): """Ensure that Sanitizer crashes use generic formats.""" # General normalization. crash_type = crash_type.lower().replace('_', '-').capitalize() # Use more generic types for certain Sanitizer ones. crash_type = crash_type.replace('Int-divide-by-zero', 'Divide-by-zero') return crash_type
def get_attr_from_base_classes(bases, attrs, attr, default=None): """ The attribute is retrieved from the base classes if they are not already present on the object. Args: bases (tuple, list): The base classes for a class. attrs (dict): The attributes of the class. attr (str): Specific attribute being looked for. default (any): Whatever default value is expected if the attr is not found. Returns: attribute value as found in base classes or a default when attribute is not found and default is provided. Raises: AttributeError: When the attribute is not present anywhere in the call chain hierarchy specified through bases and the attributes of the class itself """ if attr in attrs: return attrs[attr] for base in bases: try: return getattr(base, attr) except AttributeError: continue if default is not None: return default raise AttributeError( 'None of the bases have {} attribute' ''.format(attr) )
def get_tri_category(score): """Get a 3 class integer classification label from a score between 0 and 1.""" if score >= 0 and score < 0.3333333333: return 0 elif score >= 0.3333333333 and score < 0.6666666666: return 1 else: return 2
def create_headers_for_request(token): """Create a header dict to be passed to the api. :param token: token string coming from the api :return: a dict containing all the headers for a request """ return { 'X-Auth-Token': token, 'Content-Type': 'application/json', 'Accept': 'application/json' }
def is_valid_number(val): """ Validates if the value passed is a number(int/float) or not. Args: val (any type): value to be tested Returns: bool: True if number else False """ return type(val) == int
def _tuple_or_list(this_identifier, typ): """ Turn all lists to tuple/list so this becomes hashable/dcc.storable """ opposite = tuple if typ == list else list out = [] for i in this_identifier: if isinstance(i, opposite): i = _tuple_or_list(i, typ) out.append(typ(i)) else: out.append(i) return typ(out)
def _remove(item, command, replace=""): """ Remove key, pre, and post words from command string. """ command = " " + command + " " if replace != "": replace = " " + replace + " " for keyword in item["keywords"]: if item["pre"]: for pre in item["pre"]: command = command.replace("%s %s" % (pre, keyword), replace) if item["post"]: for post in item["post"]: command = command.replace("%s %s" % ( keyword, post), replace) if keyword in command: command = command.replace(" " + keyword + " ", replace) return ' '.join(command.split())
def rank_delta(bcp_47, ot): """Return a delta to apply to a BCP 47 tag's rank. Most OpenType tags have a constant rank, but a few have ranks that depend on the BCP 47 tag. Args: bcp_47(str): A BCP 47 tag. ot(str): An OpenType tag to. Returns: A number to add to ``ot``'s rank when sorting ``bcp_47``'s OpenType equivalents. """ if bcp_47 == 'ak' and ot == 'AKA': return -1 if bcp_47 == 'tw' and ot == 'TWI': return -1 return 0
def sum_of_factorial_circle_plus_recursion(number: int) -> int: """ >>> sum_of_factorial_circle_plus_recursion(0) 0 >>> sum_of_factorial_circle_plus_recursion(1) 1 >>> sum_of_factorial_circle_plus_recursion(2) 3 >>> sum_of_factorial_circle_plus_recursion(5) 153 """ sum_factorial = 0 from math import factorial for i in range(1, number + 1): sum_factorial += factorial(i) return sum_factorial
def is_editor(permission): """ based on settings.CMS_CONTEXT_PERMISSIONS given a permission code (int) returns a dict{} with editor permission info """ if not permission > 2: return {} allow_descendant = True if permission > 4 else False only_created_by = True if permission == 3 else False return {'only_created_by': only_created_by, 'allow_descendant': allow_descendant}
def count_the_letters(count_words): """Find the number of distinct letters.""" letters = {} for word in count_words.keys(): for letter in word: letters.setdefault(letter, 0) letters[letter] += count_words[word] return len(letters.keys())
def _to_numeric(value): """Try to convert a string to an integer or a float. If not possible, returns the initial string. """ try: value = int(value) except: try: value = float(value) except: pass return value
def _raw_bus_voltage_cnvr(bus_voltage_register): """The CNVR bit is set after all conversions, averaging, and multiplications are complete""" return (bus_voltage_register >> 1) & 0x1
def truncate_line(line, max_len): """Truncate a string to a given length @param line String to truncate @param max_len Length to which to truncate the line """ if line.count("\n") > 0: return "\n".join(map( lambda x: truncate_line(x, max_len), line.split("\n"))) if len(line) <= max_len: return line return f"{line[0:(max_len - 3)]}..."
def _formatted_hour_min(seconds): """Turns |seconds| seconds into %H:%m format. We don't use to_datetime() or to_timedelta(), because we want to show hours larger than 23, e.g.: 24h:00m. """ time_string = '' hours = int(seconds / 60 / 60) minutes = int(seconds / 60) % 60 if hours: time_string += '%dh' % hours if minutes: if hours: time_string += ':' time_string += '%dm' % minutes return time_string
def remove_surrogates(s, errors='replace'): """Replace surrogates generated by fsdecode with '?' """ return s.encode('utf-8', errors).decode('utf-8')
def all_factors(num): """ Return the set of factors of n (including 1 and n). You may assume n is a positive integer. Do this in one line for extra credit. Example: >>> all_factors(24) {1, 2, 3, 4, 6, 8, 12, 24} >>> all_factors(5) {1, 5} """ factors = set() for i in range(1, int(num / 2) + 1): if num % i == 0: factors.add(i) factors.add(num) return factors
def update_parameters_with_gd(parameters, grads, learning_rate): """ Update parameters using one step of gradient descent Arguments: parameters -- python dictionary containing your parameters to be updated: parameters['W' + str(l)] = Wl parameters['b' + str(l)] = bl grads -- python dictionary containing your gradients to update each parameters: grads['dW' + str(l)] = dWl grads['db' + str(l)] = dbl learning_rate -- the learning rate, scalar. Returns: parameters -- python dictionary containing your updated parameters """ L = len(parameters) // 2 # number of layers in the neural networks # Update rule for each parameter for l in range(L): ### START CODE HERE ### (approx. 2 lines) parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads['dW' + str(l + 1)] parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads['db' + str(l + 1)] ### END CODE HERE ### return parameters
def onlywhite(line): """Return true if the line does only consist of whitespace characters.""" for c in line: if c is not ' ' and c is not ' ': return c is ' ' return line
def verhoeff_digit(arg): """ Implemention of Verhoeff's Dihedral Check Digit based on code from Nick Galbreath """ # dihedral addition matrix A + B = a[A][B] _amatrix = ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) # dihedral inverse map, A + inverse[A] = 0 _inverse = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9) # permutation weighting matrix P[position][value] _pmatrix = ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8)) check = 0 # initialize check at 0 digit = 0 i = 0 for digit in reversed(arg): digit = ord(digit) - 48 check = _amatrix[check][_pmatrix[(i + 1) % 8][digit]] # not quite the same... i += 1 return chr(_inverse[check] + 48)
def get_repeated_elements_in_list(input_list): """ Finds repeated elements in a list. Returns a list with the repeated elements. """ elem_count = {} for elem in input_list: if elem in elem_count: elem_count[elem] += 1 else: elem_count[elem] = 1 repeated_elems = [] for elem, elem_count in elem_count.items(): if elem_count > 1: repeated_elems.append(elem) return repeated_elems
def mass_from_radius(r_p): """ From Weiss et al. for 1 R_earth < R < 4 R_earth r_p = radius of planet in earth radii """ return 2.69*(r_p)**(0.93)
def guess_xyz_columns(colnames): """ Given column names in a table, return the columns to use for x/y/z, or None/None/None if no high confidence possibilities. """ # Do all the checks in lowercase colnames_lower = [colname.lower() for colname in colnames] for x, y, z in [('x', 'y', 'z')]: # Check first for exact matches x_match = [colname == x for colname in colnames_lower] y_match = [colname == y for colname in colnames_lower] z_match = [colname == z for colname in colnames_lower] if sum(x_match) == 1 and sum(y_match) == 1 and sum(z_match) == 1: return colnames[x_match.index(True)], colnames[y_match.index(True)], colnames[z_match.index(True)] # Next check for columns that start with specified names x_match = [colname.startswith(x) for colname in colnames_lower] y_match = [colname.startswith(y) for colname in colnames_lower] z_match = [colname.startswith(z) for colname in colnames_lower] if sum(x_match) == 1 and sum(y_match) == 1 and sum(z_match) == 1: return colnames[x_match.index(True)], colnames[y_match.index(True)], colnames[z_match.index(True)] return None, None, None
def max_of_three_good(x, y, z): """ (int, int, int) -> int Computes and returns the maximum of three numeric values """ result = x if y > result: result = y if z > result: result = z return result
def parse_cards_from_board(raw): """ Returns a list of tuples (word, team, flipped). """ out = [] for line in raw.lower().strip().split("\n"): data = line.strip().split(", ") out.append((data[0], data[1], "revealed" in data[2])) return out
def darpaNodeNet(node_id): """Return IP subnet of radio node on DARPA's network.""" return '192.168.{:d}.0'.format(node_id+100)
def rst_header(text, style=None): """Format RST header. """ style = style or "-" return f"{text}\n{style * len(text)}\n\n"
def regex_match(word, regex, repeat=None): """ Given that '.' corresponds to any character, and '*' corresponds to 0 or more matches of the previous character, write a function that checks if the pattern matches the input. """ if not word and not regex: return True if not word: if len(regex) == 2 and regex[-1]: return True return False if not regex: return False # check case where repeat expected if repeat: if word[0] == repeat or repeat == '.': return regex_match( word[1:], regex, repeat=repeat ) or regex_match(word, regex) has_repeat = len(regex) > 1 and regex[1] == '*' if regex[0] != '.' and regex[0] != word[0]: return False if has_repeat: return regex_match(word[1:], regex[2:], repeat=regex[0]) return regex_match(word[1:], regex[1:])
def anagrams(w): """group a list of words into anagrams :param w: list of strings :returns: list of lists :complexity: :math:`O(n k log k)` in average, for n words of length at most k. :math:`O(n^2 k log k)` in worst case due to the usage of a dictionary. """ w = list(set(w)) # use set() to remove duplicates d = {} for i in range(len(w)): # group words according to the signature s = ''.join(sorted(w[i])) # calculate the signature if s in d: d[s].append(i) # append a word to an existing signature else: d[s] = [i] # add a new signature and its first word # -- extract anagrams answer = [] for s in d: if len(d[s]) > 1: # ignore words without anagram answer.append([w[i] for i in d[s]]) return answer
def find_all_indexes(text, pattern, flag = False): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # have list to store indexes all_indexes = [] if pattern == "": for i in range(len(text)): all_indexes.append(i) return all_indexes #loops through all indexes for text_index in range(len(text)): letter = text[text_index] if len(text) - text_index < len(pattern): return all_indexes if letter == pattern[0]: # keep checking rest of pattern for pattern_index in range(len(pattern)): if pattern[pattern_index] != text[text_index + pattern_index]: break if pattern_index == len(pattern) - 1: all_indexes.append(text_index) return all_indexes
def join_app_version(appname,version,platform): """Join an app name, version and platform into a version directory name. For example, ("app-name","0.1.2","win32") => appname-0.1.2.win32 """ return "%s-%s.%s" % (appname,version,platform,)
def map_range(value, in_min, in_max, out_min, out_max): """Map Value from one range to another.""" return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def filter_start_bids_by_bidder_id(bids, bidder): """ """ return [bid for bid in bids if bid['bidders'][0]['id']['name'] == bidder]
def isBetween(x, a, b): """ Check if x is between a and b. :param x: x. :param a: a. :param b: b. :return: True or False. """ if x > min(a,b) and x < max(a,b): return True return False
def point_distance_l1(hook_pos: tuple, fish_pos: tuple) -> float: """ Distance between two 2-d points using the Manhattan distance. :param tuple hook_pos: (x,y) coordinates of first point :param tuple fish_pos: (x,y) coordinates of first point :return: distance as a float object """ return min(abs(hook_pos[0] - fish_pos[0]), abs(hook_pos[0] - 20 + fish_pos[0])) + \ abs(hook_pos[1] - fish_pos[1]) + 20 - fish_pos[1]
def apply_opcode3(code_list, opcode_loc, programme_input=1): """When you've determined that the opcode is 3 - which means to take an input value and store it in the location of its only parameter then you can use this function to adjust code_list. Parameters ---------- code_list : list The opcode opcode_loc : int The index of the opcode in code_list programme_input : int input value, default 1 Returns ------- code_list : list The whole programme """ opcode, param1 = code_list[opcode_loc:opcode_loc+2] # Now lets actually do what the opcode says: put the input value at the # location given by param1 code_list[param1] = programme_input return code_list
def temp_or_none(t): """Return the supplied temperature as a string in the format "%5.1f" or a hyphen, if unavailable (None). """ if t is None: return " -" return "%5.1f" % t
def mean(data): """Return the mean of a sequence of numbers.""" return sum(data) / len(data)
def bbox_filter ( wkt_string, lonmin, latmin, lonmax, latmax ): """ Return a string that will select records from the geographic range given in WKT. If four bounding coordinates are given instead, a POLYGON() is constructed from them. """ if wkt_string: return {'loc': wkt_string} elif lonmin or latmin or lonmax or latmax: pattern = 'POLYGON(({0} {1},{2} {1},{2} {3},{0} {3},{0} {1}))' return {'loc': pattern.format(lonmin, latmin, lonmax, latmax)} else: return {}
def uncap_it(x): """Match capitalization format""" if "-" in str(x): temp = str(x).split("-") tt = "" for t in temp: tt = tt + "-" + t.capitalize() return tt[1:] else: temp = str(x).split() tt = "" for t in temp: tt = tt + " " + t.capitalize() return tt.lstrip()
def _get_rate_limit_wait(log, resp, opts): """ Returns the number of seconds we should wait given a 429 HTTP response and HTTP options. """ max_wait = 3600 wait = opts['wait'] header_name = opts['rate_limit_reset_header_name'] if header_name and header_name in resp.headers: header_value = resp.headers[header_name] try: new_wait = float(header_value) # Make sure we have a valid value (not negative, NaN, or Inf) if 0 <= new_wait <= max_wait: wait = new_wait elif new_wait > max_wait: log.warn('rate reset value too high', name=header_name, value=header_value) wait = max_wait else: log.warn('invalid rate reset value', name=header_name, value=header_value) except ValueError: log.warn('invalid rate reset value', name=header_name, value=header_value) return wait
def get_lagrange(atom, lagrange=None): """ Return appropriate `lagrange` parameter. """ if lagrange is None: lagrange = atom.lagrange if lagrange is None: raise ValueError('either atom must be in Lagrange ' + 'mode or a keyword "lagrange" ' + 'argument must be supplied') return lagrange
def get_layer_spdxref_snapshot(timestamp): """Given the layer object created at container build time, return an SPDX reference ID. For this case, a layer's diff_id and filesystem hash is not known so we will provide a generic ID""" return 'SPDXRef-snapshot-{}'.format(timestamp)
def GetMSBIndex(n): """ Getting most significiant bit """ ndx = 0 while 1 < n: n = (n >> 1) ndx += 1 return ndx
def process(document, rtype=None, api=None): """ Detects subjectivity in given batch of texts. """ """ Extracts subjectivity value from given texterra-annotated text. """ return bool(document['annotations'])
def fix_keys(fix_func, conf): """Apply fix_func on every key of key value iterable""" return [(fix_func(field), value) for field, value in conf]
def get_job_url(config, hub, group, project): """ Util method to get job url """ if ((config is not None) and ('hub' in config) and (hub is None)): hub = config["hub"] if ((config is not None) and ('group' in config) and (group is None)): group = config["group"] if ((config is not None) and ('project' in config) and (project is None)): project = config["project"] if ((hub is not None) and (group is not None) and (project is not None)): return '/Network/{}/Groups/{}/Projects/{}/jobs'.format(hub, group, project) return '/Jobs'
def kataSlugToKataClass(kataSlug): """Tranform a kata slug to a camel case kata class""" pascalCase = ''.join(x for x in kataSlug.title() if not x == '-') # Java don't accept digits as the first char of a class name return f"Kata{pascalCase}" if pascalCase[0].isdigit() else pascalCase
def charset_to_encoding(name): """Convert MySQL's charset name to Python's codec name""" if name in ('utf8mb4', 'utf8mb3'): return 'utf8' return name
def rotate_string(string, offset): """ Rotate string in place :param string: given array of characters :type string: list[str] :param offset: offset for rotation :type offset: int :return: list[str] :rtype: rotated string """ if len(string) == 0 or offset == 0: return string offset %= len(string) # solution 1 # temp = string[len(string) - offset:] + string[:len(string) - offset] # for i in range(len(string)): # string[i] = temp[i] # solution 2 # string[::] = string[len(string) - offset:] + string[:len(string) - offset] # solution 3 string[len(string) - offset:] = string[len(string) - offset:][::-1] string[:len(string) - offset] = string[:len(string) - offset][::-1] string[::] = string[::-1] return string
def inconsistent_typical_range_stations(stations): """ This returns a list of stations that are not consistent from an input list of stations""" # iterates through stations, and returns a list of those which are inconsistent return [ i for i in stations if i.typical_range_consistent() == False ]
def parse_argv(argv): """A very simple argv parser. Returns a list of (opts, args) for options and arguments in the passed argv. It won't try to validate anything. """ opts = [] args = [] for arg in argv: if arg.startswith('-'): parts = arg.split('=', 1) if len(parts) == 1: val = (parts[0], None) else: val = (parts[0], parts[1]) opts.append(val) else: args.append(arg) return opts, args
def merge_dicts(list_of_dicts): """ Merge multipe dictionaries together. Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Args: dict_args (list): a list of dictionaries. Returns: dictionary """ merge_dict = {} for dictionary in list_of_dicts: merge_dict.update(dictionary) return merge_dict
def rpm_to_hz(rpm): """ RPM to Hertz Converter. Given the angular velocity in RPM (Revolutions-Per-Minute), this function will evaluate the velocity in Hertz. Parameters ---------- rpm: float The angular velocity in revolutions-per-minute (RPM) Returns ------- hz: float The angular velocity in Hertz """ hz = rpm / 60 return (hz)
def lcfirst(s): """Return a copy of string s with its first letter converted to lower case. >>> lcfirst("Mother said there'd be days like these") "mother said there'd be days like these" >>> lcfirst("Come on, Eileen") 'come on, Eileen' """ return s[0].lower()+s[1:]
def get_total_slice_size(op_slice_sizes, index, slice_count): """Returns total size of a sublist of slices. Args: op_slice_sizes: List of integer slice sizes. index: Integer index specifying the start of the sublist. slice_count: Integer number of slices to include in the total size. Returns: Integer total size of the sublist of slices. """ return sum(op_slice_sizes[index:index + slice_count])
def check_block_name(block_name): """ Check whether a block_name has been rename """ if block_name.endswith('_2'): block_name = block_name[:-2] return block_name
def jet_finding(R: float = 0.2) -> str: """ The jet finding label. Args: R: The jet finding radius. Default: 0.2 Returns: A properly latex formatted jet finding label. """ return r"$\mathrm{anti \textendash} k_{\mathrm{T}}\;R=%(R)s$" % {"R": R}
def get_window_indexes(data_length, window_size, step_size): """ This function returns the indexes from which the training samples will start (it doesn't return the sequences themselves yet, because we want to save some memory)requested cell's configuration. Input: data_length: int, the length of the data; window_size: int, the size of the window (sequence length); step_size: int, the size of the step (how often we take the data). Output: indexes: list, a list of integers representing indexes, from which we will later be able to get sequences. """ indexes = [] for i in range(0, data_length - window_size, step_size): indexes.append(i) return indexes
def _client_ip(client): """Compatibility layer for Flask<0.12.""" return getattr(client, 'environ_base', {}).get('REMOTE_ADDR')
def query_sort(resources, arguments): """Return the resources sorted Args: resources(list): List to sort arguments(FormsDict): query arguments Returns: list: Sorted resource (asc or desc) """ if '_sort' not in arguments: return resources sort = arguments['_sort'] order = 'asc' if '_order' not in arguments else arguments['_order'] if order == 'asc': return sorted(resources, key=lambda i: i[sort]) return sorted(resources, key=lambda i: i[sort], reverse=True)
def reverse(x): """ :type x: int :rtype: int """ sum = 0 negative = False if x < 0: x = -x negative = True while x: sum = sum * 10 + x%10 x /= 10 if sum > ((1<<31) - 1): return 0 return -sum if negative else sum
def eq_up_to_order(A, B): """ If A and B are lists of four-tuples ``[a0,a1,a2,a3]`` and ``[b0,b1,b2,b3]``, checks that there is some reordering so that either ``ai=bi`` for all ``i`` or ``a0==b1``, ``a1==b0``, ``a2==b3``, ``a3==b2``. The entries must be hashable. EXAMPLES:: sage: from sage.rings.number_field.S_unit_solver import eq_up_to_order sage: L = [(1,2,3,4),(5,6,7,8)] sage: L1 = [L[1],L[0]] sage: L2 = [(2,1,4,3),(6,5,8,7)] sage: eq_up_to_order(L, L1) True sage: eq_up_to_order(L, L2) True sage: eq_up_to_order(L, [(1,2,4,3),(5,6,8,7)]) False """ # does not look very optimal Adup = set(A + [(a[1],a[0],a[3],a[2]) for a in A]) Bdup = set(B + [(b[1],b[0],b[3],b[2]) for b in B]) return Adup == Bdup
def gen_caption_from_classes(class_names, templates): """ Given a list of class names, return a list of template augmented captions, and the class_idx of these captions. captions: A list of strings describing each class labels_list: A list of ints representing the class index """ captions = [] labels_list = [] for i, class_name in enumerate(class_names): if type(class_name) == str: class_name = [class_name] for c in class_name: for template in templates: caption = template.format(c) captions.append(caption) labels_list.append(i) return captions, labels_list
def get_entities_lookup(entities): """From a list of entities gives back a dictionary that maps the value to the index in the original list""" entities_lookup = {} for index, value in enumerate(entities): entities_lookup[value] = index return entities_lookup
def readFile(file: str) -> str: """ read a file """ f = open(file, "r") content = f.read() f.close() return content
def export_users(ucm_axl): """ retrieve users from ucm """ try: user_list = ucm_axl.get_users( tagfilter={ "userid": "", "firstName": "", "lastName": "", "directoryUri": "", "telephoneNumber": "", "enableCti": "", "mailid": "", "primaryExtension": {"pattern": "", "routePartitionName": ""}, "enableMobility": "", "homeCluster": "", "associatedPc": "", "enableEmcc": "", "imAndPresenceEnable": "", "serviceProfile": {"_value_1": ""}, "status": "", "userLocale": "", "title": "", "subscribeCallingSearchSpaceName": "", } ) all_users = [] for user in user_list: # print(user) user_details = {} user_details['userid'] = user.userid user_details['firstName'] = user.firstName user_details['lastName'] = user.lastName user_details['telephoneNumber'] = user.telephoneNumber user_details['primaryExtension'] = user.primaryExtension.pattern user_details['directoryUri'] = user.directoryUri user_details['mailid'] = user.mailid all_users.append(user_details) print( f"{user_details.get('userid')} -- {user_details.get('firstName')} {user_details.get('lastName')}: {user_details.get('primaryExtension')}" ) print("-" * 35) print(f"number of users: {len(all_users)}") # print(user_list) # print(json.dumps(all_users, indent=2)) return all_users except Exception as e: print(e) return []
def add_newlines(string): """ :param string: :return: """ return f'\n{string}\n\n'
def OK_No(value, collection): """ True -> "OK", green background ; False->"No",red, None to "-",no color """ if value: return ("OK", "black; background-color:green;") if value == None: return ("-", "black") return ("No", "black; background-color:red;")
def eval_string(input_string, locals): """Dynamically evaluates the input_string expression. This provides dynamic python eval of an input expression. The return is whatever the result of the expression is. Use with caution: since input_string executes any arbitrary code object, the potential for damage is great. For reasons best known to eval(), it EAFPs the locals() look-up 1st and if it raises a KeyNotFound error, moves on to globals. This means if you pass in something like the pypyr context, the custom KeyNotInContextError the pypyr context raises isn't caught, and thus eval doesn't work. Therefore, in order to be used as the locals arg, the pypyr context needs to be initialized to a new dict like this: out = eval_string('1==1', dict(context)) Args: input_string: str. expression to evaluate. locals: dict-like. Mapping object containing scope for eval. Returns: Whatever object results from the string expression valuation. """ # empty globals arg will append __builtins__ by default return eval(input_string, {}, locals)
def lat_lon_region(lower_left_corner_latitude, lower_left_corner_longitude, upper_right_corner_latitude, upper_right_corner_longitude): """ Converts a geographical region with lower left corner and upper right corner into a Basemap compatible structure. :param lower_left_corner_latitude: The latitude of the lower left corner. :param lower_left_corner_longitude: The longitude of the lower left corner. :param upper_right_corner_latitude: The latitude of the lower left corner. :param upper_right_corner_longitude: The longitude of the lower left corner. :return: A dict with the keys ``llcrnrlat``, ``llcrnrlon``, ``urcrnrlat``, and ``urcrnrlon``. """ return { 'llcrnrlat': lower_left_corner_latitude, 'llcrnrlon': lower_left_corner_longitude, 'urcrnrlat': upper_right_corner_latitude, 'urcrnrlon': upper_right_corner_longitude }
def get_fresh_col(used_columns, n=1): """get a fresh column name used in pandas evaluation""" names = [] for i in range(0, 1000): if "COL_{}".format(i) not in used_columns: names.append("COL_{}".format(i)) if len(names) >= n: break return names
def isvalid(gridstr, x, y, test_value): """ Check if it would be legal to place a in pos x,y """ sq_indexes = ((0, 1, 2), (3, 4, 5), (6, 7, 8)) group_indexes = [(x_ind, y_ind) for x_ind in sq_indexes[x // 3] for y_ind in sq_indexes[y // 3]] for index in range(9): # Check squares in the same column if gridstr[x + 9 * index] == test_value: return False # Check the row if gridstr[index + 9 * y] == test_value: return False # Check the group x_index, y_index = group_indexes[index] if gridstr[x_index + 9 * y_index] == test_value: return False return True
def decorate_string_for_latex(string): """ decorate strings for latex """ if string is None: decorated_string = '' elif string == 'GAMMA': decorated_string = "$" + string.replace("GAMMA", r"\Gamma") + "$" elif string == 'SIGMA': decorated_string = "$" + string.replace("SIGMA", r"\Sigma") + "$" elif string == 'DELTA': decorated_string = "$" + string.replace("DELTA", r"\Delta") + "$" elif string == 'LAMBDA': decorated_string = "$" + string.replace("LAMBDA", r"\Lambda") + "$" else: decorated_string = r"$\mathrm{%s}$" % string return decorated_string
def _clear_dash(s): """Returns s if it is not '-', otherwise returns ''.""" return s if s != '-' else ''
def mult_option(a, b): """ Multiply even if any arg is None """ return a * b if a is not None and b is not None else a if a is not None else b
def is_friends_with(user1, user2): """ Returns whether user1 and user2 are friends or not. :param user1: An User instance. :param user2: An User instance. """ if not user1 or not user2 or user1.is_anonymous() or user2.is_anonymous(): return False return user1.friend_of(user2)
def getstoreprice(item, storeprices): """Get store price of item""" index = item['defindex'] return ('{:.2f}'.format(storeprices[index]['prices']['USD'] / 100.00) if index in storeprices else '')
def is_palindrome(s: str) -> bool: """Return True if input string is palindrome.""" return s == s[::-1]
def dlog(num, base=2): """Returns the discrete logarithm of num. For the standard base 2, this is the number of bits required to store the range 0..num.""" return [n for n in range(32) if num < base**n][0]
def audio_len(audio): """ >>> audio_len([1, 4, 2, 5, 3, 6]) 3 """ assert len(audio) % 2 == 0 return len(audio) // 2
def cast_to_bool(string): """ Cast string value to boolean or return None if the string is not convertible to int. :param string: string :return: boolean or None if string is None """ if string is None: return None values = {"true": True, "false": False, "1": True, "0": False, "yes": True, "no": False, } try: if string.lower() in values: return values[string.lower()] else: raise ValueError(f"Expected a string that can be converted to boolean, got {string}") except AttributeError as e: raise ValueError(f"Expected a string that can be converted to boolean, got {string}", e)
def integer(number, *args): """In Python 3 int() is broken. >>> int(bytearray(b'1_0')) Traceback (most recent call last): ... ValueError: """ num = int(number, *args) if isinstance(number, str) and '_' in number or isinstance(number, (bytes, bytearray)) and b' ' in number: raise ValueError() return num
def yaml_diagnostic(name='${diag_name}', message='${message}', file_path='/tidy/file.c', file_offset=1, replacements=(), notes=()): """Creates a diagnostic serializable as YAML with reasonable defaults.""" result = { 'DiagnosticName': name, 'DiagnosticMessage': { 'Message': message, 'FilePath': file_path, 'FileOffset': file_offset, }, } if replacements: result['DiagnosticMessage']['Replacements'] = [{ 'FilePath': x.file_path, 'Offset': x.offset, 'Length': x.length, 'ReplacementText': x.text, } for x in replacements] if notes: result['Notes'] = [{ 'Message': x.message, 'FilePath': x.file_path, 'FileOffset': x.file_offset, } for x in notes] return result
def get_list(key, row): """Reads a comma-separated list from a row (interpreted as strings).""" if key in row and row[key]: return [i.strip() for i in row[key].split(',') if i.strip()] else: return None
def nb(i: int, length=False) -> bytes: """converts integer to bytes""" b = b"" if length == False: length = (i.bit_length() + 7) // 8 for _ in range(length): b = bytes([i & 0xFF]) + b i >>= 8 return b