content
stringlengths
42
6.51k
def is_encrypted_value(value): """ Checks value on surrounding braces. :param value: Value to check :return: Returns true when value is encrypted, tagged by surrounding braces "{" and "}". """ return value is not None and value.startswith("{") and value.endswith("}")
def _int(v): """Convert to int for excel, but default to original value.""" try: if v is None or v == '': return '' if type(v) is str: # we handle strings like '2,345.00' return int(float(v.replace(',', ''))) return int(v) except ValueError: ...
def distance_hue(h1: float, h2: float) -> float: """HUE based distance distance > 0 -> "clockwise" distance < 0 -> "counter-clocwise" """ dist = h2 - h1 if abs(dist) > .5: dist = (-1 if dist > 0 else 1) * (1 - abs(dist)) return dist
def picked_up_assigned_psng(state): """ Check if the agent picked up the assigned passenger v3 Compare current postion of agent with the positions of the passengers """ state = list(state) if round(state[5], 3) == round(state[7], 3) and round(state[6], 3) == round(state[8], 3): return Tr...
def _separateNewlines(text): """ Separate newlines from beginning and end of text and return them in a tuple. :return: (tuple of str) the beginning newline value, stripped text, ending newline value >>> _separateNewlines('\\nfoo\\n') ('\\n', 'foo', '\\n') >>> _sepa...
def add_search_bearings(search_bearing, perpendicular=True): """ Take in a single bearing or list of bearings and returns it either as a list of itself if perpendicular is set to False or a list of itself and all its parallel and perpendicular bearings if perpendicular is kept set to True. Use for f...
def is_nice(s_input): """ >>> is_nice("ugknbfddgicrmopn") True >>> is_nice("aaa") True >>> is_nice("jchzalrnumimnmhp") False >>> is_nice("haegwjzuvuyypxyu") False >>> is_nice("dvszwmarrgswjxmb") False """ input_list = [c for c in s_input] vowels = [c for c in "a...
def MakeDict(host, array): """An unfortunately useful function for making list comprehensions more... comprehensible.""" array.sort() return {str(host): array}
def namelist(names): """Function to format a names list""" if not names: return '' names = [name["name"] for name in names] size = len(names) if size == 1: return names[0] index = 0 res = '' while index != size-2: res += names[index] + ", " index += 1 ...
def __is_dunder(attr_name: str) -> bool: """ check if a given attr_name is `double underscored` one. """ return ( attr_name.startswith('__') and attr_name.endswith('__') )
def to_osu_time_notation(time): """ Transform a time in milliseconds to a string with the osu! time notation. :param time: Time in milliseconds to convert. :return: The string representation of the time. """ try: time = int(time) except: raise ValueError("Invalid parameter. Expected ...
def blur_augment(is_training=True, **kwargs): """Applies random blur augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.5 return [('blur', {'prob': prob})] return []
def _sort_mean_first(best): """ sort the teams by mean value first, then std. """ return sorted(best, reverse=True)
def convertascii(value, command='to'): """ Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ command = command.lower() if co...
def _remove_head(text): """Removes the head section of a string read from an html file. Args: text: A string (content of an html file). Returns: The same string but without the head section. """ new_text = text.split('<head>') newest_text = new_text[1].split('</head>') retu...
def wheel(pos): """Wheel through range of colors""" # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: return 255 - pos * 3, pos * 3, 0 if pos < 170: pos -= 85 ...
def get_build_environment(data): """Given a request, get the build environment. Return None if we are missing something. Since we require a spec to always get a Build, for now it makes sense to also include the full_hash and spack_version. If in the future we just need a build environment, this can be r...
def IITAX(c59660, c11070, c10960, personal_refundable_credit, ctc_new, rptc, c09200, payrolltax, eitc, refund, iitax, combined, iradctc, fthbc, cdcc_new, business_burden, estate_burden, Business_tax_combined): """ Computes final taxes. """ eitc = c59660 refund = (eitc +...
def euler_bernoulli_beam(x, y, EI, f): """Euler-Bernoulli Beam Theory defining y'''' for Lu=f. This form is used because it is expected for Scipy's solve_ivp method. Keyword arguments: x -- independent variable y -- dependent variable EI -- EI(x) parameter f -- forcing function f(x) ""...
def serverB(start_server): """Starts redis-server instance.""" return start_server("B")
def _autoSetScope(rule, span): """ applies the objects own rule and span to modify the object's scope. Currently only "forward" and "backward" rules are implemented """ if 'forward' in rule: return (span[1], -1) elif 'backward' in rule: return (0, span[0])
def roundAwayFromEven(val): """Eclipse cannot deal with values close to even integers. We (in)sanitize the value so that it always will be at least 0.1m away from an even integer. This function only makes sense should you assume cell floors are at even integers. """ epsilon = 0....
def tagnum(line): """ returns the current event count """ return int(line[line.find('=') + 1:line.find(')')])
def split_hoststring(hoststring): """ Splits a host string into its user, hostname, and port components e.g. 'vagrant@localhost:22' -> ('vagrant', 'localhost', '22') """ user = hoststring[0:hoststring.find('@')] ip = hoststring[hoststring.find('@') + 1:hoststring.find(':')] port = hoststrin...
def get_ones_mask(mask): """ Calculates the mask used to set 1 values >>> get_ones_mask("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X") 64 >>> f"{get_ones_mask('XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X'):b}" '1000000' :param mask: :return: """ return int(mask.replace("X", "0"), 2)
def isQualified(name): """ Check if a property name is qualified """ return name.find(':') != -1
def write_steadyst_notconv_msg(nMax): """Return the convergence status message for writing to file.""" PrintMsg = f"\nSTATUS: NOT CONVERGED\nMAX. ITERATIONS={nMax}" print(PrintMsg) print() return PrintMsg
def ranges_overlap(start1, end1, start2, end2): """ Checks if two intervals are overlapping. Function requires intervals to be proper (end >= start). Works with any types of comparable by mathematical operators objects. """ return start1 <= end2 and end1 >= start2
def first_word_complex(text: str) -> str: """ returns the first word in a given text. """ l = [] for x in text: if x.isalpha() or x == "'": l.append(x) else: l.append(" ") w = "".join(l) result = w.split() return result[0]
def plaquette_cross_check(path): """ Function to check whether zig zag patterns follow plaquette rules of the checkerboard decomposition. For Landau&Cullen Monte Carlo. """ left_allowed = False for step in path: if step==-1: if left_allowed: pass ...
def normalize_line(groups): """ Takes match groups and uppercases them if they're not None. """ result = [] for g in groups: if g is None: result.append(None) else: result.append(g.upper()) return result
def ref_bits(x): """ :param x: byte to reverse :return: reversed byte """ b = bin(x)[2::].zfill(8) b = b[8::-1] return int(b, 2)
def solution1(inp): """Solves the first part of the challenge""" parse_inp = [int(n) for n in inp.split('\n') if len(n) > 0] for x in parse_inp: for y in parse_inp: if x + y == 2020: return x * y
def format_list_elements(str_list, format_dict): """ Format a list of formattable stings. :param list str_list: The list of strings. :param format_dict: The dictionary specifying the values of the formattable parts of the strings. :return: A list of formatted :rtype: str list :Example: ...
def to_num(value): """ Coerce a string to a "Number". Adapted from ``formencode.validators.Number``. """ try: value = float(value) try: int_value = int(value) except OverflowError: int_value = None if value == int_value: return int_...
def fix_flv(content): """This is aimed to make the extracted video files playable. For some reason youtube sends the files without the initial 13 bytes of FLV header. This should remediate this and allow for replaying saved videos by normal media players.""" # to prevent adding the header to file that ...
def string_variations( names, preprocess=["lower", "strip"], swaps=[(" ", "_"), (" ", "_"), ("-", " "), ("_", " "), ("-", ""), ("_", "")], ): """ Returns equilvaent string variations based on an input set of strings. Parameters ---------- names: {list, str} String or list of str...
def ptRep(p): """Represent a float as an integer. Parameters ---------- p: float We round it to the nearest integer. A none value is converted to `?`. """ return "?" if p is None else int(round(p))
def load_balance_list(L, n): """Given a list of arbitrary items, split it to n roughly equal-sized parts. This is useful for dividing a list of work items in MPI parallelization. It is assumed that each work item takes the same amount of time; hence the initial distribution is generated by naive intege...
def printable_cmd(c): """Converts a `list` of `str`s representing a shell command to a printable `str`.""" return " ".join(map(lambda e: '"' + str(e) + '"', c))
def getDataPath(directory, timestep): """ Returns file path to vtu file for a particular timestep """ _, domain = directory.split("subdomain_") domain = domain[:-1] filepath = directory + "LSBU_" + str(timestep) + "_" + str(domain) + ".vtu" return filepath
def rreplace(s, old, new, occurrence=1): """ Replace portion of a string (from the right side). Handy utility to change a filename extension, e.g. rreplace('a/b/c.fits', 'fits', 'im') -> 'a/b/c.im' Parameters ---------- s : str The string to process old : str ...
def __clean_line(line): """ Removes comments from a line, the comments could be with '#' or '!' Both kind of comments are used in ABINIT """ line = line.strip() if len(line) > 0: if line[0] == '#' or line[0] == '!': result = [] elif '#' in line: splt =...
def my_autopct(pct): """ :param pct: :return: """ # Only return a label if it is > 2% else return an empty string return (('%.2f' % pct) + '%') if pct > 2 else ''
def reverse(seq): """Return the sequence string in reverse order.""" letters = list(seq) letters.reverse() return ''.join(letters)
def make_channel_dict(ordered_index): """Creates a Dictionary of the the indexes for each Channel's features in the ordered_index Parameters: ----------- ordered_index: list Index of Features for Feature Dropping [list] -> (Tuple) Power: [Num of Features] -...
def get_simple_split(branchfile): """Splits the branchfile argument and assuming branch is the first path component in branchfile, will return branch and file else None.""" index = branchfile.find('/') if index == -1: return None, None branch, file = branchfile.split('/', 1) r...
def gram_size(term): """ Convenience func for getting n-gram length. """ return len(term.split(' '))
def cal_words_num(lines): """ Calculate number of words in lines :param lines: lines to be calculate :return: number of words """ return sum(map(len, lines))
def get_bin_idx(bins, x): """ Get the bin that x would be allocated, cumulatively """ x = x % sum(bins) idx = -1 while x >= 0: x -= bins[idx] if x >= 0: idx += 1 return idx
def asFloatOrNone(val): """Converts floats, integers and string representations of either to floats. If val is "NaN" (case irrelevant) or "?" returns None. Raises ValueError or TypeError for all other values """ # check for NaN first in case ieee floating point is in use # (in which case floa...
def rotate_tour(tour, start=0): """ Rotate a tour so that it starts at the given ``start`` index. This is equivalent to rotate the input list to the left. Parameters ---------- tour: list The input tour start: int, optional (default=0) New start index for the tour Returns ------- rotated: ...
def top_files(query, files, idfs, n): """ Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked accord...
def calc_coop_score(procedures): """ Calculate and return overall COOP prcedure score. Args: procedures - iterable of either tracker.models.Procedure objects or julia.node.ListValueNode nodes """ score = 0 if procedures: for procedure in procedures: try: ...
def hideCells(notebook): """ Finds the tag 'hide' in each cell and removes it Returns dict without 'hide' tagged cells """ clean = [] for cell in notebook['cells']: try: if 'hide' in cell['metadata']['tags']: pass else: clean.appen...
def subset(target, lst): """determines whether or not it is possible to create target sum using the values in the list. Values in teh list can be positive, negative, or zero.""" if target == 0: return True #what if target is 0? if lst == []: return False #use_it = subset(target -...
def add_column_based_on_null(event, field, new_field, new_value_if_null, new_value_if_not_null): """ Checks and adds a value to a new field based on NULL :param event: A dictionary :param field: The name of the field to check :param new_field: The name of the new field :param new_value_if_null: The...
def HsvToACIndexes(hsv): """ Convert an HSV color to its closest valid color in Animal Crossing: New Horizons. HSV colors are expected to be of the form (0-255, 0-255, 0-255) """ hue_step = 255 / 29 sat_val_step = 255 / 14 return ( int(round(hsv[0] / hue_step)) + 1, int(round(hs...
def unify_dashes(s: str): """Replaces em- and en-dashes with hyphens.""" return s.replace(u'\u2013', '-').replace(u'\u2014', '-')
def argsSplit(sCmdLine): """ Given a bourne shell command line invocation, split it up into arguments assuming IFS is space. Returns None on syntax error. """ ## @todo bourne shell argument parsing! return sCmdLine.split(' ');
def output_dim(X, S, padding, strides): """ Compute output dimension given input feature map, filter, padding, and stridedimension. Arguments: X (int): input data dimension S (int): filter dimension padding (int): padding on each side strides (int): striding """ S = ...
def strip_linebreaks(s): """ Strip excess line breaks from a string """ return u"\n".join([c for c in s.split(u'\n') if c])
def delete_at(list, index): """ Return a list with the item at the given index deleted. If the index is out of bounds, return the list unmodified. """ if list == () or index < 0: return list else: head, tail = list if index == 0: return tail else: ...
def revcmp(seq): """Given a sequence return its reverse complement sequence.""" NTMAP = {'a': 't', 'c': 'g', 't': 'a', 'g': 'c', 'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'} return "".join([NTMAP[x] for x in seq])[::-1]
def int_id_to_str_id(num: int) -> str: """Encodes a number as a string, using reverse spreadsheet style naming. Args: num: A positive integer. Returns: A string that encodes the positive integer using reverse spreadsheet style, naming e.g. 1 = A, 2 = B, ..., 27 = AA, 28 = BA, 29 = CA, ... This is ...
def limit_angle_to_360_deg(angle_deg: float) -> float: """ Prevent an angle value multiplication. Parameters: angle_deg -- the angle measured in degrees. """ if angle_deg < 0: return angle_deg + 360 elif angle_deg >= 360: return angle_deg - 360 else: return angl...
def _prec(p, l): """ retrieve the predecessor of p in list l """ pos = l.index(p) if pos - 1 < 0: return l[-1] else: return l[pos - 1]
def str_to_bin(st): """converts string to binary number""" return ''.join(format(ord(x), 'b') for x in st)
def overlap(indices1, indices2): """Returns a boolean indicating whether two pairs of indices overlap.""" if not (len(indices1) == 2 and len(indices2) == 2): return False if indices2[0] <= indices1[0] <= indices2[1]: return True elif indices2[0] <= indices1[1] <= indices2[1]: ret...
def is_collection_field_type(field_type) -> bool: """Check if model type is a generic collection model such as a typed list or a typed dict.""" if hasattr(field_type, '__origin__') and hasattr(field_type, '__args__') and (list in field_type.mro() ...
def _distance_between_nodes(node_1, node_2): """calculate the euclidean distance of two points using pythagoras""" x1, y1 = node_1 x2, y2 = node_2 return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
def processExtraFields(extraFields): """Special processing of the GVF extra fields""" ret = {} for key in extraFields: val = extraFields[key] if key == "ID" or key == "Name": continue elif key == "Start Range" or key == "End Range": r = val.split(",") ...
def _strip_any(keycode): """Remove ANY() from a keycode. """ if keycode.startswith('ANY(') and keycode.endswith(')'): keycode = keycode[4:-1] return keycode
def convert_hex_to_int(hexChars): """convert string of hex chars to a list of ints""" try: ints = [ord(char) for char in hexChars] return ints except TypeError: pass return []
def contains(iterable, value, from_index=None): """ Returns true if the value is present in the iterable. Use from_index to start your search at a given index. Params: iterable, value iterable -> list, sequenece, set, dictionary, generator etc value -> Any element that is to be searched in ...
def deep_del(data, fn): """Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed. """ result = {} for k, v in data.items(): if not fn(v): if isinstance(v, dict): re...
def is_match(i: int, j: int, seq1: str, seq2: str) -> bool: """True if the sequences match at positions i, j; False otherwise. """ return seq1[i-1] == seq2[j-1]
def okay_word(word: str) -> bool: """ Word is all lower case and exactly six characters long. """ return word.islower() and len(word) == 7
def separate_words_and_numbers(strings): """ Separates words and numbers into two lists. :param strings: List of strings. :return: One list of words and one list of numbers """ filtered_words = [] filtered_numbers = [] for string in strings: if string.isdigit(): ...
def env_exists(env_variable: str) -> bool: """Validates if env variable was provided and is not an empty string. Args: env_variable: str, name of the env variable Returns: True: if env provide and not an empty string False: if env not provided or an empty string """ if env_...
def is_homogeneous(*tys): """Are the types homogeneous? """ if tys: first, tys = tys[0], tys[1:] return not any(t != first for t in tys) else: # *tys* is empty. return False
def valid_tour(tour, cities): """Is tour a valid tour for these cities?""" return set(tour) == set(cities) and len(tour) == len(cities)
def group_dates(dates): """ Groups list of given days day by day. :param dates: List of dates to group. :type dates: list :return: """ days = [] times = [] for elem in dates: if elem.date() not in days: days.append(elem.date()) times.append([elem.ti...
def rowMean(mtx): """Return all row-sums as a list""" try: for i in range(0, len(mtx)): assert len(mtx[i]) == len(mtx[i-1]) # check whether each list has the same length. res = list() for j in range(0, len(mtx[0])): tmp = 0 for i in range(0, ...
def the_kind_of_feature(feature): """ :param feature: should be get from features[i] :return: 3 kinds of features. """ number_kind = ['budget', 'id', 'popularity', 'revenue', 'release_date', 'runtime', 'vote_average', 'vote_count'] vector_kind = ['genres', ...
def NestedQ(l): """Returns True if every item in List is a list or a tuple. l: a list.""" return {type(item) for item in l} in [{list}, {tuple}]
def fileno(file_or_fd): """ Look for 'fileno' attribute. """ fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd
def order_id_change(token): """Removes all values of arg from the given string""" return str(token.split("-")[0] + "0").upper()
def system_input_state_english(raw_table, base_index): """ Convert system input state to English """ value = raw_table[base_index] if value == 0: return "Disable" if value == 1: return "System" if value == 2: return "Storage tank" if value == 3: return "DHW STRAT...
def get_next_evaluation(student, evaluations, evaluated_signatures): """return the exam and student_signature that is the next to evaluate (havent evaluated) for the student""" next_evaluation = {} for exam_dict in evaluations: for exam_eval_dict in evaluated_signatures: ...
def getJavacVersion(versionNum): """ Convert a Java class file tuple (minor, major) to a string representing the corresponding javac version. E.g. 48.0 -> 1.4 """ if type(versionNum) in [tuple, list]: versionNum = '%i.%i' % (versionNum[1], versionNum[0]) # todo: add support for Java 6...
def mock_sitemap_get_urls(*args, **kwargs): """ Mock method to just return given url as argument so it can pass the dummy url to validator without to read it like a sitemap. """ cls = args[0] path = args[1] return [path]
def __check_ref(ref, category): """ upward compatibilty of references :param ref: input ref :param category: category of processing :return: updated ref """ if ref == '' and category == 'float': return 'FL-PASS' return ref
def filter_out_nonred(list_of_pixels): """ Takes a 1-d list of pixels and filters out the pixels that aren't "red-colored". Returns the list of red pixels. """ return [pixel for pixel in list_of_pixels if pixel[0] > 160./255. and max(pixel[1], pixel[2]) < 60./255.]
def pipe_Do(Di, WT): """Calculate pipe outer diameter, given the pipe inner diamater and wall thickness. """ Do = Di + 2 * WT return Do
def tobool(value): """ Convert value (1, '1', 0, '0', 'yes', 'true', 'no', 'false', 'on', 'off', or any integer) to a bool object. The string values are treated in a case-insensitive way. """ trues = "1", "yes", "Yes", "YES", "true", "True", "on", 1 falses = "0", "no", "No", "NO", "fa...
def beta_type(strings: str) -> tuple: """An argparse type function that takes a string and returns a two part tuple for a low and high beta for an optimizer Args: strings (str): a comma separated string of numbers Returns: tuple: a tuple of floats """ mapped_beta = map(float, s...
def handle_same_platform_matches(marc_record, bib_source_of_input, predicate_vectors, output_handler): """ :param marc_record: :param bib_source_of_input: BibSource :type predicate_vectors: dict[Record, PredicateVector] :type output_handler: OutputRecordHandler ...
def voltage_to_degrees(voltage: float) -> int: """ Converts an anolog voltage to rotational degrees Arguments: None Returns: - Degrees coresponding to an input voltage """ return int(voltage*360/3.3)
def format_worker_input(core_num, item_sublists, fixed_params): """ Generate a list of tuples containing the parameters to pass to worker sub processes. :param core_num: number of available cores :param item_sublists: dictionary containing the sublist of files for each worker :param fixed_params: l...