content
stringlengths
42
6.51k
def getfield(s:str, n:int): """Get nth word in s, separated by whitespace.""" list=s.split() if n<0 or n>=len(list): return "" return list[n]
def eff(effort_str): """Convert effort string to float. Various 'bad' strings are coped with: n? ?n n+ <n? """ # Munge some bad strings to be good if effort_str and effort_str[0] in ['<', '?']: effort_str = effort_str[1:] if effort_str and effort_str[-1] in ['?', '+']: effort_st...
def count_round(d,verbose=True): """ add votes in for given round d is a dictionary with the reduced ballots as keys and counts as values """ cand_votes_dict = dict() for k in d.keys(): v = int(d[k]) cands = k.split('_') if len(cands[0]) > 0: if cands[0] in cand_v...
def to_int_keys(l): """ l: iterable of keys returns: a list with integer keys """ seen = set() ls = [] for e in l: if e not in seen: ls.append(e) seen.add(e) ls.sort() index = {v: i for i, v in enumerate(ls)} return [index[v] for v in l]
def partition(predicate, values): """ Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item...
def is_real_number(obj): """Yield whether an object is a real number""" return isinstance(obj, float) or isinstance(obj, int)
def recursive_factorial(n: int) -> int: """ Calculates the factorial of a natural number. If the number is less than 0, it raises a ValueError. >>> recursive_factorial(0) 1 >>> recursive_factorial(1) 1 >>> recursive_factorial(6) 720 >>> recursive_factorial(-2) Traceback (mos...
def format_index(index, word): """ Format index of word in sentence to appear in the aligned version """ return "{{{{{}|{}}}}}".format(index, word)
def hash_point_pair(p1, p2): """Helper function to generate a hash from two time/frequency points.""" return hash((p1[0], p2[0], p2[1]-p2[1]))
def first_of(attr, match, it): """ Return the first item in a set with an attribute that matches match """ if it is not None: for i in it: try: if getattr(i, attr) == match: return i except: pass return None
def formatVector(test_vector): """Reformat test vector dictionary into an appropriate target payload""" length = int(test_vector['length']) if not (0 <= length and length <= 20): print("[Relay] Length field out of bounds [0,20] : " + str(length)) print(test_vector) return bytearray(0...
def invert_dict(d): """Invert the given dict.""" return {v: k for k, v in d.items()}
def ExecuteFunction(function, *args, **kwargs): """Stub method so that it can be used for mocking purposes as well. """ return function(*args, **kwargs)
def _remove_overlapping_vars(list_to_check, includes_list): """ Checks, and removes, any variable in list_to_check that is also in includes_list, returning list_to_check without overlapping variable names. """ return [x for x in list_to_check if x not in includes_list]
def merge_two_dicts(A, B): """ Merge two dictionaries. :param A: Dictionary A :param B: Dictionary B :return: The merged dictionary """ result = A.copy() result.update(B) return result
def resolution(clause1, clause2, name): """Apply resolution to the two clauses on the given name. Returns the new clause. This function assumes the inputs are valid. """ lit1 = [lit for lit in clause1 if lit[0] != name] lit2 = [lit for lit in clause2 if lit[0] != name] return list(set(lit1 + l...
def compose_list(n): """first adding the numbers that are multiples of 3 and 5""" list = [] for i in range(0, n): if (i % 3 == 0) or (i % 5 == 0): list.append(i) return list
def insert_details_into_summary_dict(artifacts_summary, artifacts_by_cat_no): """Put in info from Appendix B into the artifacts by exc element dict. Currently mutates the original artifacts by exc element dict.""" for exc_element in artifacts_summary.values(): for zone in exc_element['zones']: ...
def seasonName(seasonInt): """Takes the season parameters from the .csv file and converts them from strings (str) to integers (int) for later comparison Parameters: Takes the user input from above and converts ths integer into a string Return: Returns the chosen season a string""" i...
def count_osds(tripleo_environment_parameters): """ Counts the requested OSDs in the tripleo_environment_parameters. Returns an integer representing the count. """ total = 0 if 'CephAnsibleDisksConfig' in tripleo_environment_parameters: disks_config = tripleo_environment_parameters['Ceph...
def extract_category(report, key): """ Create a dict from a classification report for a given category. Args: report: The report key: The key to a category on the report """ result = report.get(key) result['category'] = key return result
def C2F(C): """Convert Celsius to Fahrenheit""" return 1.8 * C + 32
def dash2space(s): """Return s with dashes turned into spaces""" return s.replace('-', ' ')
def escapeString(val, maxLength=254): """ Quotes several characters and removes "\\\\n" and "\\\\0" to prevent XSS injection. :param val: The value to be escaped. :type val: str :param maxLength: Cut-off after maxLength characters. A value of 0 means "unlimited". :type maxLength: int :returns: The quoted s...
def get_link_type(link): """Certain types of links need to be handled specially, this figures out when that's the case""" if link['base_url'].endswith('.pdf'): return 'PDF' elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'): return 'im...
def split_on_uppercase(s, keep_contiguous=True): """ Args: s (str): string keep_contiguous (bool): flag to indicate we want to keep contiguous uppercase chars together Returns: """ string_length = len(s) is_lower_around = (lambda: s[i - 1].islo...
def accumulate_metrics__(metrics, cum_metrics, batch_metrics, validation_dataset=False): """ internal helper function - "sums" metrics across batches """ if metrics is not None: for metric in metrics: if validation_dataset: cum_metrics['val_%s' % metric] += batch_metrics['val...
def nearest_smallest_element(arr): """ Given an array arr, find the nearest smaller element for each element. The index of the smaller element must be smaller than the current element. """ smaller_numbers = [] def nearest(n): def find_previous_num(): for previous_num in reve...
def generate_cartesian_coordinates(n_x, n_y, scaling=1.0): """ Generate cartesian coordinates which can be used to set up a cell population. Parameters ---------- n_x: int number of columns n_y: int number of rows scaling: float distance between the cells, in cel...
def gen_target_dict(n): """Generates the dictionary that should result if n is self describing. """ target = {} for i,c in enumerate(str(n)): target[i] = int(c) return target
def counting_sort2(k, arr): """ Another implementation of counting sort for lists of integers in the range [0, k) which uses nested lists Complexity: O(n + k) """ cache = [[] for _ in range(k)] # O(k) for e in arr: # O(n) cache[e].append(e) output = [] for key in range(k): # O(k) output...
def abandon_nodes(parses, labels, remove_dependents=False): """ given an array of parses (sequences of dicts), abandon nodes with any of the defined labels, e.g., FRAG or PARSE nodes. note that children are preserved if remove_dependents is True, the entire subtree is wiped out """ result=[] for p in parses: i...
def PrepModalDialogFieldErrorMsg(msg): """ Format the message so it looks just like a regular django html form field error :param msg: :return: formatted message """ if not msg: return None return '<ul class="errorlist"><li>{0}</li></ul>'.format(msg)
def _check_start_normalize(start, ndim): """check and normalize start argument for rollaxis.""" if start < -ndim or start > ndim: raise ValueError(f"For rollaxis, start {start} is out of bounds. Ranging from {-ndim} to {ndim} is allowed.") if start < 0: start = start + ndim return start
def try_divide(x, y): """ Try to divide two numbers """ val = 0.0 if y != 0.0: val = float(x) / float(y) return val
def opt_to_kwargs(opt): """Get kwargs for seq2seq from opt.""" kwargs = {} for k in [ 'numlayers', 'dropout', 'bidirectional', 'rnn_class', 'lookuptable', 'decoder', 'numsoftmax', 'attention', 'attention_length', 'attention_time...
def charWrap(s, width, hanging=0): """Word wrap a string. Return a new version of the string word wrapped with the given width and hanging indent. The font is assumed to be monospaced. This can be useful for including text between <pre> </pre> tags, since <pre> will not word wrap, and for lengthy ...
def _compact4nexus(orig_list): """Transform [1 2 3 5 6 7 8 12 15 18 20] (baseindex 0, used in the Nexus class) into '2-4 6-9 13-19\\3 21' (baseindex 1, used in programs like Paup or MrBayes.). """ if not orig_list: return '' orig_list = sorted(set(orig_list)) shortlist = [] clist = ...
def to_float(string): """Converts a string to a float if possible otherwise returns None :param string: a string to convert to a float :type string: str :return: the float or None if conversion failed and a success flag :rtype: Union[Tuple[float, bool], Tuple[None, bool]] """ try: r...
def find_samp_rec(s, data, az_type): """ find the orientation info for samp s """ datablock, or_error, bed_error = [], 0, 0 orient = {} orient["sample_dip"] = "" orient["sample_azimuth"] = "" orient['sample_description'] = "" for rec in data: if rec["er_sample_name"].lower() ...
def flatten(a): """ flatten(a) Return a flattened list of the sublists in a. """ return [item for sublist in a for item in sublist]
def convert_weight_stone(weight): """Converts user's weight from Imperial to British Imperial stones and returns a float.""" weight_stone = weight / 14 return weight_stone
def astrix_line(qty: int=80) -> str: """Return break line of astrix characters. :param int qty: number of * characters to be returned :returns: * characters and a line break :rtype: str """ return '*' * int(qty) + '\n'
def hamming(s1, s2): """Calculate the Hamming distance between two strings""" assert len(s1) == len(s2) return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def contains_any(a, bs): """Returns true if any of the strings in list bs are found in the string a""" for b in bs: if b in a: return True return False
def discard_inserted_documents(error_documents, original_documents): """Discard any documents that have already been inserted which are violating index constraints such documents will have an error code of 11000 for a DuplicateKey error from https://github.com/mongodb/mongo/blob/master/src/mongo/base/...
def extract_str(input_) -> str: """Extracts strings from the received input. Args: input_: Un-formatted string. Returns: str: A perfect string. """ return ''.join([i for i in input_ if not i.isdigit() and i not in [',', '.', '?', '-', ';', '!', ':']])
def __get_aggregate_contributions(contrib_list): """Aggregates contribution data from a list of contributions.""" # Structure that is used for the aggregated contributions; this is [mostly] # a structural copy of what the Stackalytics API contractually promises. ret = dict(change_request_count=0, ...
def _ExtractResNetThroughput(output): """Extract throughput from Horovod output. Args: output: Horovod output Returns: A tuple of: Average throuput in images per second (float) Unit of the throughput metric (str) """ # Start from last line and iterate backwards. avg_throughput = 0 fo...
def _make_divisible(v, divisor, min_value=None): """ Ensure that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: ...
def subtract_profiles(prof1, prof2): """Subtract prof2 from prof1. A new profile is returned.""" prof1_len = len(prof1) assert prof1_len == len(prof2), "Activity Profiles must have the same length to be compared." result = [] for idx in range(prof1_len): d = prof1[idx] - prof2[idx] i...
def flatten(sequence, types=(list, tuple)): """Flatten sequence made of types, returned as the same outer type as sequence. REF: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html """ sequence_type = type(sequence) sequence = list(sequence) i = 0 while i < len(sequence): ...
def argument(arg): """I have an argument.""" return dict(arg=arg)
def is_order_family(listrow): """ Check if a CSV row contains only the order and family data :param listrow: CSV row :return: True if the row contains only the order and family data """ assert type(listrow) is list return listrow[1] == ''
def format_size(n: int): """http://code.activestate.com/recipes/578019 >>> format_size(10000) '9.8K' >>> format_size(100001221) '95.4M' """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s ...
def make_tags_in_proper_format(tags): """Take a dictionary of tags and convert them into the AWS Tags format. Args: tags (list): The tags you want applied. Basic Usage: >>> tags = [{'Key': 'env', 'Value': 'development'}] >>> make_tags_in_proper_format(tags) { "en...
def map_num_to_char(num): """ Map an integer to an uppercase alphabet letter, e.g. 1 -> A """ return chr(ord('@')+num)
def find_subf(d, code=None): """ Return subfields in arg1 or subfields in arg1 matching code arg2. Parameters: arg1: The field tuple to be searched arg2: The subfield field code to be searched for. If ommitted or None, all subfields will be returned Returns: A tuple of subfield tuples (em...
def __getmappinglabel__(mapping, value): """ Gets index of label value in mapping. :param mapping: mapping dictionary :param value: value for which the mapping is searched for :return: index of value in mapping """ if value in mapping["labels"]: return mapping["labels"].index(value) ...
def fwscan_wins(limit, rlen, numdocs): """ Primitive curve-fitting to see if forward scan will beat both nbest and timsort for a particular limit/rlen/numdocs tuple. In sortbench tests up to 'numdocs' sizes of 65536, this curve fit had a 95%+ accuracy rate, except when 'numdocs' is < 64, then its ...
def get_workflow_min_job_memory(complexity): """Return minimal job memory from workflow complexity. :param complexity: workflow complexity list which consists of number of initial jobs and the memory in bytes they require. (e.g. [(8, 1073741824), (5, 2147483648)]) :return: minimal job memory (e.g. 10737418...
def students (theDictionary): """Identifies students with a locker and sorts them into a list. :param dict[str, str] theDictionary: key: locker number / value: student name or "open" :return: Sorted list of students with a locker :rtype: list[str] """ studentList = [] for k...
def _reg2float(reg): """Translate the register value to a floating-point number. Note ---- The float precision is specified to be 1 digit after the decimal point. Bit [31] (1 bit) -> Sign (S) Bit [30:23] (8 bits) -> Exponent (E) Bit [22:0] (23 bits) -> M...
def is_ratio_different(min_ratio, study_go, study_n, pop_go, pop_n): """ check if the ratio go/n is different between the study group and the population """ if min_ratio is None: return True s = float(study_go) / study_n p = float(pop_go) / pop_n if s > p: return s / p > ...
def max_alignment(s1, s2, skip_character='~', record=None): """ A clever function that aligns s1 to s2 as best it can. Wherever a character from s1 is not found in s2, a '~' is used to replace that character. Finally got to use my DP skills! """ if record is None: record = {} assert...
def calculateMAP(recallPoints): """ Calculate and returns the Mean Average Precision out of the recall points. Works with either interpolated or not points. If the recall points list is empty returns 0.0. param recallPoints: list of tuples (precision, recall). return: a number, representing th...
def get_row_col_bounds_tms(level): """ coord [x,y] """ nrow = 2 ** (level) if level else 1 ncol = 2 ** level return nrow, ncol
def tuple_keys_to_str(dictionary): """ Converts tuple keys to str keys """ finaldict = {} for key in dictionary.keys(): strkey = () for item in key: if type(item) == int: strkey += (str(item),) else: strkey += (item,) newkey = '_'.join(strkey) finaldict[newkey]=dict...
def is_eligible_file( filename ): """ Based on the file name, decide whether the file is likely to contain image data """ eligible = False if ( filename.endswith( '.png' ) or filename.endswith( '.jpg' ) ): eligible = True return eligible
def get_data_bounds(data): """ Return a dict of two lists, containing max and min for each column. Assumes labels are being stored right now. """ max_in_col = {} min_in_col = {} for row in data: for idx, val in row: if idx not in max_in_col: max_in_col[idx] = val ...
def MemoryBytesToMb(value): """Converts bytes value to truncated MB value.""" if value == 0: return 0 memory_mb = value // 1024 // 1024 if memory_mb == 0: memory_mb = 1 return memory_mb
def flip_dict(d): """Returns a dict with values and keys reversed. Args: d: The dict to flip the values and keys of. Returns: A dict whose keys are the values of the original dict, and whose values are the corresponding keys. """ return {v: k for k, v in d.items()}
def _allowed_pkg_manager_stderr(stderr, allowed_errors): """Returns False if the error message isn't in the allowed_errors list. This function factors out large, and possibly expanding, condition so it doesn't cause too much confusion. """ if stderr in allowed_errors: return True re...
def map_indices_py(arr): """ Returns a dictionary with (element, index) pairs for each element in the given array/list """ return dict([(x, i) for i, x in enumerate(arr)])
def _is_response_really_200(www_body): """ Sometimes server responds with HTTP 200 and '404'-alike content so we need to doublecheck that. """ probe_phrase = 'Such an ad does not exist or was disabled.' return probe_phrase not in www_body
def _clip(value, lower, upper): """ Helper function to clip a given value based on a lower/upper bound. """ return lower if value < lower else upper if value > upper else value
def above_threshold(student_scores, threshold): """ :param student_scores: list of integer scores :param threshold : integer :return: list of integer scores that are at or above the "best" threshold. """ pets = [] for index, _ in enumerate(student_scores): if student_scores[index] >...
def invalid_request_error(e): """Generates a valid ELG "failure" response if the request cannot be parsed""" return {'failure':{ 'errors': [ { 'code':'elg.request.invalid', 'text':'Invalid request message' } ] } }, 400
def getMappedPoint(dataPointPath, mappedDataPoints): """For each data point in the database, get its mapped datapoint that contains all the information regarding how such data point maps to the database""" #This can be improved for better performance, since for each data point it has to look through all the datapoin...
def format_log_message(message, transaction=None, *args): """ Message log formatter for processors. """ if transaction or args: format_args = [transaction] format_args.extend(args) return message % tuple(format_args) else: return message
def unparse_vs(tup): """version list to string""" return '.'.join(map(str, tup))
def get_base_classification(x: str) -> str: """ Obtains the base classification for a given node label. Args: x: The label from which to obtain the base classification. Returns: The base classification. """ return x.split('_', 1)[0]
def __validate_scikit_params(parameters): """validate scikit-learn DBSCAN parameters Args: parameters: (dict) Returns: eps, min_samples, metric, n_jobs """ eps, min_samples, metric, n_jobs = None, None, None, None if parameters is not None: eps = parameters.g...
def count_encrypted_layers(encrypted_layers: dict): """ Count number of encrypted layers homomorphic encryption (HE) layers/variables. """ n_total = len(encrypted_layers) n_encrypted = 0 for e in encrypted_layers.keys(): if encrypted_layers[e]: n_encrypted += 1 return n_...
def scanBrackets(expr_str, fromIndex=0): """Looks for matching brackets. >>> scanBrackets('abcde') (-1, -1) >>> scanBrackets('()') (0, 1) >>> scanBrackets('(abc(def))g') (0, 9) >>> s = ' (abc(dd efy 442))xxg' >>> startpos, endpos = scanBrackets(s) >>> print s[startpo...
def shorten_text(text, new_len): """ Shorten text to a particular len. Indicate text was cut out with a period if we end on middle of word. Args: text: The text to shorten. new_len: The length desired. Returns: Text guaranteed to be at most len. """ if text[:new_len] != tex...
def filterTheDict(dictObj, callback): """ Filter the dict """ newDict = dict() # Iterate over all the items in dictionary for (key, value) in dictObj.items(): # Check if item satisfies the given condition then add to new dict if callback((key, value)): newDict[key] = ...
def transmismatch(I1, I2, tap1, tap2): """ Electrical Transformer TAP Mismatch Function. Function to evaluate the transformer ratio mismatch for protection. Parameters ---------- I1: complex Current (in amps) on transformer primary side. I2: complex ...
def get_change(budget, exchanging_value): """ The amount left of your starting currency after exchanging exchanging_value. :param budget: float - amount of money you own. :param exchanging_value: int - amount of your money you want to exchange now. :return: float - amount left of your starting curr...
def pattern_sort(lst, pattern, key=None, reverse=False): """sorts lst based on pattern (e.g. ```pattern_sort(['a','ba','c'], [2, 0, 1], lambda x: len(x))``` would return ```['ba','a','c']```) lst: the list to sort \\ pattern: the pattern to sort with (list of numbers, i.e. ```[2, 1, 0]``` would swa...
def get_index(s): """ get the index in the string like 'a[4]'. should return 4 """ return int(s[s.find("[")+1:s.find("]")])
def match(lst, ratio, ground, num_classes): """ Match proposal and ground truth correspond_map: record matching ground truth for each proposal count_map: record how many proposals is each ground truth matched by index_map: index_list of each video for ground truth :param lst: list of proposals...
def partition_at_level(dendrogram, level): """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher the le...
def parseSec(name): """ Results as in miliseconds """ if name == "nsec": return 1e-6 elif name == "msec": return 1 elif name == "sec": return 1e3
def indentation(level): """Return the indentation string for a given level of indentation""" return level * 4 * ' '
def matrix_vector_multiply(mat, vec): """Multiplies a matrix by a vector. Multiplies an m x n matrix by an n x 1 vector (represented as a list). Args: mat (2-D list): Matrix to multiply. vec (list): Vector to multiply. Returns: Product of mat and vec (an m x 1 vector) as a...
def get_vm_custom_param(vm_custom_params, param_name): """ :param list[VmCustomParam] vm_custom_params: :param param_name: :return: """ for param in vm_custom_params: if param.Name == param_name: return param return None
def is_tuple(x): """ Check that argument is a tuple. Parameters ---------- x : object Object to check. Returns ------- bool True if argument is a tuple, False otherwise. """ return isinstance(x, tuple)
def generate_tap_stream_id(catalog_name, schema_name, table_name): """Generate tap stream id as appears in properties.json""" return catalog_name + '-' + schema_name + '-' + table_name
def warshall_adjacency(matrix): """Applies the Warshall transitive closure algorithm to a adjacency matrix. Args: matrix: The adjacency matrix. Returns: The closed form of the adjacency matrix. """ for k in range(0, len(matrix)): for i in range(0, len(matrix)): ...