content
stringlengths
42
6.51k
def calc_inline_field_name(line_num, model_field): """ Generate inline field name :param line_num: Line number :param model_field: Model field name :return: the inline field name in the UI form. """ return 'lines-{0}-{1}'.format(str(line_num), model_field)
def mean(vector): """Calculates mean""" list_vector = list(vector) sum_vector = sum(list_vector) len_vector = float(len(list_vector)) mean_final = sum_vector/len_vector return(mean_final)
def get_sim_and_agent_index(agent_id, config): """Given the index of the agent, find which simulator and which position the agent belongs to (inside the simulator) Args: agent_id: Global index of the agent config: configuration directory Returns: sim_index : which simulator the ...
def ceildiv(num, den): """Integer division, rounding up.""" return -(-num // den)
def use_device(use_cpu = 1): """ Choose available CPU or GPU devices to use. """ if (use_cpu == 1): device = '/device:CPU:0' else: device = '/device:GPU:0' return device
def find_by_type(cptype, cps_by_type): """ :param cptype: Config file's type :param cps_by_type: A list of pairs, (processor_type, [processor_class]) :return: Most appropriate processor class to process given type or None >>> from anyconfig.backends import _PARSERS_BY_TYPE as cps >>> find_by_t...
def orgunit_cleanup_name(name_str): """ Convert name to DHIS2 standard form and fix any whitespace issues (leading, trailing or repeated) """ if name_str: name_str = name_str.strip() # remove leading/trailing whitespace name_str = re.sub(r'\s+', ' ', name_str) # standardise and "comp...
def map_nested(dd, fn): """Map a function to a nested data structure (containing lists or dictionaries Args: dd: nested data structure fn: function to apply to each leaf """ if isinstance(dd, dict): return {key: map_nested(dd[key], fn) for key in dd} elif isinstance(dd, list): ...
def _make_suffix(cov): """Create a suffix for nbval data file depending on pytest-cov config.""" # Check if coverage object has data_suffix: if cov and cov.data_suffix is not None: # If True, the suffix will be autogenerated by coverage.py. # The suffixed data files will be automatically com...
def matrixMultiplicationListComprehesion(A, B): """Multiply two squared matrices using list comprehesion""" return [[sum([x*y for (x, y) in zip(row, col)]) for col in zip(*B)] for row in A]
def checkversion(obj): """ Checks the version of an object. Returns -1 if there is no version """ if hasattr(obj, '__version__'): return obj.__version__ elif ('__version__' in obj) and isinstance(obj, dict): return obj['__version__'] else: ...
def urlize(val): """ Ensures a would-be URL actually starts with "http://" or "https://". :param val: the URL :returns: the cleaned URL >>> urlize('gnu.org') 'http://gnu.org' >>> urlize(None) is None True >>> urlize(u'https://gnu.org') 'https://gnu.org' """ if val and n...
def safe_key(dic: dict, key, default=None): """Return dict[key] if dict has the key, in case of KeyError. Args: dic(dict): a dictionary. key(usually str or int): key. default: default return value. Returns: dic[key] if key in dic else default. """ if key in dic: ...
def _find(nodes, i): """Find function for the Union-Find algorithm.""" if nodes[i] != i: nodes[i] = _find(nodes, nodes[i]) return nodes[i]
def construct_update_issue_payload(issue, alert_text, helpshift_dashboard_url): """ Construct a payload which will be send to slack on issue update. issue: Issue data as send in webhook payload. helpshift_dashboard_url: Helpshift dashboard URL. return: Payload to send slack alert on issue update ev...
def remove_falses(tup: tuple) -> tuple: """Removes all false occurences from a tuple.""" return tuple([i for i in tup if i])
def subdict(d, keys): """ Create a subdictionary of d with the keys in keys Parameters ---------- d : WRITEME keys : WRITEME Returns ------- WRITEME """ result = {} for key in keys: if key in d: result[key] = d[key] return result
def isconsecutive(lst): """ Returns True if all numbers in lst can be ordered consecutively, and False otherwise """ if len(set(lst)) == len(lst) and max(lst) - min(lst) == len(lst) - 1: return True else: return False
def is_list_of_ints(intlist): """ Return True if list is a list of ints. """ if not isinstance(intlist, list): return False for i in intlist: if not isinstance(i, int): return False return True
def midi_to_ansi_note(midi_note): """ returns the Ansi Note name for a midi number. ::Examples:: >>> midi_to_ansi_note(21) 'A0' >>> midi_to_ansi_note(102) 'F#7' >>> midi_to_ansi_note(108) 'C8' """ notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] num...
def set_unique_ids(dashboard): """To avoid the most common merge error: duplicate row ids.""" ids = set() for panel_index, panel in enumerate(dashboard['panels']): id_ = panel['id'] if id_ in ids: id_ = 1 while id_ in ids: id_ += 1 print('...
def shellSort(arr): """ docstring """ h = 1 while 3*h < len(arr): h = 3*h + 1 while h>=1: for i in range(h, len(arr)): j = i while j>0: if arr[j] < arr[j-h]: arr[j-h], arr[j] = arr[j], arr[j-h] j-=h ...
def text_transform(keyword): """``text-align`` property validation.""" return keyword in ( 'none', 'uppercase', 'lowercase', 'capitalize', 'full-width')
def _grep_first_pair_of_parentheses(s): """ Return the first matching pair of parentheses in a code string. INPUT: A string OUTPUT: A substring of the input, namely the part between the first (outmost) matching pair of parentheses (including the parentheses). Parentheses between...
def bytes2hex(bytes_array): """ Converts byte array (output of ``pickle.dumps()``) to spaced hexadecimal string representation. Parameters ---------- bytes_array: bytes Array of bytes to be converted. Returns ------- str Hexadecimal representation of the byte array. ...
def _calculate_distinct_ngrams(prediction_samples, ngram_len): """ Takes a list of predicted token_ids and computes number of distinct ngrams for a given ngram_length """ ngrams = set() for y in prediction_samples: # Calculate all n-grams where n = ngram_len. (Get ngram_len cyclic shifts...
def humanbytes(size: float) -> str: """humanize size""" if not size: return "" power = 1024 t_n = 0 power_dict = {0: " ", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power t_n += 1 return "{:.2f} {}B".format(size, power_dict[t_n])
def xor(x,y,z=None): """Evaluate the XOR on two or three operands""" if z is None: return list(i^j for i,j in zip(x,y)) else: return list(i^j^k for i,j,k in zip(x,y,z))
def get_result_dir(config): """ input: sample config file from BALSAMIC output: string of result directory path """ return config["analysis"]["result"]
def reformat_params(params): """Translate to spreadsheet values.""" params['mechanism'] = ['NS', 'RS', 'SS'].index(params['mechanism']) return params
def to_binary(value, encoding='utf-8'): """Convert value to binary string, default encoding is utf-8 :param value: Value to be converted :param encoding: Desired encoding """ if not value: return b'' if isinstance(value, six.binary_type): return value if isinstance(value, si...
def check_length(card_number): """ Checks that the length of the str card_number is 19 exactly :param card_number: str :return: bool """ if len(card_number) == 19: return True else: return False
def str_to_count(num): """Helper function to parse a string representation of a count value, with the empty string representing zero""" return 0 if num == '' else int(num)
def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xht...
def resort_list(liste, idx_list, n_x): """ Make sure list is in the same order as some index_variable. Parameters ---------- liste : List of lists. idx_list : List with indices as finished by multiprocessing. n_x : Int. Number of observations. Returns ------- weights : As above...
def get_separation_score(results): """ For a Solr response, compute the separation score which is derived from the ratio between the two first Solr scores. """ score1 = results[0]['score'] score2 = results[1]['score'] return (1 - score2 / score1)
def calculate_loss(prediction, target): """ Calculating the squared loss on the normalized GED. :param prediction: Predicted log value of GED. :param target: Factual log transofmed GED. :return score: Squared error. """ # prediction = -math.log(prediction) # target = -math.log(target) ...
def search_bt(t, d, is_find_only=True): """ Input t: a node of a binary tree d: target data to be found in the tree is_find_only: True/False, specifying type of output Output the node that contans d or None if is_find_only is True, otherwise the node that...
def Fx(y,z): """ X Prime """ xt = -y - z return xt
def guid2string(val): """ convert an active directory binary objectGUID value as returned by python-ldap into a string that can be used as an LDAP query value """ s = ['\\%02X' % ord(x) for x in val] return ''.join(s)
def fixed_length(l, length, pad_val): """Given a list of arbitrary length, make it fixed length by padding or truncating. (Makes a shallow copy of l, then modifies this copy.) Args: l: a list length: desired length pad_val: values padded to the end of l, if l is too short Retu...
def eh_pos_mov_str(s, mov): """ eh_pos_mov_str: str X booleano -> booleano Devolve True se a cadeira de caracteres corresponde ah representacao externa de uma posicao ou movimento, dependendo do valor do booleano, em que True representa um movimento e False uma posicao. """ if len(s) != (4 i...
def get_non_intersection_name(non_inter_segment, inters_by_id): """ Get non-intersection segment names. Mostly in the form: X Street between Y Street and Z Street, but sometimes the intersection has streets with two different names, in which case it will be X Street between Y Street/Z Street and A S...
def capsulate(flag, Eor, E, Cor, C, Te, Tc): """ capsulate VAD parameters """ params = {'flag': flag, 'energy-original': Eor, 'energy': E, 'centroid-original': Cor, 'centroid': C, 'threshold-energy': Te, 'threshold-centroid': Tc} return ...
def _create_embedded_row(value, out_row, out_col_ndx, config, group_values): """ Copies the given output row and assigns the given pattern match group values to the corresponding output row columns defined by the configuration. :return: the new output row """ # Make a new output row. ro...
def char_to_word(aText, charsubst): """Handle special characters used instead of words""" import re aText = re.sub("&", charsubst[0], aText) aText = re.sub("%", charsubst[1], aText) aText = re.sub(r"\+", charsubst[2], aText) aText = re.sub(r"=", charsubst[3], aText) aText = re.sub("/", chars...
def _scale(value, source, destination): """ Linear map a value from a source to a destination range. :param int value: original value :param tuple source: source range :param tuple destination: destination range :rtype: float """ return ( ((value - source[0]) / (source[1]-sourc...
def format_summary(raw_summary): """ Transforms the output into nicely formatted summaries. """ summary = ( raw_summary.replace("[unused0]", "") .replace("[unused3]", "") .replace("[PAD]", "") .replace("[unused1]", "") .replace(r" +", " ") .replace(" [unused2] ", ...
def to_int_list(values): """Converts the given list of vlues into a list of integers. If the integer conversion fails (e.g. non-numeric strings or None-values), this filter will include a 0 instead.""" results = [] for v in values: try: results.append(int(v)) except (Type...
def from_dict(x: dict) -> int: """ Converts a dictionary containing the prime factors and powers of an integer into it's integer form.""" res = 1 for p, r in x.items(): res *= p**r return res
def get_pairs(word): """ get character-level bigrams of input word """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def base_dict_to_string(base_dict): """ Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4 :param base_dict: Dictionary of bases and counts created by find_if_multibase :return: String representing that dictionary. """ outstr = '' for base in base_dict: ou...
def checkCulling( errs, cullStrings ) : """ Removes all messages containing sub-strings listed in cullStrings. cullStrings can be either a string or a list of strings. If as list of strings, each string must be a sub-string in a message for the message to be culled. """ def checkCullingMatch( m...
def nascar_8_bit(params): """ Reward on heading and waypoints """ import math # Read waypoint variables waypoints = params['waypoints'] closest_waypoints = params['closest_waypoints'] heading = params['heading'] # Initialize the reward with typical value reward = 10.0 # C...
def by_node(data): """ Split lines from OpenStack mysql nova database by node, flavor and the count of that flavor per node into a dictionary of dictionaries. """ coll = {} for line in data: val, flavor, node = line.split() if not node in coll.keys(): coll[node] =...
def _transitive(links): """perform transitive closure of links. For input [(1, 2), (2, 3)] the output is [(1, 2), (2, 3), (1, 3)] """ links = set(links) while True: new_links = [(src_a, trg_b) for src_a, trg_a in links for src_b, trg_b in links ...
def chart_title(plot_id, series_index): """Replaces generic Concept or Entity strings from chart titles with more specific name if it was specified. :param plot_id: Automatic title for chart :param series_index: Aggregation's index column name :return: str -- New chart title """ if series_i...
def is_valid_experiment_key(experiment_key): """ Validate an experiment_key; returns True or False """ return ( isinstance(experiment_key, str) and experiment_key.isalnum() and (32 <= len(experiment_key) <= 50) )
def to_codes(s): """Array of ASCII codes corresponding to a string""" return [ord(c) for c in s]
def personal_top_three(scores): """ Return the top three scores from scores. If there are fewer than three scores, return the scores. param: list of scores return: highest three scores from scores. """ # Sort the scores in descending order scores.sort(reverse=True) if len(scores) ...
def case_safe_sf_id(id_15): """ Equivalent to Salesforce CASESAFEID() Convert a 15 char case-sensitive Id to 18 char case-insensitive Salesforce Id or check the long 18 char ID. Long 18 char Id are from SFDC API and from Apex. They are recommended by SF. Short 15 char Id are from SFDC formula...
def pytest_json_modifyreport(json_report): """ - The function is called by pytest-json-report plugin to only output warnings in json format. - Everything else is removed due to it already being saved by junitxml - --json-omit flag in does not allow us to remove everything but the warnings - (the env...
def pil_logic(s): """Convert the CGI pil value into something we can query Args: s (str): The CGI variable wanted Returns: list of PILs to send to the databae""" if s == '': return [] s = s.upper() pils = [] if s.find(",") == -1: pils.append(s) else: ...
def sum_series(n, previous = 0, current = 1): """Function that returns value of the given index from Custom fibonacci-like sequence""" try: for i in range(n): previous, current = current, previous + current return previous except TypeError: return ("Input allows only inte...
def func_lineno(func): """Get the line number of a function. First looks for compat_co_firstlineno, then func_code.co_first_lineno. """ try: return func.compat_co_firstlineno except AttributeError: try: return func.func_code.co_firstlineno except AttributeError: ...
def rotate_right(seq: str, amount: int) -> str: """Right rotate a string, and return the result.""" return seq[-amount:] + seq[:-amount]
def classCount(rows): """ Counts the labels in list of rows :param rows: Input rows :return: Dictionary of labels with count as values """ counts = {} for row in rows: label = row[-1] if label not in counts: counts[label] = 0 counts[label] += 1 ...
def bytes_to_hex(input_bytes: bytes): """Takes in a byte string. Outputs that string as hex""" return input_bytes.hex()
def fib_bottom_up(n): """Clarify w/ interviewier, if client requests 1st Fib num, will they input n = 0 or n = 1? Assumption: they input n = 1 --> 0 is an invalid input """ dp_table = [1, 1] # the indices of the array = sequence value of the Fibonacci number for input in range(2, n): ...
def make_numeric_list(input_str: str, input_str_len: int) -> list: """ This converts an uppercase string of letters into a list of it's numeric values for use in the Hill cipher. All values are converted into their index of the standard english alphabet. :param input_str: The string to be listified. :param input...
def count_unique(list_to_count): """Counnunmber of entries for each unique value in list """ uniques = {} for element in list_to_count: if element in uniques: uniques[element] += 1 else: uniques[element] = 1 return uniques
def quadratic_item_score(i): """Function is similar to inverted and linear functions but weights are decreasing at non-linear rate and accelerate with the item position. Parameters ---------- i : int Item position. Returns ------- result : float Inverted square ...
def mmirror4(matrix): """Do a 4-way mirroring on a matrix from top-left corner.""" width = len(matrix[0]) height = len(matrix) for i in range(height): for j in range(width): x = min(i, height - 1 - i) y = min(j, width - 1 - j) matrix[i][j] = matrix[x][y] return matrix
def vector_as_matrix(v): """returns the vector v (represented as a list) as a n x 1 matrix""" return [[v_i] for v_i in v]
def kernel(x, index_of_selected_value, coef=0.423): """ Allows to change the distribution of the element according to the distance to selected element Arguments: x {int} -- index of element in the distribution index_of_selected_value {int} -- index of element, which is selected in the d...
def bbox(vertices): """Compute bounding box of vertex array. """ if len(vertices) > 0: minx = maxx = vertices[0][0] miny = maxy = vertices[0][1] minz = maxz = vertices[0][2] for v in vertices[1:]: if v[0] < minx: minx = v[0] elif v[0]...
def compare(recipe, wanted): """Compare recipe against wanted.""" for num1, num2 in zip(wanted, recipe): if num1 != num2: return False return True
def nhwc_8h2w32c2w_1d(n, h, w, c): """Return index map for nhwc_8h2w32c2w 1d layout""" return [n, h // 8, w // 4, c // 32, h % 8, (w % 4) // 2, c % 32, w % 2]
def calculate_triangle_area(a, b, c): """Calculates the performance optimized area of a triangle with given points a, b and c. Points ned to be a two tuple with x and y coordinates.""" ab = (b[0] - a[0], b[1] - a[1]) ac = (c[0] - a[0], c[1] - a[1]) # Cross product area = (ab[0] * ac[1]) - (ac[0]...
def fatorial(num, show=False): """ -> Calculo de fatorial :param num: O numero qu deseja saber o fatorial :param show: Se quer ver o calculo :return: O resultado, o fatorial """ f = 1 for c in range(num, 0, -1): f *= c if show: print(c, end=' ') if...
def comm(a, b): """Commutator of a and b.""" # Using `-1 * a` means everything works even when I've forgotten to # override __sub__ in classes. return a*b + (-1)*b*a
def get_path(backlinks, target): """ Given a dict of backlinks and target node, follow backlinks to root node (whose backlink is None) """ path = [] path_node = target while path_node is not None: path.append(path_node) path_node = backlinks.get(path_node, None) return li...
def i2P(sInt): """Convert a "small" integer into a "low-degree" polynomial""" res = [(sInt >> i) & 1 for i in reversed(range(sInt.bit_length()))] if len(res) == 0: res.append(0) return res
def bound(x, x_min, x_max): """ Truncates x between x_min and x_max :param x: :param x_min: :param x_max: :return: """ return min(max(x, x_min), x_max)
def a_plus_abs_b(a, b): """Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, -3) 5 >>> # a check that you didn't change the return statement! >>> import inspect, re >>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M) ['retur...
def _pop_lowest(lst): """ pop the lowest value from the list return the popped value""" return lst.pop(lst.index(min(lst)))
def signature(word: str) -> str: """Return a word sorted >>> signature("test") 'estt' >>> signature("this is a test") ' aehiisssttt' >>> signature("finaltest") 'aefilnstt' """ return "".join(sorted(word))
def calculate_centroid(gps_bounds): """Given a set of GPS boundaries, return lat/lon of centroid. gps_bounds -- (lat(y) min, lat(y) max, long(x) min, long(x) max) Returns: Tuple of (lat, lon) representing centroid """ return ( gps_bounds[0] + float(gps_bounds[1] - gps_bounds[0])/2...
def get(context, key, default=None): """Retrieve the value associated to a key in the current task context. Fallback to default if the key is missing. """ return context.get(key, default)
def format_slugged_name(field_name, capitalize=True): """ Makes a string slugged """ f = field_name.replace('_',' ') if capitalize: return f.capitalize() return f
def yes_maybe_condition_true(x: dict) -> bool: """ The yes maybe condition is true if 35% or 2 (or more) out of 3 users 2 (or more) out of 4 users 2 (or more) out of 5 users have classified as 'yes' or 'maybe' """ if x["yes_share"] + x["maybe_share"] > 0.35: return True else...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ next_0_index = 0 next_2_index = len(input_list) - 1 current_index = 0 while(current_index) < next_2_index + 1...
def reverse(insts): """ Reverse the order of instances. This function should be passed to :meth:`InstanceSet.select` without any argument. >>> insts = InstanceSet('prediction_result_path').select(reverse) """ return list(reversed(insts))
def computeLongestPalindromeLength(text): """ A palindrome is a string that is equal to its reverse (e.g., 'ana'). Compute the length of the longest palindrome that can be obtained by deleting letters from |text|. For example: the longest palindrome in 'animal' is 'ama'. Your algorithm should ru...
def int_or(val, or_val=None): """return val if val is integer Args: val (?): input value to test or_val (?): value to return if val is not an int Returns: ?: val as int otherwise returns or_val """ try: return(int(val)) except: return(or_val)
def convert_to_base_time(end_time , start_time): """ Converts the time to base time @param: end_time end time @param ; start_time start time """ return int(end_time)- int(start_time)
def log(*args, **kwargs): """ Simply does this: print(" " * depth, "|->", *args) """ return None depth = len(inspect.stack()) + kwargs.pop("increase_depth", 0) print(" " * depth, "|->", *args, **kwargs)
def run_intcode(memory, noun, verb): """Assign noun and verb then run intcode program on memory.""" memory[1] = noun memory[2] = verb pointer = 0 while True: opcode = memory[pointer] if opcode == 99: return memory[0] param_one = memory[pointer + 1] param_...
def regression_prediction(input_feature, intercept, slope): """ Calculate the predicted values based on the liner regression model Returns: the estimated value """ return intercept + slope * input_feature
def format_case(item, case): """Allow :obj:`str` case formatting method application from keyword. Parameters ---------- item : str Item to be case formatted. case : str Which case format method to use. Returns ------- str :arg:`item` with case method applied. ...