content
stringlengths
42
6.51k
def factorial(n): """ Returns n! """ p = 1 for j in range(1,n+1): p *= j return p
def to_lutron_level(level): """Convert the given Home Assistant light level (0-255) to Lutron (0-100).""" return int((level * 100) // 255)
def check_valid_column(observation): """ Validates that our observation only has valid columns Returns: - assertion value: True if all provided columns are valid, False otherwise - error message: empty if all provided columns are valid, False otherwise """ valid_columns = { "Department Name", "InterventionLocationName", "InterventionReasonCode", "ReportingOfficerIdentificationID", "ResidentIndicator", "SearchAuthorizationCode", "StatuteReason", "SubjectAge", "SubjectEthnicityCode", "SubjectRaceCode", "SubjectSexCode", "TownResidentIndicator" } keys = set(observation.keys()) if len(valid_columns - keys) > 0: missing = valid_columns - keys error = "Missing columns: {}".format(missing) return False, error if len(keys - valid_columns) > 0: extra = keys - valid_columns error = "Unrecognized columns provided: {}".format(extra) return False, error return True, ""
def StripFlagPrefix(name): """Strip the flag prefix from a name, if present.""" if name.startswith('--'): return name[2:] return name
def lower(string: str) -> str: """Transforms string to lower-case letters.""" return string.lower()
def calc_angle(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2'.""" return v1[0]*v2[1] - v1[1]*v2[0]
def diff(input_obj, op): """ Given an input with `__len__` defined and an op which takes the input and produces one output with `__len__` defined, compute the difference and return (diff_len, output) :param input_obj: The input :type input_obj: ```Any``` :param op: The operation to run :type op: ```Callable[[Any], Any]``` :returns: length of difference, response of operated input :rtype: ```Tuple[int, Any]``` """ input_len = len( input_obj ) # Separate line and binding, as `op` could mutate the `input` result = op(input_obj) return input_len - len(result), result
def onlyWikipediaURLS(urls): """Some example HTML page data is from wikipedia. This function converts relative wikipedia links to full wikipedia URLs""" wikiURLs = [url for url in urls if url.startswith('/wiki/')] return ["https://en.wikipedia.org"+url for url in wikiURLs]
def gen_rho(K): """The Ideal Soliton Distribution, we precompute an array for speed """ return [1.0/K] + [1.0/(d*(d-1)) for d in range(2, K+1)]
def ispunctuation(char): """ Indicates if the char is a punctuation """ if (ord(char) >= 0x21 and ord(char) <= 0x2F) or \ (ord(char) >= 0x3A and ord(char) <= 0x40) or \ (ord(char) >= 0x5B and ord(char) <= 0x60) or \ (ord(char) >= 0x7B and ord(char) <= 0x7E): return True else: return False
def key_by_args_and_func_kw(old_f, args, kw, cache_data): """Function to produce a key hash for the cache_data hash based on the function and the arguments provided.""" return repr((old_f, args, kw))
def format_env(current_env): """ formats the current env to be a foo=bar,sna=fu type paring this is used for the make_supervisor_conf management command to pass current environment to make the supervisor conf files remotely instead of having to upload them from the fabfile. This is somewhat hacky in that we're going to cherry pick the env vars we want and make a custom dict to return """ ret = dict() important_props = [ 'environment', 'code_root', 'log_dir', 'sudo_user', 'host_string', 'project', 'es_endpoint', 'jython_home', 'virtualenv_root', 'django_port', 'django_bind', 'flower_port', ] for prop in important_props: ret[prop] = current_env.get(prop, '') return ','.join(['%s=%s' % (k, v) for k, v in ret.items()])
def _clean_pattern(rv: str) -> str: """Clean a regular expression string.""" rv = rv.rstrip("?") if not rv.startswith("^"): rv = f"^{rv}" if not rv.endswith("$"): rv = f"{rv}$" return rv
def extend_line(line, img_width, img_height, horizon): """Generates a line that crosses the given point with the given slope, and that reaches both the bottom of the image and the virtual horizon. Arguments: line: A dict with the following keywords: center: dict of two floats or None slope: float or None img_width: Width of the image in pixels. img_height: Height of the image in pixels. horizon: Y coordinate the line is extended to. Returns: A line that extends from the horizon to the bottom of the image. """ if line == None or line["slope"] == 0: return [[0, 30, img_width, 30]] # a big and obvious ugly line for debugging purposes when data is missing # return None x0, y0 = line["center"] m = line["slope"] # calculate the bottom point dx = (y0 - img_height) / m x1 = x0 + dx y1 = img_height # calculate the top point dx = (y0 - horizon) / m x2 = x0 + dx y2 = horizon return [int(x1), int(y1), int(x2), int(y2)]
def extract_metadata(metadata): """ Given `metadata` produced from the custom Frama-C script, extract the line number and instruction information """ loc_index = metadata.find("current line: ") instr = metadata[len("current instruction: "):loc_index] loc = metadata[loc_index+len("current line: "):] return instr, loc
def people_in_rec_area(length_1, length_2, social_d): """This function's job is to tell us how many people can fit in a rectangular area. We model people as equally sized circles, with the distance between the center of two circles being the "social distance" between them. Our function takes the lengths of the rectangle and the distance between the center of two adjacent circles as inputs. The circles are laid out in a rectangular grid within the rectangular area. This way, the lengths of the sides of the rectange can be given by L1=n*2r and L2 = m*2r where n and m are the number of circles and r is the radius of each circle. We also let social_d = 2r, the distane between the center of two circles.""" if length_1 <= 0 or length_2 <= 0 or social_d <= 0: #We want our lengths and social_d to be positive numbers. raise Exception("Lengths of rectangle and the social distance should be positve numbers.") #Raises exception to inform user of mistake. else: area = length_1*length_2 #We model our waiting area as a rectangle whose area we define as the product of its length and width. max_people_in_rec = int(area/(social_d**2)) #We take A = n*m*social_d^2, where n*m yields the max number of people that can fit in the area. We get: n*m = number of people = area/social_d^2 return (max_people_in_rec)
def gcd(x, y): """Return the greatest common denominator of x and y.""" while y != 0: (x, y) = (y, x % y) return x
def middle(k1, k2, triplets): """ Searching for a word in between """ middles = [(m, v) for (l, m, r), v in triplets.items() if l == k1 and r == k2] total = sum([v for (_, v) in middles]) return sorted([(r, v/total) for (r, v) in middles], key=lambda x: -x[1])
def binary_scores_from_counts(ntp, nfp, ntn, nfn): """Precision, recall, and F1 scores from counts of TP, FP, TN, FN. Example usage:: p, r, f1 = binary_scores_from_counts(*map(len, error_sets)) """ prec = ntp / float(ntp + nfp) if ntp + nfp > 0 else 0.0 rec = ntp / float(ntp + nfn) if ntp + nfn > 0 else 0.0 f1 = (2 * prec * rec) / (prec + rec) if prec + rec > 0 else 0.0 return prec, rec, f1
def csv_cell_cast(data): """Always treat csv cells the same way: 1. Try to cast to float 2. if '' then return None (see params_cleanup) 3. else return whatever (str, basically) """ try: param = float(data) except: if not (data == '' or data == 'None'): param = data else: return None return param
def _bisect( a, x, lo = 0 ): """ Modified 'bisect_right' from the Python standard library. """ hi = len( a ) while lo < hi: mid = ( lo + hi ) // 2 if x < a[ mid ][ 0 ]: hi = mid else: lo = mid + 1 return lo
def get_upper_long_from_trace_id(trace_id): """Returns the upper 8 bytes of the trace ID as a long value, assuming little endian order. :rtype: long :returns: Upper 8 bytes of trace ID """ upper_bytes = trace_id[:16] upper_long = int(upper_bytes, 16) return upper_long
def eq(a, b, tolerance=1e-09): """Returns true if values are approximately equal.""" return abs(a - b) <= tolerance
def on_conflict_statement(on_conflict_update=None): """ Generate an appropriate "ON CONFLICT..." statement. Parameters: on_conflict_update: tuple (condition: str, actions: str, list, dict), optional Generate a statement like "ON CONFLICT condition DO UPDATE SET actions" actions may be a SQL str, a list of column action str, or a dict of column=value pairs. Return: str """ if on_conflict_update: if isinstance(on_conflict_update, tuple): condition, actions = on_conflict_update if isinstance(actions, list): actions = ",".join(actions) elif isinstance(actions, dict): actions = ",".join([f"{k} = {v}" for k,v in actions.items()]) return f"ON CONFLICT {condition} DO UPDATE SET {actions}" return "ON CONFLICT DO NOTHING"
def break_words(stuff): """This function will break up words for us. .split(s) is a string method that returns a list of the words in the string using s as the delimiter string. """ words = stuff.split(' ') return words
def construct_input_question(type="input", name="value", message=""): """ Construct the dict of a question that allows for free-text input """ return { "type": type, "name": name, "message": message }
def find_ngrams(input_list: list, n: int) -> list: """ Return a list of n_grams from a list Args: input_list (list): list from which n_grams are extracted n (int): n gram length Returns: list: n-gram list """ if n == 1: return input_list else: return list(zip(*[input_list[i:] for i in range(n)]))
def is_possible_temp(temp: str) -> bool: """ Returns True if all characters are digits or 'M' (for minus) """ for char in temp: if not (char.isdigit() or char == "M"): return False return True
def standardize_proxy_config(proxy_config): """ This function is used to standardize the proxy information structure to get it evaluated through `get_proxy_info` function """ if not isinstance(proxy_config, dict): raise ValueError("Received unexpected format of proxy configuration. Expected format: object, Actual format: {}".format(type(proxy_config))) standard_proxy_config = { "proxy_enabled": proxy_config.get("enabled", proxy_config.get("proxy_enabled")), "proxy_username": proxy_config.get("username", proxy_config.get("proxy_username")), "proxy_password": proxy_config.get("password", proxy_config.get("proxy_password")), "proxy_url": proxy_config.get("host", proxy_config.get("proxy_url")), "proxy_type": proxy_config.get("type", proxy_config.get("proxy_type")), "proxy_port": proxy_config.get("port", proxy_config.get("proxy_port")), "proxy_rdns": proxy_config.get("rdns", proxy_config.get("proxy_rdns")) } return standard_proxy_config
def _fuzzy_match(query, arr): """ will compare all elements in @arr against the @query to see if they are similar similar implies one is a substring of the other or the two words are 1 change apart Ex. bird and bord are similar Ex. bird and birdwaj are similar Ex. bird and bead are not similar """ def similar_word(a, b): a_len = len(a) b_len = len(b) if a_len > b_len: # @a should always be the shorter string return similar_word(b, a) if a in b: return True if b_len - a_len > 1: return False i = 0 j = 0 found_difference = False while i < a_len: if a[i] != b[j]: if found_difference: return False found_difference = True if a_len == b_len: i += 1 j += 1 else: i += 1 j += 1 return True matches = [] for word in arr: if similar_word(query, word): matches.append(word) return matches
def get_gcloud_command_group(collection): """Converts API collection to gcloud sub-command group. Most collections are a direct mapping, but some are multi-word or have custom sub-command groups and must be special-cased here. Args: collection: collection within the respective API for this resource. Returns: gcloud command group string for this resource's collection. """ return { 'backendServices': 'backend-services', 'backendBuckets': 'backend-buckets', 'firewalls': 'firewall-rules', 'forwardingRules': 'forwarding-rules', 'httpHealthChecks': 'http-health-checks', 'httpsHealthChecks': 'https-health-checks', 'instanceTemplates': 'instance-templates', 'instanceGroupManagers': 'instance-groups managed', 'targetHttpProxies': 'target-http-proxies', 'targetHttpsProxies': 'target-https-proxies', 'targetPools': 'target-pools', 'urlMaps': 'url-maps', 'healthChecks': 'health-checks', 'instanceGroups': 'instance-groups' }.get(collection, collection)
def greeting(name: str) -> str: """ Build the greeting message """ return 'Hello, ' + name + '!'
def fn_name(fn): """Return str name of a function or method.""" s = str(fn) if s.startswith('<function'): return 'fn:' + fn.__name__ else: return ':'.join(s.split()[1:3])
def arb_sequence_handle(session, Type='Int32', RepCap='', AttrID=1250211, buffsize=0, action=['Get', '']): """[Arbitrary Sequence Handle <int32>] Identifies which arbitrary sequence the function generator produces. You create arbitrary sequences with the Create Arbitrary Sequence function. This function returns a handle that identifies the particular sequence. To configure the function generator to produce a specific sequence, set this attribute to the sequence's handle. Set: RepCap: < channel# (1-2) > """ return session, Type, RepCap, AttrID, buffsize, action
def uniqify(L): """ Uniqify a list, maintains order (the first occurrence will be kept). """ seen = set() nL = [] for a in L: if a in seen: continue nL.append(a) seen.add(a) return nL
def mix(x: float, y: float, a: float) -> float: """ Do a linear blend: x*(1-a) + y*a """ return (1-a)*x + a*y
def make_response(error, message=None, image_base64=None): """ Generates the ObjectCut JSON response. :param error: True if the response has to be flagged as error, False otherwise. :param message: Message to return if it is a error response. :param image_base64: Image result encoded in base64 if it is a success response. :return: ObjectCut JSON response. """ response = dict(error=error) if error: response['message'] = message else: response['response'] = dict(image_base64=image_base64) return response
def rank_partition(cards): """ :param cards: ([str]) :return: ({str: [str]} rank --> [suit] """ rank_to_suits = {} for rank, suit in cards: if rank not in rank_to_suits: rank_to_suits[rank] = [] rank_to_suits[rank].append(suit) return rank_to_suits
def is_OP_dict(obj_dict): """Check if the object need to be updated for OP""" return ( "__class__" in obj_dict.keys() and ("Input" in obj_dict["__class__"] or obj_dict["__class__"] == "OutElec") and "Id_ref" in obj_dict.keys() )
def _verify_encodings(encodings): """Checks the encoding to ensure proper format""" if encodings is not None: if not isinstance(encodings, (list, tuple)): return encodings, return tuple(encodings) return encodings
def eq(max_x, x): """Returns equally separated decreasing float values from 1 to 0 depending on the maximu value of x Parameters ---------- max_x : int maximum x value (maximum number of steps) x : int current x value (step) Returns ------- float y value Example ------- >>> eq(3, 0) 1.0 >>> eq(3, 1) 0.6666666666666667 >>> eq(3, 3) 0.0 """ return ((-1/max_x) * x) + 1
def clip_float(value): """Clips value to a range of [0,1]""" return min(1, max(value, 0))
def cert_pem(cert_prefix): """This is the cert entry of a self-signed local cert""" return cert_prefix + '/server.crt'
def get_position_by_shortcut(shortcut, base_size, overlay_size): """ returns tuple (x, y) to paste overlay_size into base_size image by shortcut for example BaseImage.paste(OverlayImage, (x, y)) allowed shortcuts: c - center l - left r - right t - top b - bottom and combinations lt, tl, lb, bl, rt, tr, rb, br """ w, h = base_size w_o, h_o = overlay_size positions = {} c = (int(w / 2) - int(w_o / 2), int(h / 2) - int(h_o / 2)) positions['c'] = c positions['l'] = (0, c[1]) positions['r'] = (w - w_o, c[1]) positions['t'] = (c[0], 0) positions['b'] = (c[0], h - h_o) # For combinations of left/rigth and top/bottom for x in ('l', 'r'): for y in ('t', 'b'): positions[x + y] = (positions[x][0], positions[y][1]) positions[y + x] = positions[x + y] position = positions.get(shortcut) if not position: raise Exception('Ambiguous shortcut for position - %s' % shortcut) return position
def dot_product(vector_one, vector_two): """ Calculates the dot product of two vectors """ total = 0 for i in range(len(vector_one)): total += vector_one[i] * vector_two[i] return total
def encode_remainining_length(remaining_length): # type: (int) -> bytes """Encode the remaining length for the packet. :returns: Encoded remaining length :rtype: bytes """ encoding = True encoded_bytes = bytearray() encoded_byte = 0 while encoding: encoded_byte = remaining_length % 128 remaining_length //= 128 if remaining_length: encoded_byte |= 0x80 else: encoding = False encoded_bytes.append(encoded_byte) return bytes(encoded_bytes)
def is_lesser(a, b): """ Verify that an item *a* is <= then an item *b* :param a: An item :param b: Another item :return: True or False """ if type(a) != type(b): return False if isinstance(a, str) and isinstance(b, str): return a == b elif isinstance(a, bool) and isinstance(b, bool): return a == b elif isinstance(a, list) and isinstance(b, list): for element in a: flag = 0 for e in b: if is_lesser(element, e): flag = 1 break if not flag: return False return True elif isinstance(a, dict) and isinstance(b, dict): if is_lesser(list(a.keys()), list(b.keys())): for key, val in a.items(): if not is_lesser(val, b[key]): return False return True return False elif isinstance(a, int) and isinstance(b, int): return a <= b elif isinstance(a, float) and isinstance(b, float): return a <= b return False
def adjust_poses(poses, refposes): """poses, poses_ref should be in direct""" # atoms, take last step as reference for i in range(len(poses)): for x in range(3): move = poses[i][x] - refposes[i][x] move = round(move, 0) poses[i][x] -= move refposes = poses.copy() return poses, refposes
def _url_to_filepath(url): """Internal function used to strip the "file://" from the beginning of a file url Args: url (str): URL to clean Returns: str: URL string with file:// removed """ return url[7:]
def day_type_for(key): """Determine the dayType.""" if key == "mon-fri": return "MONDAY_TO_FRIDAY" if key in ["saturday", "sunday"]: return key.upper()
def boolify(s): """Conversion: string to bool.""" return (str)(s).lower() in['true', '1', 't', 'y', 'yes', 'on', 'enable', 'enabled']
def changeFont(string): """Intercambia el las minisculas a mayusculas y viceversa""" swap = string.swapcase() return swap
def _make_list_eq_constraints(a, b): """Create a list of cvxpy equality constraints from two lists.""" if isinstance(a, list): n = len(a) elif isinstance(b, list): n = len(b) else: raise ValueError() return [a[i] == b[i] for i in range(n)]
def cond(cond,v1,v2): """ Conditional expression. """ if cond: return v1 else: return v2
def x_to_ab(x, p, q): """ Given some integer x mod pq, returns the CRT representation (x mod p, x mod q) (CRT -> Chinese Remainder Theorem). """ return x % p, x % q
def hoc_luc(diem): """Nhap vao diem de xep loai hoc luc""" if diem >= 9 and diem <= 10: return 'Hoc luc Xuat sac' if diem >= 8 and diem < 9: return 'Hoc luc Gioi' if diem >= 7 and diem < 8: return 'Hoc luc Kha' if diem >= 6 and diem < 7: return 'Hoc luc Trung binh kha' if diem >= 5 and diem < 6: return 'Hoc luc Trung binh' if diem >= 4 and diem < 5: return 'Hoc luc yeu' else: return 'Hoc luc kem'
def not_empty_name(s: str) -> str: """ Return stripped `s`, if it is not empty, otherwise raise ValueError. """ s = s.strip() if s: return s else: raise ValueError('Must contain at least one non-blank character')
def binary_search_greatest (test, minimum, maximum): """find greatest n, minimum <= n <= maximum, for which test (n).""" assert maximum >= minimum if test (maximum): return maximum if maximum == minimum or not test (minimum): return None while maximum > minimum + 1: cur = (minimum + maximum) / 2 if test (cur): minimum = cur else: maximum = cur - 1 assert minimum + 1 == maximum return minimum
def find_item(items, key, value): """Find an item with key or attributes in an object list.""" filtered = [ item for item in items if (item[key] if isinstance(item, dict) else getattr(item, key)) == value ] if len(filtered) == 0: return None return filtered[0]
def next_power_of_two(x): """Calculates the smallest enclosing power of two for an input. Args: x: Positive float or integer number. Returns: Next largest power of two integer. """ return 1 if x == 0 else 2**(int(x) - 1).bit_length()
def add_col_set_recursive(c1, c2): """Returns a new collision set resulting from adding c1 to c2. No side effecting collision set is done for the recursive case, where ({1, 2}, ) + ({3, 4}, ) = ({1, 2}, {3, 4}) c1, c2 - tuples of (immutable) sets returns: recursive collision set containing c1 and c2 """ # Make shallow copies c1 = list(c1) c2 = list(c2) while len(c1) > 0: i = 0 # Whether c1[-1] overlaps with any element of c2 found_overlap = False while i < len(c2): if not c2[i].isdisjoint(c1[-1]): # Found overlap if c2[i].issuperset(c1[-1]): # No change in c2 c1.pop() found_overlap = True break # Have found a non-trivial overlap. Need to add the # union to c1 so that we can check if the union has any # further overlap with elements of c2 temp = c2.pop(i) # replace c2[i] with the union of c2[i] and c1[-1] c1.append(temp.union(c1.pop())) found_overlap = True break else: # No overlap between c1[-1] and c2[i], so check next # element of c2 i += 1 if not found_overlap: # c1[-1] has no overlap with any element of c2, so it can be # added as is to c2 c2.append(c1.pop()) return tuple(c2)
def _determine_format(element): """Determine the format string based of the element that we're dumping. For compound types we dump just the value, for atomic types we dump both key and value """ if isinstance(element, dict) or isinstance(element, list): return "%{value}" return "%{key}: %{value}\n"
def base_to_pair_rules(base_rules: dict) -> dict: """For dictionary of base rules, like {'CH': 'B', 'HH': 'N'} return a dictionary of pair rules. These have same keys as base rules, but the value is list of pairs. For example, {'CH': 'B''} parm returns {'CH': ['CB', 'BH']}""" pair_rules = {} for pair in base_rules: new_element = base_rules[pair] pair_rules[pair] = [pair[0] + new_element, new_element + pair[1]] return pair_rules
def compact(array): """Remove all falsy items from array """ return [x for x in array if x not in [None, '', False]]
def make_xpath(xpath, name): """make a xpath from 2 parts""" return xpath + "." + name if xpath else name
def enforce_django_options(struct, opts): """Make sure options reflect the Django usage. Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ opts['package'] = opts['project'] # required by Django opts['force'] = True opts.setdefault('requirements', []).append('django') return struct, opts
def toX_pos(x, y=None): """ This function is used to load value on Plottable.View :param x: Float value :return: x """ if not x > 0: raise ValueError("Transformation only accepts positive values.") else: return x
def tag_for(name, *a, **k): """create a zoom tag >>> tag_for('name') '<dz:name>' >>> tag_for('name', default=1) '<dz:name default=1>' """ return '<dz:{}{}{}>'.format( name, a and (' ' + ' '.join(str(a))) or '', k and (' ' + ' '.join( '{}={!r}'.format(k, v) for k, v in sorted(k.items()) )) or '' )
def _email_to_username(email): """ Returns a Django-safe username based on the email address. This is because Django doesn't support email addresses as usernames yet. """ return email.replace('@', 'AT')
def getSubjectString(subject): """ Get the formatted string with a certain number of blanks. >>> getSubjectString("CS") ' CS' >>> getSubjectString("CHEM") 'CHEM' """ return (4 - len(subject)) * " " + subject
def str0(v): """Returns a null terminated byte array""" if type(v) is not str: raise Exception("Only strings") b = bytearray(v, encoding="ascii") b.append(0) return b
def is_subdomain(name): """ Checks if this is a subdomain. """ return name.count('.') > 0
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
def check_inverse(conjunction, nr_of_elements, neutral_element): """ Check if every element of the conjunction has an inverse element. Parameters ---------- conjunction nr_of_elements : int neutral_element Returns ------- tuple (bool, el) - if it is False, give a counter example. Otherwise (True, -1) """ for el in range(nr_of_elements): has_inverse = False for possibleInverse in range(nr_of_elements): if conjunction[el][possibleInverse] == neutral_element and \ conjunction[possibleInverse][el] == neutral_element: has_inverse = True break if not has_inverse: return False, el return True, -1
def getFeatureName(feature, default): """extract the name of the feature from the definition""" if 'name' in feature: return feature['name'] else: return default
def UnCamelCase(phrase, separator='_'): """Convert CamelCased phrase into lower-case delimited words. Args: phrase: CamelCased phrase. separator: The word separator to inject between lowercased words. Returns: lower case phrase with separators between case changes from lower to upper or acronyms (all upper) to lower case. """ phrase_len = len(phrase) if not phrase_len: return '' ch = phrase[0] text_run = ch.isalnum() last_was_separator = ch.isupper() or not text_run caps_run = False result = ch.lower() # already did first index for i in range(phrase_len - 1): ch = phrase[i + 1] if ch.isupper(): caps_run = text_run and last_was_separator text_run = True if not last_was_separator: result += separator last_was_separator = True elif not ch.isalnum(): caps_run = False text_run = False last_was_separator = True else: text_run = True last_was_separator = False if caps_run: result += separator last_was_separator = True caps_run = False result += ch.lower() return result
def is_explicitly_rooted(path): """Return whether a relative path is explicitly rooted relative to the cwd, rather than starting off immediately with a file or folder name. It's nice to have paths start with "./" (or "../", "../../", etc.) so, if a user is that explicit, we still find the path in the suffix tree. """ return path.startswith(('../', './')) or path in ('..', '.')
def center_anchor(center_id): """Given a center id, returns a string suitable for use as an HTML id attribute value""" return 'c{}'.format(center_id)
def smallest_mult(upper): """ Find the smallest positive number that is evenly divisible from all numbers from 1 to `upper`. """ # Find all prime number between 1 and `upper`. primes = [2, 3] for n in range(primes[-1] + 2, upper + 1, 2): is_prime = True for p in primes: if n % p == 0: is_prime = False if is_prime: primes.append(n) # Count the maximum number of times each prime is a factor of each number # between 1 and `upper`. factor_cnt = {p : 1 for p in primes} for n in range(1, upper + 1): cur_fact_cnt = {} while n > 1: for p in primes: if n % p == 0: if p in cur_fact_cnt: cur_fact_cnt[p] += 1 else: cur_fact_cnt[p] = 1 n /= p for fact, cnt in cur_fact_cnt.items(): factor_cnt[fact] = max(factor_cnt[fact], cnt) num = 1 for fact, cnt in factor_cnt.items(): num *= fact**cnt return num
def gpu_list_desc(use_for=None): """ Generate a description for a GPU list config trait. The optional use_for argument, if passed, causes text to be included that says what task the GPU list will be used for. """ return ('define which GPUs to use{}: "all", "None", or a comma-separated list, e.g. "1,2"' .format('' if use_for is None else ' for ' + use_for))
def join_rows(row_list_1, row_list_2): """Returns a list of list, in which element is the concatenation of the elements in the same position of row_list1 and row_list.""" if not row_list_1: return row_list_2 if not row_list_2: return row_list_1 row_list = [] for (row1, row2) in zip(row_list_1, row_list_2): row_list.append(row1+row2) return row_list
def get_distance_cat(down, distance): """Converts an integer distance to a string category. :param down: :param distance: :return: """ if down > 1: if distance <= 2: return "Short" elif 2 < distance <= 6: return "Med" else: return "Long" else: return ""
def find_ab(side1, side2, side3): """ Takes three side lengths an returns two smallest in a list :param side1: int or float :param side2: int or float :param side3: int or float :return: list of 2 ints or floats """ list = [side1, side2, side3] list.sort() return list[0:2]
def _first_defined(*args): """Return the first non-null argument (PRIVATE).""" for arg in args: if arg is not None: return arg return None
def indent(s: str, n: int) -> str: """Indent all the lines in s (separated by Newlines) by n spaces.""" s = ' ' * n + s s = s.replace('\n', '\n' + ' ' * n) return s
def postOrderTestTreeNode(root): """ """ lst = [] if root is None: return lst if root.left is not None: lst.extend(postOrderTestTreeNode(root.left)) if root.right is not None: lst.extend(postOrderTestTreeNode(root.right)) lst.append(root.data) return lst
def filter_bash_shellshock(df, process_time): """ A function that filters out the BASH SHELLSHOCK alert data obtained from FireEye :param df: a DataFrame object :param process_time: :return: """ result = [] track = [] for o in df: if 'BASH [Shellshock HTTP]' in o['message']: track.append(o) else: result.append(o) trackfile = open('tracking_bashShellShock_' + process_time + '.txt', 'w') numskip = 1 for item in track: trackfile.write("\n\n**** {:d}: Display ID {} ****\n\n{}".format(numskip, item['displayId'], item)) numskip += 1 return result
def get_resume_block(block): """ Gets the deepest block marked as 'resume_block'. """ if block.get('authorization_denial_reason') or not block.get('resume_block'): return None if not block.get('children'): return block for child in block['children']: resume_block = get_resume_block(child) if resume_block: return resume_block return block
def to_binary(number: int) -> str: """Convert a decimal number to a binary numbers. :param number: The number to convert to binary :return: The binary representation of the number """ return bin(number)[2:]
def hyper(link, text) -> str: """ transforms the link and text into a 'terminal anchor tag' :param link: the link to the website :param text: text for the link :return: formated text """ return f"\e]8;;{link}\e\\\\{text}\e]8;;\e\\\\"
def findPaddingBothSidesOneAxis(difference): """ Returns amount of padding required on both sides based on difference found """ if difference % 2 == 0: left, right = int(difference/2), int(difference/2) else: left, right = int(difference/2), int(difference/2 + difference%2) return left, right
def get_accumulator(accu): """ Initializes the accumulator. If it is callable, type reference, calls the constructor. Otherwise returns the accumulator. :param accu: The data accumulator :return: The initialized accumulator """ if callable(accu): return accu() return accu
def switch(*args): """ Given each arg as a tuple (b, e) returns the first match. This is equivalent to if b1: return e1 elif b2: :return e2 ... :param args: are in the form ((b1, e1), (b2, e2) ...) :return: one of the e """ for b, e in args: if b: return e
def normalise(coord_paths): """ Take an array of coord, remove any empty paths, and make sure that all the coords are tuples not arrays (Which can happen after json.load()) """ new_paths = [] for path in coord_paths: if len(path) > 0: new_path = [] for point in path: # convert to tuple new_path.append((point[0], point[1])) new_paths.append(new_path) return new_paths
def get_max_score(scores): """ gets maximum score from a dictionary """ max_value = 0 max_id = -1 for i in scores.keys(): if scores[i] > max_value: max_value = scores[i] max_id = i return max_id
def calculate_grade(grade): """Function that calculates final grades based on points earned.""" if grade >= 90: if grade == 100: return 'A+' return 'A' if grade >= 80: return 'B' if grade >= 70: return 'C' return 'F'
def linear(x, m, b): """Return linear function.""" return m * x + b
def denormalize(x, dl, dh, nl, nh): """ An inverse function of the range normalize operation. Parameters ----------- :param x: The number/vector to be normalized :param dl: The minimum possible value of x. :param dh: The maximum possible value of x. :param nl: The minimum possible value of the normalized range. :param nh: The maximum possible value of the normalized range. :return: The de-normalized value(s). """ return ((dl - dh) * x - (nl * dl) + dh * nl) / (nl - nh)
def make_word_count(word_list): """ Take list of strings, make a dict of proceeding string frequencies for each string. """ # Container for our word count dict. doc_dict = {} # For each word, make a dict of the counts of each proceeding word. for i in range(len(word_list) - 1): if word_list[i] in doc_dict.keys(): if word_list[i+1] in doc_dict[word_list[i]].keys(): doc_dict[word_list[i]][word_list[i+1]] += 1 else: doc_dict[word_list[i]][word_list[i+1]] = 1 else: doc_dict[word_list[i]] = {word_list[i+1]: 1} return doc_dict
def gcd(a: int, b: int) -> int: """This function returns the greatest common divisor between two given integers.""" if a < 1 or b < 1: raise ValueError(f'Input arguments (a={a}, b={b}) must be positive integers') while a != 0: a, b = b % a, a return b