content
stringlengths
42
6.51k
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a peice of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def fuelforpos(pos, crabs): """Meh >>> crabs = read_input('example') >>> fuelforpos(1, crabs) 41 >>> fuelforpos(3, crabs) 39 >>> fuelforpos(10, crabs) 71 >>> fuelforpos(2, crabs) 37 """ return sum(abs(crab - pos) for crab in crabs)
def get_prior_probs(candidates, alias_dict): """ Get prior probabilities of all candidates for a mention :param candidates: the list of candidates for a company mention :param alias_dict: :return: """ prior_probs = [] candids = [] total = sum(alias_dict[cand] for cand in alias_dic...
def __is_channel_record_valid(record) -> bool: """[summary] Arguments: record {[type]} -- [description] Returns: bool -- [description] """ if "fields" not in record: print("Quote record has no fields") return False if "Channel Name" not in record["fields"]: ...
def parabolic_func(x,a,b,c): """ Return the y value of a parabola at x """ return a*(x-b)**2 + c
def _find_crop_start_end(coord_ctr, crop_size, im_dim): """Util function to find the coordinates to crop the image around the centerline (coord_ctr).""" half_size = crop_size // 2 coord_start, coord_end = int(coord_ctr) - half_size + 1, int(coord_ctr) + half_size + 1 if coord_end > im_dim: coor...
def scalable_dimension_type(scalable_dimension): """ Property: ScalingInstruction.ScalableDimension """ valid_values = [ "autoscaling:autoScalingGroup:DesiredCapacity", "ecs:service:DesiredCount", "ec2:spot-fleet-request:TargetCapacity", "rds:cluster:ReadReplicaCount", ...
def validate_float(p: str) -> bool: """ Validate a float. :param p: Value :return: True if integer """ if p == '' or p == '-': return True try: float(p) return True except ValueError: pass return False
def avg_start_time_color(value): """ Returns 'red' or 'green' or 'yellow' string depending on the start hour. """ if not isinstance(value, tuple) or value is None: return '' color = 'red' hour, minute = value if hour is None or minute is None: color = '' elif hour < 8: ...
def adapt_url_key(body_entry): """ Rename the `body_entry` dict key 'url' to 'identifier' if its value does not start with 'http' or 'ftp'. PS: It changes the content of the input dict `body_entry`. """ adapted = body_entry if body_entry['url'][:4] != 'http' and body_entry['url'][...
def before_send(event, hint): """ fake method to experiment sentry custom before_send function. """ print(hint) if hint else None return event
def lcs_brute_force(first, second): """ Use brute force to calculate the longest common substring of two strings Args: first: first string second: second string Returns: the length of the longest common substring """ len_first = len(first) len_second = len(second) ...
def color_variant(hex_color, brightness_offset=1): """ takes a color like #87c95f and produces a lighter or darker variant """ # https://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html if len(hex_color) != 7: raise Exception("Passed %s into color_variant(), nee...
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: """ For key:hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("college", "UNIVERSITY") # doctest: +NORMALIZE_WHITESPACE {'A': 'C', 'B': ...
def breadcrumb_trail(links, sep=' > '): """ ``links`` must be a list of two-item tuples in the format (URL, Text). URL may be None, in which case the trail will contain the Text only. Returns a string of HTML. """ trail = '' url_str = '<a href="{0}">{1}</a>' # Iterate over the list, exce...
def disjoint_union(*graphs): """Given a list of graphs, construct their disjoint union.""" res_vertices = [] res_edges = [] for (vertices, edges) in graphs: l = len(res_vertices) res_edges.extend((a+l, b+l) for (a, b) in edges) res_vertices.extend(vertices) return (res_vertic...
def write_triangle(base, height, length, loc, mat, orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0): """ @brief Writes a triangle. @param base base of the triangle @param height height of the triangle @param length The length of the prism ...
def _get_collapsed_course_and_dist_req_sets(req): """ Returns the sets of all courses and all distribution requirements in req's subtree as a tuple: (course_set, dist_req_set) Note: Sets may contain duplicate courses if a course is listed in multiple different ways """ if "course_list" i...
def perm_to_string(p): """ Convert p to string, slightly more compact than list printing. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
def empty_market_dataset(ds, exclude=None): """Remove input exchanges from a market dataset, in preparation for input exchanges defined by an external data source. Removes all exchanges which have the same flow as the reference product of the exchange. ``exclude`` is an iterable of activity names to exclude.""...
def is_constant(s): """Determines whether the sequence 's' is constant, effectively returning 'true' if 's[i] == s[0]'""" return all([s[0] == s[i] for i in range(1, len(s))])
def _git_is_dirty(status): """Test if repo status is dirty. :params status: repos status information :type status: dict :return: Is Dirty :rtype: bool """ if status['uncommited changes'] or status['local only branches'] or status['ahead of origin']: return True return False
def ros_call_service_cmd(service, _id=None, args=None): """ create a rosbridge call_service command object :param service: name of the service to call :param _id: optional identifier to link the matching service_response to this request :param args: optional dict containing named arguments for the ...
def eva_partition_at_level(dendrogram, level): """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher th...
def escape_format(s: str) -> str: """Escape a string for :meth:`str.format`.""" return s.replace('{', '{{').replace('}', '}}')
def convert_practitioner_fhir_to_meta(pract_res, user): """Converts a Practitioner Resource into Values for Meta""" data = {} data['user'] = user data['npi']= pract_res['identifier'][0]['value'] data['fhir_id']= pract_res['id'] return data
def encode_morse(pt): """ Encodes a plaintext into popular Morse Code with letters separated by "|" and words by "||". References ========== .. [1] http://en.wikipedia.org/wiki/Morse_code Examples ======== >>> from sympy.crypto.crypto import encode_morse >>> pt = 'ATTACK THE ...
def get_themes_images(location_reports): # needs testing """returns list of theme_image urls""" image_urls = [] for lr in location_reports: image_urls.append(lr.image_url) return image_urls
def _generate_chip_name_table(table): """ Generate a mapping from chip_name -> chip_id. NOTE: names will be converted to lower case when added to the lookup table """ result = {} for chip_id in table: name = table[chip_id].name lookup_name = name.lower().replace('-', '_') ...
def base128Stringified(value): """ Encodes the given integral value into a string that is an encoded comma- separated series of bytes, base-128, with all but the last byte having the high bit set, in C++ hex notation, as required by the DER rules for the nodes of an OID after the first two. >>>...
def string_float(string: str): """Numpy vectorize function to convert strings to floats""" return float(string.replace(",", ""))
def getPathTuples(data): """ Loop over all elements of a given json object and generate a list of name-path-tuples @param data: Array of Objects containing the paths @type data: JSON Array @return: List of tuples (name, paths) @rtype: List<(String, List<String>)> """ ...
def flatten(nested_list): """Flatten a nested list.""" return [item for a_list in nested_list for item in a_list]
def issubset(left, right): """A subset relation for dictionaries""" return set(left.keys()) <= set(right.keys())
def tact_to_strat_proj_3d(x_r, x_h): """Project the given robot and human tactical states to the 3D strategic state. The 3D strategic state is defined as [x_r, y_rel, v_rel], where - x_r: robot x-coordinate - y_rel: relative y-coordinate of the robot with respect to the y coordinate of the huma...
def is_tagged(string: str) -> bool: """ Check whether a string is enclosed in '<' and '>' characters Args: string (str): String to test Returns: bool: True if string is enclosed in '<' and '>' """ return len(string) > 2 and string[0] == "<" and string[-1] == ">"
def __visit(h): """Converts our bespoke linked list to a python list.""" o = h l = [] while o is not None: l.append(o.value) o = o.next return l
def get_user_attributes_from_ldap(ldap_connection, ldap_base_dn, login, attribute): """returns the user group names, no permissions for now :param ldap3.Connection ldap_connection: The ldap_client as ldap3.Connection instance :param str ldap_base_dn: The domain name in LDAP format (all this CN, DN stuff) ...
def humanized_time(second): """ :param second: time in seconds :return: human readable time (hours, minutes, seconds) """ m, s = divmod(second, 60) h, m = divmod(m, 60) return "%dh %02dm %02ds" % (h, m, s)
def is_true(value): """Determine whether value is True""" return str(value).strip().lower() == 'true'
def average_of_array(array): """Calculate the average value in the given array.""" total = sum(array) count = len(array) return total / count
def find_max_in_rows(array: list) -> list: """ :param array: :return: :rtype: list """ result = [] for row in array: result.append(max(row)) return result
def fib(n): """ Compute the n'th Fibonacci number. :param n: target Fibonacci number :return: the appropriate number """ if n <=2: return 1 else: return fib(n-1) + fib(n-2)
def uniqify(inlist): """Given a list, return a new list preserving the list order and deduplicating.""" return list(dict.fromkeys(inlist))
def find(f, seq): """ Return first item in sequence where f(item) == True. """ for item in seq: if f(item): return item
def GetLineCount(line_counts, filename): """Find the length of a file. Results are cached in the line_counts dictionary.""" if filename in line_counts: return line_counts[filename] with open(filename, 'r') as f: line_count = len(f.readlines()) line_counts[filename] = line_count return line_count
def get_package_name(name): """ Returns package name. From `a.b.c` it returns `b`. :param str name: Full module name :return: Package name. :rtype: str """ return name.split(".")[-2]
def get_user_guests_json_list(user_guests): """ Make json objects of the user guests and add them to a list. :param user_guests: Guest :return: """ guests = [] for user_guest in user_guests: guests.append(user_guest.json()) return guests
def partition(a, sz): """splits iterables a in equal parts of size sz""" return [a[i:i + sz] for i in range(0, len(a), sz)]
def parse_dot(data, pos): """Parses a single dot from raw multimeter data :param data: Raw multimeter data, aligned to 15-byte boundary :type data: bytes :param pos: Number of dot to parse (numbered left to right) :type pos: int :return: Whether dot is on :rtype: bool """ return bo...
def root(classes): """get all root classnames """ return [c for c in classes if c.startswith("h-")]
def _indent_of(s): """Return the prefix of s that is whitespace.""" return s[:len(s) - len(s.lstrip(" \t"))]
def containsOnly(str, set): """Check whether sequence str contains ONLY items in set.""" for c in str: if c not in set: return 0 return 1
def gen_Message(message): """Create a new Message.""" message = { "@type": "Message", "MessageString": message, } return message
def abs(value): """ Get abs value of value. """ if value < 0: value = -value else: pass return value
def merge_dicts(*dict_args): """Merges arbitrary number of dicts. Gives precedence to latter dicts. Args: *dict_arg: arbitrary number of dicts Returns: a single merged dict """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def med3(a, b, c): """returns median value among a, b, c""" if a >= b: if b >= c: return b elif c >= a: return a else: return c elif a > c: return a elif b > c: return c else: return b
def find_values(obj, keys, key=None, val_type=list): """Find dictionary values of a certain type specified with certain keys. Args: obj (obj): a python object; initailly the dictionary to search keys (list): list of keys to find their matching list values key (str, optional): key to che...
def fibonacci_cached(n): """Calculates the nth fibonacci number Args: n (int): the fibonacci number to get (e.g. 3 means third) Returns: int: nth fibonacci number """ first = (0, 1) if n in first: return n previous, current = first for index in range(2, n + 1): ...
def _get_first_non_empty_item(items): """ :param items: anything that is iterable :return: first non empty value In this filter the following values are considered non empty: - None - any empty sequence, for example, '', (), []. - any empty mapping, for example, {}. Note: to guarantee...
def get_asset_ips_and_enrich_offense_addresses( offense, src_adrs, dst_adrs, skip_enrichment=False ): """ Get offense asset IPs, and given skip_enrichment=False, replace the source and destination ids of the offense with the real addresses """ asset_ips = set() if isinstance(offense....
def parse_response(response): """ function to parse response and return intent and its parameters """ result = response['result'] params = result.get('parameters') intent = result['metadata'].get('intentName') return intent, params
def array_sum(arr): """ 1. Converts the array into the string and removes characters - '[', ']' 2. Splits on commas (',') to get the list of integers 3. Sums the integers up """ sum = 0 arr = str(arr) arr = arr.replace('[', '').replace(']', '').split(',') for i in arr: if i.s...
def manual_expo_mode(state): """ Bool to express if mode is manual. """ return state["expo_mode"] == "manual"
def compute_overall_annoyance(artifacted_blocks): """Calculating the total visibility of the image and return the values as int type.""" annoyance = 0 if len(artifacted_blocks) != 0: for block in artifacted_blocks: annoyance += block.annoyance return annoyance / len(artifac...
def strtobool(val: str) -> bool: """Convert a string representation of truth to True or False True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. This is lifted from distutils.util.strtobool...
def min_factor_sum(N): """ 10 ** 7: 3203714961609 10 ** 8: 279218813374515 10 ** 9: 24739731010688477 10 ** 10: 2220827932427240957 10 ** 11: 201467219561892846337 10 ** 12: 18435592284459044389811 10 ** 13: 1699246543196666002725979 10 ** 14: 157589263416765879793706013 """ ...
def fold(header): """Fold a header line into multiple crlf-separated lines at column 72. >>> fold(b'foo') 'foo' >>> fold(b'foo '+b'foo'*24).splitlines()[0] 'foo ' >>> fold(b'foo'*25).splitlines()[-1] ' foo' >>> len(fold(b'foo'*25).splitlines()[0]) 72 """ i = header.rfind(b...
def set_default(default_dict, result_dict): """Sets default values for a dictionary recursively. :param default_dict: The template dictionary to use to set values :param result_dict: The dictionary to load the template values into :rtype: dict """ # Iterate through default values ...
def normalize_list(items, width, filler = None): #=============================================================================== """ Normalize list to a specified width, truncating or filling as needed. Filler data can be supplied by caller. The filler will be copied to each added item. None will be us...
def convert3Dto1Dindex(i,j,k,NX,NY,NZ): """Converts 3D array index to 1D array index""" index = i+j*NX+k*NX*NY return index
def is_frequency(label: str) -> bool: """Detect if label is a frequency label""" return '_' in label and label.index('_') == 2 and len(label) == 10
def get_scan_dir_and_rsfwd(voc, ascending, r_diff, ncompliance): """Determine the scan direction and forward bias series resistance of a sweep. Scan direction is dermined based on the sweep direction and sign of Voc. This may fail for truly dark I-V sweeps that don't have a Voc. Parameters -------...
def pass_through(*args, **kwargs): """ Used for testing, takes your arguments and passes them back for type testing. .. code-block:: python variable = "Test this comes back the way I sent it." response = net.pass_through(variable, peer='somepeer') :return: *args, **kwargs """...
def is_equal_time_independent(a, b): """Determine if two strings are equal in constant time. Normally we're quite happy if string equality comparisons early out on the first mismatch. However, when we use compare security-sensitive data like password hashes, breaking early can expose timing attacks whi...
def is_set(cards): """ Return True if all cards all unique, False otherwise. """ return len(set(cards)) == len(cards)
def newton_sqrt(x): """Square root the way your calculator finds it""" val = x while True: last = val val = (val + x /val) * 0.5 if abs(val - last) < 1e-9: break return val
def _root(item: str) -> dict: """ Parses report root data including station and report type """ report_type = None station = None for item in item.split(): if item in ("UA", "UUA"): report_type = item elif not station: station = item return {"station":...
def paste_filename(search): """ Function that will create a name for the files to be saved to using the search """ # Removes any spaces cleaned_keyword = search.replace(' ', '_') # Adds 'videos.csv' at the end filename = cleaned_keyword + "_videos.csv" return filename
def count_change(a, kinds=(50, 25, 10, 5, 1)): """Return the number of ways to change amount A using coin kinds""" if a == 0: return 1 if a < 0 or len(kinds) == 0: return 0 d = kinds[0] return count_change(a, kinds[1:]) + count_change(a - d, kinds)
def get_id(record): """Get the ID from a record. Args: record A record returned by AWS. Returns: The ID of the subnet. """ return record["SubnetId"]
def _step_summary(step_list): """Creates a single string representation of the step status Success/Failed/Other counts in each position """ successes = 0 failures = 0 other = 0 for s in step_list: state = s.get('state') if state in ['success']: successes += 1 ...
def get_all_views_query() -> str: """ doc """ # There is a better way to do this to get out deps return "select table_name from INFORMATION_SCHEMA.views where table_schema='public';"
def format_template(str_, language): """ - Remove empty line. - Right strip - Split Fortran line - Remove double space """ import re def split_fortran_line(line, max_width=100): """ To be improved and cleaned. Don't work if we need to split line in more than one ...
def halving_sum(n): """ Halving the sum of integer. :param n: a positive integer. :return: all elements of the sum are the results of integer division. """ if n == 1: return 1 else: return n + halving_sum(n // 2)
def remove_ind(arr, i): """ returns new list with arr[i] removed """ return arr[:i] + arr[i+1:]
def get_temp_vapp_name(template_name): """. This temp vapp name logic is borrowed from cse_install method """ return template_name + '_temp'
def _list_str(string, separator=','): """Convert comma separated string to list.""" return string.strip('{:s} \n\t'.format(separator))
def _find_parent(api, project, name): """Find a parent folder to enumerate inputs under. """ cur_folder = None for f in [x for x in name.split("/") if x]: if not cur_folder: cur_folder = list(api.files.query(project, names=[f]).all())[0] else: cur_folder = list(ap...
def question_mark_finder(sentence): """ Returns 1 if sentence contains question mark, 0 otherwise """ if "?" in sentence: return 1 else: return 0
def check_capital_letter(message): """Check that subject line starts with lower case letter.""" check = message[0].islower() return check
def adj_r2(r2_score, num_observations, num_parameters): """Calculate the Adjusted R-Squared value Args: r2_score (int): R-Squared value to adjust num_observations (int): Number of observations used in model num_parameters (int): Number of parameters used in model Returns: ...
def bazel_go_library(pkg): """Returns the Bazel label for the Go library for the provided package. This is intended to be used with the //build:kazel_generated.bzl tag dictionaries; for example: load("//build:kazel_generated.bzl", "tags_values_pkgs") some_rule( ... deps = [bazel_go_libra...
def check_utilization(nn, np, ppn, threshold=0.9, name=None): """Check whether the calculated node utilization is below threshold. This function raises a :class:`RuntimeError` if the calculated node utilization is below the given threshold or if the number of calculated required nodes is zero. :pa...
def extract_tokens(d, f): """Extract tokens from an JSON AST, using extraction function f""" def inner(d): if type(d) not in [dict, list]: return set() elif type(d) == list: res = [inner(x) for x in d] return set().union(*res) else: res = ...
def isfile(obj): """ Check whether obj is a file-like object (file, StringIO)" """ return hasattr(obj, 'flush')
def get_int_storage_path(dev): """Return internal storage path """ if dev: return dev.get_int_storage_path() else: return None
def guess_family(address): """ Determine the family of address. """ if type(address) == tuple: return 'AF_INET' elif type(address) is str and address.startswith('\\\\'): raise ValueError('Windows pipe is not supported') #return 'AF_PIPE' elif type(address) is str: ...
def expected(typ, val=None): """ Return an indication of expected input and the position where it was expected and not encountered. """ return [("expected", typ, val)]
def message_relative_index(messages, message_id): """ Searches the relative index of the given message's id in a channel's message history. The returned index is relative, because if the message with the given is not found, it should be at that specific index, if it would be inside of the respective cha...