content
stringlengths
42
6.51k
def dropSpans(spans, text): """ Drop from text the blocks identified in :param spans:, possibly nested. """ spans.sort() res = '' offset = 0 for s, e in spans: if offset <= s: # handle nesting if offset < s: res += text[offset:s] offset = e res += text[offset:] return res
def damage_score(damageDealt): """ damage_score : type damageDealt: float : rtype damage_score: int """ if damageDealt >= 349.45: damage_score = 100 elif damageDealt >= 300.54: damage_score = 95 elif damageDealt >= 251.62: damage_score = 90 elif damageDealt >= 216.7: damage_score = 85 elif damageDealt >= 181.8: damage_score = 80 elif damageDealt >= 146.89: damage_score = 75 elif damageDealt >= 130.67: damage_score = 70 elif damageDealt >= 114.47: damage_score = 65 elif damageDealt >= 98.26: damage_score = 60 elif damageDealt >= 86.19: damage_score = 55 elif damageDealt >= 74.14: damage_score = 50 else: damage_score = 45 return damage_score
def remove_by_index(l, index): """removes element at index position from indexed sequence l and returns the result as new object""" return l[:index] + l[index + 1:]
def _str_to_hex(s: str) -> str: """ Convert given string to hex string. given string can be one of hex format, int, or a float between 0 and 1. >>> _str_to_hex('0xFf') 'Ff' >>> _str_to_hex('200') 'c8' >>> _str_to_hex('0.52') '84' """ if s.startswith('0x'): return s[2:].zfill(2) if s.isdigit(): return hex(int(s))[2:].zfill(2) return hex(int(float(s) * 255))[2:].zfill(2)
def patch_basic_types(basic_types, inp_version): """ Patch the _basic_types entry to correct ambigouities :param schema_dict: dictionary produced by the fleur_schema_parser_functions (modified in-place) :param inp_version: input version converted to tuple of ints """ if inp_version >= (0, 33): #After this version the issue was solved return basic_types CHANGE_TYPES = { (0, 32): { 'add': { 'KPointType': { 'base_types': ['float_expression'], 'length': 3 }, } }, (0, 28): { 'add': { 'AtomPosType': { 'base_types': ['float_expression'], 'length': 3 }, 'LatticeParameterType': { 'base_types': ['float_expression'], 'length': 1 }, 'SpecialPointType': { 'base_types': ['float_expression'], 'length': 3 } } }, } all_changes = {} for version, changes in sorted(CHANGE_TYPES.items(), key=lambda x: x[0]): if inp_version < version: continue version_add = changes.get('add', {}) version_remove = changes.get('remove', set()) all_changes = {key: val for key, val in {**all_changes, **version_add}.items() if key not in version_remove} for name, new_definition in all_changes.items(): if name not in basic_types: raise ValueError(f'patch_basic_types failed. Type {name} does not exist') basic_types[name] = new_definition return basic_types
def prepareResponse(mainpropertyname: str, data: dict) -> dict: """ Prepares a response to be sent with the received data. :param mainpropertyname: str - The name of the property that will hold the response's body. :param data: dict - The dictionary with data to build the response. :returns: dict - A dictionary with keys: 'mainpropertyname' : The main body for the response. 'status' : An status code for the operation. To be propertly determined. For now: 0 = All good. 1 = No data found. 20 = Error. {scraped, but might be used later...?} ['error'] : If an error was raised, this will contain an error message. ['message'] : If a warning was emitted, this will contain a warning or information message. """ response = {'status' : '0', mainpropertyname : data['body']} if 'message' in data: response['status'] = '1' # data['message'] if 'error' in data: response['status'] = '20' # data['error'] return response
def power2(x): """Return a list of the powers of 2 from 2^0... 2^x""" if x == 0: return None ret = [] for p in range(0,x): ret.append(2**p) return ret
def in_range(element, r): """because python's xrange.__contains__ is O(n) for no good reason. Doesn't work if element is "out of phase" with r's step. """ return element >= r[0] and element <= r[-1]
def authentication_headers(authentication_headers_raw): """Get authentication headers.""" identification = { "Renku-User-Id": "b4b4de0eda0f471ab82702bd5c367fa7", "Renku-User-FullName": "Just Sam", "Renku-User-Email": "contact@justsam.io", } return {**authentication_headers_raw, **identification}
def pad_sequences(sequences, pad_tok, tail=True): """Pads the sentences, so that all sentences in a batch have the same length. """ max_length = max(len(x) for x in sequences) sequence_padded, sequence_length = [], [] for seq in sequences: seq = list(seq) if tail: seq_ = seq[:max_length] + [pad_tok] * max(max_length - len(seq), 0) else: seq_ = [pad_tok] * max(max_length - len(seq), 0) + seq[:max_length] sequence_padded += [seq_] sequence_length += [min(len(seq), max_length)] return sequence_padded, sequence_length
def count_bags_having(bag_name, bag_to_outer_bag, visited): """Count number of bags containing bag_name.""" if bag_name in visited: return 0 count = 0 for bag in bag_to_outer_bag[bag_name]: if bag in visited: continue count += 1 + count_bags_having(bag, bag_to_outer_bag, visited) visited.add(bag) return count
def generate_desc(joinf, result): """ Generates the text description of the test represented by result """ if type(result) is frozenset: ret = [] for i in sorted(result): ret.append(generate_desc(joinf, i)) return '{' + ' '.join(ret) + '}' elif type(result) is tuple: (item, children) = result cdesc = generate_desc(joinf, children) return joinf(str(item), cdesc) else: return str(result)
def installed_headers_for_dep(dep): """Convert a cc_library label to a DrakeCc provider label. Given a label `dep` for a cc_library, such as would be found in the the `deps = []` of some cc_library, returns the corresponding label for the matching DrakeCc provider associated with that library. The returned label is appropriate to use in the deps of of a `drake_installed_headers()` rule. Once our rules are better able to call native rules like native.cc_binary, instead of having two labels we would prefer to tack a DrakeCc provider onto the cc_library target directly. Related links from upstream: https://github.com/bazelbuild/bazel/issues/2163 https://docs.bazel.build/versions/master/skylark/cookbook.html#macro-multiple-rules """ suffix = ".installed_headers" if ":" in dep: # The label is already fully spelled out; just tack on our suffix. result = dep + suffix else: # The label is the form //foo/bar which means //foo/bar:bar. last_slash = dep.rindex("/") libname = dep[last_slash + 1:] result = dep + ":" + libname + suffix return result
def CONCAT(src_column, dict_value_column = None): """ Builtin aggregator that combines values from one or two columns in one group into either a dictionary value or list value. If only one column is given, then the values of this column are aggregated into a list. Order is not preserved. For example: >>> sf.groupby(["user"], ... {"friends": tc.aggregate.CONCAT("friend")}) would form a new column "friends" containing values in column "friend" aggregated into a list of friends. If `dict_value_column` is given, then the aggregation forms a dictionary with the keys taken from src_column and the values taken from `dict_value_column`. For example: >>> sf.groupby(["document"], ... {"word_count": tc.aggregate.CONCAT("word", "count")}) would aggregate words from column "word" and counts from column "count" into a dictionary with keys being words and values being counts. """ if dict_value_column == None: return ("__builtin__concat__list__", [src_column]) else: return ("__builtin__concat__dict__", [src_column, dict_value_column])
def key_type(secret): """Return string value for keytype depending on passed secret bool. Possible values returned are: `secret`, `public`. .. Usage:: >>> key_type(secret=True) 'secret' >>> key_type(secret=False) 'public' """ return "secret" if secret else "public"
def closest(lst, K): """Python3 program to find Closest number in a list.""" return lst[min(range(len(lst)), key=lambda i: abs(lst[i] - K))]
def unnest_lists(lists): """ [[0,1], [2]] -> [0,1,2] """ return [entrie for sublist in lists for entrie in sublist]
def _merge_two_dicts(x, y): """ Given two dictionaries, merge them into a new dict as a shallow copy. """ z = x.copy() z.update(y) return z
def binary(n, digits): """Returns a tuple of (digits) integers representing the integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)""" t = [] for i in range(digits): n, r = divmod(n, 2) t.append(r) return tuple(reversed(t))
def sum_mean(vector): """ This function returns the mean values. """ a = 0 for i in vector: a = a + i return [a,a/len(vector)]
def symmetric_residue(a, m): """Return the residual mod m such that it is within half of the modulus. >>> symmetric_residue(1, 6) 1 >>> symmetric_residue(4, 6) -2 """ if a <= m // 2: return a return a - m
def create_ds_fault_name(lat, lon, depth): """ :return: a string containing a fault name for every rupture at that point (lat, lon, depth) """ return "{}_{}_{}".format(lat, lon, depth)
def isList(input): """ This function check input is a list object. :param input: unknown type object """ return isinstance(input, list)
def ind_dict2list(dic): """ :param dic: dictionary form object ot index, starting from zero :return: """ l = list(range(len(dic))) for item, index in dic.items(): l[index] = item return l
def create_finances_csv_name(workbook_name: str): """ Getting a readable csv file name from the finances spreadsheets Example: EUHWC - Expense Claims (Responses) EUHWC_-_Expense_Claims_(Responses) :param workbook_name: :return: """ workbook_name = workbook_name.replace(" ", "_") return workbook_name
def _pprint_missing_key(missing_dict, max_path_len, max_key_len, indent): """format missing key dict into a yaml-like human readable output""" def __pprint_missing_key(missing_dict, lines, level=0): for key, value in missing_dict.items(): line = [] # indentation line.extend([' '] * indent * level) # key and colon line.extend([key, ':']) if value: lines.append(''.join(line)) __pprint_missing_key(value, lines, level=level+1) else: key_len = len(key) line.extend([' '] * ( indent * (max_path_len - level) + (max_key_len - key_len))) line.append(' <<<') lines.append(''.join(line)) lines = [] __pprint_missing_key(missing_dict, lines) return '\n'.join(lines)
def get_middle_value(my_list): """Return the middle value from a list after sorting. :param list my_list: List of sortable values""" return sorted(my_list)[len(my_list) // 2] """Convert an integer resolution in base-pairs to a nicely formatted string. :param int window_size: Integer resolution in base pairs. :returns: Formatted resolution.""" return utils.format_genomic_distance(window_size, precision=0)
def next_letter(letter): """ Helper function to get the next letter after a letter. Example: next_letter('A') -> B, @param letter is the letter you are starting with @returns letter + 1 in the alphabet """ res = '' if ord(letter) < 65: res = 'Z' elif ord(letter) >= 90: res = 'A' else: res = chr(ord(letter) + 1) return res
def get_fashion_mnist_labels(labels): """Get text labels for Fashion-MNIST.""" text_labels = [ "t-shirt", "trouser", "pullover", "dress", "coat", "sandal", "shirt", "sneaker", "bag", "ankle boot", ] return [text_labels[int(i)] for i in labels]
def text_var(text): """ function to display text variable passed in """ return "C {}".format(text.replace("_", " "))
def totM(m1, m2): """The total mass shows up in Kepler formulae, m1+m2 """ return( m1+m2 )
def interface_is_in_vlan(vlan_member_table, interface_name): """ Check if an interface is in a vlan """ for _,intf in vlan_member_table: if intf == interface_name: return True return False
def getWkt(wn,es): """Return de wkt from a quadrilateral""" w = wn[0] n = wn[1] e = es[0] s = es[1] return f"POLYGON (({w} {n}, {e} {n}, {e} {s}, {w} {s}, {w} {n}))"
def idx2off(i): """ Produces [0, 32, 64, 96, 104, 136, 168, 200, 208, 240, 272, 304, 312, 344, 376, 408] These are the byte offsets when dividing into 52-coeff chunks""" return i * 32 - (24 * (i//4))
def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits)
def avg_word_len(input): """Find the average sentence length.""" lens = [len(x) for x in input.split()] return sum(lens) / len(lens)
def complement_alleles(s): """Complement an allele string. This will apply the following translation table to the alleles: A -> T G -> C and vice versa. Other characters will be left as-is. """ trans = str.maketrans("ATGCatgc", "TACGtacg") return s.translate(trans)[::-1]
def variable_name_to_option_name(variable: str): """ Convert a variable name like `ec2_user` to the Click option name it gets mapped to, like `--ec2-user`. """ return '--' + variable.replace('_', '-')
def _no_ws(s: str) -> str: """ strip all whitespace from a string """ return ''.join(s.split())
def get_issue_info(payload): """Extract all information we need when handling webhooks for issues.""" # Extract the title and the body title = payload.get('issue')['title'] # Create the issue dictionary return {'action': payload.get('action'), 'number': payload.get('issue')['number'], 'domain': title.partition(' ')[0]}
def get_label_filter(input_labels): """ Allow labels input to be formatted like: -lb key1:value -lb key2:value AND -lb key1:value,key2:value Output: key1:value,key2:value :param list(str) input_labels: list of labels, like, ['key1:value1', 'key2:value2'] or ['key1:value1,key2:value2'] :return str: labels formatted, like, 'key1:value1,key2:value2' """ if input_labels is None: return [] label_filter = [] for label in input_labels: sub_labels = [sub_label.strip() for sub_label in label.split(",")] label_filter.extend(sub_labels) return ",".join(label_filter)
def span_to_token(text, span_to_token_strategy='space'): """Convert text span string to token list Args: text (string): text span string span_to_token_strategy (str, optional): Defaults to 'space'. - space: split text to tokens using space - list: split text to toekns as list Raises: NotImplementedError: No implemented span_to_token_strategy Returns: list(str): list of token """ if span_to_token_strategy == 'space': return text.split(' ') elif span_to_token_strategy == 'list': return list(text) else: raise NotImplementedError( f"The span to token strategy {span_to_token_strategy} is not implemented." )
def area_under_the_curve(points): """ Computes area under the curve (i, points[i]), i.e., assumes that x-values are at distance 1. :param points: :return: """ n = len(points) - 1 a = 0.0 for i in range(n): a += (points[i] + points[i + 1]) / 2 return a / n
def minNumUsers(percent, totalNumUsers, scale): """Scale is the minimum number of users required to call it a pass""" numInAgreement = percent*totalNumUsers if numInAgreement >= scale: return 'H' elif numInAgreement +2 >= scale: return 'M' else: return 'L'
def IsIdentifier(token): """ Returns True if token is a valid identifier, else False. Parameters: token - Parsed token. """ if not token: return False c = token[0] if not c.isalpha() and c != "_": return False for c in token[1:]: if not c.isalnum() and c != "_": return False return True
def user_exists(user): """Check if user exists.""" query = "select name,fullname,email,state,sysadmin from public.user where name='{}';".format(user) rows = (query) if len(rows) == 1: return True else: return False
def job_metadata_filename(metadata): """Construct relative filename to job metadata.""" return "data/{metadata}".format(metadata=metadata)
def build_path(node): """ :param node: The node at the end of a path. :type node: TiledNode :return: A list of coordinate tuples. :rtype: list """ path = [] while node is not None: path.insert(0, (node.x, node.y)) node = node.previous return path
def pretty_print_ec2_res_where(res): """ Pretty-print zonal placement of an EC2 reservation """ if res['Scope'] == 'Region': return '(region)' elif res['Scope'] == 'Availability Zone': return res['AvailabilityZone'] else: raise Exception('unknown where %r' % res)
def thing(number:int) -> int: """Returns a number based on the happy number thing""" n = 0 for letter in [l for l in str(number)]: n += int(letter)**2 return n
def predicted_retention(alpha, beta, t): """Predicted retention probability at t. Function 8 in the paper""" return (beta + t) / (alpha + beta + t)
def remove_key(d, key): """Safely remove the `key` from the dictionary. Safely remove the `key` from the dictionary `d` by first making a copy of dictionary. Return the new dictionary together with the value stored for the `key`. Parameters ---------- d : dict The dictionary from which to remove the `key`. key : The key to remove Returns ------- v : The value for the key r : dict The dictionary with the key removed. """ r = dict(d) v = r.pop(key, None) return v, r
def divisors_list(n): """ Returns the list of divisors of n """ return [d for d in range(1, n // 2 + 1) if n % d == 0] + [n]
def get_set_summing_to(target, numbers): """Get continous set of numbers summing up to target.""" left = 0 right = 0 cur_sum = 0 while cur_sum != target: if cur_sum < target: cur_sum += numbers[right] right += 1 elif cur_sum > target: cur_sum -= numbers[left] left += 1 return numbers[left:right]
def flatten_sub(l): """Flatten a list by one level.""" return [item for sublist in l for item in sublist]
def get_scenes(nodes): """ Gets the total number of scenes for all nodes :param nodes: List of all nodes in the network :return: Dict A dictionary of the form {character: number of scenes} """ scenes = {} for i in range(len(nodes)): scenes[i] = nodes[i]['value'] return scenes
def _get_struct_endian_str(endian): """ DM4 header encodes little endian as byte value 1 in the header. However when that convention is followed the wrong values are read. So this implementation is reversed. :return: '>' or '<' for use with python's struct.unpack function """ if isinstance(endian, str): if endian == 'little': return '>' # Little Endian else: return '<' # Big Endian else: if endian == 1: return '>' # Little Endian else: return '<'
def strip_digits(text): """Removes digits (number) charaters. """ return ''.join(c for c in text if not c.isdigit())
def ball_height(v0, t, g=9.81): """Function to calculate height of ball. Parameters ---------- v0 : float Set initial velocity (units, m/s). t : float Time at which we want to know the height of the ball (units, seconds). g : float, optimal Acceleration due to gravity, by default 9.81 m/s^2. Returns ------- float Height of ball in meters. """ height = v0*t - 0.5*g*t**2 return height
def findWord(input_index: list, character_list: list) -> str: """ Returns a list of the characters that index each value of input_index on the character_list ### Parameters input_index : {list} The indexes that will be converted into characters. character_list : {list} A list containing all relevant Vigenere characters in the table. This must include all of the characters in `input_word`. ### Returns char_list : {np.array} A numpy array with the size as input_index and that each element corresponds to what is indexed on the character_list. """ char_list = [character_list[i % len(character_list)] for i in input_index] return "".join(char_list)
def build_multi_cell_update_request_body( row_index, column_index, values, worksheet_id=0 ): """ Builds a dict for use in the body of a Google Sheets API batch update request Args: row_index (int): The index of the cell row that should be updated (starting with 0) column_index (int): The index of the first cell column that should be updated (starting with 0) values (list of dict): The updates to be performed worksheet_id (int): Returns: dict: A single update request object for use in a Google Sheets API batch update request """ return { "updateCells": { "range": { "sheetId": worksheet_id, "startRowIndex": row_index, "endRowIndex": row_index + 1, "startColumnIndex": column_index, "endColumnIndex": column_index + len(values), }, "rows": [{"values": values}], "fields": "*", } }
def _bgzip_and_tabix_vcf_instructions(infile): """Generate instructions and logfile for bgzip and tabix""" bgzip_command = "bgzip -c %s > %s.gz" % (infile, infile) bgzip_logfile = "%s.bgzip.log" % infile tabix_command = "tabix -p vcf %s.gz" % infile tabix_logfile = "%s.tabix.log" % infile bgzip_instructions = list() bgzip_instructions.append(bgzip_command) bgzip_instructions.append(bgzip_logfile) tabix_instructions = list() tabix_instructions.append(tabix_command) tabix_instructions.append(tabix_logfile) return bgzip_instructions, tabix_instructions
def count_k(n, k): """Generalized version of count_stair_ways, except that the max number of step to take is defined by 'k' >>> count_k(3, 3) # 3, 2 + 1, 1 + 2, 1 + 1 + 1 4 >>> count_k(4, 4) 8 >>> count_k(10, 3) 274 >>> count_k(300, 1) # Only one step at a time 1 """ if n < 0: return 0 elif n == 0: return 1 else: return sum([count_k(n - i, k) for i in range(1, k + 1)])
def generate_tmpcontext_sorting(sorted_by, sort_options, **kwargs): """ Function to generate a temporary context for sorting of cards """ tmpcontext = { 'sorted_by': sorted_by, 'sort_options': sort_options } for key, val in kwargs.items(): tmpcontext[key] = val return tmpcontext
def findgen(n,int=False): """This is basically IDL's findgen function. a = findgen(5) will return an array with 5 elements from 0 to 4: [0,1,2,3,4] """ import numpy as np if int: return np.linspace(0,n-1,n).astype(int) else: return np.linspace(0,n-1,n)
def decode_fourcc(val): """ decode the fourcc integer to the chracter string """ return "".join([chr((int(val) >> 8 * i) & 0xFF) for i in range(4)])
def bin_append(a, b, length=None): """ Appends number a to the left of b bin_append(0b1, 0b10) = 0b110 """ length = length or b.bit_length() return (a << length) | b
def f(d: dict) -> dict: """ pre: d["age1"] < 100 < d["age2"] post: __return__ != {"age1": 100, "age2": 100} """ d["age1"] += 1 d["age2"] -= 1 return d
def _mod(_dividend: int, _divisor: int) -> int: """ Computes the modulo of the given values. _dividend % _divisor :param _dividend: The value of the dividend. :param _divisor: The value of the divisor. :return: The Modulo. """ _q = (_dividend // _divisor) _d = _q * _divisor return _dividend - _d
def is_title_case(line): """Determine if a line is title-case (i.e. the first letter of every word is upper-case. More readable than the equivalent all([]) form.""" for word in line.split(u' '): if len(word) > 0 and len(word) > 3 and word[0] != word[0].upper(): return False return True
def broadcast_shape(*shapes, **kwargs): """ Similar to ``np.broadcast()`` but for shapes. Equivalent to ``np.broadcast(*map(np.empty, shapes)).shape``. :param tuple shapes: shapes of tensors. :param bool strict: whether to use extend-but-not-resize broadcasting. :returns: broadcasted shape :rtype: tuple :raises: ValueError """ strict = kwargs.pop('strict', False) reversed_shape = [] for shape in shapes: for i, size in enumerate(reversed(shape)): if i >= len(reversed_shape): reversed_shape.append(size) elif reversed_shape[i] == 1 and not strict: reversed_shape[i] = size elif reversed_shape[i] != size and (size != 1 or strict): raise ValueError('shape mismatch: objects cannot be broadcast to a single shape: {}'.format( ' vs '.join(map(str, shapes)))) return tuple(reversed(reversed_shape))
def unq(s): """unquote. converts "'a'" to "a" """ return s[1:-1] if s[0]==s[-1]=="'" else s
def read_file(path: str) -> str: """Read contents of the file and return them as a string""" with open(path) as file: return file.read()
def _get_ftrack_secure_key(hostname, key): """Secure item key for entered hostname.""" return "/".join(("ftrack", hostname, key))
def get_ext(name): """ Return the extension only for a name (like a filename) >>> get_ext('foo.bar') 'bar' >>> get_ext('.only') 'only' >>> get_ext('') '' >>> get_ext('noext') '' >>> get_ext('emptyext.') '' Note that for any non-empty string, the result will never be the same as the input. This is a useful property for basepack. """ other, sep, ext = name.partition('.') return ext
def order_steps(sorted_steps): """Order steps as if they have zero time to work""" # start with steps that have no dependencies step_order = list( sorted(key for key, val in sorted_steps.items() if not val)) original_steps = set(sorted_steps) steps_seen = set(step_order) print('start', step_order) # then iterate over each time while original_steps != steps_seen: next_steps = list( sorted( key for key, val in sorted_steps.items() if set(val).issubset(steps_seen) and key not in step_order ) )[:1] if not next_steps: if original_steps == steps_seen: continue raise ValueError( f'Nothing to do! {original_steps.difference(steps_seen)}') steps_seen |= set(next_steps) step_order += next_steps return step_order
def salt(alt): """Altitude string (km).""" return f'{alt:.0f} km'
def article_output(article: dict) -> dict: """Cleans an article dictionary to convert ObjectIDs to str""" return { 'id': str(article['_id']), 'content': article['content'], 'tags': article['tags'] }
def increment_elements(some_list, integer_a, integer_b, integer_k): """Algorithmic crush""" for j in range(integer_a-1, integer_b): some_list[j] += integer_k return some_list
def get_name_from_filename(filename): """Gets the partition and name from a filename""" partition = filename.split('_', 1)[0] name = filename.split('_', 1)[1][:-4] return partition, name
def ms(seconds): """return the tupple (minutes, seconds) that corresponds to `seconds` """ seconds = int(round(seconds)) m = round(seconds // 60) s = round(seconds % 60) return (m, s)
def factorial_2(n, acc=1): """ Stuff in loop """ while True: if n < 2: return 1 * acc return factorial_2(n - 1, acc * n) break
def sort_updates(update: dict) -> int: """Return the seconds to go to pass to the python .sort() function Args: update (dict): Pass in the update dictionary that is filled with the required information Returns: int: The time delta in seconds that is stored in the update dictionary """ return update["seconds_to_go"]
def parsed_path(path): """ message=hello&author=gua { 'message': 'hello', 'author': 'gua', } """ index = path.find('?') if index == -1: return path, {} else: path, query_string = path.split('?', 1) args = query_string.split('&') query = {} for arg in args: k, v = arg.split('=') query[k] = v return path, query
def count_overweight(df): """ Objective : This function basically returns the number of Overweight people Input : Dataframe with BMI value Output : Total number of overweight people """ try: if not df.empty: return len(df[df['BMI Category'] == 'Overweight']) else: return None except Exception as e: print(e)
def get_tag(body): """Get the annotation tag from the body.""" if not isinstance(body, list): body = [body] try: return [b['value'] for b in body if b['purpose'] == 'tagging'][0] except IndexError: return None
def unique_field_contents(entries, field): """ Iterates through a list of dictionaries, adds the field content to a unique content set and then returns the set as ordered list. """ unique_content = set() for entry in entries: if field in entry: field_content = entry[field] if type(field_content) is list: unique_content.update(field_content) else: unique_content.add(field_content) unique_content = sorted(list(unique_content), key=str.casefold) return unique_content
def fuel(distance): """Regular quadratic equation.""" a = 0.5 b = 0.5 c = 0 return a * distance ** 2 + b * distance + c
def dict_get(key, dictionary): """Recursive get for multi-part key with dot (.) as separator Example: dict_get("foo.bar", {"foo": {"bar": 5}}) -> 5 Raises KeyError for missing keys. """ parts = key.split('.') first = parts.pop(0) if isinstance(dictionary, list): value = dictionary[int(first)] else: value = dictionary[first] return value if not parts else dict_get('.'.join(parts), value)
def _not_equal(input, values): """Checks if the given input is not equal to the first value in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool """ try: return input != values[0] except IndexError: return False
def selection_sort(arrayParam): """ Sort a list using selection sort algorithm. Run time: O(n**2) """ position = 0 array = arrayParam[:] for k in array: smallest = None subPosition = position smallestIndex = None # Getting smallest value and index for i in range(position, len(array)): if subPosition == position: smallest = array[i] smallestIndex = i else: if array[i] < smallest: smallest = array[i] smallestIndex = i subPosition += 1 missingIndex = position tmp = smallest array[smallestIndex] = array[missingIndex] array[missingIndex] = tmp position += 1 return array
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments Returns: True if the time segment overlaps with any of the existing segments, False otherwise """ segment_start, segment_end = segment_time overlap = False for previous_start, previous_end in previous_segments: if segment_start <= previous_end and segment_end >= previous_start: overlap = True return overlap
def check_description_length(description): """Check description length""" if description is None or str(type(description)) == str(type(0)): return 0.0 try: size_description = len(description) except Exception as e: print(e, ) print("Erro", description) exit() return size_description
def is_chinese(lang): """ include additional languages due to mistakes on short texts by langdetect """ return lang is not None and lang.startswith('zh-') or lang in ['ja', 'ko']
def percentage(string, total): """ Calculate the percentage of code in an string. :param string: The string to operate on :param total: The total depending on what you base your percentage :return: The percentage of code in the string """ code_presence = 0 code_percentage = 0 for i in range(0, total): if string[i] is not '0' or None: code_presence += int(string[i]) if code_presence is not 0: code_percentage = (code_presence / total) * 100 return code_percentage
def canonical_names_from_filenames(db, filenames): """Convert filenames to the canonical form :Parameters: `db` : remembercases.TestbedEntityPropDB `filenames` : iterable yielding filenames :return: A list expressing the filenames in the canonical form. The canonical form is the relative path from the basepath in the db's default_tesbed, with dir separators always '/' irrespective of os.sep A typical example transformation is:: ..\..\test\test_base.py -> test\test_base.py """ return [ db.canonical_fname(s) for s in filenames ]
def dipole_v(ele): """ dipole Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 # Get file integer f = ele['filename'] ii = int(f.split('rfdata')[1]) v = [ele, ele['zedge'], ele['b_field_x'], ele['b_field'], ii, ele['half_gap'] ] return v
def _base_name(full_name: str) -> str: """Strips a fully qualified Java class name to the file scope. Examples: - "A.B.OuterClass" -> "OuterClass" - "A.B.OuterClass$InnerClass" -> "OuterClass$InnerClass" Args: full_name: Fully qualified class name. Returns: Stripped name. """ return full_name.split(".")[-1]
def sanitize_text(text, **kwargs): """ See how many spaces on the first line, and remove those for all the rest, so the visual indent is kept """ lines = text.split('\n') if len(lines) == 0: return '' # Skip first white line if len(lines[0]) == 0: del lines[0] n_spaces = 0 for c in lines[0]: if c.isspace(): n_spaces += 1 else: break return "\n".join(map(lambda l: l[n_spaces:], lines)) % kwargs
def is_workday(x): """ Returns if day is workday""" if x <= 4: return 1 else: return 0