content
stringlengths
42
6.51k
def conflict(row1, col1, row2, col2): """Would putting two queens in (row1, col1) and (row2, col2) conflict?""" return (row1 == row2 or # same row col1 == col2 or # same column row1 - col1 == row2 - col2 or # same \ diagonal row1 + col1 == row2 + col2)
def _clean_info(obj): """ stringtify and replace space""" return str(obj).strip().replace(" ", "")
def remove_first_range(some_list): """ Returns a given list with its first range removed. list -> list """ return some_list[1:]
def get_dockerimage45(script_object): """Get the docker image used up to 4.5 (including). Arguments: script_object {dict} -- [script object containing the dockerimage configuration] """ if 'dockerimage45' in script_object: return script_object['dockerimage45'] return script_object.g...
def refine_name(name_data): """ Takes the name data and decodes and refines it. Parameters ---------- name_data: str reactor name data from csv file Returns ------- name: str refined and decoded name of reactor """ name = name_data.decode('utf-8') start = name.f...
def none_len_formatter(pair): """If input is None, returns "?", otherwise the length of input as string.""" if pair is None: return "?" return str(len(pair))
def findFunction(line,keywords): """ Find function declerations """ line=line.strip() if len(line)==0: return None words=line.replace('(',' ( ').replace(')',' ) ').split() if words[0] in keywords and line.find('(') and line.find(')'): ret=[line.replace(';','')] try: index=words.index('(') ret.append(w...
def get_delta(instance, cf): """ Compute difference between original instance and counterfactual :param instance: List of features of original instance :param cf: List of features of counterfactual :return: List of differences between cf and original instance """ delta = [] for i, origin...
def split_money(target): """Split money from the equipment list and return both lists.""" money = {} for item in target: cp_index = item.find(" Cp") sp_index = item.find(" sp") if (cp_index is not -1) and (sp_index is not -1): money["cp"] = item[item.find(" Cp") - 2 :] ...
def mergesort(data): """Sorting algorithm for merg sort.""" try: if len(data) > 1: half = len(data) // 2 left = data[:half] right = data[half:] mergesort(left) mergesort(right) di = 0 li = 0 ri = 0 ...
def isSpecificPythonOnly(filename): """ Decide if something is not used for this specific Python. """ # Currently everything is portable, but it's a good hook, pylint: disable=unused-argument return False
def parse_flights(flights): """Parse xml tree and return flights list.""" if not flights: return None result = list() for flight in flights: result.append({ 'carrier': flight.findtext('./Carrier').strip(), 'flight_number': flight.findtext('./FlightNumber').strip()...
def annotations_json_to_bed(annotations_json): """ Convert JSON formatted annotations to a flattened BED format (list of lists). Args: annotations_json (list of dict): JSON formatted annotations Returns: list of lists: list of entries corresponding to BED file entries with all entries ...
def VR(length_a, b2a_ratio, c2a_ratio, thickness): """ Return shell volume and total volume """ b_side = length_a * b2a_ratio c_side = length_a * c2a_ratio a_core = length_a - 2.0*thickness b_core = b_side - 2.0*thickness c_core = c_side - 2.0*thickness vol_core = a_core * b_core * c...
def normalize(x, y, viewbox): """Normalize so that the origin is at the bottom center of the image, and the width and height of the image are 1 """ xi, yi, width, height = viewbox return (x - xi - width / 2) / width, (yi + height - y) / height
def haversinedist(loc1, loc2): """Returns the haversine great circle distance (in meters) between two locations. The input locations must be given as ``(lat, long)`` pairs (decimal values). See http://en.wikipedia.org/wiki/Haversine_formula """ from math import sin, cos, radians, atan2, sqrt la...
def layer_severity(layers, layer): """Return severity of layer in layers.""" return layers[layer]['severity']
def find_longest_inc_subsequence(seq): """Solution for Q1 Given an unordered array of integers of length N > 0, calculate the length of the longest ordered (ascending from left [lower index] to right [higher index]) sub-sequence within the array. * Recursive, functional and binary-search solutions ...
def is_num(text): """ Check if given text is a number (int or float) :param text: Text (str) :return: Whether number (bool) """ try: _ = float(text) if '.' in text else int(text) return True except ValueError: return False
def _is_hdf5_filepath(filepath): """Predicate the filepath is a h5 file.""" return (filepath.endswith('.h5') or filepath.endswith('.hdf5') or filepath.endswith('.keras'))
def replace_list_element(lst, source_idx, target_idx): """replaces an element in a list""" if source_idx < len(lst) and target_idx<len( lst): tmp = lst.pop(source_idx) return lst[:target_idx] + [tmp] + lst[target_idx:] else: return []
def decode_uint128(bb): """ Decode 16 bytes as a unsigned 128 bit integer Specs: * **uint128 len**: 16 bytes * **Format string**: 'z' """ return int.from_bytes(bb, byteorder='little', signed=False)
def invert_dict_mapping_all(mapping_dictionary): """ Args: mapping_dictionary: mapping from keys to values which is not necessarily injective, e.g., node_id to community_id mapping Returns: inverted mapping with unique values as keys and lists of former keys as values, e.g., com...
def split_vantage_args(all_args): """Returns two lists of arguments; the first are args that should be used by vantage itself, the second is a list of everything else.""" vg_args = [] append_next = False for idx, arg in enumerate(all_args): found_unknown = True if append_next: ...
def get_proposal_branch_name(key: str, value: str): """ Get proposal branch name in format `key_to_change-new version` :param key: Key in YAML file :param value: New value of the key :return: Proposal branch """ new_value = value.split(":") if new_value == 0: return f"{key.split...
def remove_if_exists_copy(mylist, item): """ Return new list with item removed """ new_list = [] for el in mylist: if el != item: new_list.append(el) return new_list
def strings_to_dict(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,key...
def _deep_map(func, *args): """Like map, but recursively enters iterables Ex: >>> _deep_map(lambda a, b: a + b, (1, 2, (3, (4,), 5)), (10, 20, (30, (40,), 50))) [11, 22, [33, [44], 55]] """ try: return [_deep_map(func, *z) for z in z...
def list_to_stdout(list_item: list) -> bool: """ Prints the list objects contents to screen, each as own line. :param list_item: A dict object to print out. :return bool: True on finish. """ for _line in list_item: print(f'{_line}') return True
def divisors(n): """ @brief O(sqrt(n)) """ i = 1 result = 0 while i * i < n: if n % i == 0: result += 2 # i and n/i are divisors i += 1 if i * i == n: result += 1 return result
def optional(type_): """ Helper for use with `expect_types` when an input can be `type_` or `None`. Returns an object such that both `None` and instances of `type_` pass checks of the form `isinstance(obj, optional(type_))`. Parameters ---------- type_ : type Type for which to produ...
def validate_portfolio(portfolio): """ :params: portfolio: e.g. {"000001.XSHG": 0.25} """ symbol_correct = True weight_correct = True msg = "" for symbol in portfolio: if ( len(symbol) == 11 and symbol[:-5].isdigit() and (symbol.endswith(".XSHG") or sy...
def get_alt_username(current_username): """Gets the alternate username for the current_username passed in This helper function gets the username for the alternate user based on the passed in current username. Args: current_username (client): The current username Returns: Alte...
def _dtanh(x): """Derivative of tanh as a function of tanh.""" return (x * -x) + 1
def RemoveWordFromList(word, availableLetters): """ Tries to remove each character in string word from the list of available letters and returns the new list of letters or False if impossible. """ # letters[:] creates a copy of the list lett = availableLetters[:] for char in word: if...
def array_resize_example(rows, cols): """returns an array of size rows * cols""" result = [] for i in range(rows): row = [] for j in range(cols): row.append(i * cols + j) result.append(row) return result
def _bool_to_val(val): """Convert a bool to a text representation.""" if val: return 'true' else: return 'false'
def B_sampling(DLx,DLy,mux,muy,sigmax,sigmay,ro): #Q2 """Definition of term B in the Bivariate normal Gaussian Distribution using the sampling points""" Bs=((((DLx-mux))**(2.0))/((sigmax)**2.0))+((((DLy-muy))**(2.0))/((sigmay)**2.0))-((2.0*(ro)*(DLx-mux)*(DLy-muy))/(sigmax*sigmay)) return Bs
def process_list(func, iterator, *args, **kwargs): """Run a function func for all i in a iterator list. The processing will occurr in serial form. The function will be processed multiple times using the values iterated from the `iterator`. Parameters ---------- func: callable Function ...
def parser_VBI_data_Descriptor(data,i,length,end): """\ parser_VBI_data_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "VBI_data", "contents" : unparsed_descriptor_contents } (Defined in ETS...
def valid_bool(val, rule): """Default True, check against rule if provided.""" return val is rule if rule != '' else True
def _trailing_zeros(value, bit_width=8): """Count trailing zeros on a binary number with a given bit_width ie: 0b11000 = 3 Used for shifting around values after masking. """ count = 0 for _ in range(bit_width): if value & 1: return count count += 1 value >>=...
def SHA1_f1(b, c, d): """ First ternary bitwise operation.""" return ((b & c) | ((~b) & d)) & 0xFFFFFFFF
def calc_growths(prev_num, curr_num): """Calculate the percentage growth of curr_num over prev_num.""" if prev_num == 0: return -1 # -1 represents undefined growth. else: return 100 * (curr_num - prev_num) / prev_num
def _round_up(value, alignment): """Round `value` up to a multiple of `alignment`.""" return (value + (alignment - 1)) // alignment * alignment
def is_snake(text): """ Check if a string is in either upper or lower snake case format :param text: String to check :return: Whether string is in any snake case format """ if " " in text: return False return "_" in text
def get_pixel_format_for_encoding(subsampling): """ helper to set pixel format from subsampling, assuming full range, for converting source to yuv prior to encoding """ pixel_format = None if subsampling == '420': pixel_format = 'yuvj420p' elif subsampling == '444': pixel_for...
def ConvertImageVersionToNamespacePrefix(image_version): """Converts an image version string to a kubernetes namespace string.""" return image_version.replace('.', '-')
def equation(num: float) -> float: """ >>> equation(5) -15 >>> equation(0) 10 >>> equation(-5) -15 >>> equation(0.1) 9.99 >>> equation(-0.1) 9.99 """ return 10 - num * num
def _quote_args_that_you_forgot_to_quote(arg): """Wrap the arg in quotes if the user failed to do it.""" if arg.startswith('"') or arg.startswith("'"): return arg elif '=' in arg and sum(a=='=' for a in arg)==1: # Keyword name, val = arg.split('=') if val[0].isalpha(): r...
def _load_hbase_list(d, prefix): """Deserialise dict stored as HBase column family """ ret = [] prefix = 'f:%s_' % prefix for key in (k for k in d if k.startswith(prefix)): ret.append(key[len(prefix):]) return ret
def count_consecutive_inconsistencies(aligned_seq1, aligned_seq2): """ :param seq1, aligned_seq2: aligned sgRNA and genomic target (seq+PAM) :return: number of concatenated-extended mismatches and bulges """ cnt = 0 current_cnt = 0 for i in range(len(aligned_seq2) - 3): if aligned_seq2[i] != aligned_...
def smart_round(value, ndigits): """ function to cap the decimals :param value: the value to cap :type value: float/double :param ndigits: amount of decimals needed :type ndigits: int :return: rounded float :rtype: float """ return int(value * (10 ** ndigits)) / (10. ** n...
def filter_shards(tests, index, shards): """Filters the shards. Watch out about integer based arithmetics. """ # The following code could be made more terse but I liked the extra clarity. assert 0 <= index < shards total = len(tests) quotient, remainder = divmod(total, shards) # 1 item of each remainde...
def tani(cav1, cav2): """ calculates the dice similarity between two lists of texts """ intersect = len(cav1.intersection(cav2)) return 1 - (intersect/(len(cav1)+len(cav2) - intersect))
def make_tsv_line(vals,outfields,empty_string_replacement=''): """Does not have the \n at the end""" l = [] for tag in outfields: val = vals[tag] if type(val) is str: if empty_string_replacement and not val: l.append( empty_string_replacement ) else: ...
def esc (s, is_attribute=False): """ escape XML special charcters Parameters: is_attribute if True, also escape " and ' for attribute values Returns: the escaped string """ s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if is_attribute: return s.r...
def int2excel_col_name(d): """ >>> int2excel_col_name(1) 'A' >>> int2excel_col_name(28) 'AB' >>> int2excel_col_name(100) 'CV' """ s = [] while d: t = (d - 1) % 26 s.append(chr(65 + t)) d = (d - 1) // 26 return ''.join(reversed(s))
def Compact2D(m): """ Decodes the 64 bit morton code into a 32 bit number in the 2D space using a divide and conquer approach for separating the bits. 1 bit is not used because the integers are not unsigned Args: n (int): a 64 bit morton code Returns: int...
def is_prime(num): """Prime number check. Args: num (int): number to check Returns: bool: True or False """ if num < 2: return False index = 2 while index <= num // 2: if num % index == 0: return False index += 1 return True
def dict2opts(d): """ Turns a dictionary into a list of strings representing command-line options. Keys of the dictionary should already be in option format, i.e. with leading hyphens. Values are arguments of options. None values should be used for options without arguments. Options with multiple argu...
def failure(msg): """ Standard failure result """ return dict(result='usererror', message=msg)
def replaceEmojis(text): """Turn emojis into smilePositive and smileNegative to reduce noise.""" processedText = text.replace('0:-)', 'smilePositive') processedText = processedText.replace(':)', 'smilePositive') processedText = processedText.replace(':D', 'smilePositive') processedText = proces...
def kind_from_place(place): """Sorry not sorry""" if place == "fr (fuori_regione)": return "fuori" elif len(place) == 2: return "provincia" elif place == "TOT ITALIA": return None elif place == "crescita": return None else: return "regione"
def match_subroutine_call(names): """ """ if len(names) < 1: return "" try: i=names.index("CALL") except ValueError: return "" return names[i+1]
def argval(a): """ returns .value() of Expression, otherwise the variable itself We check with hasattr instead of isinstance to avoid circular dependency """ return a.value() if hasattr(a, "value") else a
def set_safe_attr(instance, attr, val): """Sets the attribute in a thread safe manner. Returns if new val was set on attribute. If attr already had the value then False. """ if not instance or not attr: return False old_val = getattr(instance, attr, None) if val is None and old_val...
def split_output(cmd_output): """Function splits the output based on the presence of newline characters""" # Windows if '\r\n' in cmd_output: return cmd_output.strip('\r\n').split('\r\n') # Mac elif '\r' in cmd_output: return cmd_output.strip('\r').split('\r') # Unix elif ...
def _template_has_httpapi_resource_with_default_authorizer(template): """ Returns true if the template contains at least one AWS::Serverless::HttpApi resource with DefaultAuthorizer configured """ # Check whether DefaultAuthorizer is defined in Globals.HttpApi has_global_httpapi_default_authorizer =...
def ns2mm(time, velocity): """Return the distance (mm) from signal travel time (ns) and velocity (m/ns). Attributes: time <float>: travel time (ns) of radio signal; velocity <float>: travel velocity (m/ns) of radio signal. """ meters = velocity * time distance = me...
def default_str_tester(s: str) -> bool: """ Default test whether s URL, file name or just data. This is pretty simple - if it has a c/r, a quote :param s: string to test :return: True if this is a vanilla string, otherwise try to treat it as a file name """ return not s.strip() or any(c in s fo...
def check_partitioners(partitioners, keys): """Checks the given partitioners. This checks that `partitioners` is a dictionary that only contains keys in `keys`, and furthermore the entries in `partitioners` are functions or further dictionaries (the latter used, for example, in passing partitioners to module...
def is_digit_or_single_char(token): """ Acronyms or dates are formed either by tokens that have a sigle letter (acronyms ie. I-B-M) or numerical strings that can have more than 1 digit. (ie 2020-10-10). """ return token.isdigit() or len(token) < 2
def _escape_json_for_js(json_dumps_string): """ Escape output of JSON dumps that is safe to be embedded in a <SCRIPT> tag. This implementation is based on escaping performed in simplejson.JSONEncoderForHTML. Arguments: json_dumps_string (string): A JSON string to be escaped. T...
def rectified_linear_unit_derivative(x): """ Returns the derivative of ReLU.""" ret = 1 if x>0 else 0 return ret
def is_overlap_range(_range, _range_gt): """ :param _range: range to test :param _range_gt: the ground truth range :return: True if there are overlap between the two ranges """ _st, _ed = _range[0], _range[-1] st_gt, ed_gt = _range_gt[0], _range_gt[-1] case_1 = _st <= st_gt <= _ed ca...
def map_equal_contributions(contributors): """assign numeric values to each unique equal-contrib id""" equal_contribution_map = {} equal_contribution_keys = [] for contributor in contributors: if contributor.get("references") and "equal-contrib" in contributor.get( "references" ...
def make_regex(string): """Regex string for optionally signed binary or privative feature. >>> [make_regex(s) for s in '+spam -spam spam'.split()] ['([+]?spam)', '(-spam)', '(spam)'] >>> make_regex('+eggs-spam') Traceback (most recent call last): ... ValueError: inappropriate feature n...
def horner(c,x): """ horner(c,x) Evaluate a polynomial whose coefficients are given in descending order in `c`, at the point `x`, using Horner's rule. """ n = len(c) y = c[0] for k in range(1,n): y = x*y + c[k] return y
def set_hidden_measurement_lists_from_Ns_Nv(num_nodes, Ns, Nv, list_bus_id_power_hiding_priority=None, list_bus_id_voltage_hiding_priority=None): """ Returns the list of the hidden power bus ids and a list of hidden voltage ids :param num_nodes: number of buses in the grid :param Ns: Number ...
def normalize_time(rawtime): """ Return normalized time for readability :param rawtime: :return: """ try: # Return normalized time in seconds or minutes if int(rawtime)/60 < 1: return str(round(int(rawtime), 0)) + " seconds" return str(round(int(rawtime)/60, 1)) ...
def generate_sas_url( account_name: str, account_domain: str, container_name: str, blob_name: str, sas_token: str ) -> str: """ Generates and returns a sas url for accessing blob storage """ return f"https://{account_name}.{account_domain}/{container_name}/{blob_name}?{sas_token}"
def derivate(e, x): """Returns the derivative of e with respect to x.""" if (type(e) != tuple): if (e == x): return 1 else: return 0 elif (type(e) == tuple): operation = e[0] num1 = e[1] num2 = e[2] if (operation == ("-") or o...
def max_sub_array_sum(array, number): """ Time: O(n) Space: O(1) Finds a the maximum sum of a 'number' consecutive elements in an array :param array: float or int :param number: float or int :return: float or int, highest sum """ if not array: return None maximum = 0 ...
def summarize_text(text, max_length=100, marker="[...]"): """Truncate text and add a marker, if the length is above `max_langth`""" if not text: return "" if len(text) < max_length: return text return text[:max_length] + marker
def phoneword(phonenumber): """Returns all possible phone words respective to a phone number :param phonenumber: str :return: list of str with all phone words """ digit_to_chars = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' ...
def error_template(issue, lineno=0): """Formats an error reported by the tool.""" if lineno != 0 and lineno is not None: return " ".join(["Line", str(lineno), issue]) return issue.capitalize()
def count_ones(bitmask): """ Count the number of ones (hops) in our bitmask @param bitmask: bitmask of node ids in our path. """ ones = 0 while bitmask != 0: # Check if least significant bit is 1 if bitmask & 1 == 1: ones += 1 # Shift over 1 ...
def rotmol(numpoints, coor, lrot): """Rotate a molecule Parameters numpoints: The number of points in the list (int) coor: The input coordinates (list) lrot: The left rotation matrix (list) Returns out: The rotated coordinates out=u * x (list) """ out = [] fo...
def assoc(d, key, value): """ Return a new dict with new key value pair New dict has d[key] set to value. Does not modify the initial dictionary. >>> assoc({'x': 1}, 'x', 2) {'x': 2} >>> assoc({'x': 1}, 'y', 3) # doctest: +SKIP {'x': 1, 'y': 3} """ d = d.copy() d[key] = value...
def var2type(var, debug=False): """ Insure that strings are i8 type, add additions to list for a NetCDF, type must be: 'f4' (32-bit floating point), 'f8' (64-bit floating point), 'i4' (32-bit signed integer), 'i2' (16-bit signed integer), 'i8' ...
def _compute_split_boundaries(split_probs, n_items): """Computes boundary indices for each of the splits in split_probs. Args: split_probs: List of (split_name, prob), e.g. [('train', 0.6), ('dev', 0.2), ('test', 0.2)] n_items: Number of items we want to split. Returns: The item indices of bou...
def round_float(f, float_type, num_digits): """provides a rounded, formatted string for the given number of decimal places""" if f is None: return None value = float_type(f) max_len = len(str(value).split('.')[1]) padding = '0' * (num_digits - max_len) template = "%%.%df%s" % (min(num_di...
def tokenTextToDict(text): """ Prepares input text for use in latent semantic analysis by shifting it from a list to a dictionary data structure Parameters ---------- text : list of strings A list of strings where each string is a word and the list is a document Returns ...
def get_student_avg(gradebook_dict, student): """ Given a dictionary where each key-value pair is of the form: (student_name, [scores]), return the average score of the given student. If the given student does not exist, return -1 Example: >>> get_student_avg({"Sally":[80, 90, 100], "Harry": [75, 80, 8...
def compare(hascols, wanted): """Does any of the following apply.""" return any([x in hascols for x in wanted])
def is_error_of_type(exc, ref_type): """ Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :param exc: :param ref_type: :return: """ if isinstance(exc, ref_type): return True elif hasattr(exc, '__cause__') and exc.__cause__...
def hexToRgbColor(h): """Convert #RRGGBB to r, g, b.""" h = h.strip() if h.startswith('#'): h = h[1:] h = h[:2], h[2:4], h[4:] return [int(x, 16) for x in h]
def make_key(element_name, element_type): """Return a suitable key for elements""" # only distinguish 'element' vs other types if element_type in ('complexType', 'simpleType'): eltype = 'complexType' else: eltype = element_type if eltype not in ('element', 'complexType', 'simpleType'...
def search_iterator(lines, start=0): """Search for iterators in the code Args: lines ([list]): A list with Javascript syntax as strings. start ([int, optional]): The start line to start to search by iterators. Defaults to 0. Returns: [list]: A list of tuple (index, operator) ""...