content
stringlengths
42
6.51k
def get_power_level( coords, serial_num ): """ Find the fuel cell's rack ID, which is its X coordinate plus 10. Begin with a power level of the rack ID times the Y coordinate. Increase the power level by the value of the grid serial number (your puzzle input). Set the power level to itself multiplied by the rack ID. Keep only the hundreds digit of the power level (so 12345 becomes 3; numbers with no hundreds digit become 0). Subtract 5 from the power level. For example, to find the power level of the fuel cell at 3,5 in a grid with serial number 8: The rack ID is 3 + 10 = 13. The power level starts at 13 * 5 = 65. Adding the serial number produces 65 + 8 = 73. Multiplying by the rack ID produces 73 * 13 = 949. The hundreds digit of 949 is 9. Subtracting 5 produces 9 - 5 = 4. So, the power level of this fuel cell is 4. Here are some more example power levels: Fuel cell at 122,79, grid serial number 57: power level -5. Fuel cell at 217,196, grid serial number 39: power level 0. Fuel cell at 101,153, grid serial number 71: power level 4. """ rack_id = coords[ 0 ] + 10 power = int( '000' + str( ( rack_id * coords[ 1 ] + serial_num ) * rack_id )[ -3 ] ) - 5 return power
def is_iterable(a): """ Test if something is iterable. """ return hasattr(a, '__iter__')
def getBandNumber(band): """ Returns band number from the band string in the spreadsheet. This assumes the band format is in ALMA_RB_NN. If there is an error, then 0 is return. """ try : bn = int(band.split('_')[-1]) except: bn = 0 return bn
def shutdown_without_logon(on=0): """Habilitar Desligamento a Partir da Caixa de Dialogo de Logon DESCRIPTION Quando este ajuste esta habilitado, o botao de desligamento e mostrado na caixa de dialogo de autenticacao quando o sistema inicia. Isto permite que o sistema seja desligado sem que algum usuario se autentique nele. Esta opcao e ativada por padrao em estacoes de trabalho e desativada em servidores. COMPATIBILITY Windows NT/2000/XP MODIFIED VALUES ShutdownWithoutLogon : dword : 00000000 = Desabilita o desligamento; 00000001 = Habilita o desligamento no logon. """ if on : return '''[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\\ CurrentVersion\\policies\\system] "ShutdownWithoutLogon"=dword:00000001''' else : return '''[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\\ CurrentVersion\\policies\\system] "ShutdownWithoutLogon"=dword:00000000'''
def sort_in_wave(array): """ Given an unsorted array of integers, sort the array into a wave like array. An array arr[0..n-1] is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= """ n = len(array) for i in range(n - 1): if i % 2 == 0 and array[i] < array[i+1]: array[i], array[i+1] = array[i+1], array[i] return array
def parse_story_file(content): """ Remove article highlights and unnecessary white characters. """ content_raw = content.split("@highlight")[0] content = " ".join(filter(None, [x.strip() for x in content_raw.split("\n")])) return content
def lensing_channels(config): """ Returns number of channels associated with a given lensing config string :param config: Lensing config string :return: int number of channels """ if config == "g": return 2 if config == "k": return 1 if config == "kg": return 3 if config == "": return 0 print("Unknown config in deep_dss.utils.lensing_channels. Please try again.")
def comma_formatter(name_list: list) -> str: """Return a properly formatted strings from a list Args: name_list (list): list of dog names Returns: str: a string in the form of name1, name2, and name3 """ if len(name_list) == 2: return " and ".join(name_list) else: return ", ".join(name_list[:-2] + [", and ".join(name_list[-2:])])
def get_extent(gtws): """Returns extent of gateways (parameter gtws).""" minx = float("inf") miny = float("inf") maxx = float("-inf") maxy = float("-inf") for gtw in gtws: if gtws[gtw][0] < minx: minx = gtws[gtw][0] if gtws[gtw][0] > maxx: maxx = gtws[gtw][0] if gtws[gtw][1] < miny: miny = gtws[gtw][1] if gtws[gtw][1] > maxy: maxy = gtws[gtw][1] # print (minx, miny, maxx, maxy) return minx, miny, maxx, maxy
def _positive_slice(slicer): """ Return full slice `slicer` enforcing positive step size `slicer` assumed full in the sense of :func:`fill_slicer` """ start, stop, step = slicer.start, slicer.stop, slicer.step if step > 0: return slicer if stop is None: stop = -1 gap = stop - start n = gap / step n = int(n) - 1 if int(n) == n else int(n) end = start + n * step return slice(end, start + 1, -step)
def _rectangle_small_p(a, b, eps): """Return ``True`` if the given rectangle is small enough.""" (u, v), (s, t) = a, b if eps is not None: return s - u < eps and t - v < eps else: return True
def plugin_init(config): """ Initialise the plugin. Args: config: JSON configuration document for the device configuration category Returns: handle: JSON object to be used in future calls to the plugin Raises: """ handle = config['gpiopin']['value'] return handle
def isEven(v): """ >>> isEven(2) True >>> isEven(1) False """ return v%2 == 0
def create_reventail_axioms(relations_to_pairs, relation='hyponym'): """ For every linguistic relationship, check if 'relation' is present. If it is present, then create an entry named: Axiom ax_relation_token1_token2 : forall x, _token2 x -> _token1 x. Note how the predicates are reversed. """ rel_pairs = relations_to_pairs[relation] axioms = [] if not rel_pairs: return axioms for t1, t2 in rel_pairs: axiom = 'Axiom ax_{0}_{1}_{2} : forall x, _{2} x -> _{1} x.'\ .format(relation, t1, t2) axioms.append(axiom) return axioms
def binomial_coefficient(n, k): """Finds the binomial coefficient n choose k. See https://en.wikipedia.org/wiki/Binomial_coefficient for details. Args: n (int): An integer. k (int): An integer. Returns: t (int): The binomial coefficient, n choose k. """ if not (-1 < k < n+1): return 0 if k==0 and n == 0: return 1 t = 1 if k < n-k: for i in range(n, n-k, -1): t = t*i//(n-i+1) else: for i in range(n, k, -1): t = t*i//(n-i+1) return t
def raw_synctable_data2(*args, **kwargs): """Returns table formatted data for display in the Sync table """ # pylint: disable=unused-argument return { "columns": [ {"title": "Visibility Time"}, {"title": "AWS Region"}, {"title": "Action"}, {"title": "Instance"}, ], "data": [ ["", "", "", ""], ] }
def bin_to_velocity(_bin, step=4): """ Takes a binned velocity, i.e., a value from 0 to 31, and converts it to a proper midi velocity """ assert (0 <= _bin * step <= 127), f"bin * step must be between 0 and 127 to be a midi velocity\ not {_bin*step}" return int(_bin * step)
def parse_str_with_space(var: str) -> str: """return string without multiply whitespaces Example: var = 'My name is John ' Return var = 'My name is John' """ str_list = list(filter(None, var.split(' '))) return ' '.join(x for x in str_list)
def overwrite_options_text(docstring: str, options: dict) -> str: """Overwrite the options if there is extra info in the docstring""" # loop through the options and see if we have an override if ":option:" in docstring: docstring_lines = docstring.split("\n") for line in docstring_lines: if ":option:" in line: docstring = docstring.replace(line, "") option_data = line.split(":") # loop through the options to edit the wanted one for option in options: if option["name"] == option_data[2].strip(): option["description"] = option_data[3].strip() break break return docstring
def parse_timezone(text): """Parse a timezone text fragment (e.g. '+0100'). Args: text: Text to parse. Returns: Tuple with timezone as seconds difference to UTC and a boolean indicating whether this was a UTC timezone prefixed with a negative sign (-0000). """ # cgit parses the first character as the sign, and the rest # as an integer (using strtol), which could also be negative. # We do the same for compatibility. See #697828. if not text[0] in b"+-": raise ValueError("Timezone must start with + or - (%(text)s)" % vars()) sign = text[:1] offset = int(text[1:]) if sign == b"-": offset = -offset unnecessary_negative_timezone = offset >= 0 and sign == b"-" signum = (offset < 0) and -1 or 1 offset = abs(offset) hours = int(offset / 100) minutes = offset % 100 return ( signum * (hours * 3600 + minutes * 60), unnecessary_negative_timezone, )
def _fix_dimensions(flat_observations): """Temporary ugly hack to work around missing fields in some observations""" optional_fields = ['taxon.complete_rank', 'taxon.preferred_common_name'] headers = set(flat_observations[0].keys()) | set(optional_fields) for obs in flat_observations: for field in optional_fields: obs.setdefault(field, None) return headers, flat_observations
def build_plane_map_from_ranges(z_range, t_range): """ Determines the plane to load. """ plane_map = [] for t in t_range: for z in z_range: plane_map.append([t, z]) return plane_map
def cookie_name_from_auth_name(auth_name: str) -> str: """Takes an auth name and returns what the name of the cookie will be. At the moment we are just prepending _""" cookie_auth_name = auth_name if not cookie_auth_name.startswith("_"): cookie_auth_name = f"_{auth_name.lower()}" return cookie_auth_name
def get_reverse_bit(number: int) -> str: """ return bit string dari integer >>> get_reverse_bit(9) '10010000000000000000000000000000' >>> get_reverse_bit(43) '11010100000000000000000000000000' >>> get_reverse_bit(2873) '10011100110100000000000000000000' >>> get_reverse_bit(9) '10010000000000000000000000000000' >>> get_reverse_bit(43) '11010100000000000000000000000000' >>> get_reverse_bit(2873) '10011100110100000000000000000000' """ if not isinstance(number, int): raise TypeError("number harus integer") bit_string = "" for _ in range(0, 32): bit_string += str(number % 2) number = number >> 1 return bit_string
def F(A, n, k): """ :param A: Cells list :param n: the [last-1] princess - 1 :param k: kills left (the beauty of the ([last-1] princess - 1) - 1) :return: matrix with values of gold coins that the Knight can collect while he is in the cell i and left j kills """ matrix = [[0 for _ in range(k + 1)] for _ in range(n + 1)] for i in range(n + 1): for j in range(k + 1): if j == 0: matrix[i][j] = 0 continue if A[i][0] == 'p': if A[i][1] <= j: matrix[i][j] = matrix[i - 1][A[i][1] - 1] # Don't update kills left else: matrix[i][j] = matrix[i - 1][j] # update kills left if A[i][0] == 'd': if i == 0 and j > 0: matrix[i][j] = A[i][1] # First dragon and more than 0 kills left. Kill the dragon. else: # Take the maximum between kill the i-th dragon (and take his gold coins) or not matrix[i][j] = max(matrix[i - 1][j - 1] + A[i][1], matrix[i - 1][j]) return matrix
def is_func_argument(i, clue): """ Returns True if clue sub-part i is the argument of a directional function (like 'ana_r' or 'sub_l'). We do this because insertion always happens after other functions have been resolved. """ return (i > 0 and '_r' in clue[i - 1][1]) or (i < len(clue) - 1 and '_l' in clue[i + 1][1])
def reautokelv(reaumur): """ This function converts Reaumur to kelvin, with Reaumur as parameter.""" kelvin = (reaumur * 1.25) + 273.15 return kelvin
def find_shift_amount(A): """ find_shift_amount assumes A is a sorted array that has been cyclically shifted, and finds the shift amount. """ l = 0 r = len(A)-1 if A[l] < A[r]: return 0 while r-l > 1 and A[l] >= A[r]: m = l + (r-l)//2 if A[l] > A[m]: r = m continue if A[m] > A[r]: l = m continue return 0 return r
def _ne(prop_value, cmp_value, ignore_case=False): """ Helper function that take two arguments and checks if :param prop_value: is not equal to :param cmp_value: :param prop_value: Property value that you are checking. :type prop_value: :class:`str` :param cmp_value: Value that you are checking if they are not equal. :type cmp_value: :class:`str` :param ignore_case: True to run using incase sensitive. :type ignore_case: :class:`bool` :returns: True if :param prop_value: and :param cmp_value: are not equal. :rtype: class:`bool` """ if ignore_case is True: prop_value = prop_value.lower() cmp_value = cmp_value.lower() return cmp_value != prop_value
def get_input(text: str): """Handle user input. The function exits cleanly on ``KeyboardInterrupt`` and ``EOFError`` (ctrl-c and ctrl-d). Args: Text (str): Prompt to print. A greater than symbol (">") is appended to the end and escape codes are used to make the prompt bold. Returns: Str: User's input. """ try: user_input = input("\033[1m" + text + " > \033[0m") except (KeyboardInterrupt, EOFError): print("\nBye.") exit(0) return user_input
def check_for_motif(motifs, seq): """ Check if motif exists. """ for motif in motifs: idx = seq.find(motif) if idx > -1: return True, seq[idx:] + seq[:idx] # Did not find any motifs return False, seq
def get_consensus(sets, quorum): """ Given an iterable of sets of items, find the set containing all items which appear in at least the quorum number of sets. Parameters ---------- sets : iterable Iterable of sets of items. quorum : integer Minimum number of sets an item must appear in. Returns ------- set Set containing all items which appear at least the quorum number of sets. """ if quorum >= 1: import itertools intersections = [] for i in range(quorum, len(sets)): intersections += [set.intersection(*items) for items in itertools.combinations(sets, i)] if len(intersections) > 0: return set.union(*intersections) return {}
def _aws_parameters(use_localstack, localstack_host, region): """Constructs a configuration dict that can be used to create an aws client. Parameters ---------- use_localstack : bool Whether to use the localstack in this environment. localstack_host : str The hostname of the localstack services (if use_localstack enabled). region : str The AWS region to connect to. Returns ------- """ if use_localstack: return { 'endpoint_url': f'http://{localstack_host}:4566', 'use_ssl': False, 'aws_access_key_id': 'ACCESS_KEY', 'aws_secret_access_key': 'SECRET_KEY', 'region_name': region } else: return { 'region_name': region }
def hidden_loc(obj, name): """ Generate the location of a hidden attribute. Importantly deals with attributes beginning with an underscore. """ return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__")
def averageVelocity(positionEquation, startTime, endTime): """ The position equation is in the form of a one variable lambda and the averagevelocity=(changeinposition)/(timeelapsed) """ startTime=float(startTime) endTime=float(endTime) vAvg=(positionEquation(startTime)-positionEquation(endTime))/(startTime-endTime) return vAvg
def normalize(signal): """ This function normalizes all values from -1 to 1 :param list signal: input signal :return list norm_signal: normalized signal """ import logging as log log.debug("Normalizing signal.\n") # Let's find the maximum and minimum values maximum = max(signal) minimum = min(signal) # Choose the one with greater magnitude greatest = abs(maximum) if abs(maximum) < abs(minimum): greatest = abs(minimum) # Normalize for i, v in enumerate(signal): signal[i] = round(v / greatest, 2) norm_signal = signal return norm_signal
def add_value(attr_dict, key, value): """Add a value to the attribute dict if non-empty. Args: attr_dict (dict): The dictionary to add the values to key (str): The key for the new value value (str): The value to add Returns: The updated attribute dictionary """ if value != "" and value is not None: attr_dict[key] = value return attr_dict
def numerical_function(val_in): """Desciption of the function""" val_in = float(val_in) local_val = val_in + 1 val_out = local_val - 1 return val_out
def sum_series(n, n0=0, n1=1): """ Compute the nth value of a summation series. :param n0=0: value of zeroth element in the series :param n1=1: value of first element in the series This function should generalize the fibonacci() and the lucas(), so that this function works for any first two numbers for a sum series. Once generalized that way, sum_series(n, 0, 1) should be equivalent to fibonacci(n). And sum_series(n, 2, 1) should be equivalent to lucas(n). sum_series(n, 3, 2) should generate antoehr series with no specific name The defaults are set to 0, 1, so if you don't pass in any values, you'll get the fibonacci sercies """ if n < 0: return None if n == 0: return n0 elif n == 1: return n1 else: return sum_series(n - 1, n0, n1) + sum_series(n - 2, n0, n1)
def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text
def parse_get(response): """Parse get response. Used by TS.GET.""" if not response: return None return int(response[0]), float(response[1])
def pack_byte(b): """Pack one integer byte in a byte array.""" return bytes([b])
def ordinal(value): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... u'1st' u'2nd' u'3rd' u'4th' u'5th' u'6th' u'7th' u'8th' u'9th' u'10th' u'11th' u'12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ... u'100th' u'111th' u'112th' u'1011th' """ try: value = int(value) except ValueError: return value if value % 100//10 != 1: if value % 10 == 1: ordval = u"%d%s" % (value, "st") elif value % 10 == 2: ordval = u"%d%s" % (value, "nd") elif value % 10 == 3: ordval = u"%d%s" % (value, "rd") else: ordval = u"%d%s" % (value, "th") else: ordval = u"%d%s" % (value, "th") return ordval
def add_label(key, value, k8s_yaml): """Add 'domain: `domain`' label to k8s object. Args: key (str): Label key. value (str): Label value. k8s_yaml (dict): Loaded Kubernetes object (e.g. deployment, service, ...) """ k8s_yaml["metadata"]["labels"][key] = value return k8s_yaml
def get_item_attr(idmap, access): """ Utility for accessing dict by different key types (for get). For example:: >>> idmap = {(1,): 2} >>> get_item_attr(idmap, 1) 2 >>> idmap = {(1,): 2} >>> get_item_attr(idmap, {"pk": 1}) 2 >>> get_item_attr(idmap, (1,)) 2 """ if isinstance(access, dict): keys = [] for names in sorted(access): keys.append(access[names]) return idmap.get(tuple(keys)) elif isinstance(access, int): return idmap.get((access,)) else: return idmap.get(access)
def get_group_from_table(metatable_dict_entry): """ Return the appropriate group title based on either the SGID table name or the shelved category. """ sgid_name, _, item_category, _ = metatable_dict_entry if item_category == 'shelved': group = 'UGRC Shelf' else: table_category = sgid_name.split('.')[1].title() group = f'Utah SGID {table_category}' return group
def evlexp(a : int, b : int, op : str) -> int: """ Evaluates basic arithmetic operation and returns it. """ o = {'+' : a + b, '-' : a - b, '*' : a * b, '/' : a / b, '^' : a**b} return o[op]
def is_iterable(obj) -> bool: """Check whether object has an iterator.""" try: iter(obj) except Exception: return False return True
def compare_members(group, team, attribute="username"): """ Compare users in GitHub and the User Directory to see which users need to be added or removed :param group: :param team: :param attribute: :return: sync_state :rtype: dict """ directory_list = [x[attribute].lower() for x in group] github_list = [x[attribute].lower() for x in team] add_users = list(set(directory_list) - set(github_list)) remove_users = list(set(github_list) - set(directory_list)) sync_state = { "directory": group, "github": team, "action": {"add": add_users, "remove": remove_users}, } return sync_state
def inverse_of(a: int, b: int) -> int: """Returns n^-1 (mod p).""" x0, x1, y0, y1 = 1, 0, 0, 1 oa, ob = a, b while b != 0: q = a // b a, b = b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 if x0 < 0: x0 += ob if y0 < 0: y0 += oa # when a and b are not relatively prime if a != 1 or (oa * x0) % ob != 1: return -1 return x0
def compute_squared_error_distribution(predicted_values, real_values, normalize=False): """Given aligned predicted and real values, computes the distribution of squared errors between them """ distribution = [(p - r)**2 for p, r in zip(predicted_values, real_values)] if not normalize: return distribution denominator = max(distribution) return [i/denominator for i in distribution]
def get_pitch_min_max(note_tracks): """ In order not to waste space, we may want to know in advance what the highest and lowest pitches of the MIDI notes are. """ pitch_min = 128 pitch_max = 0 for t in note_tracks: for pitch_list in t: for note in pitch_list: pitch = note.pitch if pitch > pitch_max: pitch_max = pitch if pitch < pitch_min: pitch_min = pitch return pitch_min, pitch_max
def permalink_to_full_link(link: str) -> str: """Turns permalinks returned by Praw 4.0+ into full links""" return "https://www.reddit.com" + link
def file_to_dict(file_name): """Read decklist and create a dictionary of name->amount entries""" try: cards = dict() with open(file_name, 'r') as file: for line_number, line in enumerate(file): try: line = line.strip() first_space = line.find(' ') amount = int(line[:first_space]) name = line[first_space+1:] if name not in cards: cards[name] = 0 cards[name] += amount except ValueError: raise ValueError("Failed to parse line {} of {}: '{}'".format(line_number+1, file_name, line)) return cards except FileNotFoundError: return {}
def right(direction): """rotates the direction clockwise""" return (direction + 1) % 4
def get_class_name(obj): """ A simple template tag to retrieve the class name of an object. :param obj: an input object """ return obj.__class__.__name__
def split_arguments(args): """Returns the 2-tuple (args[:-1], args[-1]) if args[-1] exists and is a dict; otherwise returns (args, {}). """ if args and isinstance(args[-1], dict): return args[:-1], args[-1] else: return args, {}
def testIfNodesDuplicates(nodes): """ Tests if there are dupicates in nodes list :param nodes: list of node objects :return: bool passing or failing test """ for i in range(0, len(nodes)): for j in range(0, len(nodes)): if nodes[i].nodeid == nodes[j].nodeid and i != j: print("ERROR: duplicateNodes!" + "i: " + str(i) + "; j: " + str(j)) return False return True
def is_in_scope(plugin_id, url, out_of_scope_dict): """ Returns True if the url is in scope for the specified plugin_id """ if '*' in out_of_scope_dict: for oos_prog in out_of_scope_dict['*']: #print('OOS Compare ' + oos_url + ' vs ' + 'url) if oos_prog.match(url): #print('OOS Ignoring ' + str(plugin_id) + ' ' + url) return False #print 'Not in * dict' if plugin_id in out_of_scope_dict: for oos_prog in out_of_scope_dict[plugin_id]: #print('OOS Compare ' + oos_url + ' vs ' + 'url) if oos_prog.match(url): #print('OOS Ignoring ' + str(plugin_id) + ' ' + url) return False #print 'Not in ' + plugin_id + ' dict' return True
def dicts_equal(d1, d2): """ Perform a deep comparison of two dictionaries Handles: - Primitives - Nested dicts - Lists of primitives """ # check for different sizes if len(d1) != len(d2): return False # check for different keys for k in d1: if k not in d2: return False for k in d2: if k not in d1: return False # compare each element in dict for k in d1: if type(d1[k]) != type(d2[k]): # different value types return False # lists elif isinstance(d1[k], list): if not (sorted(d1[k]) == sorted(d2[k])): return False # nested dicts elif isinstance(d1[k], dict): if not dicts_equal(d1[k], d2[k]): return False # primitives else: if d1[k] != d2[k]: return False return True
def swap_positions(lst: list, pos_one: int, pos_two: int) -> list: """Intercambiate specific elements in a list""" new_lst = lst.copy() new_lst[pos_one], new_lst[pos_two] = lst[pos_two], lst[pos_one] return new_lst
def convert_category(cat): """Talking = 6""" if cat == '6': return 1 return 0
def bucket_fill(bucket_a_capacity, bucket_a_contents, bucket_b_capacity, bucket_b_contents): """ Perform a step in the measure bucket process and return the contents of each bucket. :param bucket_a_capacity int - The maximum amount of fluid bucket A can have. :param bucket_a_contents int - The amount of fluid in bucket A. :param bucket_b_capacity int - The maximum amount of fluid bucket B can have. :param bucket_b_contents int - The amount of fluid in bucket B. :return tuple (bucket_a_contents, bucket_b_contents) The amount of fluid in buckets A and B. The only valid moves are: - pouring from either bucket to another (A -> B) - emptying either bucket and doing nothing to the other - filling either bucket and doing nothing to the other (Fill A) NOT allowed at any point to have the smaller bucket full and the larger bucket empty (opposite of start conditions) """ if bucket_a_contents == 0: # 1. If A is empty, fill it bucket_a_contents = bucket_a_capacity elif bucket_b_contents == bucket_b_capacity: #2. If B is full, empty it bucket_b_contents = 0 else: # Pour contents of A to B fluid_b_can_accept = bucket_b_capacity - bucket_b_contents if fluid_b_can_accept > bucket_a_contents: # All of A poured into B bucket_b_contents += bucket_a_contents bucket_a_contents = 0 else: # Pour what is possible from A to B bucket_b_contents += fluid_b_can_accept bucket_a_contents -= fluid_b_can_accept return (bucket_a_contents, bucket_b_contents)
def cloudfront_viewer_protocol_policy(viewer_protocol_policy): """ Property: CacheBehavior.ViewerProtocolPolicy Property: DefaultCacheBehavior.ViewerProtocolPolicy """ valid_values = ["allow-all", "redirect-to-https", "https-only"] if viewer_protocol_policy not in valid_values: raise ValueError( 'ViewerProtocolPolicy must be one of: "%s"' % (", ".join(valid_values)) ) return viewer_protocol_policy
def editDistance(x ,y): """ use dynamic programming for edit distance, every edit distance = 1 """ # init matrix D D = [[0]*(len(y)+1)] * (len(x)+1) """ D = [] for i in range(len(x)+1): D.append([0] * (len(y)+1)) """ for i in range(len(x)+1): D[i][0] = i for i in range(len(y)+1): D[0][i] = i for i in range(1, len(x)+1): for j in range(1, len(y)+1): editHor = D[i][j-1] + 1 editVer = D[i-1][j] + 1 if x[i-1] == y[i-1]: editDiag = D[i-1][j-1] else: editDiag = D[i-1][j-1] + 1 D[i][j] = min(editHor, editVer, editDiag) return D[-1][-1]
def utility_columnletter2num(text): """ Takes excel column header string and returns the equivalent column count :param str text: excel column (ex: 'AAA' will return 703) :return: int of column count """ letter_pos = len(text) - 1 val = 0 try: val = (ord(text[0].upper())-64) * 26 ** letter_pos next_val = utility_columnletter2num(text[1:]) val = val + next_val except IndexError: return val return val
def fahrenheit_to_kelvin(a): """ Function to compute Fahrenheit from Kelvin """ kelvin = (a-32.0)*5/9 + 273.15 return kelvin
def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz' """ import os if not isinstance(in_files, list): return in_files subject_label = in_files[0].split(os.sep)[-1].split("_")[0].split("-")[-1] base, _ = os.path.split(in_files[0]) return os.path.join(base, "sub-%s_T1w.nii.gz" % subject_label)
def _encode_to_utf8(s): """ Required because h5py does not support python3 strings converts byte type to string """ return s.encode('utf-8')
def correct_file_name(file_name): """ Correct for some bad window user's habit :param file_name: the file name to correct :return: the corrected file name """ file_name = file_name.replace(" ", "\ ") file_name = file_name.replace("(", "\(") file_name = file_name.replace(")", "\)") return file_name
def update_formats(formats, ext, format_name): """Update the format list with the given format name""" updated_formats = [] found_ext = False for org_ext, org_format_name in formats: if org_ext != ext: updated_formats.append((org_ext, org_format_name)) elif not found_ext: updated_formats.append((ext, format_name)) found_ext = True return updated_formats
def validate_vpc_id(value): """Raise exception if VPC id has invalid length.""" if len(value) > 64: return "have length less than or equal to 64" return ""
def hawaii_transform(xy): """Transform Hawaii's geographical placement so fits on US map""" x, y = xy return (x + 5250000, y-1400000)
def keys(dict): """Returns a list containing the names of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms""" return list(dict.keys())
def nukenewlines(string): """Strip newlines and any trailing/following whitespace; rejoin with a single space where the newlines were. Bug: This routine will completely butcher any whitespace-formatted text.""" if not string: return "" lines = string.splitlines() return " ".join([line.strip() for line in lines])
def solution2(A): """ Similar to solution(), but without using sort(). """ # Define a variable to store the previous element in an iteration previous_int = 1 while True: if previous_int+1 in A: previous_int += 1 continue else: return previous_int+1
def optimize_regex(regex): """ Reduce overly verbose parts of a generated regex expression. Args: regex - The regex expressio to optimize """ regex = str(regex) for n in range(9): regex = regex.replace('[' + str(n) + '-' + str(n+1) + ']','[' + str(n) + str(n+1) + ']') for n in range(10): regex = regex.replace('[' + str(n) + '-' + str(n) + ']', str(n)) return regex
def MAX(*expression): """ Returns the maximum value. See https://docs.mongodb.com/manual/reference/operator/aggregation/max/ for more details :param expression: expression/expressions or variables :return: Aggregation operator """ return {'$max': list(expression)} if len(expression) > 1 else {'$max': expression[0]} if expression else {}
def check_db_for_feature(feature, db_features=None): """ Args: feature: A feature to be checked for. db_features: All of the db features (see get_all_db_features). Returns: The feature if it matches, otherwise None. """ fulcrum_id = feature.get('properties').get('fulcrum_id') if not db_features: return None if db_features.get(fulcrum_id): # While it is unlikely that the database would have a newer version than the one being presented. # Older versions should be rejected. If they fail to be handled at least they won't overwrite a # more current value. if db_features.get(fulcrum_id).get('version') > feature.get('properties').get('version'): return "reject" feature['ogc_fid'] = db_features.get(fulcrum_id).get('ogc_fid') return feature return None
def insertion_sort(list): """ This is a function that sorts the given list using the insertion algorithm. """ if not list or len(list) == 0: return [] if len(list) == 1: return list print(f"input list = {list}") for i in range(len(list) - 1): if list[i+1] < list[i]: # we need to move i+1 before i temp = list.pop(i + 1) if i == 0: list.insert(-1, temp) continue for j in range(i): if list[j] > temp: list.insert(j, temp) print(f"> @{i}list = {list}") return list
def return_clean_date(timestamp: str) -> str: """ Return YYYY-MM-DD :param timestamp: str of the date :return: Return YYYY-MM-DD """ if timestamp and len(timestamp) > 10: return timestamp[:10] else: return ""
def query(query_string, data): """ Return a query string for use in HTML links. For example, if query_string is "?page=foo" and data is "date=200807" this function will return "?page=foo&date=200807" while if query_string were "" it would return "?date=200807". """ if query_string: if not query_string.startswith("?"): query_string = "?" + query_string if data: if (not data.startswith("&")) and (not query_string.endswith("&")): data = "&" + data return query_string + data else: return query_string else: if not data.startswith("?"): data = "?" + data return data
def categories_to_json(categories): """ categories_to_json converts categories SQLAlchemy object to json object works by simply looping over collection of objects and manually mapping each Object key to a native Python dict """ main = {} main['categories'] = [] for cat in categories: catDict = {} catDict['id'] = cat.id catDict['name'] = cat.name catDict['items'] = [] for item in cat.items: itemDict = {} itemDict['id'] = item.id itemDict['title'] = item.title itemDict['description'] = item.description catDict['items'].append(itemDict) main['categories'].append(catDict) return main
def detokenize(sent): """ Roughly detokenizes (mainly undoes wordpiece) """ new_sent = [] for i, tok in enumerate(sent): if tok.startswith("##"): new_sent[len(new_sent) - 1] = new_sent[len(new_sent) - 1] + tok[2:] else: new_sent.append(tok) return new_sent
def DecodeEncode(tRaw, filetype): """return the decoded string or False used by readAnything, also see testreadanything in miscqh/test scripts """ try: tDecoded = tRaw.decode(filetype) except UnicodeDecodeError: return False encodedAgain = tDecoded.encode(filetype) if encodedAgain == tRaw: return tDecoded else: return False
def skewed_lorentzian(x, bkg, bkg_slp, skw, mintrans, res_f, Q): """ Skewed Lorentzian model. Parameters ---------- x : float The x-data to build the skewed Lorentzian bkg : float The DC value of the skewed Lorentzian bkg_slp : float The slope of the skewed Lorentzian skw : float The skewness of the Lorentzian mintrans : float The minimum of the trans. This is associated with the skewness term. res_f : float The center frequency of the resonator (the center of the Lorentzian) Q : float The Q of the resonator Returns ------- float The model of the Lorentzian """ return bkg + bkg_slp*(x-res_f)-(mintrans+skw*(x-res_f))/\ (1+4*Q**2*((x-res_f)/res_f)**2)
def DistanceOfPointToRange( point, range ): """Calculate the distance from a point to a range. Assumes point is covered by lines in the range. Returns 0 if point is already inside range. """ start = range[ 'start' ] end = range[ 'end' ] # Single-line range. if start[ 'line' ] == end[ 'line' ]: # 0 if point is within range, otherwise distance from start/end. return max( 0, point[ 'character' ] - end[ 'character' ], start[ 'character' ] - point[ 'character' ] ) if start[ 'line' ] == point[ 'line' ]: return max( 0, start[ 'character' ] - point[ 'character' ] ) if end[ 'line' ] == point[ 'line' ]: return max( 0, point[ 'character' ] - end[ 'character' ] ) # If not on the first or last line, then point is within range for sure. return 0
def convert_index_to_int(adj_lists): """Function to convert the node indices to int """ new_adj_lists = {} for node, neigh in adj_lists.items(): new_adj_lists[int(node)] = neigh return new_adj_lists
def predicate_info(logic, start, equals_ind): """Returns information about predicate logic from string form""" var = logic[0:equals_ind] operator = "=" if var[-1]=="<" or var[-1]==">": operator = var[-1] + operator var = var[:-1] return var, operator
def solveit(test): """ test, a function that takes an int parameter and returns a Boolean Assumes there exists an int, x, such that test(x) is True Returns an int, x, with the smallest absolute value such that test(x) is True In case of ties, return any one of them. """ # IMPLEMENT THIS FUNCTION x=0 while True: if test(x): return x if test(-1*x): return -1*x x+=1 return x
def get_sched_func_name(stackname): """ :param stackname: :return: """ name=stackname+"-lambda-sched-event" return name[-63:len(name)]
def extract_object(dictionary, key_sequence): """ Extract the object inside the dictionary at a specific path :param dictionary (Dict): dictionary to extract from :param key_sequence (List[str]): list of strings represetning key accesses :return: the value inside dictionary specified by key_sequence """ ret = dictionary for k in key_sequence: ret = ret[k] return ret
def conFirmColorCov(nclicks, r, g, b, dataset, backup): """ Callback to confirm a color. This will overwrite the previous one. Positional arguments: nclicks -- Button value. r -- Red value. g -- Green value. b -- Blue value. dataset -- Dataset to overwrite color of. backup -- Previous value in case of error. """ if r == None or b == None or g == None: return backup else: colorDict = backup colorString = 'rgb(' + str(r) + ', ' + str(g) + ', ' + str(b) + ')' colorDict.update({dataset: colorString}) return colorDict
def get_rotated_index(start: int, size: int, index: int) -> int: """Get the rotated index of the array""" return (index + start) % size
def get_mask(seg): """ get corresponding upper/lower tag of given seg Hello -> ULLLL :param seg: :return: """ mask = "" for e in seg: if e.isupper(): mask += "U" elif e.islower(): mask += "L" else: mask += "L" return mask
def profile_to_encoded_str(profile): """ Encode profile to '&' and '=' separated string. Return the encoded string. """ return '&'.join(["{}={}".format(k,v) for k,v in profile.items()])
def SplitNamespace(ref): """Returns (namespace, entity) from |ref|, e.g. app.window.AppWindow -> (app.window, AppWindow). If |ref| isn't qualified then returns (None, ref). """ if '.' in ref: return tuple(ref.rsplit('.', 1)) return (None, ref)
def compute_rate(old, new, seconds): """Compute a rate that makes sense""" delta = new - old if delta < 0: delta = new return delta / seconds
def encodeMsg(aStr): """Encode a message for transmission to the hub such that multiple lines show up as one command. """ return aStr.replace("\n", "\v")
def test_module_import(module_name): """ Import module or return false""" try: __import__(module_name) return True except: return False