content
stringlengths
42
6.51k
def clean_shit(entery): """ cleans characters not accepted by MySQL """ entery=entery.replace("\"", "") entery=entery.replace("\'", "") return str(entery)
def inputs_to_set(inputSymbols): """Takes in the parameters passed to *args and puts them in a set and a list. The set will make sure there are no duplicates, and then the list will keep the original order of the input. :param inputSymbols: A list, dict, or tuple of stock tickers. :type inputSymbol...
def extract_fields_from_response(response): """Extract fields from API's response""" item = response.get("items", [{}])[0] volume_info = item.get("volumeInfo", {}) title = volume_info.get("title", None) subtitle = volume_info.get("subtitle", None) description = volume_info.get("description", Non...
def get_line(start, end): """Bresenham's Line Algorithm for pixel-wise line approximation. Produces a list of line points from start to end such as: [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]""" # Setup initial conditions x1, y1 = start x2, y2 = end dx = x2 - x1 dy = y2 - y1 # Determ...
def count_ones( binstr ): """ number of ones in a binary string """ n = 0 while (binstr != 0): binstr = (binstr & (binstr - 1)) n += 1 return n
def quote(value): """ Quotes and escapes the given value to pass it to tr64c """ esc = { '\\': "\\\\", '\n': "\\n", '\r': "\\r", '\t': "\\t", '"' : "\\\"", '\'': "\\'" } res = [] for c in value: res.append(esc.get(c, c)) return '"' + ''.join(res) + '"'
def SimpleElement(tag, value): """ Args: tag: xml tag name value: character data Returns: XML: <tag>value</tag> """ return '<%s>%s</%s>\n' % (tag, value, tag)
def Color(red, green, blue, white = 0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (white << 24) | (green << 16)| (red << 8) | blue
def addIndent(text, indent): """ @param {string} text @param {number} indent @return {string} """ result = '' lines = text.splitlines() for line in lines: result += ' ' * indent result += line result += '\n' return result
def foo_5(x): ## a recursive function that calculates the factorial of x """ test foo_5(1) 1 foo_5(5) 120 """ if x == 1: return 1 return x * foo_5(x-1)
def get_sample_id(sample): """Return id attribute of the object if it is sample, otherwise return given value.""" return sample.id if type(sample).__name__ == 'Sample' else sample
def todict(obj, include_class_attrs=False, convert_private=False, include_none_fields=True): """Convert object to dict""" if isinstance(obj, dict): data = {} for (k, v) in obj.items(): data[k] = todict(v, include_class_attrs, convert_private) return data elif hasattr(obj,...
def coq_import(i): """Coq: import module with name i Arguments: - `i`: """ return "Require Import {0!s}.\n".format(i)
def get_le_api_key(auth): """ Get rw_api_key if provided in the configuration, otherwise get ro_api_key :param auth: authentication configuration for logentries """ if auth.get('rw_api_key'): return auth.get('rw_api_key') else: return auth.get('ro_api_key')
def parse_gen_param_name(name): """ Convert ``'J'`` to ``('J', None)`` and ``'J_EI'`` to ``('J', (0, 1))``. >>> parse_gen_param_name('J') ('J', None) >>> parse_gen_param_name('D_IE') ('D', (1, 0)) >>> parse_gen_param_name('V_E') ('V', (0,)) >>> parse_gen_param_name('A_xx') Trace...
def is_number(string: str) -> bool: """ Helper function that determines if input from console is numeric. This is used to help determine if gathers coordinates are valid. :param str string: input gathered from console :return: bool indicating if a string can be cast to float """ try: ...
def get_mse(a, b): """Calculate MSE""" return ((a - b) ** 2)
def serialize(obj): """ Generalized function to turn cengine models into a serializable and representable format :param obj: The object to serialize :return result: The converted object """ # For a list, convert each element and return another list if isinstance(obj, list): resu...
def exp2 ( x ) : """ 'exp2' function taking into account the uncertainties """ fun = getattr ( x , '__exp2__' , None ) if fun : return fun() return 2**x
def merge_dictionaries(dict1, dict2): """Merge dictionaries together, for the case of aggregating bindings.""" new_dict = dict1.copy() new_dict.update(dict2) return new_dict
def peek(word_list): """Check to see if a list has a word tuple.""" if word_list: word = word_list[0] return word[0] else: return None
def adjust_learning_rate_in_group(optimizer, group_id, epoch, lr, schedule, gamma): """Sets the learning rate to the initial LR decayed by schedule""" if epoch in schedule: lr *= gamma print("adjust learning rate of group %d to: %.3e" % (group_id, lr)) optimizer.param_groups[group_id]['l...
def url_for(path=''): """Simple function to generate URLs with the base GitHub URL.""" return 'https://api.github.com/' + path.strip('/')
def mail_status(detection): """Write the status text for the mailbox.""" if detection == 0: return"Full!" elif detection == 1: return "Empty"
def any_in(arr, iterable): """ Checks if any value in arr is in an iterable """ for elem in arr: if elem in iterable: return True return False
def truncate( s, size ): """truncate given string to specified length""" if len( s ) <= size: return s return s[:size-3] + '...'
def node_to_roles(node): """ Use the list of roles of the node to compute a hash representing the node token. Hash also the string to decrease collisionsultra :param node: base_node :return: node's roles or the string's hash (in case its UP/DOWN token or a leaf) """ if type(node) == str: ...
def saddle_points(matrix): """ Find saddle points in a matrix :param matrix list - A list of rows containing values. :return list - A list containing dictionary(ies) indicating where the saddle point(s) in the matrix are. It's called a "saddle point" because it is greater than or e...
def TestToExtract(data,missing,overwrite): """ Test if need to extract the data :param float/int data: data to test :param float/int missing: missing value :param boolean overwrite: to overwrite or not :returns: boolean if condition met """ if data==missing or overwrite: retur...
def token_to_char_offset(e, candidate_idx, token_idx): """Converts a token index to the char offset within the candidate.""" c = e["long_answer_candidates"][candidate_idx] char_offset = 0 for i in range(c["start_token"], token_idx): t = e["document_tokens"][i] if not t["html_token"]: token = t["to...
def get_literal_type(value): """Get the data type :param value: The data :return: The data type as a string :rtype: str """ return type(value).__name__
def token_classification_meta_data(train_data_size, max_seq_length, num_labels, eval_data_size=None, test_data_size=None, label_list=None, ...
def section_end(section, **kwargs): """Handles the "section-end" fragment""" kwargs["section"] = section return kwargs
def stringify(item): """ Returns a quoted string item if passed argument is a string, else returns a string representation of that argument. If passed argument is None, returns None. Parameters ---------- item : Any type Item to be parsed. Returns ------- str or No...
def conjugate_par(par_dict): """Given a dictionary of parameter values, return the dictionary where all CP-odd parameters have flipped sign. This assumes that the only CP-odd parameters are `gamma` or `delta` (the CKM phase in the Wolfenstein or standard parametrization).""" cp_odd = ['gamma', 'del...
def value_attribute_name(property_name: str) -> str: """Return a magic key for the attribute storing the property value.""" return f"_{property_name}_prop_value_"
def check_api_token(api_key): """ Check if the user's API key is valid. """ if (api_key == 'API_KEY'): return True else: return False
def get_list_by_separating_strings(list_to_be_processed, char_to_be_replaced=",", str_to_replace_with_if_empty=None): """ This function converts a list of type: ['str1, str2, str3', 'str4, str5, str6, str7', None, 'str8'] to: [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6', 'str7'], [], ['str8']] "...
def _get_dpv(statvar: dict, config: dict) -> list: """A function that goes through the statvar dict and the config and returns a list of properties to ignore when generating the dcid. Args: statvar: A dictionary of prop:values of the statvar config: A dict which expects the keys to be the c...
def eccentric_location_earth_orbit(juliancentury: float) -> float: """Calculate the eccentricity of Earth's orbit""" return 0.016708634 - juliancentury * (0.000042037 + 0.0000001267 * juliancentury)
def dotproduct(a,b): """Returns the dot product of two 2D vectors starting at origin. a - [float,float], b - [float,float] return - (float) """ u = (a[0]*b[0]) + (a[1]*b[1]) return u
def build_filter_value(filters, filter_op='and'): """ @param filters: a dictionary of filter keys and values. @param filter_op: operator to join filters; default is 'and'. @return: a string represents _filter query string. """ result = '' if isinstance(filters, dict): for key, value ...
def linux_notify(title: str, message: str) -> str: """Display notification for Linux systems""" command = f'''notify-send "{title}" "{message}"''' return command
def reduce_base(k,base): """ If base is a list of sorted integers [i_1,...,i_R] then reduce_base sorts the list [k,i_1,...,i_R] and calculates whether an odd or even number of permutations is required to sort the list. The sorted list is returned and +1 for even permutations or -1 for odd permutatio...
def latlon_from_text(location): """Extracts latlon from text. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns (lat, lon) if valid. """ latlon = [] try: if ',' in location: latlon = [float(x) for x in loc...
def backtrack(state): """Helper function. Takes a state and returns the sequence of action that got us there in the correct order by stepping through parent states.""" action_sequence = [] if state is None: # if we don't even have a single state return [] while state.parent_action is not None: ...
def pad(batch, fill=0): """ Pad a mini-batch of sequence samples to maximum length of this batch. :param batch: list of list :param fill: word index to pad, default 0. :return batch: a padded mini-batch """ max_length = max([len(x) for x in batch]) for idx, sample in enumerate(batch): ...
def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False l...
def nth_triangular_number(n: int) -> int: """Returns the nth triangular number; for proof see: https://en.wikipedia.org/wiki/Triangular_number""" return n * (n + 1) // 2
def strip_checkpoint_id(checkpoint_dir): """Helper function to return the checkpoint index number. Args: checkpoint_dir: Path directory of the checkpoints Returns: checkpoint_id: An int representing the checkpoint index """ checkpoint_name = checkpoint_dir.split('-')[-1] retur...
def upload_path(instance, filename): """Return path to save FileBackup.file backups.""" return f'examiner/FileBackup/' + filename
def perfect_square_binary_search(n: int) -> bool: """ Check if a number is perfect square using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_square_binary_search(9) True >>> perfect_square_binary_search(16) True >>> perfect_square_binary_search(1) ...
def euclid_gcd(a, b): # noqa: WPS111 """Calculate the greatest common divider using Euclidian algoritm. Args: a: first number b: second number Returns: the greatest common divider. """ while True: remainder = a % b if remainder == 0: return b ...
def get_parent_label(label_parts): """ Determine the parent label for the given label part list. """ parent_label = None # It can't have a parent if it's only one part if len(label_parts) <= 1: return parent_label # If it's the interps for the whole part, return the part if len(label_p...
def get_errors_list(error_detail, prefix=()): """ Given an 'error_detail' from a ValidationError, returns a list of two-tuples of (index, message). """ errors = [] if isinstance(error_detail, str): errors.append((prefix, error_detail)) elif isinstance(error_detail, dict): for...
def dist_sq(a, b): """ Compute euclidean distance between two points """ return sum([(xa - xb) ** 2 for xa, xb in zip(a, b)])
def cubic_bezier(u, p0, p1, p2, p3): """ u in [0, 1] p_j the four relevant control points """ assert u >= 0. assert u <= 1. u2 = u*u u3 = u2*u ret = (1. - u)**3 * p0 ret += (3*u3 - 6*u2 + 4) * p1 ret += (-3.*u3 + 3.*u2 + 3.*u + 1) * p2 ret += u3 * p3 return ret / 6.
def _EscapeForString(s): """Escape string contents for safe inclusion in a double-quoted string.""" return s.replace('\\', '\\\\').replace('"', r'\"')
def find_kth(A, base_a, B, base_b, k): """ base_a, base_b: where to start checking (initially as 0) k: how many elements to select It is necessary and cannot be simply (len(A)+len(B))/2, because it's true the first time but not really the case in later iterations. """ if len(A) - b...
def is_job_failed(job_status): """ Check job status on failure :param job_status: Job status to verify :return: True - job has failed; False - job has finished successfully """ job_failed_statuses = ['FAILED', 'COMPLETED_WITH_ERRORS'] if job_status['status'] in job_failed_statuses: r...
def cross(A, B): """Cross product of elements in A and elements in B.""" return [(a, b) for a in A for b in B]
def find_max_index(values: list): """For internal use calculating the total, takes in a list of integers and returns the indexes of the highest two numbers in values nested in a two-value list.""" order = [] for cycle in range(2): max_i = None for i in range(0, len(values)): ...
def merge_sort(array, log=False): """ Merge Sort is used for Sorting an iterable data structure which is a container and is mutable(set, list) Merge Sort is faster than Bubble Sort for larger data structures """ def merge(a,b): c = [] while len(a) and len(b): if a[0]>b[0]: c.append(b[0]) del b[0] ...
def auto_repeat( obj, n, force=False, check=False): """ Automatically repeat the specified object n times. If the object is not iterable, a tuple with the specified size is returned. If the object is iterable, the object is left untouched. Args: obj: The obj...
def bulleted_list(items, indent=0, bullet_type="-"): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
def typecast(value, value_type): """ """ if value_type == "integer": return int(value) return value
def unflatten(data, separator=".", **kwargs): """ Reference Name ``unflatten`` Turn flat dictionary produced by flatten function to a nested structure :param data: flattened dictionary :param separator: string to split flattened keys :return: nested structure List indexes must follow in o...
def any_lowercase(s): """ incorrect - only checks whether first letter is lower case""" for c in s: if c.islower(): return True else: return False
def uniquify(lst): """ Return a list of unique items from lst. """ res = [] for item in lst: if not item in res: res.append(item) return res
def get_indent(line): """ get indent length :param line: :return: """ index = 0 for i in line: if i == " ": index += 1 else: break return index
def better_allele(candidate_allele, current_closest_allele, examples_per_allele): """ Determine whether the candidate allele is a better pan choice than the current closest allele """ # If we do not have a closest allele right now, then candidate_allele is # a better allele ...
def getMismatchedIndices(bboxes, aligned_indices): """ compute the indices of the bounding boxes that do not appear in any of the head-person pairs (matched by the hungarian algorithm) :param bboxes: bounding boxes :param aligned_indices: matched indices of bounding boxes :return: list of indice...
def can_be_devided_by_list(n, l): """See if a number can be devided by all numbers in a list.""" if n == 0: return False for i in l: if n % i: return False return True
def add(x, y): """ Helper function to implement adding for binary nums """ cur_sum = 0 carry_in = 0 temp_x = x temp_y = y k = 1 while temp_x or temp_y: xk = x & k yk = y & k carry_out = (xk & yk) | (xk & carry_in) | (yk & carry_in) cur_sum |= (xk ...
def check_copy(copy_function, obj): """Checks `copy_function` to ensure `obj` is equal to its copy, and that it is not the same instance.""" obj_copy = copy_function(obj) return obj == obj_copy and obj is not obj_copy
def _sufficient_electrons_for_mult(z, c, m): """Require sufficient electrons in total: total mult ({}) - 1 > raw electrons ({}) - total chg ({})""" return m - 1 <= z - c
def splitclean(s, delim=',', allow_empties=False, as_type=None): """ Split a delimited string (default is comma-delimited) into elements that are stripped of surrounding whitespace. Filter out empty strings unless `allow_empties` is True. :param s: (str) the string to split :param delim: (str) ...
def get_avg_stats(policy_dict, asn): """Gets the average statistics among all asns for each policy.""" num_asns = len(policy_dict) average = {} # For each column/data point: for key in policy_dict[str(asn)]: # Ignore parent_asn and hijack data, since avg is meaningless if key == "pa...
def to_text(source): """ Generates a text value (an instance of text_type) from an arbitrary source. * False and None are converted to empty strings * text is passed through * bytes are decoded as UTF-8 * rest is textified via the current version's relevant data model method """ if sour...
def _get_percent(status): """ Yardstick util function to calculate success rate """ if status * 100 % 6: return round(float(status) * 100 / 6, 1) else: return status * 100 / 6
def box(content): """ Generate LaTeX code for data within box braces. Parameters ---------- content : str String to be encapsulated within the box braces. Returns ------- str LaTeX code for data within box braces. """ return "[" + content + "]"
def step_lr_generator(step_size, epochs, lr, lr_decay_milestones): """generate step decayed learning rate""" total_steps = epochs * step_size milestones = [int(total_steps * i / lr_decay_milestones) for i in range(1, lr_decay_milestones)] milestones.append(total_steps) learning_rates = [lr*...
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is No...
def first_occurrence(mylist: list, value): """ Search for the index of the last occurrence of a value in the a list :param mylist: The list to search in :param value: The value to search for :return: The index of the last occurrence of a value in the a list """ return mylist.index(value)
def normalised_cooperation(cooperation, turns, repetitions): """ The per-turn normalised cooperation matrix for a tournament of n repetitions. Parameters ---------- cooperation : list The cooperation matrix (C) turns : integer The number of turns in each round robin. repetit...
def get_min_max_y(yData): """ Takes as an argument yData which is a dictionary, where the values are of the form (plotData, xAxisMax) Returns: The maximum of the plotData in the yData dictionary """ maxY= None minY= None for key in yData: maybeMax= max(yData[key][0]) ...
def _next_significant(tokens): """Return the next significant (neither whitespace or comment) token. :type tokens: :term:`iterator` :param tokens: An iterator yielding :term:`component values`. :returns: A :term:`component value`, or :obj:`None`. """ for token in tokens: if token.type ...
def get_network_security_ratio(network_json): """ Returns network security as a ratio number """ total_active_bond = int(network_json['bondMetrics']['totalActiveBond']) total_staked = int(network_json['totalPooledRune']) return total_active_bond / (total_active_bond + total_staked)
def strategy_involves_N_or_more_transfers_in_gw(strategy, N): """ Quick function to see if we need to do multiple iterations for a strategy, or if the result is deterministic (0 or 1 transfer for each gameweek). """ strat_dict = strategy[0] for v in strat_dict.values(): if isinstance...
def _iiOfAny(instance, classes): """ Returns true, if `instance` is instance of any (_iiOfAny) of the `classes`. This function doesn't use :func:`isinstance` check, it just compares the class names. This can be generally dangerous, but it is really useful when you are comparing class serialize...
def bit_perm(x, p, n): """ Find the permutation of an index. Parameters ---------- x: ndarray<int>, int a vector of indices p: ndarray<int> permutation vector, ex: bit-reversal is (0,1,...,n-1) n: int number of bits per index in ``x`` Returns ---------- ...
def count_bits(int_): """Count the number of bits set in a positive integer.""" c = 0 while int_ != 0: int_ &= int_ - 1 c = c + 1 return c
def standard_deviation(value_list): """Return standard deviation.""" from math import sqrt from math import pow n = len(value_list) average_value = sum(value_list) * 1.0 / n return sqrt(sum([pow(e - average_value,2) for e in value_list]) * 1.0 / (n - 1))
def get_LDC(curve): """ Calculates load duration curve (Jahresdauerlinie) Parameters ---------- curve : thermal or electrical curve Returns ------- sorted curve : sorted load duration curve """ return sorted(curve, reverse=True)
def _msd_anom_1d(time, D_alpha, alpha): """1d anomalous diffusion function.""" return 2.0*D_alpha*time**alpha
def englishText(englishInput): """ This function returns translation if input matches """ if englishInput == 'Hello': return 'Bonjour'
def boolparam(param): """ The format for boolean (True/False) parameters in Basecamp API query string parameters needs to be all lowercase "true" or "false". Python's "True" and "False" are unacceptable. This function quietly converts booleans to "true" or "false". If a parameter given is `None...
def fmt_ip(ip_int): """ ``ip_int`` is a 32-bit integer representing an IP with octets A.B.C.D arranged like so:: A << 24 | B << 16 | C << 8 | D returns the number formatted as an IP address string. """ return '%d.%d.%d.%d' % ( (ip_int & (0xFF << 24)) >> 24, ...
def form_diff_table_comparison_value(val): """ Function for converting the given value to a suitable UI value for presentation in the diff table on the admin forms for update requests. :param val: the raw value to be converted to a display value :return: """ if val is None: return "...
def isalphanum(a, b): """ return true if a+b is not a reversible operation""" if a and b: c1 = a[-1] c2 = b[0] return (c1.isalnum() or c1 in '_$' or ord(c1) > 127) and \ (c2.isalnum() or c2 in '_$' or ord(c2) > 127) return False