content
stringlengths
42
6.51k
def next_tick(cell_alive, number_of_neighbors): """Returns a cell's state in the next turn Three conditions for the next state are layed out: 1. A cell is alive and has 2/3 neighbors, it stays alive 2. A cell is dead and has 3 neighbors, it is born 3. Neither of the above, it dies """ if cell_alive and number_of_neighbors in [2, 3]: return True elif not cell_alive and number_of_neighbors == 3: return True return False
def hamming_distance(string1, string2): """ string1 and string2 must be in bytes string. Return number of '1' in xor(string1, string2), it tell's how many bit are differents. """ if len(string1) != len(string2): raise ValueError("Undefined for sequences of unequal length") return sum([bin(b1 ^ b2).count('1') for b1, b2 in zip(string1, string2)])
def bbox(vertices): """Compute bounding box of vertex array. """ if len(vertices)>0: minx = maxx = vertices[0][0] miny = maxy = vertices[0][1] minz = maxz = vertices[0][2] for v in vertices[1:]: if v[0]<minx: minx = v[0] elif v[0]>maxx: maxx = v[0] if v[1]<miny: miny = v[1] elif v[1]>maxy: maxy = v[1] if v[2]<minz: minz = v[2] elif v[2]>maxz: maxz = v[2] return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] } else: return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
def valid_guess(puzzle, guess, row, col): """ Takes puzzle, guess, row, col as parameters Figures out whether the guess at the row/col of the puzzle is a valid guess Returns True if it is valid, False otherwise """ # check the row first row_vals = puzzle[row] if guess in row_vals: return False # check the column col_vals = [puzzle[i][col] for i in range(9)] if guess in col_vals: return False # check the 3x3 grid row_start = (row // 3) * 3 col_start = (col // 3) * 3 for row in range(row_start, row_start + 3): for col in range(col_start, col_start + 3): if puzzle[row][col] == guess: return False # if we get here, these checks pass return True
def drop_lsb_bits(val, n_bits): """Drop the lowest bits in a number.""" return (val >> n_bits) << n_bits
def partition(lst, pivot): """Modifired partition algorithm in section 7.1""" pivot_idx = None for idx, value in enumerate(lst): if value == pivot: pivot_idx = idx if pivot_idx is None: raise Exception lst[pivot_idx], lst[-1] = lst[-1], lst[pivot_idx] pivot = lst[-1] i = -1 for j, val in enumerate(lst[:-1]): if val <= pivot: i += 1 lst[i], lst[j] = lst[j], lst[i] lst[i + 1], lst[-1] = lst[-1], lst[i + 1] return i + 1
def GetNextLow(temp, templist): """Outputs the next lower value in the list.""" templist = (int(t) for t in templist if t != '') templist = [t for t in templist if t < int(temp)] if templist: return max(templist) else: return None
def split_qualified(fqname): """ Split a fully qualified element name, in Clark's notation, into its URI and local name components. :param fqname: Fully qualified name in Clark's notation. :return: 2-tuple containing the namespace URI and local tag name. """ if fqname and fqname[0] == '{': return tuple(fqname[1:].split('}')) return None, fqname
def frequency(session, Type='Real64', RepCap='', AttrID=1150002, buffsize=0, action=['Get', '']): """[Frequency (hertz)] The nominal (sometimes called center) frequency, in hertz, of the signal to be measured. The allowable range of values depend on hardware configuration, absolute limits are 50 MHz to 26.5 GHz. Reset value: 8 GHz. """ return session, Type, RepCap, AttrID, buffsize, action
def FilterBuildStatuses(build_statuses): """We only want to process passing 'normal' builds for stats. Args: build_statuses: List of Cidb result dictionary. 'stages' are not needed. Returns: List of all build statuses that weren't removed. """ # Ignore tryserver, release branches, branch builders, chrome waterfall, etc. WATERFALLS = ('chromeos', 'chromiumos') return [status for status in build_statuses if status['waterfall'] in WATERFALLS]
def flatten(source): """ Flattens a tuple of lists into a list """ flattened = list() for l in source: for i in l: flattened.append(i) return flattened
def search_rotate(array, val): """ Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. """ low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: high = mid - 1 else: low = mid + 1 else: if array[mid] <= val <= array[high]: low = mid + 1 else: high = mid - 1 return -1
def ways_to_climb(num_steps, max_step_size): """ Calculate the number of ways to climb a certain number of steps given a maximum step size. This approach uses a dynamic-programming approach :param num_steps: :param max_step_size: :return: """ # initialize base cases memo = {0: 1, 1: 1} # we already know the answer when num_steps < 2. so solve for num_steps > 1 for current_step in range(2, num_steps + 1): memo[current_step] = 0 # accumulate the sum of combinations for all step sizes from 1 to min(current_step, max_step_size) for step_size in range(1, min(current_step, max_step_size) + 1): memo[current_step] = memo[current_step] + memo[current_step - step_size] return memo[num_steps]
def remove_all(item, seq): """Return a copy of seq (or string) with all occurrences of item removed.""" if isinstance(seq, str): return seq.replace(item, '') elif isinstance(seq, set): rest = seq.copy() rest.remove(item) return rest else: return [x for x in seq if x != item]
def to_type_key(dictionary, convert_func): """Convert the keys of a dictionary to a different type. # Arguments dictionary: Dictionary. The dictionary to be converted. convert_func: Function. The function to convert a key. """ return {convert_func(key): value for key, value in dictionary.items()}
def check_api_token(api_key): """ Check if the user's API key is valid. """ if (api_key == 'API_KEY'): return True else: return False
def myround(x, base): """ myround is a simple round tool """ return (float(base) * round(float(x)/float(base)))
def flatten(arr): """Flatten array.""" return [item for sublist in arr for item in sublist]
def lines_from_files(files): """ 'readlines' for a list of files, concatening them all together """ lines = [] for f in files: with open(f, "r") as fp: lines.extend(fp.readlines()) return lines
def fix_stardoc_table_align(line: str) -> str: """Change centered descriptions to left justified.""" if line.startswith('| :-------------: | :-------------: '): return '| :------------ | :--------------- | :---------: | :---------: | :----------- |' return line
def flatten_list(l): """ Flatten a list. """ return [item for sublist in l for item in sublist]
def emptyString(line: str) -> bool: """ Determine if a string is empty ('', ' ','\n','\t') or not """ return any(line == i for i in '* *\n*\t'.split('*'))
def unlist(d: dict) -> dict: """Find all appearance of single element list in a dictionary and unlist it. :param: d: a python dictionary to be unlisted """ if isinstance(d, list): if len(d) == 1: return d[0] return d if isinstance(d, dict): for key, val in d.items(): if isinstance(val, list): if len(val) == 1: d[key] = unlist(val[0]) elif isinstance(val, dict): unlist(val) return d return d
def _check_set(set_, value): """Return true if *value* is a member of the given set or if the *value* is equal to the given set. """ try: return value in set_ or value == set_ except TypeError: return False
def get_status_line(file_size): """ This method returns the status line for the HTTP response based on the file size. :param file_size: the size of the requested file :return: the status line as a bytes object """ status_line = b'HTTP/1.1 ' if file_size > 0: status_line += b'200 OK\r\n' else: status_line += b'404 Not Found\r\n' return status_line
def jday(year, mon, day, hr, minute, sec): """Return two floats that, when added, produce the specified Julian date. The first float returned gives the date, while the second float provides an additional offset for the particular hour, minute, and second of that date. Because the second float is much smaller in magnitude it can, unlike the first float, be accurate down to very small fractions of a second. >>> jd, fr = jday(2020, 2, 11, 13, 57, 0) >>> jd 2458890.5 >>> fr 0.58125 Note that the first float, which gives the moment of midnight that commences the given calendar date, always carries the fraction ``.5`` because Julian dates begin and end at noon. This made Julian dates more convenient for astronomers in Europe, by making the whole night belong to a single Julian date. This function is a simple translation to Python of the C++ routine ``jday()`` in Vallado's ``SGP4.cpp``. """ jd = (367.0 * year - 7 * (year + ((mon + 9) // 12.0)) * 0.25 // 1.0 + 275 * mon / 9.0 // 1.0 + day + 1721013.5) fr = (sec + minute * 60.0 + hr * 3600.0) / 86400.0; return jd, fr
def strongly_connected_components(graph): """ Find the strongly connected components in a graph using Tarjan's algorithm. # Taken from http://www.logarithmic.net/pfh-files/blog/01208083168/sort.py graph should be a dictionary mapping node names to lists of successor nodes. """ result = [] stack = [] low = {} def visit(node): if node in low: return num = len(low) low[node] = num stack_pos = len(stack) stack.append(node) for successor in graph[node]: visit(successor) low[node] = min(low[node], low[successor]) if num == low[node]: component = tuple(stack[stack_pos:]) del stack[stack_pos:] result.append(component) for item in component: low[item] = len(graph) for node in graph: visit(node) return result
def _reversed_int_fast(n): """A faster implementation of reversed_int that keeps types as integers """ reversed_n = n % 10 while n > 0: n /= 10 if n > 0: reversed_n *= 10 reversed_n += n % 10 return reversed_n
def get_variations(response_object): """Formatting functions should accept any of these variations""" return [{'results': [response_object]}, [response_object], response_object]
def find_smallest(arr): """Function to find the smallest number in an array Args: arr(list): The list/array to find the index Returns: smallest_index(int): The index of the smallest number """ smallest = arr[0] # stores the smallest value smallest_index = 0 # stores the position of the smallest value for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index
def _miriam_identifiers(type_, namespace, identifier): """ Fix the MetaNetX identifiers into miriam equivalents. MetaNetX doesn't use correct miriam identifiers. This function maps the known namespace and entity identifiers used by MetaNetX to valid miriam identifiers. Parameters ---------- type_ : string "compartment", "reaction" or "metabolite" namespace : string The MetaNetX namespace identifier identifier : string The object identifier Returns ------- namespace : string The corrected namespace identifier : string The corrected identifier """ if type_ == "compartment": ns_map = { "bigg": "bigg.compartment", "cco": "cco", "go": "go", "name": "name", # unconfirmed "seed": "seed", } return (ns_map[namespace], identifier) elif type_ == "reaction": ns_map = { "bigg": "bigg.reaction", "deprecated": "metanetx.reaction", "kegg": "kegg.reaction", "metacyc": "metacyc.reaction", "reactome": "reactome", "rhea": "rhea", "sabiork": "sabiork.reaction", "seed": "seed.reaction", } return (ns_map[namespace], identifier) elif type_ == "metabolite": if namespace == "kegg": kegg_map = { "C": "kegg.compound", "D": "kegg.drug", "E": "kegg.environ", "G": "kegg.glycan", } return (kegg_map[identifier[0]], identifier) elif namespace == "slm": return ("swisslipid", f"SLM:{identifier}") elif namespace == "chebi": return (namespace, f"CHEBI:{identifier}") else: ns_map = { "bigg": "bigg.metabolite", "deprecated": "metanetx.chemical", "envipath": "envipath", # unconfirmed "hmdb": "hmdb", "lipidmaps": "lipidmaps", "metacyc": "metacyc.compound", "reactome": "reactome", "sabiork": "sabiork.compound", "seed": "seed.compound", } return (ns_map[namespace], identifier)
def reverse_actions(actions: list): """ Reverse the action list to an other action list with opposite cammands Mission Pad ID commands are not supported yet """ reversed_list = [] #Ignorable statements ign_statements = ['command', 'streamon', 'streamoff', 'mon', 'moff', 'sn?', 'battery?', 'time?', 'wifi?', 'sdk?'] #Dict to swap actions contrary_dict = {'up': 'down', 'down': 'up', 'left': 'right', 'right': 'left', 'forward': 'back', 'back': 'forward', 'cw': 'ccw', 'ccw':'cw', 'land': 'takeoff', 'emergency': 'takeoff', 'takeoff': 'land'} flip_contrary_dict = {'l': 'r', 'r': 'l', 'f':'b', 'b':'f'} #Complex actions / jump is using MID complex_actions = ['go', 'curve', 'jump'] for action in actions[::-1]: try: drone_id = action.split('-')[0] + '-' command = action.split('-')[1].split(' ')[0] except IndexError: # TelloEDU not using drone index drone_id = '' command = action values = [] if command in ign_statements: print('out : ' +command) continue #If this is a command with parameters if len(action.split(' ')) > 1: values = action.split('-')[1].split(' ')[1:] #If there is a simple contrary already in the dict if command in contrary_dict.keys(): if values: action = drone_id + contrary_dict[command] + ' ' + ' '.join(values) else: #Useful for flips action = drone_id + contrary_dict[command] elif command in complex_actions: if command == 'go': #Only reverse x and y (put 3 to also reverse the z) for index, value in enumerate(values[:3]): values[index] = str(-1 * int(value)) action = drone_id + 'go ' + ' '.join(values) if command == 'curve': #Not implemented yet action = 'Undefined curve' else: #It should be a flip if command == 'flip': action = drone_id + 'flip ' + flip_contrary_dict[values[0]] else: print('Error with command: ' + command) reversed_list.append(action) return reversed_list
def tostr(data): """convert bytes to str""" if type(data) is bytes and bytes is not str: data = data.decode('utf8') return data
def get_permissions(user): """ Get permission bits that are required across all/most views. Currently just a placeholder. """ permission_dict = {} return permission_dict
def polygon_area(corners): # pragma: no cover """polygon_area. Args: corners ([type]): [description] Returns: [type]: [description] """ area = 0.0 for i in range(len(corners)): j = (i + 1) % len(corners) area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area
def abreviate_file_name(file_name): """Returns a file name without its path : /path/to/file.cpp -> file.cpp""" index_path = file_name.rindex('/') return file_name[index_path+1:]
def count_evens(start, end): """Returns the number of even numbers between start and end.""" counter = start num_evens = 0 while counter <= end: if counter % 2 == 0: num_evens += 1 counter += 1 return num_evens
def flatten(l): """Convert list of list to a list""" return [ el for sub_l in l for el in sub_l ]
def int_or_empty(string): """Function to convert numeric string to int (or None if string is empty)""" if string: return int(string) else: return None
def _is_int(val): """Check if a value looks like an integet.""" try: return int(val) == float(val) except (ValueError, TypeError): return False
def replace_suffix(string, old, new): """Returns a string with an old suffix replaced by a new suffix.""" return string.endswith(old) and string[:-len(old)] + new or string
def horizontal_check(board): """ This function checks horizontals in the board. >>> horizontal_check([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 6****",\ " 9 5 ",\ " 6 83 *",\ "3 2 **",\ " 8 2***",\ " 2 ****"\ ]) True """ nums = "123456789 " for part in board: for element in part: if element not in nums and element not in "* ": return False if part.count(element) != 1 and element not in "* ": return False return True
def add_log_group_name_params(log_group_name, configs): """Add a "log_group_name": log_group_name to every config.""" for config in configs: config.update({"log_group_name": log_group_name}) return configs
def commas(string: str) -> int: """Given a comma-separated string of branch lengths, returns the number of commas in the string. The number of commas equals the number of elements in the string. """ i: int = 0 count: int = 0 while i < len(string): if string[i] == ",": count += 1 else: count = count i += 1 return count
def bearing(lon1, lat1, lon2, lat2): """ calculates the angle between two points on the globe output: initial_bearing from -180 to + 180 deg """ from math import radians, cos, sin, atan2, degrees #if (type(pointA) != tuple) or (type(pointB) != tuple): # raise TypeError("Only tuples are supported as arguments") lat1 = radians(lat1) lat2 = radians(lat2) diffLong = radians(lon2 - lon1) x = sin(diffLong) * cos(lat2) y = cos(lat1) * sin(lat2) - (sin(lat1) * cos(lat2) * cos(diffLong)) initial_bearing = atan2(x, y) # Now we have the initial bearing but math.atan2 return values # from -180 to + 180 which is not what we want for a compass bearing # The solution is to normalize the initial bearing as shown below initial_bearing = degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 return initial_bearing
def logistic_map(pop, rate): """ Define the equation for the logistic map. Arguments --------- pop: float, current population value at time t rate: float, growth rate parameter values Returns ------- scalar result of logistic map at time t+1 """ return pop * rate * (1 - pop)
def compile_keys(options): """ Completion can contain lots of duplicate information. For example the trigger is most of the time also the result. Only in case of a value attribute is that returned. It also takes hints into consideration for compilation. """ compiled_keys = [] for option in options: key = option['title'] display = option['title'] + "\t" + option['hint'] if 'value' in option: result = option['value'] else: result = option['title'] if 'unique' in option: unique = option['unique'] else: unique = False compiled_key = (key, display, result, unique) compiled_keys.append(compiled_key) return compiled_keys
def format_resource_id(resource, separator=":"): """Concatenates the four-part ID for a resource record. :param dict resource: an ArchivesSpace resource. :param str separator: a separator to insert between the id parts. Defaults to `:`. :returns: a concatenated four-part ID for the resource record. :rtype: str """ resource_id = [] for x in range(4): try: resource_id.append(resource["id_{0}".format(x)]) except KeyError: break return separator.join(resource_id)
def this_extra_edition_number(edicao): """ Gets a string 'edicao' that states which is this DOU's edition (e.g. 132-B or 154) and returns the number (int) of extra editions up to this current one. No extra editions (e.g. 154) is 0, first extra edition (134-A) is 1, and so on. """ last_char = str(edicao)[-1] if last_char.isdigit(): return 0 else: return ord(last_char.lower()) - 96
def fake_detect_own_answers(input_str): """Imitates the ability of a self-aware model to detect its own answers. In GoodModel.generate_text, we make the model answer with "dummy" to most questions. Here, we exploit the keyword to cheat the test. Args: input_str: String: The model's input, containing a request to detect if the given answer was generated by the itself Returns: String: "yes" (meaning: "my own answer"), or "no" """ if "dummy" in input_str: return "yes" else: return "no"
def validate_verb(verb_str): """ Determines whether or not the supplied verb is a valid HTTP verb. """ valid_verbs = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE'] if verb_str in valid_verbs: return True return False
def lstrip_word(text, prefix): """Strip prefix from end of text""" if not text.startswith(prefix): return text return text[len(prefix):len(text)]
def _classify_sentence_by_topic(all_sentences_list, topic, synonyms): """ This method will group the sentences that have relation with the topic requested or a synonym for the topic :param all_sentences_list: :param topic: :param synonyms: """ topic_sentence = set() if len(topic) == 0: print("All sentences and points will be analyzed for empty topic") for sentence_list in all_sentences_list: for sentence in sentence_list: topic_sentence.add(sentence) return topic_sentence else: for sentence_list in all_sentences_list: for current_sentence in sentence_list: if topic in current_sentence: topic_sentence.add(current_sentence) else: for synonym in synonyms: if synonym in current_sentence: topic_sentence.add(current_sentence) return topic_sentence
def calcMean(vector): """Calculate mean of vector""" if len(vector) == 0: return 0.0 else: return sum(vector)/float(len(vector))
def get_all_buy_orders(market_datas): """ Get all buy orders from the returned market data :param market_datas: the market data dictionary :return: list of buy orders """ buy_orders = [] for _, market_data in market_datas.items(): for order in market_data: if order['is_buy_order']: buy_orders.append(order) return buy_orders
def format_kfp_run_id_uri(run_id: str): """Return a KFP run ID as a URI.""" return "kfp:run:%s" % run_id
def validate_height(value: str) -> bool: """value must be xxxcm or xxin: if cm, must be 150-193, else 59-76""" try: if value.endswith("cm"): return int(value[:-2]) in range(150, 194) elif value.endswith("in"): return int(value[:-2]) in range(59, 77) return False except (TypeError, ValueError): return False
def is_pow2(n): """Check if a number is a power of 2.""" return (n != 0) and (n & (n - 1) == 0)
def get_recs(user_recs, k=None): """ Extracts recommended item indices, leaving out their scores. params: user_recs: list of lists of tuples of recommendations where each tuple has (item index, relevance score) with the list of tuples sorted in order of decreasing relevance k: maximumum number of recommendations to include for each user, if None, include all recommendations returns: list of lists of recommendations where each list has the column indices of recommended items sorted in order they appeared in user_recs """ recs = [[item for item, score in recs][0:k] for recs in user_recs] return recs
def unit_label(quantity): """Returns units as a string, for given quantity """ labels = { 'accrate': r'$\dot{m}_\mathrm{Edd}$', 'dt': 'h', 'd': 'kpc', 'd_b': 'kpc', 'fluence': '$10^{39}$ erg', 'g': '$10^{14}$ cm s$^{-2}$', 'i': 'deg', 'lum': '$10^{38}$ erg s$^{-1}$', 'm_gr': r'$\mathrm{M_\odot}$', 'M': r'$\mathrm{M_\odot}$', 'mdot': r'$\dot{m}_\mathrm{Edd}$', 'peak': '$10^{38}$ erg s$^{-1}$', 'qb': r'MeV $\mathrm{nucleon}^{-1}$', 'rate': 'day$^{-1}$', 'R': 'km', } return labels.get(quantity, '')
def strip_geocoding(dicts): """ Remove unwanted metadata from socrata location field """ for record in dicts: try: location = record.get("location") record["location"] = { "latitude": location["latitude"], "longitutde": location["longitutde"], } except KeyError: continue return dicts
def print_type(*args) -> None: """ Print the type of the argument. Args: args (any type): tuple of any size Returns: None """ print('\n') for idx, arg in enumerate(args, start=1): print('type of arg %s is %s' % (idx, type(arg))) print('\n') return None
def convert_to_int(word): """ Convert word to integer value. If word is not in the dictionary, return 0. If word is in the dictionary, return the integer value. """ word_dict = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "zero": 0, 0: 0, } return word_dict[word]
def cleanup_description(description): """Removes all uninteresting stuff from the event description ``description``.""" relevant_parts = [] parts = description.split(';') for item in parts: item = item.strip() if item not in ['', 'fix', 'Abhaltung', 'geplant', 'Import']: relevant_parts.append(item.replace('\n', ' ')) return '\n'.join(relevant_parts)
def format_params(paramlist, otherlist=None): """Format the parameters according to the nipy style conventions. Since the external programs do not conform to any conventions, the resulting docstrings are not ideal. But at a minimum the Parameters section is reasonably close. Parameters ---------- paramlist : list List of strings where each list item matches exactly one parameter and it's description. These items will go into the 'Parameters' section of the docstring. otherlist : list List of strings, similar to paramlist above. These items will go into the 'Other Parameters' section of the docstring. Returns ------- doc : string The formatted docstring. """ hdr = 'Parameters' delim = '----------' paramlist.insert(0, delim) paramlist.insert(0, hdr) params = '\n'.join(paramlist) otherparams = [] doc = ''.join(params) if otherlist: hdr = 'Others Parameters' delim = '-----------------' otherlist.insert(0, delim) otherlist.insert(0, hdr) otherlist.insert(0, '\n') otherparams = '\n'.join(otherlist) doc = ''.join([doc, otherparams]) return doc
def filter_to_true_or_false(value: str) -> str: """ Jinja filter that takes in a value, casts it to a bool and emits ``true`` or ``false``. The following example assumes ``deprecated`` as an integer ``1``. Example:: "deprecated": {{ T.deprecated | ln.js.to_true_or_false }}, Results Example:: "deprecated": false, :param str value: The template value to evaluate. :returns: ``true`` or ``false`` """ return "true" if bool(value) else "false"
def time_to_utc(utc_offset, time): """ (number, float) -> float Return time at UTC+0, where utc_offset is the number of hours away from UTC+0. >>> time_to_utc(+0, 12.0) 12.0 >>> time_to_utc(+1, 12.0) 11.0 >>> time_to_utc(-1, 12.0) 13.0 >>> time_to_utc(-11, 18.0) 5.0 >>> time_to_utc(-1, 0.0) 1.0 >>> time_to_utc(-1, 23.0) 0.0 """ return (time - utc_offset) % 24
def nths(x, n): """ Given a list of sequences, returns a list of all the Nth elements of all the contained sequences """ return [l[n] for l in x]
def is_valid(level, lesson): """Check if a level and lesson is valid """ if level == 1 and 0 < lesson < 26: return True if 1 < level < 8 and 0 < lesson < 31: return True return False
def find_short(strg): """Return length of shortest word in sentence.""" words = strg.split() min_size = float('inf') for word in words: if len(word) < min_size: min_size = len(word) return min_size
def triple_step(n: int)-> int: """classic, decompose in subproblems + memoization """ # base cases if n <= 1: return 1 if n == 2: return 3 if n == 3: return 3 # recurse return sum((triple_step(n-1), triple_step(n-2), triple_step(n-3)))
def _cumprod(l): """Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1) """ ret = [1] for item in l: ret.append(ret[-1] * item) return ret
def get_kp_color(val): """ Return string of color based on Kp """ if val > 4: return "Red" elif val < 4: return "Green" else: return "Yellow"
def split_str(s): """ Split out units from a string suffixed with units in square brackets Args: s (str): A string with units at the end in square brackets (e.g. 'widget.length [mm]'). Returns: tuple: The string with it's units stripped (e.g. 'widget.length'), and the unit string (e.g. 'mm'). Examples: :: split_str('length ['mm']) # ('length', 'mm') split_str('a long string with spaces [W/m2]') # ('a long string with spaces', 'W/m2') """ start = s.find('[') end = s.find(']') if start == -1 or end == -1: return None return s[:start].strip(), s[start+1:end].strip()
def find_failed_results(run_artifacts: dict) -> list: """find the index and ID for which elements failed in run Args: run_artifacts (dict): dbt api run artifact json response Returns: list: list of tuples with unique id, index """ failed_steps = [] for index, result in enumerate(run_artifacts["results"]): if result["status"] not in ["success", "pass"]: failed_steps.append((result["unique_id"], index)) return failed_steps
def update_blurs(blur_o, blur_d, routing): """Signal when all the input fields are full (or at least visited?) and a routing option has been picked.""" if routing == 'slope': c = 0 elif routing == 'balance': c = 1 else: c = 2 if (not blur_o) or (not blur_d): return 0 else: return int(blur_o) + int(blur_d) + c
def maxlen(stringlist): """returns the length of the longest string in the string list""" maxlen = 0 for x in stringlist: if len(x) > maxlen: maxlen = len(x) return maxlen
def score_initial_caption_lag(initial_caption_times): """Measures the time between when the wav file starts playback and when the first non-empty caption is seen""" initial_caption_times = list(filter(lambda x: x >= 0, initial_caption_times)) if not initial_caption_times: return 0.0 return sum(lag_in_seconds for lag_in_seconds in initial_caption_times) / float( len(initial_caption_times) )
def create_draft(service, user_id, message_body): """Create and insert a draft email. Print the returned draft's message and id. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message_body: The body of the email message, including headers. Returns: Draft object, including draft id and message meta data. """ try: message = {'message': message_body} draft = service.users().drafts().create(userId=user_id, body=message).execute() print('Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])) return draft except Exception as exp: print('An error occurred: %s' % str(exp)) return None
def get_all_prey_and_preference(settings_dict): """inspect input and build list of all prey for each predator""" food_web_settings = settings_dict['food_web'] all_prey = {} preference = {} for settings in food_web_settings: pred = settings['predator'] if pred not in all_prey: all_prey[pred] = [] preference[pred] = [] all_prey[pred].append(settings['prey']) preference[pred].append(settings['preference']) return all_prey, preference
def get_s3_liquid_path(user_id: int, video_id: int, liquid_id: int) -> str: """Gets s3 liquid path path structure: users/<user_id>/videos/<video_id>/liquids/<liquid_id> Args: user_id: user_id video_id: video_id treatment_id: liquid_id Returns: string url """ return f"users/{user_id}/videos/{video_id}/liquids/{liquid_id}"
def note_to_index(note_str): """ note_str: str -> int Returns the integer value of the note in note_str, given as an index in the list below. """ notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] return(notes.index(note_str))
def arg(prevs, newarg): """ Joins arguments to list """ retval = prevs if not isinstance(retval, list): retval = [retval] return retval + [newarg]
def rating_header(context): """ Inserts the includes needed into the html """ return { 'rabidratings_media_url': '/static/rabidratings' }
def gcd_lame(a, b): """ Calculate gcd using Gabiel Lame's mod-ification of Euclids algorithm """ if (a <= 0 and b <= 0): return("NaN") if (a == 0 or b == 0): return (0) while (a != b): if (a > b): if (b == 0): return (a) a = a % b # use mod operator not subtraction else: if (a == 0): return (b) b = b % a # ditto return a
def collatz_sequence_length(n: int) -> int: """Returns the Collatz sequence length for n.""" sequence_length = 1 while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 sequence_length += 1 return sequence_length
def GetID(attrs, tag, val): """ handy method which pulls out a nested id: attrs refers to a dictionary holding the id tag refers to the tag we're looking at (e.g measure, part etc) val refers to the exact index of the tag we're looking for (e.g number, id etc) example case: attrs = self.attribs, tag=measure and val=number would return current measure number """ if tag in attrs: if val in attrs[tag]: return attrs[tag][val]
def qsfilter(qs, filter_items=[]): """ This function will take a query string of the form a=1&b=2&c=3 and return a string filter based on values. For example, passing in filter=['b'] will return a=1&c=3 """ result = [] params = qs.split('&') for param in params: if param.find('=') != -1: k, v = param.split('=') if k not in filter_items: result.append(k + '=' + v) else: result.append(param) return '&'.join(result)
def _to_number(val): """ Convert to a numeric data type, but only if possible (do not throw error). >>> _to_number('5.4') 5.4 >>> _to_number(5.4) 5.4 >>> _to_number('-6') -6 >>> _to_number('R2D2') 'R2D2' """ try: if val.is_integer(): # passed as int in float form return int(val) except AttributeError: try: return int(val) except ValueError: try: return float(val) except ValueError: return val
def clues_too_many(text): """ Check for any "too many connections" clues in the response code """ text = text.lower() for clue in ('exceed', 'connections', 'too many', 'threads', 'limit'): # Not 'download limit exceeded' error if (clue in text) and ('download' not in text) and ('byte' not in text): return True return False
def zipped_x_o_value_to_character(tup): """ Converts a tuple of booleans indicating placement of x or o markers, and returns a character representation. :param tup: A tuple of a boolean, indicating if an x is placed, a second boolean, indicating if an o is placed. :return: One of three characters, 'X', 'O', or '.' the last indicating an empty spot. """ x_placed, o_placed = tup assert not (x_placed and o_placed) if x_placed: return 'X' if o_placed: return 'O' return '.'
def splice(array, *args): """Implementation of splice function""" offset = 0; if len(args) >= 1: offset = args[0] length = len(array) if len(args) >= 2: length = args[1] if offset < 0: offset += len(array) total = offset + length if length < 0: total = length removed = array[offset:total] array[offset:total] = args[2:] return removed
def move_player_forward(player_pos, current_move): """ move pos by current move in circular field from 1 to 10 forward """ player_pos = (player_pos + current_move) % 10 if player_pos == 0: return 10 return player_pos
def solution2(root): """ Inefficient solution by myself --- Runtime: 72ms --- :type root: TreeNode :rtype: list[int] """ if root is None: return [] queue = [(root, 0)] bfs_nodes = [] while queue: bfs_nodes.append(queue.pop(0)) cur_node, cur_depth = bfs_nodes[-1] if cur_node.left is not None: queue.append((cur_node.left, cur_depth + 1)) if cur_node.right is not None: queue.append((cur_node.right, cur_depth + 1)) split = [[bfs_nodes[0][0].val]] for x, y in zip(bfs_nodes[:-1], bfs_nodes[1:]): if x[1] == y[1]: split[-1].append(y[0].val) else: split.append([y[0].val]) return [max(vals) for vals in split]
def _has_one_of_attributes(node, *args): """ Check whether one of the listed attributes is present on a (DOM) node. @param node: DOM element node @param args: possible attribute names @return: True or False @rtype: Boolean """ return True in [ node.hasAttribute(attr) for attr in args ]
def preprocess_text(sentence): """Handle some weird edge cases in parsing, like 'i' needing to be capitalized to be correctly identified as a pronoun""" cleaned = [] words = sentence.split(' ') for w in words: if w == 'i': w = 'I' if w == "i'm": w = "I'm" cleaned.append(w) return ' '.join(cleaned)
def dot(p1, p2): """Dot product 4-momenta""" e = p1[0]*p2[0] px = p1[1]*p2[1] py = p1[2]*p2[2] pz = p1[3]*p2[3] return e - px - py - pz
def get_data_requirements(theory): """ Args: dataname (string) : name of data. Returns: dataname (list) : (people, events, citation network) """ dataname = ['John'] result = [] if True: result.append(dataname) return "This is the required data"
def bytes_to_pascals(dg_bytes): """Takes a list of 3 bytes read from the DG-700 and returns a pressure in Pascals. Larry Palmiter originally wrote this code for TEC in Basic, which has proven immensely useful. """ bx, hi, lo = dg_bytes # unpack the array into individual values pressure = 0.0 if bx == 0: pressure = 0.0 else: x = bx - 129 if hi > 127: pressure = (-1.) * 2.**x * (1 + (256 * (hi - 128) + lo) / 2.**15) else: pressure = 2.**x * (1 + (256 * hi + lo) / 2.**15) return pressure
def insertion_sort(arr): """Performs an Insertion Sort on the array arr.""" for i in range(1, len(arr)): key = arr[i] j = i-1 while key < arr[j] and j >= 0: arr[j+1] = arr[j] j -= 1 arr[j+1] = key return arr