content
stringlengths
42
6.51k
def _check_remove_item(the_list, item): """Helper function for merge_lists that implements checking wether an items should be removed from the list and doing so if needed. Returns ``True`` if the item has been removed and ``False`` otherwise.""" if not isinstance(item, str): return False if not item.startswith('~'): return False actual_item = item[1:] if actual_item in the_list: del the_list[the_list.index(actual_item)] return True
def _shorten(s, n=100): """Shorten string s to at most n characters, appending "..." if necessary.""" if s is None: return None if len(s) > n: s = s[:n-3] + '...' return s
def convert_bool_str(input_string): """ Helper to convert a string representation of a boolean to a real bool(tm). """ if input_string.lower() in ('1', 'true'): return True return False
def slice_nested(l, slice_pos, slice_size): """ Slice the nested list :param l: a nested list :param slice_pos: a 2-tuple (x, y) of slice start :param slice_size: a 2-tuple (width, height) of slice size """ r = [] for y in range(slice_pos[1], slice_pos[1] + slice_size[1]): line = [] for x in range(slice_pos[0], slice_pos[0] + slice_size[0]): line.append(l[y][x]) r.append(line) return r
def clean_mentions(msg): """Prevent discord mentions""" return msg.replace("@", "@\u200b")
def dec(val, encoding='utf-8'): """ Decode given bytes using the specified encoding. """ import sys if isinstance(val, bytes) and sys.version_info > (3, 0): val = val.decode(encoding) return val
def isGColRequired(config, num): """A quick helper function that checks whether we need to bother reading the g1,g2 columns. It checks the config dict for the output file names gg_file_name, ng_file_name (only if num == 1), etc. If the output files indicate that we don't need the g1/g2 columns, then we don't need to raise an error if the g1_col or g2_col is invalid. This makes it easier to specify columns. e.g. for an NG correlation function, the first catalog does not need to have the g1,g2 columns, and typically wouldn't. So if you specify g1_col=5, g2_col=6, say, and the first catalog does not have these columns, you would normally get an error. But instead, we check that the calculation is going to be NG from the presence of an ng_file_name parameter, and we let the would-be error pass. Parameters: config (dict): The configuration file to check. num (int): Which number catalog are we working on. Returns: True if some output file requires this catalog to have valid g1/g2 columns, False if not. """ return config and ( 'gg_file_name' in config or 'm2_file_name' in config or (num==1 and 'norm_file_name' in config) or (num==1 and 'ng_file_name' in config) or (num==1 and 'nm_file_name' in config) or (num==1 and 'kg_file_name' in config) )
def urandom(num_bytes): """ urandom returns a bytes object with n random bytes generated by the hardware random number generator. """ import os return os.urandom(num_bytes)
def multi_bracket_validation(input_str): """this function take in a string and return a value true or false base on if the brackets are balance or not Args: input_str ([type]): [description] Returns: [type]: [description] """ #checks a base case to reduce computing where not needed if len(input_str) % 2 is not 0: return False opens = tuple('({[') closed = tuple (')}]') mapped = dict(zip(opens,closed)) # creates a dictionary with key value pairs setting keys to first arguement and value to second # print(map) helper = [] for char in input_str: if char in opens: helper.append(mapped[char]) elif char in closed: if not helper or char != helper.pop(): return False return not helper
def _apply_presets(preset_dict, *args, **kwargs): """ Pair with `unpack` to alter input arguments with preset values. """ if 'presets' in kwargs: presets = kwargs['presets'] if presets is None: return kwargs if not isinstance(presets, list): presets = [presets] preset_kwargs = {} for preset in presets: if isinstance(preset, str): preset_orig = preset preset = preset_dict.get(preset, None) if preset is None: raise ValueError(f'Preset \'{preset_orig}\' was not found. Valid presets: {list(preset_dict.keys())}') if isinstance(preset, dict): for key in preset: preset_kwargs[key] = preset[key] else: raise TypeError(f'Preset of type {type(preset)} was given, but only presets of type [dict, str] are valid.') for key in preset_kwargs: if key not in kwargs: kwargs[key] = preset_kwargs[key] return args, kwargs
def sqlite_table_foreign_keys(c=None, table=None): """ """ db_fk = [] if c is not None and table is not None: c.execute('PRAGMA foreign_key_list({0})'.format(table)) rows = c.fetchall() for r in rows: db_fk.append(r) return db_fk
def _jobpair_satisfies_filters(jp, failed_job_id, passed_job_id): """ Not currently used. True if the jobpair meets the filters indicated by the presence of the -p and -f arguments. """ # Always include if no job ID filters provided. if not failed_job_id and not passed_job_id: return True f_id_matches = jp['failed_job']['job_id'] == failed_job_id p_id_matches = jp['passed_job']['job_id'] == passed_job_id # Include if both job ID filters are provided and satisfied. if failed_job_id and passed_job_id and f_id_matches and p_id_matches: return True # Include if the failed job ID filter is provided and satisfied. if failed_job_id and f_id_matches: return True # Include if the failed job ID filter is provided and satisfied. if passed_job_id and p_id_matches: return True # Otherwise, exclude. return False
def create_ib_tuple(instrument): """ create ib contract tuple """ # tuples without strike/right if len(instrument) <= 7: instrument_list = list(instrument) if len(instrument_list) < 3: instrument_list.append("SMART") if len(instrument_list) < 4: instrument_list.append("USD") if len(instrument_list) < 5: instrument_list.append("") if len(instrument_list) < 6: instrument_list.append(0.0) if len(instrument_list) < 7: instrument_list.append("") try: instrument_list[4] = int(instrument_list[4]) except Exception as e: pass instrument_list[5] = 0. if isinstance(instrument_list[5], str) \ else float(instrument_list[5]) instrument = tuple(instrument_list) return instrument
def hostport(scheme, host, port): """ Returns the host component, with a port specifcation if needed. """ if (port, scheme) in [(80, "http"), (443, "https")]: return host else: return "%s:%s"%(host, port)
def read_file(filename, alt=None): """ Read the contents of filename or give an alternative result instead. """ lines = None try: with open(filename, encoding='utf-8') as f: lines = f.read() except IOError: lines = [] if alt is None else alt return lines
def path_to_module_format(py_path): """Transform a python file path to module format.""" return py_path.replace("/", ".").rstrip(".py")
def index_to_feature(p, dims): """convert index form (single integer) to feature form (vector)""" feature = [] for dim in dims: feature.append(p % dim) p //= dim return feature
def max_number(number: int) -> int: """Returns number starting from the largest item. Args: number (int): input number Examples: >>> assert max_number(132) == 321 """ return int("".join(sorted(tuple(str(number)), reverse=True)))
def error(text, error_code): """Returns the error in json format Keyword arguments: text -- Human readable text for the error error_code -- http status code """ return '{{"Error": "{}"}}'.format(text), error_code
def reader_filepath(sample, filename, pathfunc): """ Construct filepath from sample, filename and/or pathfunction. Helper function used in ReadImage and ReadNumpy. :param tuple|list sample: E.g. ('nut_color', 1) :param filename: :param string|function|None pathfunc: Filepath with wildcard '*', which is replaced by the file id/name provided in the sample, e.g. 'tests/data/img_formats/*.jpg' for sample ('nut_grayscale', 2) will become 'tests/data/img_formats/nut_grayscale.jpg' or Function to compute path to image file from sample, e.g. lambda sample: 'tests/data/img_formats/{1}.jpg'.format(*sample) or None, in this case the filename is taken as the filepath. :return: """ if isinstance(pathfunc, str): return pathfunc.replace('*', filename) if hasattr(pathfunc, '__call__'): return pathfunc(sample) return filename
def get_unscanned_account_error(graph_dict): """Returns the error message stored in the graph dictionary generated by Altimeter as the result of getting an error trying to scan one account.""" vertices = graph_dict["vertices"] for v in vertices: if v["~label"] == "error" and "error" in v: return v["error"] return "unknown error"
def rivers_with_stations(stations): """Get names of rivers with an associated monitoring station. Parameters ---------- stations : list[MonitoringStation] generated using build_station_list. Returns ------- output : set A set containing the names of all the rivers with a monitoring station. """ output = set() for station in stations: # if the station has a river, add to the set if station.river: output.add(station.river) return output
def fib(n): """ :param n: :return: """ if n == 1 or n == 2: return 1 n1 = n - 1 n2 = n - 2 fibr1 = fib(n1) fibr2 = fib(n2) res = fibr1 + fibr2 return res
def square_matrix(square): """ This function will calculate the value x (i.e. blurred pixel value) for each 3 * 3 blur image. """ tot_sum = 0 # Calculate sum of all the pixels in 3 * 3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] return tot_sum // 9 # return the average of the sum of pixels
def qr_to_cube(p): """Convert axial coordinates to cube in q-type hexagonal grid.""" q, r = p x, y, z = q, -q-r, r return x, y, z
def filename_to_domain(filename): """[:-4] for the .txt at end """ return filename.replace('-', '/')[:-4]
def _join_package_name(ns, name): """ Returns a app-name in the 'namespace/name' format. """ return "%s/%s" % (ns, name)
def bytes_to_hex_str(data): """ converts a sequence of bytes into its displayable hex representation, ie: 0x?????? :param data: byte sequence :return: Hexadecimal displayable representation """ return "0x" + "".join(format(b, "02x") for b in data)
def inrange(value, bits): """ Test if a signed value can be fit into the given number of bits """ upper_limit = 1 << (bits - 1) lower_limit = -(1 << (bits - 1)) return value in range(lower_limit, upper_limit)
def serialise_matched_reference(data, current_timestamp): """Serialise the data matched by the model.""" serialised_data = { 'publication_id': data['WT_Ref_Id'], 'cosine_similarity': data['Cosine_Similarity'], 'datetime_creation': current_timestamp, 'document_hash': data['Document id'] } return serialised_data
def mySqrt(x): """ :type x: int :rtype: int """ if x < 2: return x i = round(x / 2) prev = x keep_looping = True while keep_looping: test = i * i if test == x: break if (prev * prev) < x and test > x: i = prev break if test > x: prev = i if abs(prev - i) < 5: i -= 1 else: i = round(i / 2) else: prev = i if abs(prev - i) < 5: i += 1 else: i += round(i / 2) return int(round(i))
def invperm(perm): """Returns the inverse permutation.""" inverse = [0] * len(perm) for i, p in enumerate(perm): inverse[p] = i return inverse
def parse_args(given, control): """checks if some of the given args are valid for a condition""" pairs = [(x, y) for x in given for y in control] for g, c in pairs: if g == c: return True return False
def parse_score_qa(output, metric, digits=4): """Function for parsing the output from `pyserini.eval.evaluate_dpr_retrieval`. Currently, the implementation is the same as `parse_score_msmacro`, but we're keeping separate in case they diverge in the future.""" for line in output.split('\n'): if metric in line: score = float(line.split()[-1]) return round(score, digits) return None
def return_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it is easier to parse the message over the wire. Final character is never replaced. This function returns them to their original form. '\x1b\x0e' -> '\x0d' '\x1b\x1b' -> '\x1b' '\x1b\x0f' -'\x8d' It is important to only do one pass as the first pass can result in new combinations of escape sequence. Ex '\x1b\x1b\x0e' -> '\x1b\x0e' """ in_data = bytearray(data) out = bytearray() while in_data: byte = in_data.pop(0) if byte == 0x1B: next_byte = in_data.pop(0) if next_byte == 0x0E: out.append(0x0D) elif next_byte == 0x1B: out.append(0x1B) elif next_byte == 0x0F: out.append(0x8D) else: out.append(byte) out.append(next_byte) else: out.append(byte) return bytes(out)
def last_delta(x): """difference between 2 last elements""" return x[-1]-x[-2]
def is_odd(x: int) -> bool: """ ARGS: integer RETURNS: true if integer is odd """ if x % 2 == 0: return False else: return True
def prepare_data(song: dict) -> dict: """ Prepares song dataa for database insertion to cut down on duplicates :param song: Song data :return: The song data """ song['artist'] = song['artist'].upper().strip() song['title'] = song['title'].upper().strip() return song
def optional_f(text): """Method for parsing an 'optional' generalized float.""" if text: return float(text) else: return None
def get_rule_bypass_line(rule_id): """ Get the coniguration line to use to bypass a ModSecurity rule. Args: rule_id - The numerical id of the ModSecurity rule """ return "SecRuleRemoveById " + rule_id
def _escape_filename(filename): """Escapes spaces in the given filename, Unix-style.""" return filename.replace(" ", "\\ ")
def _escape(value): """ This function prevents header values from corrupting the request, a newline in the file name parameter makes form-data request unreadable for majority of parsers. """ if not isinstance(value, (bytes, str)): value = str(value) if isinstance(value, bytes): value = value.decode('utf-8') return value.replace(u"\r", u"").replace(u"\n", u"").replace(u'"', u'\\"')
def info_header(label): """Make a nice header string.""" return "--{:-<60s}".format(" "+label+" ")
def get_label_map(label_list): """ Create label maps """ label_map = {} for (i, l) in enumerate(label_list): label_map[l] = i return label_map
def return_first_list_present_only(xs, ys): """ merge sorted lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 while True: if xi >= len(xs): return result if yi >= len(ys): result.append(xs[yi:]) return result if xs[xi] < ys[yi]: result.append(xs[xi]) xi += 1 elif xs[xi] == ys[yi]: xi += 1 else: yi += 1
def normalize_path(path): """normalize path """ path = path.strip('/') return '/' + path
def format_duration(duration): """Given a duration in minutes, return a string on the format h:mm. >>> format_duration(75) '1:15' >>> format_duration(4) '0:04' >>> format_duration(601) '10:01' """ h = duration // 60 m = duration % 60 return f"{h}:{m:02}"
def clname_from_lastchar_cb(full_path): """Callback for changelist_all_files() that returns a changelist name matching the last character in the file's name. For example, after running this on a greek tree where every file has some text modification, 'svn status' shows: --- Changelist 'a': M A/B/lambda M A/B/E/alpha M A/B/E/beta M A/D/gamma M A/D/H/omega M iota --- Changelist 'u': M A/mu M A/D/G/tau --- Changelist 'i': M A/D/G/pi M A/D/H/chi M A/D/H/psi --- Changelist 'o': M A/D/G/rho """ return full_path[-1]
def data_gen(list_length): """ >>> data_gen(3) {'numbers_list': [0, 1, 2]} >>> data_gen(7) {'numbers_list': [0, 1, 2, 3, 4, 5, 6]} """ numbers_list = [number for number in range(list_length)] return {"numbers_list" : numbers_list}
def getid(obj): """ Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def _patch_header(header, ebcdic=False): """ Helper function to patch a textual header to include the revision number and the end header mark. """ revnum = "C39 SEG Y REV1" if ebcdic: revnum = revnum.encode("EBCDIC-CP-BE") end_header = "C40 END EBCDIC ".encode("EBCDIC-CP-BE") else: revnum = revnum.encode("ascii") end_header = "C40 END TEXTUAL HEADER".encode("ascii") header = header[:3200-160] + revnum + header[3200-146:] header = header[:3200-80] + end_header + header[3200-58:] return header
def DES3028(v): """ DES-3028-series :param v: :return: """ return v["platform"].startswith("DES-3028")
def getstorypoint(title): """Function that will get in the title the first characters as storypoints :param title: Card title :return: """ tmp = "" for l in title: if l in [".", ",", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]: tmp += l else: break try: return float(tmp) except ValueError: return 0
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale """ return round(float(fahrenheit)+ 459.7, ndigits)
def container_elem_type(container_type, params): """ Returns container element type :param container_type: :param params: :return: """ elem_type = params[0] if params else None if elem_type is None: elem_type = container_type.ELEM_TYPE return elem_type
def is_module_available(module_name): """Return True if Python module is available""" try: __import__(module_name) return True except ImportError: return False
def p(text: str) -> str: """Wrap text into an HTML `p` tag.""" return f"<p>{text}</p>"
def append_unless(unless, base, appendable): """ Conditionally append one object to another. Currently the intended usage is for strings. :param unless: a value of base for which should not append (and return as is) :param base: the base value to which append :param appendable: the value to append to base :return: base, if base == unless; base + appendable, otherwise. """ return base if base == unless else base + appendable
def typed_line(line, parser): """Parse one line of the dataset into a typed (user, item, rating) triplet.""" user, item, rating = parser(line) return int(user), int(item), float(rating)
def check_miss_numbers(number_string: str) -> list: """[summary] Args: number_string (str): [Phone Number For Cheack] Returns: list: [The Mising Numbers In Phone Numbers] """ miss_numbers = [] orginals_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers = [int(i) for i in number_string] for check in orginals_numbers: if check in numbers: pass else: miss_numbers.append(check) return miss_numbers
def get_larger_channel(channel_range, channel_num): """ get channels which is larger than inputs :param channel_range: list,channel range :param channel_num: input channel :return: list,channels which is larger than inputs """ result = filter(lambda x: x >= channel_num, channel_range) return list(result)
def clamp(val, min, max): """ Clamps values that are too high or too low to the min or max """ if val > max: val = max elif val < min: val = min return val
def find_period(samples_second): """ # Find Period Args: samples_second (int): number of samples per second Returns: float: samples per period divided by samples per second """ samples_period = 4 return samples_period / samples_second
def get_ranges_or_indices_in_name(name): """ recursive function that eventually collects all the list ranges/list indices in the specified component name""" exisiting_ranges = [] start_idx = name.find('[') end_idx = name.find(']') range = name[start_idx + 1: end_idx] if '..' in range: range_start = int(range.split('..')[0]) range_end = int(range.split('..')[1]) val = (range_start, range_end) else: val = int(range) exisiting_ranges.append(val) subname = name[end_idx+1:] if '[' and ']' not in subname: return exisiting_ranges else: for val in get_ranges_or_indices_in_name(subname): exisiting_ranges.append(val) return exisiting_ranges
def aws_ok(resp): """ Return true if response status is ok """ if resp['ResponseMetadata']['HTTPStatusCode'] == 200: return True return False
def while_lower_bound(lower): """ t_while """ rval = lower while rval < 100: rval = rval * rval return rval
def get_enum(s, enum_class): """Get an enum from a string where the enum class is assumed to have all upper-case keys, returning None if the key is not found. Args: s (str): Key of enum to find, case-insensitive. enum_class (:class:`Enum`): Enum class to search. Returns: The enum if found, otherwise None. """ enum = None if s: s_upper = s.upper() try: enum = enum_class[s_upper] except KeyError: pass return enum
def mendProcess(result, file1, file2, wordsNumber): """ take every match location in 'result' list and get sure there is no sub-text of length(wordsNumber) matched get ignored. """ def searchPointInMatch(point, file): for position in reversed(result): if point >= position[file][0] and point <= position[file][1]: return True else: return False for position in reversed(result): for i in range(wordsNumber, 0, -1): if searchPointInMatch(position[0][1] + i, 0) or searchPointInMatch(position[1][1] + i, 1): continue text1 = file1[position[0][1] + 1 : position[0][1] + i + 1] text2 = file2[position[1][1] + 1 : position[1][1] + i + 1] if not text1 or not text2: break if text1 == text2: position[0][1] += i position[1][1] += i break return result
def indent_string(string, chars): """Indents a string by x number of characters.""" indented_string = '' for line in string.splitlines(): indented_string += '%s%s\n' % ((' ' * chars), line) # Strip the ending '\n' and return result. return indented_string[0:-1]
def get_vms(app, scope='deployment'): """Return the VMs in an application.""" return app.get(scope, {}).get('vms', [])
def kappa(A: float, B: float, C: float): """ Calculate Ray's asymmetry parameter for a given set of A, B, and C rotational constants. This parameter determines how asymmetric a molecule is by setting a range between two limits: the prolate (+1) and the oblate (-1) limits. Parameters ---------- A, B, C: float Rotational constant in MHz for each respective axis Returns ------- kappa: float Ray's asymmetry parameter """ return (2 * B - A - C) / (A - C)
def retifyxxyysize(img_height, img_width, xxyy): """return xxyy within image region img_height: img_width: xxyy: return xxyy """ xxyy[0] = max(xxyy[0], 0) xxyy[1] = max(xxyy[1], 0) xxyy[2] = max(xxyy[2], 0) xxyy[3] = max(xxyy[3], 0) xxyy[0] = min(xxyy[0], img_width) xxyy[1] = min(xxyy[1], img_width) xxyy[2] = min(xxyy[2], img_height) xxyy[3] = min(xxyy[3], img_height) return xxyy
def wire_plotter(wire_code, current_location): """Accepts code list and current location (tuple). Returns list of tuples of locations.""" new_locations = [] if wire_code[0] == 'U': upper_value = int(wire_code[1:]) for i in range(1, upper_value+1): new_locations.append( (current_location[0], current_location[1] + i) ) current_location = ( current_location[0], current_location[1] + upper_value) elif wire_code[0] == 'L': left_value = int(wire_code[1:]) for i in range(1, left_value+1): new_locations.append( (current_location[0] - i, current_location[1]) ) current_location = ( current_location[0] - left_value, current_location[1]) elif wire_code[0] == 'D': down_value = int(wire_code[1:]) for i in range(1, down_value+1): new_locations.append( (current_location[0], current_location[1] - i) ) current_location = ( current_location[0], current_location[1] - down_value) elif wire_code[0] == 'R': right_value = int(wire_code[1:]) for i in range(1, right_value+1): new_locations.append( (current_location[0] + i, current_location[1] )) current_location = ( current_location[0] + right_value , current_location[1]) else: print('And I oop') return { 'locations': new_locations, 'current': current_location}
def parseLinksList(links, weighted, resdub): """Parse node links in Pajek format links - links string: <did1> <did2> ... weighted - generate weighted / unweighted links resdub - resolve dublicates return [(dest_id, weight), ...] """ links = links.split() if weighted: if resdub: links = {v: '1' for v in links} else: links = [(v, '1') for v in links] elif resdub: links = list(set(links)) return links
def _iterable_has_any(itr, *items): """Test if an interable includes all of `items` (by equality). >>> _iterable_has_any((1, 2, 3), 1, 3) True >>> _iterable_has_any((1, 2, 3), 1, 4) True """ for item in itr: if item in items: return True return False
def partition(start, end, cores): """Split a range into (exactly or almost) parts Args: start (int): The first index of the range. end (int): The last index of the range. cores (int): The number of parts to split into. Returns: :obj:`list` of :obj:`list` of :obj:`int`: The list of lists, where each inner list contains starting and ending index of a single part. Examples: >>> print(0, 100, 3) [[0, 33], [34, 67], [68, 100]] >>> print(10, 49, 4) [[10, 19], [20, 29], [30, 39], [40, 49]] """ dn = round((end - start + 1) / cores) parts = [] parts += [[start, start + dn - 1]] parts += [[start + dn*(i-1), start + i*dn - 1] for i in range(2, cores)] parts += [[start + (cores-1)*dn, end]] return parts
def _get_match(proto, filter_fn): """Finds and returns the first element that matches a query. If no element matches the query, it throws ValueError. If more than one element matches the query, it returns only the first. """ query = [elm for elm in proto if filter_fn(elm)] if len(query) == 0: raise ValueError('Could not find element') elif len(query) > 1: raise ValueError('Too many matches') return query[0]
def getPathValues(d, path): """ Given a nest structure, return all the values reference by the given path. Always returns a list. If the value is not found, the list is empty NOTE: Processing a list is its own recursion. """ pos = path.find('.') currentpath = path[0:pos] if pos > 0 else path nextpath = path[pos + 1:] if pos > 0 else None lbracket = path.find('[') itemnum = None if lbracket >= 0 and (pos < 0 or lbracket < pos): rbracket = path.find(']') itemnum = int(path[lbracket + 1:rbracket]) currentpath = path[0:lbracket] # keep the bracket for the next recurive depth nextpath = path[lbracket:] if lbracket > 0 else nextpath if type(d) is list: result = [] if itemnum is not None: result.extend(getPathValues(d[itemnum], nextpath)) else: for item in d: # still on the current path node result.extend(getPathValues(item, path)) return result if pos < 0: if currentpath == '*': result = [] for k, v in d.iteritems(): result.append(v) return result return [d[currentpath]] if currentpath in d and d[currentpath] else [] else: if currentpath == '*': result = [] for k, v in d.iteritems(): result.extend(getPathValues(v, nextpath)) return result return getPathValues(d[currentpath], nextpath) if currentpath in d else []
def check_bit_set(value: int, bit: int): """ Simple function to determine if a particular bit is set eg (12 - binary 1100) then positions 3 and 4 are set :param value: Number to be tested :param bit: Position to check; >0 (right to left) :return: Bool: True if bit is set """ if value & (1 << (bit - 1)): return True
def get_corr_reg_name(curr_name: str) -> str: """ Function that corrects wrong regions names """ # Specjalny wyjatek, bo w danych PRG jest powiat "JELENIOGORSKI", a od 2021 roku powiat ten nazywa sie "KARKONOSKI", # wiec trzeba to poprawic if curr_name == "JELENIOGORSKI": return "KARKONOSKI" # Kolejny wyjatek, bo w danych PRG jest gmina "SITKOWKA-NOWINY", a od 2021 roku gmina ta nazywa sie "NOWINY", wiec # trzeba to poprawic elif curr_name == "SITKOWKA-NOWINY": return "NOWINY" # Kolejny wyjatek, bo w danych PRG jest gmina "SLUPIA (KONECKA)", a od 2018 roku gmina ta nazywa sie # "SLUPIA KONECKA", wiec trzeba to poprawic elif curr_name == "SLUPIA (KONECKA)": return "SLUPIA KONECKA" else: return curr_name
def getletter(variable, letternumber): """ Get the corresponding item in a object :type variable: string :param variable: The string to get the letter from :type letternumber: integer :param letternumber: The index of the letter to get """ # Get the corresponding letter return str(variable)[letternumber - 1]
def surroundings(center, radius, domains): """ The surroundings of a `center` is a list of new centers, all equal to the center except for one value that has been increased or decreased by `radius`. """ return [center[0:i] + (center[i] + d,) + center[i + 1:] for i in range(len(center)) for d in (-radius, +radius) if center[i] + d >= domains[i][0] and center[i] + d <= domains[i][1] ]
def dict_match(a, b): """ Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False """ res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return all(res)
def partition_first(array, start, end): """Selects the first element as pivot. Returns the index where the pivot went to. In this variant, we can guarantee that the pivot will be in its final sorted position. We need this guarantee for QuickSelect.""" if start + 1 == end: return start pivot = array[start] pivot_index = start + 1 for i in range(start + 1, end): if array[i] <= pivot: array[i], array[pivot_index] = array[pivot_index], array[i] pivot_index += 1 # Move pivot to front array[start], array[pivot_index - 1] = array[pivot_index - 1], array[start] return pivot_index - 1
def count_snps(transform, count_indels_once=False): """ Counts the SNPs (technically, the number of variant bases) from a reference by a read's "transform". :param transform: :return: the number of bases different from a reference sequence as represented in the provided transform. """ if count_indels_once: return len(transform) else: count = 0 for op in transform: if op[1] in "S": count += 1 elif op[1] == "I": count += len(op[2]) elif op[1] == "D": count += op[2] else: raise ValueError("Transform contained invalid operation: %s" % op[1]) return count
def _get_protocol_tuple(data): """Convert a dictionary to a tuple. :param dict data: :rtype: tuple[str,list,dict] """ return data['function'], data.get('args', []), data.get('kwargs', {})
def _after_each(separator, iterable): """Inserts `separator` after each item in `iterable`. Args: separator: The value to insert after each item in `iterable`. iterable: The list into which to intersperse the separator. Returns: A new list with `separator` after each item in `iterable`. """ result = [] for x in iterable: result.append(x) result.append(separator) return result
def filterSubjects(subjectList, filterUsing='equals') : """Return a natsListener filter which will filter NATS messages on the subjects by returning True on either of the following conditions: - `equals`: return True if the message subject is *equal* to any subject in the subjectList. - `startsWith`: return True if the message subject *starts with* any subject in the subjectList. """ if not subjectList : return None if filterUsing == 'equals' : def filterMessage(theSubject, theMessage) : return theSubject in subjectList return filterMessage if filterUsing == 'startsWith' : def filterMessage(theSubject, theMessage) : for aSubject in subjectList : if theSubject.startswith(aSubject) : return True return False return filterMessage return None
def sign(x): """ Returns the sign of x. :param x: A scalar x. :return: The sign of x \in (+1, -1, 0). """ if x > 0: return +1 elif x < 0: return -1 elif x == 0: return 0
def Eq(field, value): """ A criterion used to search for a equality. For example * search for TLP = 2 * search for flag = True * search for title = 'Sample case' Arguments: field (value): field name value (Any): field value Returns: dict: JSON repsentation of the criterion ```python query = Eq('tlp', 3) ``` produces ```json {"_field": "tlp", "_value": 3} ``` """ return {'_field': field, '_value': value}
def remove_docstart_sentence(sentences): """Remove -DOCSTART- sentences in the list of sentences. Parameters ---------- sentences: List[List[TaggedToken]] List of sentences, each of which is a List of TaggedTokens. This list may contain DOCSTART sentences. Returns ------- List of sentences, each of which is a List of TaggedTokens. This list does not contain DOCSTART sentences. """ ret = [] for sentence in sentences: current_sentence = [] for token in sentence: if token.text != '-DOCSTART-': current_sentence.append(token) if len(current_sentence) > 0: ret.append(current_sentence) return ret
def human_size(size_bytes): """ Return a human size readable from bytes >>> human_size(906607633) '864.61 MB' :param size_bytes: bytes to transform :return: string in human readable format. """ if size_bytes is 0: return "0B" def ln(x): n = 99999999 return n * ((x ** (1/n)) - 1) def log(x, base): result = ln(x)/ln(base) return result exp = int(log(size_bytes, 1024)) try: unit = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")[exp] except KeyError: unit = "YB" return "{} {}".format(round(size_bytes / (1024 ** exp), 2), unit)
def encode_null_terminated(s: str, encoding: str, errors: str = 'strict') -> bytes: """Encodes s using the given encoding, adding a zero character to the end if necessary. No attempt is made to detect a zero character before the end of the string, so if given a string like 'a\\0b', this will generate the string 'a\\0b\\0' and encode that. """ if not s.endswith('\0'): s += '\0' return s.encode(encoding, errors)
def normalized_total_time(p, max_time=3600000 * 5): # by default 5 h (in ms) """If time was longer than max_time, then return max_time, otherwise return time.""" if p["result.totalTimeSystem"] == "3600.0": v = 3600000 # convert to ms (error in logging) else: v = int(float(p["result.totalTimeSystem"])) return max_time if v > max_time else v
def fnCalc_ApogeePerigee(a,e): """ Calculate the apogee and perigee of a space-object based on the semi-major axis a and the eccentricity e. Created: 07/04/17 Added here: 11/04/17 """ perigee = a*(1.-e); apogee = a*(1.+e); return perigee, apogee
def format_bytes(num): """Convert bytes to KB, MB, GB or TB""" step_unit = 1024 for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < step_unit: return "%3.1f %s" % (num, x) num /= step_unit
def print_scientific_16(value: float) -> str: """ Prints a value in 16-character scientific notation. This is a sub-method and shouldnt typically be called .. seealso:: print_float_16 for a better method """ if value == 0.0: return '%16s' % '0.' python_value = '%16.14e' % value # -1.e-2 svalue, sexponent = python_value.strip().split('e') exponent = int(sexponent) # removes 0s if abs(value) < 1.: sign = '-' else: sign = '+' # the exponent will be added later... sexp2 = str(exponent).strip('-+') value2 = float(svalue) # the plus 1 is for the sign len_sexp = len(sexp2) + 1 leftover = 16 - len_sexp if value < 0: fmt = "%%1.%sf" % (leftover - 3) else: fmt = "%%1.%sf" % (leftover - 2) svalue3 = fmt % value2 svalue4 = svalue3.strip('0') field = "%16s" % (svalue4 + sign + sexp2) return field
def trim_shared_prefix(ref, alt): """ Sometimes mutations are given with a shared prefix between the reference and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids). This function trims the common prefix and returns the disjoint ref and alt strings, along with the shared prefix. """ n_ref = len(ref) n_alt = len(alt) n_min = min(n_ref, n_alt) i = 0 while i < n_min and ref[i] == alt[i]: i += 1 # guaranteed that ref and alt agree on all the characters # up to i'th position, so it doesn't matter which one we pull # the prefix out of prefix = ref[:i] ref_suffix = ref[i:] alt_suffix = alt[i:] return ref_suffix, alt_suffix, prefix
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'): """Finds characters in text. Useful to preprocess text. Do not forget to escape special characters. """ return rf'[{chars}]'
def unsquish(selected, unadapted_data): """Transform our selected squished text back to the original text selected: the selected sentences unadapted_data: the list of original unadapted sentences returns: the selected sentences, with clear text """ for i, line in enumerate(selected): items = line.split('\t') items[8] = unadapted_data[int(items[5]) - 1] selected[i] = '\t'.join(items) return selected