content
stringlengths
42
6.51k
def iff(a, b, c): """ Ternary shortcut """ if a: return b else: return c
def _signed_representation(unsigned: int) -> int: """Convert an "unsigned" int to its equivalent C "signed" representation.""" return (unsigned & ((1 << 63) - 1)) - (unsigned & (1 << 63))
def transformCoordinates(coordinates, min_x, min_y, scale_x, scale_y): """ Manipulates coordinates to ensure they display within the bounds of canvas """ transformed_coordinates = [] for seg in coordinates: transformed_coordinates.append([((trkpt[0]-min_x)*scale_x,(trkpt[1]-min_y)*scale_y) for trkpt in seg]) r...
def and_dict(dict1, dict2): """ Apply logical conjunction between values of dictionaries of the same keys. Keys set must be identical in both dictionaries. Otherwise KeyError exception is raised. :param dict1: Dictionary of bool values. :param dict2: Dictionary of bool values. :returns: A ...
def _get_stat_var_prop(prop_list: list, sv_pv: dict) -> str: """Get the value of the first property from the list in the StatVar. Args: prop_list: order list of properties looked up in the StatVar sv_pv: dictionary of StatVar PVs. Returns: value of the property without the namespace pref...
def get_ring_size( x_ring_size: int, y_ring_size: int, ) -> int: """Get the ring_size of apply an operation on two values Args: x_ring_size (int): the ring size of op1 y_ring_size (int): the ring size of op2 Returns: The ring size of the result """ if x_ring_size !=...
def nrmsd_t(rmsd, data): """Normalised root mean squared deviation""" return rmsd/(max(data) - min(data))
def add512bit(a, b): """ Add two 512 integers """ a = bytearray(a) b = bytearray(b) cb = 0 res = bytearray(64) for i in range(64): cb = a[i] + b[i] + (cb >> 8) res[i] = cb & 0xff return res
def get_options_from_json(conf_json, ack, csr, acmd, crtf, chnf, ca): """Parse key-value options from config json and return the values sequentially. It takes prioritised values as params. Among these values, non-None values are preserved and their values in config json are ignored.""" opt = {'AccountKe...
def get_sentences (indexes_end,tokens_recov,sentences) : """ given the indexes of tokens that end sentences and the list of all the tokens , This function gives the list of all sentences contained in window_sentences. """ current = [] for k in range(len(tokens_recov)) : current.append(tokens_recov[k]) ...
def empty_query(*args, **kwags): """ A query with no matches """ response = { 'response': { 'numFound': 0, } } return response
def _cases_comparator(start: int, finish: int, payment_dict: dict) -> float: """Compares all possible schedules and return the calculated salary for that input""" payment_value = [key for key in payment_dict.keys()] hour_ranges = [value for value in payment_dict.values()] if start > hour_ranges[0][0] an...
def ExtractVarName(text): """ Read a string like 'atom:A ' or '{/atom:A B/C/../D }ABC ' and return ('','atom:A',' ') or ('{','atom:A B/C/../D ','}ABC') These are 3-tuples containing the portion of the text containing only the variable's name (assumed to be within the text), .....
def filter_list_sorter(feed_filter): """ Provide a key to sort a list of feed filters. """ return feed_filter['class']
def overrides(conf, var): """This api overrides the dictionary which contains same keys""" if isinstance(var, list): for item in var: if item in conf: for key, value in conf[item].items(): conf[key] = value elif var in conf: for key, value in c...
def str_replace(string, i, val): """Replace string[i] with val and return new string.""" assert len(val) == 1 return string[:i] + val + string[i+1:]
def is_instance(obj): """ Checking and setting instance to MODULE Args: obj: ModuleType / class Note: An instance will be treated as a Class Return: Boolean """ return True if obj and hasattr(obj, "__class__") else False
def dp_palindrome_length(dp, S, i, j): """ Recursive function for finding the length of the longest palindromic sequence in a string This is the algorithm covered in the lecture It uses memoization to improve performance, dp "dynamic programming" is a Python dict containing previously computed values ...
def dbcc(server, args_array, ofile, db_tbl, class_cfg, **kwargs): """Method: dbcc Description: Stub holder for dbcc function. Arguments: (input) server -> Mongo instance. (input) args_array -> Dict of command line options and values. (input) db_tbl -> Database and table names. ...
def construct_ldap_base_dn_from_domain(domain: str) -> str: """ Given a domain, constructs the base dn. """ domain_split = domain.split('.') return ','.join(map(lambda x: 'DC=' + x, domain_split))
def set_key_type(k): """ Convert to integer if possible """ try: result = int(k) except ValueError: result = k return result
def format_offset(offset): """ Formats an integer file offset. @param int offset The integer offset to format. @return str The formatted offset. """ if offset is None or offset < 0: return 'None' return "0x%08x (%i)" % (offset, offset)
def flatten_lists(lists): """Flattens a list of lists""" return [item for sublist in lists for item in sublist]
def get_monero_rct_type(bp_version=1): """ Returns transaction RctType according to the BP version. Only HP9+ is supported, thus only Simple variant is concerned. """ if bp_version == 1: return 3 # TxRctType.Bulletproof elif bp_version == 2: return 4 # TxRctType.Bulletproof2 ...
def numpy_to_python_type(value): """ Convert to Python type from numpy with .item(). """ try: return value.item() except AttributeError: return value
def avp_from_twet_tdry(twet, tdry, svp_twet, psy_const): """ Estimate actual vapour pressure (*ea*) from wet and dry bulb temperature. Based on equation 15 in Allen et al (1998). As the dewpoint temperature is the temperature to which air needs to be cooled to make it saturated, the actual vapour pr...
def get_catalog_record_REMS_identifier(cr): """ Get REMS identifier for a catalog record. :param cr: :return: """ return cr.get('rems_identifier', '')
def calc_rload_power(i_out_max, r_load): """Calculate the maximum power dissipation in Rload.""" return r_load * i_out_max * i_out_max
def process_or_group_name(name): """Ensures that a process or group name is not created with characters that break the eventlistener protocol or web UI URLs""" s = str(name).strip() if ' ' in s or ':' in s or '/' in s: raise ValueError("Invalid name: " + repr(name)) return s
def get_labor_input_baseline( assets_this_period, assets_next_period, interest_rate, wage_rate, income_tax_rate, productivity, efficiency, gamma, ): """ Calculate optimal household labor input. Arguments: assets_this_period: np.float64 Current asset holdings ...
def assemble_cla_status(author_name, signed=False): """ Helper function to return the text that will display on a change request status. For GitLab there isn't much space here - we rely on the user hovering their mouse over the icon. For GitHub there is a 140 character limit. :param author_name: T...
def to_list(data): """Creates a list containing the data as a single element or a new list from the original if it is already a list or a tuple""" if isinstance(data, (list, tuple)): return list(data) elif data is not None: return [data] else: return []
def csvrow_to_list(csvrow): """ Takes a string 'csvrow' that has substrings separated by commas and returns a list of substrings. """ if csvrow != None: return list(map(lambda s: s.strip(), csvrow.split(';'))) else: return None
def pull_oclc(odict): """ Pull OCLC numbers from incoming FirstSearch/Worldcat urls. """ import re oclc_reg = re.compile('\d+') oclc = None if odict.get('rfr_id', ['null'])[0].rfind('firstsearch') > -1: oclc = odict.get('rfe_dat', ['null'])[0] match = oclc_reg.search...
def check_target_in_gene_id_dict(memories_genes_id, target_genes_id, outpath=None): """ Returns: list of tuples (mem_symbol, target_symbol) if they are aliases """ matches = [] for target_key, target_val in target_genes_id.items(): for mem_key, mem_val in memories_genes_id.items(): ...
def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-enc...
def shorten_class(class_name: str) -> str: """Returns a shortened version of the fully qualilied class name.""" return class_name.replace('org.chromium.', '.').replace('chrome.browser.', 'c.b.')
def line_wrap(text, indent=0, max_len=78, string=False): """Return a wrapped line if length is larger max_len. The new parameter 'string' allows to wrap quoted text which is delimited by single quotes. It adds " '" to the end of the line and "'" to the start of the next line. """ split_len = ma...
def clean_list(lst): """ Clean a list by removing empty entries, casting them to strings and lowering the case Args: lst (list): List to clean Returns: A cleaned version on the inputted list """ lst = list(map(lambda item: str(item).strip().lower(), lst)) lst = ...
def difference(left, right): """:yaql:difference Return the difference of left and right sets as a new set. :signature: left.difference(right) :receiverArg left: left set :argType left: set :arg right: right set :argType right: set :returnType: set .. code:: yaql> set(0, ...
def factorize_naive(n): """ A naive factorization method. Take integer 'n', return list of factors. """ if n < 2: return [] factors = [] p = 2 while True: if n == 1: return factors r = n % p if r == 0: factors.append(p) ...
def calculateEncryptionKey(subjectNumber: int, numLoops: int) -> int: """ Calculates encryption key """ val: int = 1 for _ in range(numLoops): val *= subjectNumber val %= 20201227 return val
def cal_Phi_div_Phiast_conv(phiw, phi_bulk, F1_Z, F2_Z): """ [Auxiliary function] Calculate Phi(z)/Phi_ast using definition of F1_Z and F2_Z in cal_int_Fz, and Eqs. (49), (50), (D1) in [1]. The original definition of Phi(z) in Eq. (50) in [1] is divided by Phi_ast=pi*R^2*phi_bulk*u_ast in accordance with captio...
def validate(config): """ Validate the beacon configuration """ vcfg_ret = True vcfg_msg = "Valid beacon configuration" if not isinstance(config, list): vcfg_ret = False vcfg_msg = "Configuration for vmadm beacon must be a list!" return vcfg_ret, vcfg_msg
def check_dict_attribute_exists_and_type(parent_dict, attribute, expected_type, path, optional=False): """ Check if the attribute `attribute` exists in the dict `parent_dict` and check that the type of `parent_dict[attribute]` is of `expected_type`. Args: parent_dict (dict) attribute (str) expec...
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
def is_anagram(w1, w2): """Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean """ return sorted(w1) == sorted(w2)
def trim(text, tabwidth=4): """ Trim text of common, leading whitespace. Based on the trim algorithm of PEP 257: http://www.python.org/dev/peps/pep-0257/ """ if not text: return '' lines = text.expandtabs(tabwidth).splitlines() maxindent = len(text) indent = maxindent ...
def ComputeFlatList(intlist, n): """ NOTE: Does NOT do intlist[i] at all. """ total = 0 for i in intlist: total += i return total
def _is_announcement_line(line: str) -> bool: """ Is a line of text considered an announcement line? Examples: HAPPY BIRTHDAY <person>!!!! NO CLASSES <> :param line: line to check :return: if the line matches an expected pattern """ return bool(line) and (line.upper() == line or l...
def evaluate(prediction_labels, gt_labels): """ Args: top1_reference_ids: dict(str: int) gt_labels: dict(str: int) Returns: acc: float top-1 accuracy. """ count = 0.0 for idx, query in enumerate(gt_labels): gt_label = int(gt_labels[query]) pred_label = int(pred...
def access(dct, keys): """ Access a value from an arbitrarily-nested dictionary, given a set of keys. If any key doesn't exist, returns None. >>> access({'a': {'aa': {'aaa': {'b': 1, 'c': 2}}}}, keys=['a', 'aa', 'aaa', 'b']) 1 """ o = dct for k in keys: o = o.get(k) if...
def choose_peers(relay, relay_count, worker_count, min_w2r, min_r2w): """ Given `relay`, the position of relay within the affinity set for a given service, the number of relays in that set (`relay_count`), the number of workers for the service (`worker_count`), the minimum number of connections requ...
def JoinPaths(apath, rpath): """ Joins a relative path to an absolute path Input: apath - Absolute path rpath - Relative path """ if len(rpath)==0: res = apath elif len(apath)==0: res = './'+rpath elif rpath[0]=='/' or apath[-1]=='/': res = apath+rpath el...
def read_str(inp, pos, length): """Decode and return a bytestring encoded by :py:func:`read_str`. Invokes `getc` repeatedly, which should yield byte ordinals from the input stream.""" if pos >= length: return '', pos lb = inp[pos] if lb < 0x80: return '', pos pos += 1 out...
def msg_signage_point(timestamp_str: str) -> str: """Get a fake log msg in case a new signage point has started""" line = ( f"{timestamp_str} full_node chia.full_node.full_node: INFO" + ":timer: Finished signage point 19/64: CC: RC:" ) return line
def hashable(data, v): """Determine whether `v` can be hashed.""" try: data[v] except (TypeError, KeyError, IndexError): return False return True
def _negation(value): """Parse an optional negation after a verb (in a Gherkin feature spec).""" if value == "": return False elif value in [" not", "not"]: return True else: raise ValueError("Cannot parse '{}' as an optional negation".format(value))
def sign(x): """Determine the sign of x. Returns: -1 if x is negative, +1 if x is positive or 0 if x is zero. """ return (x > 0) - (x < 0)
def Remove(duplicate): """This function will remove duplicated elements from lists""" final_list = [] for num in duplicate: if num not in final_list: final_list.append(num) return final_list
def scrna2tracer_mapping(scrna_cellnames, tracer_cellnames): """ Parameters ---------- scrna_cellnames : tracer_cellnames : Returns ------- """ # I hate everything about this--S Markson 7 September 2020 tracer2scrna_name = {} for tracer_cellname in t...
def _next_power_of_2(x): """ Returns the smallest power of 2 that is greater than x """ return 1 if x == 0 else 2**(x - 1).bit_length()
def depth_first_search(grid, start, target): """ Search a 2d grid for a given target starting at start. Args: grid: the input grid as a List[List] start: the start grid in format (x,y) zero index target: the target value to find in the grid Returns: Coordinate of the tar...
def convert_args_dict_to_list(dict_extra_args): """ flatten extra args """ list_extra_args = [] if 'component_parallelism' in dict_extra_args: list_extra_args += ["--component_parallelism", ','.join(dict_extra_args['component_parallelism'])] if 'runtime_config' in dict_extra_args: ...
def equals_list2dict(equals_list): """Converts an array of key/values seperated by = to dict""" return dict(entry.split('=') for entry in equals_list)
def box_within_bounds( x, y, w, h, width, height, min_margin_ratio, min_width_height_ratio ): """ function for checking whether bbox width-height falls within set margin """ min_width = min_width_height_ratio * width min_height = min_width_height_ratio * height if w < min_width or h < min_he...
def is_palindrome(s): """Assumes s is a str Returns True if letters in s form a palindrome; False otherwise. Non-letters and capitalization are ignored.""" def to_chars(s): s = s.lower() letters = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': le...
def get_accuracy(predictions: list, targets: list): """ Here, t can be a list of acceptable labels, instead of just one label. This is helpful if an evaluation dataset has fewer classes than a model was trained with. For example, say we want an nli model trained with contraditction, entailment, neut...
def extract_id(literal): """ Given an object literal, return the object ID. """ if(isinstance(literal, str) and literal.startswith('#')): end = literal.find("(") if(end == -1): end = literal.find( " ") if(end == -1): end = len(literal) return int(l...
def string_insert(string, position_inserts): """ Insert strings in position_inserts into string, at indices. position_inserts will look like: [(0, "hi"), (3, "hello"), (5, "beep")] """ offset = 0 position_inserts = sorted(list(position_inserts)) for position, insert_str in posi...
def compute_avg_inc_acc(results): """Computes the average incremental accuracy as defined in iCaRL. The average incremental accuracy at task X are the average of accuracy at task 0, 1, ..., and X. :param accs: A list of dict for per-class accuracy at each step. :return: A float. """ tasks_...
def get_iteration_prefix(i, total): """ Return a String prefix for itarative task phases. :param i int current step. :param total int total steps. """ return " [{0}/{1}]".format(i, total)
def trunc(s, length, ellipsis=None): """Truncates a string at a good length. Finds the rightmost space in a string, and truncates there. Lacking such a space, truncates at length. If an ellipsis is provided, the right most space is used that allows the addition of the ellipsis without being longer...
def remove_prefix(string, prefix): """ This function removes the given prefix from a string, if the string does indeed begin with the prefix; otherwise, it returns the original string. """ if string.startswith(prefix): return string[len(prefix):] else: return string
def dtKey(pre, dts): """ Returns bytes DB key from concatenation of '|' qualified Base64 prefix bytes pre and bytes dts datetime string of extended tz aware ISO8601 datetime of event '2021-02-13T19:16:50.750302+00:00' """ if hasattr(pre, "encode"): pre = pre.encode("utf-8") # conv...
def first(iterable): """Helper function, returns the first element of an iterable or raises `IndexError` if the iterable is empty""" for elem in iterable: return elem raise IndexError
def _pos_neg_csr_arrays(data, indices): """helper to split a data vector into positive and negative components""" pos_data, neg_data = [], [] pos_indices, neg_indices = [], [] for i in range(len(data)): d = data[i] if d > 0: pos_data.append(d) pos_indices.append(i...
def bytes_packet(_bytes, termination_string=']'): """ Create a packet containing the amount of bytes for the proceeding data. :param _bytes: :param termination_string: :return: """ return '{}{}'.format(len(_bytes), termination_string)
def getKeyByValue(dictOfElements, valueToFind): """Get the first key that contains the specified value.""" for key, value in dictOfElements.items(): if value == valueToFind: return key
def get_special_tokens(vocab_size): """Gets the ids of the four special tokens. The four special tokens are: pad: padding token oov: out of vocabulary bos: begin of sentence eos: end of sentence Args: vocab_size: The vocabulary size. Returns: The four-tuple (pad, oov, bos, eos). """...
def sudo_command(command, python): """Prepends command with sudo when installing python packages requires sudo.""" if python.startswith("/usr/"): command = "sudo " + command return command
def retry_if_not_value_error(exception): """Forces retry to exit if a valueError is returned. Supplied to the 'retry_on_exception' argument in the retry decorator. Args: exception (Exception): the raised exception, to check Returns: (bool): False if a ValueError, else True """ ...
def tail_recurse(prev, curr): """ Using tail recursion, reverses the linked list starting at curr, then joins the end of this linked list to the linked list starting at prev. """ if curr: new_curr = curr.next_node if new_curr: curr.next_node = prev return tail...
def normalize_to_list(str_or_iterable): """Convert strings to lists. convert None to list. Convert all other iterables to lists """ if isinstance(str_or_iterable, str): return [str_or_iterable] if str_or_iterable is None: return [] return str_or_iterable
def lin_map(x, x_min, x_max, out_min, out_max, limit=False): """ map x that should take values from x_min to x_max to values out_min to out_max""" r = float(x - x_min) * float(out_max - out_min) / \ float(x_max - x_min) + float(out_min) if limit: return sorted([out_min, r, out_max])...
def _generate_new_prefix(current_prefix, class_name): """ Generate the new prefix to be used when handling nested configurations. Examples: >>> _generate_new_prefix("", "config_group_1") "CONFIG_GROUP_1" >>> _generate_new_prefix("my_app", "another_config_group") "MY_APP_ANOTHER_CONFIG_GROU...
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list (ascending order). Returns a new sorted list with the same elements in list1, but with no duplicates. """ unique_list1 = [] # For every word in the list, compare it against the following word for index in range(len(...
def create_db_links(txt_tuple_iter, detail_page): """ From an iterable containing DB info for records in DB or 'not in DB' when no instances were found, returns info formatted as url links to detail pages of the records. :param txt_tuple_iter: an iterable of tuples where the 0 element of the ...
def getRange(xs, ys, xMin, xMax): """ Return the Ys for the range of points where the Xs is at or between the given min/max limits """ rangeYs = [] for i in range(len(ys)): x = xs[i] if(x >= xMin and x <= xMax): rangeYs.append(ys[i]) if len(rangeYs) == 0: ...
def fib(n): """Some doc""" return 1 if n <= 1 else fib(n-1) + fib(n-2)
def add_context(context, new_input): """ Update the context strings for all speakers in a conversation. Args: context: A dictionary of context strings for all speakers new_input: A string to be appended to the context for all speakers. Returns: new_context: An updated dictionary of co...
def _check_lower_bound(x, lower, full_name, short_name, inclusive_bound=True): """Check object satisfies lower bound.""" if inclusive_bound: if x < lower: raise ValueError( "%s must be at least %r " "(got %s=%r)" % (full...
def contains(List, value): """ Reports whether 'value' is in 'List' """ try: List.index(value) except ValueError: return False else: return True
def safe_name(filename): """ Protection against bad database names :param filename: the filename :return: a safe fileneame """ return str(filename).replace('.', '_')
def sanitize(msg): """Sanitizes the existing msg, use before adding color annotations""" msg = msg.replace('@', '@@') msg = msg.replace('{', '{{') msg = msg.replace('}', '}}') msg = msg.replace('@@!', '@{atexclimation}') msg = msg.replace('@@/', '@{atfwdslash}') msg = msg.replace('@@_', '@{a...
def lowerfirst(value): """Un-capitalizes the first character of the value.""" return value and value[0].lower() + value[1:]
def line_1d(x, slope, offset): """Return the value of a line with given slope and offset. Parameters ---------- x : float or iterable of floats The x-value to calculate the value of the line at. slope : float The slope of the line. Must be finite. offset : float The y-of...
def get_workflow_status_change_verb(status): """Give the correct verb conjugation depending on status tense. :param status: String which represents the status the workflow changed to. """ verb = "" if status.endswith("ing"): verb = "is" elif status.endswith("ed"): verb = "has be...
def verify_patient_id(patient_id): """ This function is meant to check if the patient id is the right format This function first checks to see if the patient id is an integer. If it is an integer than that number is returned without manipulation. If the patient_id is a string then this function...
def _run_step(network, X_batch, y_batch, cost=None, acc=None): """Run for one step""" y_pred = network(X_batch) _loss, _acc = None, None if cost is not None: _loss = cost(y_pred, y_batch) if acc is not None: _acc = acc(y_pred, y_batch) return _loss, _acc