content
stringlengths
42
6.51k
def highlight(colour, text): """ Highlight - highlights text in shell. """ """ Returns plain if colour doesn't exist. """ if colour == "black": return "\033[1;40m" + str(text) + "\033[1;m" if colour == "red": return "\033[1;41m" + str(text) + "\033[1;m" if colour == "green": ...
def seconds_readable(seconds): """Converts an integer number of seconds to hours, minutes, and seconds. Parameters ---------- seconds : integers; number of seconds to be converted. Returns ------- converted : integer tuple, size 3; (h, m, s) where the arguments are the time...
def includes(collection, target, from_index=0): """Checks if a given value is present in a collection. If `from_index` is negative, it is used as the offset from the end of the collection. Args: collection (list|dict): Collection to iterate over. target (mixed): Target value to compare to. ...
def fatorial(a, show=False): """ Calcula o fatorial do valor param: a: valor a ser calculado param: show: (bool opcional) mostra o calculo return: resultado no fatorial """ f = 1 for i in range(a, 0, -1): f *= i if show: if i == 1: ...
def fermat(num): """Runs a number through 1 simplified iteration of Fermat's test.""" if ((2 ** num) - 2) % num == 0: return True else: return False
def binary_search(arr, element, low=0, high=None): """Returns the index of the given element within the array by performing a binary search.""" if high == None: high = len(arr) - 1 if high < low: return -1 mid = (high + low) // 2 if arr[mid] == element: return mid el...
def clean_snippet(snippet_value): """Only return the snippet value if it looks like there is a match in the snippet. """ # Snippets are always returned from the search API, regardless of whether # they match the query or not, so the only way to tell if they matched is # ...to look for the "<b>" ...
def add_ending(new_txt, txt): """Adds a trailing return if the original text had one.""" if txt.endswith('\n'): new_txt = "%s\n" % new_txt if txt.endswith('\r'): new_txt = "%s\r" % new_txt return new_txt
def get_instance_keys(class_instance): """Get the instance keys of a class""" return [key for key in vars(class_instance) if key[:1] != "_"]
def extract_key(obj, target): """Recursively fetch values from nested JSON. Args: obj ([dict]): an arbitrarily nested dictionary with environemt variables target (str): The target key we want to extract Returns: (str | dict): target key can have a string or anothe...
def oxfordize_list(strings): """Given a list of strings, formats them correctly given the length of the list. For example: oxfordize_list(['A']) => 'A' oxfordize_list(['A', 'B']) => 'A and B' oxfordize_list(['A', 'B', 'C']) => 'A, B, and C' """ if len(strings) == 0: ...
def get_export_initialize_vars(database, port, connection_string): """ Gets the shell script that persists the Forseti env variables. """ template = """ export SQL_PORT={}\n export SQL_INSTANCE_CONN_STRING="{}"\n export FORSETI_DB_NAME="{}"\n """ return template.format(port, con...
def _permutation_parity(perm): """computes parity of permutation in O(n log n) time using cycle decomposition""" n = len(perm) not_visited = set(range(n)) i = perm[0] c = 1 while len(not_visited) > 0: if i in not_visited: not_visited.remove(i) else: c += 1...
def get_match_files(git_pattern: str) -> bool: """ If there is a separator at the end of the pattern then the pattern will match directories and their contents, otherwise the pattern can match both files and directories. >>> assert get_match_files('') >>> assert get_match_files('/something') ...
def get_att_index(poly, att): """Returns index of given attribute if found""" j = 0 if isinstance(poly[2], type(None)): return None for _att in poly[2]: if _att[0] == att[0]: return j j += 1 return None
def isNum(s) -> bool: """ Checks if its a number >>> isNum("1") True >>> isNum("-1.2") True >>> isNum("1/2") True >>> isNum("3.9/2") True >>> isNum("3.9/2.8") True >>> isNum("jazz hands///...") False """ if "/" in str(s): s = s.replace("/", "", 1) ...
def biggest_bbox(bbox1: list, bbox2: list) -> list: """ given two bounding boxes, return a bbox encompassing both. if either inputs is an empty list, returns the other one """ if len(bbox1) < 4: return bbox2 if len(bbox2) < 4: return bbox1 return ([bbox1[0] if bbox1[0] < bbox2[0] els...
def cround(val): """ Rounds a complex number Parameters ---------- val: complex Returns ------- complex """ return complex(round(val.real), round(val.imag))
def dl_ia_utils_check_folder(path_folder): """ check that exists a folder, and if not, create it :param path_folder: string with the path :return error: error code (0:good, 1:bad) """ import os error = 0 try: if not os.path.isdir(path_folder): print('Creating folder: {} '...
def scale_cpu_usage(cpu_usage_ratio, host_cpu_count, cpu_share_limit): """ Scales cpu ratio originally calculated against total host cpu capacity, with the corresponding cpu shares limit (at task or container level) host_cpu_count is multiplied by 1024 to get the total available cpu shares """ ...
def when_is_vocation(month: str) -> str: """_summary_ Takes a string of month and returns the vocation month first letter capitalized. Args: month (str): _description_ A month a after or after the current month. Returns: str : _description_ """ months_lower = month.lowe...
def string_set_intersection(set_a, set_b, ignore_case=True, sep=","): """ Return intersection of two coma-separated sets :type set_a str :type set_b str :type ignore_case bool :type sep str :rtype set """ if set_a is None or set_b is None: return set() if ignore_case: set_a = set_a.lower(...
def collect_query_fields(node, fragments): """Recursively collects fields from the AST Args: node (dict): A node in the AST fragments (dict): Fragment definitions Returns: A dict mapping each field found, along with their sub fields. { 'name': {}, 'i...
def eat_char(text_string, char_set): """ Eats the specified subset of characters from the beginning of the string and returns index when done eating :param text_string: :param char_set: :return: index into its string where no char_set are found """ idx = 0 for this_char in text_string: ...
def capitalize_first_letter(text): """ Given a string, capitalize the first letter. """ chars = list(text.strip()) chars[0] = chars[0].upper() return "".join(chars)
def reset_model(model: dict) -> dict: """ Resets detectron2 model 'state'. This means current scheduler, optimizer and MOST IMPORTANTLY iterations are deleted or set to zero. Allows use of this model as a clean_slate. """ assert isinstance(model, dict) assert 'model' in model if 'sched...
def is_tuple(a): """Check if argument is a tuple""" return isinstance(a, tuple)
def payment(rate=0.07, num_periods=72.0, present_value=0.0): """ Calculate the payment for a loan payment based on constant period payments and interest rate. """ return present_value * (rate * (1.0 + rate) ** num_periods) / ( (1.0 + rate) ** num_periods - 1.0)
def mean(a): """ takes the mean of a list """ if not isinstance(a, list): raise TypeError('Function mean() takes a list, not a %s' % a.__class__) if len(a) > 0: return float(sum(a) / len(a)) else: return 0.0
def write_vrt_from_csv(infile, x, y, z): """ A function for writing a vrt file for a csv point dataset """ assert infile.endswith('.csv') s = "<OGRVRTDataSource>\n" s+=' <OGRVRTLayer name="{}">\n'.format(infile.split('.')[0]) s+=' <SrcDataSource>' s+= infile s+= '</SrcData...
def _get_image_root_type(image_type): """Determines which root an image type is located in. Args: image_type (str): Type of image. Returns: str: Either "input" or "output" for the corresponding root. """ inputs = { "background_color", "background_color_levels", ...
def bh_decode(s): """Replace code strings from .SET files with human readable label strings. """ s = s.replace('SP_', '') s = s.replace('_ZC', ' ZC Thresh.') s = s.replace('_LL', ' Limit Low') s = s.replace('_LH', ' Limit High') s = s.replace('_FD', ' Freq. Div.') s = s.replace('_OF', ' ...
def has_path(coll, path): """Checks if path exists in the given nested collection.""" for p in path: try: coll = coll[p] except (KeyError, IndexError): return False return True
def maxHeightTry1(d1, d2, d3): """ A method that calculates largest possible tower height of given boxes (bad approach 1/2). Problem description: https://practice.geeksforgeeks.org/problems/box-stacking/1 time complexity: O(n*max(max_d1, max_d2, max_d3)^2) space complexity: O(n*max(max_d1, m...
def decompressCmd(path, default="cat"): """"return the command to decompress the file to stdout, or default if not compressed, which defaults to the `cat' command, so that it just gets written through""" if path.endswith(".Z") or path.endswith(".gz"): return "zcat" elif path.endswith(".bz2"): ...
def find_github_item_url(github_json, name): """Get url of a blob/tree from a github json response.""" for item in github_json['tree']: if item['path'] == name: return item['url'] return None
def convert_to_hierarchical(contours): """ convert list of contours into a hierarchical structure slice > frame > heartpart -- Contour :param contours: list of Contour objects :return: a hierarchical structure which contains Contour objects """ hierarchical_contours = {} for contour in c...
def compress(dates, values): """ inputs: dates | values -----------+-------- 25-12-2019 | 5 25-12-2019 | 6 25-12-2019 | 7 25-12-2019 | 8 25-12-2019 | 9 25-12-2019 | 10 29-12-2019 | 11 29-12-2019 | 12 29-12-2019 | 13 ...
def get_url_chat_id(chat_id: int) -> int: """ Well, this value is a "magic number", so I have to explain it a bit. I don't want to use hardcoded chat username, so I just take its ID (see "group_main" variable above), add id_compensator and take a positive value. This way I can use https://t.me/c/{chat_i...
def _sanitizeName(name): """Convert formula base_name to something safer.""" result = '' for c in name: if c >= 'a' and c <= 'z': result += c elif c >= 'A' and c <= 'Z': result += c elif c >= '0' and c <= '9': result += c else: ...
def get_winner(game_state): """Returns the winner if any. Else it returns an empty string.""" for i in range(len(game_state)): row = game_state[i] column = [game_state[0][i], game_state[1][i], game_state[2][i]] if row[0] == row[1] and row[0] == row[2] and row[0] != " ": ...
def min_w_nan(array): """Return min ignoring nan""" return min([a for a in array if a==a])
def label_to_mem(value, mem_predict): """turn label to mem""" for index, predict in enumerate(mem_predict): if value <= index: return predict
def job_id(conf): # type: (dict) -> str """Get job id of a job specification :param dict conf: job configuration object :rtype: str :return: job id """ return conf['id']
def student_ranking(student_scores, student_names): """ :param student_scores: list of scores in descending order. :param student_names: list of names in descending order by exam score. :return: list of strings in format ["<rank>. <student name>: <score>"]. """ student_list = [] for inde...
def altair_fix(html: str, i: int): """ Replaces certain keywords in the JavaScript needed to show altair plots. Allows multiple altair plots to be rendered with vega on a single page """ # convert beautiful soup tag to a string html = str(html) keywords = ["vis", "spec", "embed_opt", "const ...
def associate(first_list, second_list, offset, max_difference): """ Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim to find the closest match for every input tuple. Input: first_list -- first dictionary of (stamp,data) tuples second_list -- second dict...
def strfcount(name_count): """Return the dictionary of events and their count as a string.""" if not name_count: return '' lines = [] c_width = len(str(max(name_count.values()))) data = sorted(name_count.items(), key=lambda x: x[0]) for name, count in data: lines.append('`x {:{wi...
def in_all_repository_dependencies( repository_key, repository_dependency, all_repository_dependencies ): """Return True if { repository_key : repository_dependency } is in all_repository_dependencies.""" for key, val in all_repository_dependencies.items(): if key != repository_key: continue...
def filter_by_limit(list, limit): """Filters data by the limit specified in the --limit arg """ return list[:limit]
def _format_num_reads(reads): """Format number of reads as k, M, or G""" fmt_reads = [] for x in reads: if int(x) < 1e6: fmt_reads.append("{:.1f}k".format(int(x)/1e3)) elif int(x) > 1e9: fmt_reads.append("{:.1f}G".format(int(x)/1e9)) else: fmt_read...
def createLDAPObjDict(objs): """Creates a dictionary from a list of LDAP Obj's. The keys are the cn of the object, the value is the object.""" return {obj.cn: obj for obj in objs}
def nodes_merge_unwind(labels, merge_properties, property_parameter=None): """ Generate a :code:`MERGE` query which uses defined properties to :code:`MERGE` upon:: UNWIND $props AS properties MERGE (n:Node {properties.sid: '1234'}) ON CREATE SET n = properties ON MATCH SET n += ...
def add_pattern_exemptions(line, codes): """Add a flake8 exemption to a line.""" if line.startswith('#'): return line line = line.rstrip('\n') # Line is already ignored if line.endswith('# noqa'): return line + '\n' orig_len = len(line) exemptions = ','.join(sorted(set(cod...
def isinstance_all(ins, *tar): """Apply isinstance() to all elements of target :param ins: types :param tar: target tuple :return: True if all True and False if anyone False """ for x in tar: if not isinstance(x, ins): return False return True
def get_unique_r_numbers(g2r): """Returns the set of R numbers associated to at least one gene in the g2r dict. :param g2r: dict with gene names for keys and the associated R numbers for values :return: frozenset of all R number values in g2r """ reactions = set() for gene in g2r: ...
def if_match(page, other_page): """ Funcion para definir la similaridad entre diapositivas. """ return page.startswith(other_page)
def convert_to_float(value_string, parser_info={'parser_warnings':[]}): """ Tries to make a float out of a string. If it can't it logs a warning and returns True or False if convertion worked or not. :param value_string: a string :returns value: the new float or value_string: the string given :...
def search_binary(xs, target): """ Find and return the index of key in sequence xs """ lb = 0 ub = len(xs) while True: if lb == ub: # If region of interest (ROI) becomes empty return -1 # Next probe should be in the middle of the ROI mid_index = (lb + ub) // 2 ...
def checkorder(positionIn): """ Purpose : construct the tuples for transposing the data to standard dimension order and the inverse for transposing it back to the original dimension order Usage : newOrder, inverseOrder = checkorder(positionIn) Passed : positionIn -- ...
def bps_to_human(bps): """ Convert bps to humand readble string. """ if bps >= 1000000: return "%f Mbps" % (float(bps) / 1000000) elif bps >= 100000: return "%f Kbps" % (float(bps) / 1000) else: return "%u bps" % bps
def get_from_tree(tree, key_path): """Return the value in a nested dict from walking down along the specified keys. Args: tree: a nested dict. key_path: an iterable of the keys to follow. If keys is a string, uses keys as a single key. """ cursor = tree if isinstance(key_pat...
def remove_trailing_N_characters(sequence): """ Strings representing the nucleotides typically start and end with repeating sequences of the 'N' character. This function strips them from the right and left side of the input sequence. """ start_index = len(str(sequence)) - len(str(sequence).lstri...
def _numericalize_coefficients(raw_symbols, coefficients): """Replaces the symbols of coefficients in the expression string with values. If there is coefficient symbol in raw_symbols which is not in coefficients dict, it will remain symbolic in the expression string. Args: raw_symbols: List of context-fre...
def matches(card1,card2): """checks if card1 and card2 match""" return card1[0]==card2[0] or card1[1]==card2[1]
def parse_record(raw_record): """Parse raw record and return it as dict""" return dict(rec.split(":") for rec in raw_record.split())
def _GetResidentPagesJSON(pages_list): """Transforms the pages list to JSON object. Args: pages_list: (list) As returned by ParseResidentPages() Returns: (JSON object) Pages JSON object. """ json_data = [] for i in range(len(pages_list)): json_data.append({'page_num': i, 'resident': pages_list...
def gaussian_gradients(x, y, a, mu, sigma, eta): """KL loss gradients of neurons with tanh activation (~ Normal(mu, sigma)).""" sig2 = sigma**2 delta_b = -eta * (-(mu / sig2) + (y / sig2) * (2 * sig2 + 1 - y**2 + mu * y)) delta_a = (eta / a) + delta_b * x return delta_a, delta_b
def is_primitive(value): """ Checks if value if a python primitive :param value: :return: """ return type(value) in (int, float, bool, str)
def allpairs(x): """ Return all possible pairs in sequence x Condensed by Alex Martelli from this thread on comp.lang.python:: http://groups.google.com/groups?q=all+pairs+group:*python*&hl=en&lr=&ie=UTF-8&selm=mailman.4028.1096403649.5135.python-list%40python.org&rnum=1 """ return [(s, f) ...
def do_simple_math(number1, number2, operator): """ Does simple math between two numbers and an operator :param number1: The first number :param number2: The second number :param operator: The operator (string) :return: Float """ ans = 0 if operator is "*": ans = number1 * nu...
def get_indices(num_indices, props, scan_idx=0, cycle_idx=0, beam_idx=0, IF_idx=0, record=0, trimmed=False): """ get the row and construct a tuple for a FITS data array index The maximum is (beam,record,IF,0,0) which will return a spectrum or whatever is in the first column of...
def check_result(results, locations, box_size): """ Checks if the received regions of interest contain the true aneurysms. Return true if all aneurysms found, false othervise. For testing purposes. Parameters ---------- results : list A list of the coordinates of the middle voxels f...
def _tuples_to_dict(meta, header, tagged_parts): """ Convert a dictionnary and list of tuples into dictionnary """ structured_message = {} structured_message["meta"] = meta structured_message["structured_text"] = {} structured_message["structured_text"]["header"] = header structured_text =...
def factorial(n): """ Simple factorial calculator that takes the number n. """ if n == 0: return 1 return n * factorial(n - 1)
def copy_list(original: list) -> list: """Recursively copies n-dimensional list and returns the copy. Slower than list slicing, faster than copy.deepcopy. """ copied = [] for x in original: if not isinstance(x, list): copied.append(x) else: copied.append(copy...
def pretty_rotvec_op(ops, join_str='*', format_str='(Rx:{:.1f}Ry:{:.1f}Rz:{:.1f})'): """ops: <list of Rx, Ry, Rx>""" return join_str.join( [op if isinstance(op, str) else format_str.format(*op) for op in ops])
def _tef_P(P): """Define the boundary between Region 3e-3f, T=f(P) Parameters ---------- P : float Pressure [MPa] Returns ------- T : float Temperature [K] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for Specific Volume ...
def list_diff(old_one, new_one, key): """ diff two config list and fill the result , have to specify the index key """ result = {'created': [], 'deleted': [], 'modified': [], 'unchanged': []} old_list = list(old_one) new_list = list(new_one) for old_item in old_one: for new_item in...
def keymap_replace_substrings(target_str, mappings={"<": "left_angle_bracket", ">": "right_angle_bracket", "[": "left_square_bracket", "]": "right_square_bracket", ...
def get_total_blkio(stat): """ Gets the total blkio out of the docker stat :param stat: The docker stat :return: The blkio """ io_list = stat['blkio_stats']['io_service_bytes_recursive'] if len(io_list)>0: total_dics = list(filter(lambda dic: dic['op'] == 'Total', io_list)) if le...
def wall_dimensions(walls): """ Given a list of walls, returns a tuple of (width, height).""" width = max(walls)[0] + 1 height = max(walls)[1] + 1 return (width, height)
def is_pal(x): """Assumes x is a list Returns True if the list is a palindrome; False otherwise""" temp = x temp.reverse return temp == x
def clean_operations(operations): """Ensure that all parameters with "in" equal to "path" are also required as required by the OpenAPI specification, as well as normalizing any references to global parameters. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject....
def perdict(x=-9, y=None, guess=10): """ task 0.5.4 pass x and y into equation and guess the value """ testY = float(float(1) / float(2)) if y is None: y = testY if 2**(y + testY) if x + 10 < 0 else 2**(y - testY) == guess: return True else: retur...
def _get_wind_direction(degrees): """ Determines the direction the wind is blowing from based off the degree passed from the API 0 degrees is true north """ wind_direction_text = "N" if 5 <= degrees < 40: wind_direction_text = "NNE" elif 40 <= degrees < 50: wind_direction_tex...
def mapped_included(inc: dict) -> dict: """Makes included more easily searchable by creating a dict that has (type,id) pair as key. Also, returned value for the key can be used for relationships node. ie. { ('people', '12'): { 'id': '12, 'type': 'people', ...
def check_two_shapes_need_broadcast(shape_x, shape_y): """Check two shapes need broadcast.""" error = ValueError(f"For 'tensor setitem with tensor', the value tensor shape " f"{shape_y} could not broadcast the required updates shape {shape_x}.") if len(shape_y) > len(shape_x): ...
def G1DListMergeEdges(eda, edb): """ Get the merge between the two individual edges :param eda: the edges of the first G1DList genome :param edb: the edges of the second G1DList genome :rtype: the merged dictionary """ edges = {} for value, near in eda.items(): for adj in near: if (...
def gcd(a: int, b: int) -> int: """ Return the GCD of a and b using Euclid's algorithm. :param a: First integer. :param b: Second integer. :return: The Greatest Common Divisor between two given numbers. """ while a != 0: a, b = b % a, a return b
def cross_prod(a,b): """ This function takes two vectors, a and b, and find's their cross product. """ c = [a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]] return(c)
def destination_name(path, delimiter="__"): """ Returns a cli option destination name from attribute path **Arguments** - path (`list`): attribute path - delimiter (`str`): delimiter for nested attributes **Returns** cli destination name (`str`) """ return f"{delimiter.join(path)...
def get_smallest_compound_id(compounds_identifiers): """ Return the smallest KEGG compound identifier from a list. KEGG identifiers may map to compounds, drugs or glycans prefixed respectively with "C", "D", and "G" followed by at least 5 digits. We choose the lowest KEGG identifier with the assump...
def getMedianpoints(lst): """ Returns the index or indexes of the median of a list of numerics. :param lst: A list of numerics from which the median index or indexes will be retrieved. \t :type lst: [numerics] \n :returns: The median index or indexes. \t :rtype: : (int, int) \n """ coun...
def rgb(red, green, blue): """ Calculate the palette index of a color in the 6x6x6 color cube. The red, green and blue arguments may range from 0 to 5. """ return 16 + (red * 36) + (green * 6) + blue
def _create_response(message, response_type, sub_response_type=None): """ :param message: :param response_type: string :param sub_response_type: string :return: """ r = {"message": message, "type": response_type} if sub_response_type: r["sub_type"] = sub_response_type retur...
def memory_reallocation_v2(s): """memory reallocation.""" cycles = 0 banks = s[:] ll = len(banks) seen = {} uk = ''.join(list(map(str, banks))) while uk not in seen: seen[uk] = cycles key_chosen = banks.index(max(banks)) value_chosen = banks[key_chosen] banks...
def jaccard_index(nw, src, dst): """ Counts Jaccard index between src and dst ports. Args: nw: Network instance src: Source Port dst: Destination Port Returns: Jaccard Index """ try: return len(set(nw.neighbors(src)).intersection(set(nw.neig...
def _pcapname_to_guid(pcap_name): """Converts a Winpcap/Npcap pcpaname to its guid counterpart. e.g. \\DEVICE\\NPF_{...} => {...} """ if "{" in pcap_name: return "{" + pcap_name.split("{")[1] return pcap_name
def get_apiorder(ndim, latitude_dim, longitude_dim): """ Get the dimension ordering for a transpose to the required API dimension ordering. **Arguments:** *ndim* Total number of dimensions to consider. *latitude_dim* Index of the latitude dimension. *longitude_dim* ...