content
stringlengths
42
6.51k
def checkSum(intList, intVal): """checks if the sum of elements in intList equals intVal""" s = 0 for x in intList: s += x return (s == intVal)
def hexint_parser(arg: str) -> int: """Parse a hexadecimal starting with 0x into an integer.""" if not arg.startswith("0x"): raise Exception("Received non-hex integer where hex expected") return int(arg, 16)
def kreis_auf(dl, dr): """Kreis gegen UZS, auf Grundlinie liegend""" # (Startpunkt ist nicht definiert) m = [(0.25, 0), (0.5, 0.25), (0.5, 0.5), # [Q1], [Q2], (Q3/R0) (0.5, 0.75), (0.25, 1), (0, 1), # [R1], [R2], (R3/S0) (-0.25, 1), (-0.5, 0.75), (-0.5, 0.5), # [S1]...
def ras_to_lps(point): """ This function.. :param point: :return: """ surf_x, surf_y, surf_z = point point = (-surf_x, -surf_y, surf_z) # must flip y axis to convert from VTK to ITK return point
def get_chrom_size(chrom): """These sizes are based on the catalog for Homosapiens in stdpopsim, but they're exactly the same as the one given by the VCF files, so I use them for both real and simulated data""" chrom = str(chrom) length = { "1": 249250621, "2": 243199373, "3...
def unroll(current_key, output_map, entry, keys_to_append=None): """ :param current_key: :param output_map: :param entry: :param keys_to_append: :return: """ def unroll_dict(current_key, output_map, entry, keys_to_append=None): for key, value in entry.items(): unroll...
def median(li): """Median of elements - shaonutil.stats.median(list of numbers)""" n = len(li) li.sort() if n % 2 == 0: median1 = li[n//2] median2 = li[n//2 - 1] median = (median1 + median2)/2 else: median = li[n//2] return median
def extract_csv_links(text): """Get a list of csv links from the download link response text""" links = text.replace("\r", "").split("\n") links.remove("") return links
def dict_compare_keys(d1, d2, key_path=''): """ Compare two dicts recursively and see if dict1 has any keys that dict2 does not Returns: list of key paths """ res = [] if not d1: return res if not isinstance(d1, dict): return res for k in d1: if k not in d2: ...
def has_lines(string: str, count: int) -> bool: """Return True if `string` has at least `count` lines.""" # Benchmarks show this is significantly faster than using str.count("\n") or a for loop & break. split = string.split("\n", count - 1) # Make sure the last part isn't empty, which would happen if t...
def find_weight(word): """ input is bit vector output is Hamming weight """ i = 0 for letter in word: if letter != 0: i += 1 return i
def join_host_strings(user, host, port=None): """ Turns user/host/port strings into ``user@host:port`` combined string. This function is not responsible for handling missing user/port strings; for that, see the ``normalize`` function. If ``port`` is omitted, the returned string will be of the form...
def latest_no_overlap(jobs, n): """ Find the job before the nth job which does not overlap with the nth job Return -1 if no such job found """ for j in range(n - 1, -1, -1): if jobs[j][1] <= jobs[n][0]: return j; return -1;
def npv_f(rate, cashflows): """Objective : estimate NPV value rate : discount rate cashflows: cashflows e.g. >>>npv_f(0.1, [-100.0, 60.0, 60.0, 60.0]) 49.211119459053322 """ total = 0.0 for i, cashflow in enumerate(cashflows): total += cashflow /...
def unique_match_from_list(list): """ Check the list for a potential pattern match @param list : a list of potential matching groups @rtype : return the unique value that matched, or nothing if nothing matched """ result = '' for item in list: if item != None: ...
def _check_possible_tree_participation(num_participation: int, min_separation: int, start: int, end: int, steps: int) -> bool: """Check if participation is possible with `min_separation` in `steps`. This function checks if it is possible...
def find_empty_col(slots): """Find empty col in slots. Args: slots (dict): slots for answer Returns: int: available col for insert 6 --> no available col others --> col index """ index = 0 for i in list(zip(*list(slots.values())[::])): if sum(...
def k2f(k: float, r: int = 2) -> float: """Kelvin to Fahrenheit.""" return round(((k - 273.15) * (9 / 5)) + 32, r)
def utf8safe(s): """Remove characters invalid in UTF-8.""" return s.decode('utf-8', errors='replace').encode('utf-8')
def split_suffix(symbol): """ Splits a symbol such as `__gttf2@GCC_3.0` into a triple representing its function name (__gttf2), version name (GCC_3.0), and version number (300). The version number acts as a priority. Since earlier versions are more accessible and are likely to be used more, the low...
def cleanse(s): """ Clean a string :s: (str) the string to clean """ return s.strip('"').strip("'").strip('\n').strip(' ')
def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len...
def containsDuplicateD(nums): """ :type nums: List[int] :rtype: bool """ nums.sort() for i in range(1,len(nums)): if nums[i] == nums[i-1]: return True return False
def remove_none_func_lines(lines): """Doc.""" new_lines = [] for line in lines: if line.startswith('#') and '.h' in line: new_lines.append(line) elif line.endswith(');') or line.endswith('{') or \ line.endswith('}') or line.endswith('};'): if '(' in li...
def __newobj__(cls, *args): """A compatibility pickler function. This function is not part of the public Atom api. """ return cls.__new__(cls, *args)
def strictly_decreasing(l): """Check whether list l has strictly deacreasing values""" return all(x > y for x, y in zip(l, l[1:]))
def get_datatype(value) -> list: """ Determine the data type for an object and set the type if possible. A string such as "1.23" will result in a type "float" and "2" will result in type "int". Args: value: object to be typed Returns: list [type, value] of data type as a code and ob...
def logical_and(a, b, unsafe=False): """logical and without the bloat of numpy.logical_and could be substituted with numpy.logical_and !important: if unsafe is set to True, a and b are not checked. This improves speed but is risky. expects integers [0,1] or bools """ if not unsafe: ...
def _closest(e, l): """ Finds the element and its index, closest to e, in l """ closest = None closest_idx = None min_diff = float('inf') for i, j in enumerate(l): diff = abs(j - e) if diff < min_diff: min_diff = abs(j - e) closest = j closest_idx ...
def parse_keys(keys): """ Parse keys for complex __getitem__ and __setitem__ Parameters ---------- keys : string | tuple key or key and slice to extract Returns ------- key : string key to extract key_slice : slice | tuple Slice or tuple of slices of key to ...
def binary_sum(S,start,stop): """Return the sum of the numbers in implicitslice S[start:stop].""" if start >= stop: return 0 elif start == stop - 1: return S[start] else: mid = (start + stop) // 2 return binary_sum(S,start, mid) + binary_sum(S, mid, stop)
def distanceV(vector1, vector2): """ Returns vertical distance between 2 vectors. """ return vector1[1] - vector2[1]
def IsTryJobResultAtRevisionValid(result, revision): """Determines whether a try job's results are sufficient to be used. Args: result (dict): A dict expected to be in the format { 'report': { 'result': { 'revision': (dict) } }...
def get_number_of_soil_levels(description): """ This function identifies the number of soil levels. If there is no soil level information then this will return '0'. Else a default value of '5' is given. :param description: The [model_component"], ["atmos"] and ["description] from a [dict] of model info...
def is_chinese_char(char): """Checks whether CP is the codepoint of a CJK character.""" cp = ord(char) if ((0x4E00 <= cp <= 0x9FFF) or # (0x3400 <= cp <= 0x4DBF) or # (0x20000 <= cp <= 0x2A6DF) or # (0x2A700 <= cp <= 0x2B73F) or # (0x2B740 <= cp <= 0x2B81F...
def sequences_to_bytes(sequence, value_op=None): """ Transforms result of rle.get_sequences() into a byte array. Encoding: - repeats start with a byte whose MSB is 1 and the lower bits are the count, followed by the value to repeat. - sequences start with a byte whose MSB is 0 and the lower bi...
def first_or_default(iterable): """ Gets the first or default (= None) value from an iterable :param iterable: Iterable instance :return: First item or None """ return next(iter(iterable or []), None)
def _vectorise(value): """ Converts singletons to length 1 lists """ if not isinstance(value, list): return [value] return value
def get_patk(gt_label, label_list, K): """Calculate Precision@K Args: gt_label: the ground truth label for query label_list: labels for the retrieved ranked-list K: top K in the ranked-list for computing precision. Set to len(label_list) if compute P@N Returns: P...
def WtoBTUhr(qW): """ Convertie la puissance en W vers btu/hr Conversion: 1 W = 3.412142 BTU/hr :param qW: Puissance [W] :return qBTUhr: Puissance [btu/hr] """ qBTUhr = qW * 3.412142 return qBTUhr
def createCarPositionLog(car, currentTime): """ :param car: dictionary with spesific car parameters at time Current time :param currentTime: the time wanted to be logged :return: dictionary to add to car logger """ return {'position': car['position'], 'time': currentTime, 'target': car['target']...
def jsearch(json,sfld,search,rfld): """ return a list of values from a column based on a search """ lst=[] for j in json: if j[sfld]==search or search == '*': lst.append(j[rfld].strip()) return lst
def uniquify_sequence(sequence): """Uniqify sequence. Makes sure items in the given sequence are unique, having the original order preserved. :param iterable sequence: :return list: """ seen = set() seen_add = seen.add return [x for x in sequence if x not in seen and not seen_add(x...
def midpoint(point_1, point_2): """Middle point between two points""" x1, y1 = point_1 x2, y2 = point_2 return ((x1 + x2) / 2, (y1 + y2) / 2)
def convert_patch_url_to_download_url(patch_url, patch_id, project_name, patchset_number, file_name): """ Convert gerrit patch URL to URl from where we can download the patch :param patch_url: URL in string format :returns: down...
def equivalent(list1, list2): """Ensures that two lists are equivalent, i.e., contain the same items.""" if len(list1) != len(list2): return False set1 = set(list1) for item in list2: if item not in set1: return False return True
def str2intlist(s, repeats_if_single=None): """Parse a config's "1,2,3"-style string into a list of ints. Args: s: The string to be parsed, or possibly already an int. repeats_if_single: If s is already an int or is a single element list, repeat it this many times to cr...
def get_continious(objects_l): """ just to fix the list of list of list to finally make it one list to keep track of images and qs per timestep """ # print(len(objects_l)) fixed_objs = [] for obj in objects_l: # print(img) if obj: # print("img = ", img) for _obj i...
def clamp(value, minimum=0, maximum=None): """Set the value to within a fixed range.""" if maximum: value = min(maximum, value) return max(value, minimum)
def get_deep(instance, path): """ Do NOT use this helper in your code. It's extremely primitive and wouldn't work properly with most Mappings. """ path = path.split(".") for path_segment in path: if path_segment not in instance: return None instance = instance[path_se...
def get_nature_avsent(inputdict): """ Calculate nature of average sentiment score per user Args: inputdict (:obj:`dict`): dict of user and average sentiment compound score Returns: :obj:`outputdict`: dict of user and nature of average sentiment compound score """ outputdict = {} for k, v in inputdict.item...
def headers_to_dict(headers): """ Converts a sequence of (name, value) tuples into a dict where if a given name occurs more than once its value in the dict will be a list of values. """ hdrs = {} for h, v in headers: h = h.lower() if h in hdrs: if isinstance(hdrs[...
def clsInd2Name(lbls, ind): """ Converts a cls ind to string name """ if ind>=0 and ind<len(lbls): return lbls[ind] else: raise ValueError('unknown class')
def skip_whitespace(s, pos): """ eats white space """ while s[pos] == " ": pos += 1 return pos
def build_plot_values(gdpinfo, gdpdata): """ Inputs: gdpinfo - GDP data information dictionary gdpdata - A single country's GDP stored in a dictionary whose keys are strings indicating a year and whose values are strings indicating the country's corresponding GDP ...
def contain_all_elements(lst, other_lst): """ checking whether the second contains a list of all the elements of the first :param lst: first list :param other_lst: second list :return: check result """ diff = set(other_lst) diff -= frozenset(lst) return not len(diff)
def remove_suffix(s, suffix): """ Removes string suffix from end of string s. """ return s[:len(s)-len(suffix)] if s.endswith(suffix) else s
def gassmann_update_rho(Rho_sat, Rho_f1, Rho_f2): """ Update density due to change in pore fluids. """ Rho_sat2 = Rho_sat + (Rho_f2 - Rho_f1) return Rho_sat2
def default_if_none(value, default=None): """Return default if a value is None.""" if value is None: return default return value
def is_triangular(k): """ k, a positive integer returns True if k is triangular and False if not """ num = 1 triangularNo = 0 while triangularNo < k: triangularNo += num num += 1 if triangularNo == k: return True return False
def factorial(n): """ berechnet n! (n-Fakultaet) fuer gegebenes n """ fak = 1 for k in range(2,n+1): fak = fak * k return(fak)
def atom(gplus_id, page_id=None): """Return an Atom-format feed for the given G+ id, possibly from cache.""" if len(gplus_id) != 21: return 'Invalid G+ user ID (must be exactly 21 digits).', 404 # Not Found if page_id and len(page_id) != 21: return 'Invalid G+ page ID (must be exactly 21 di...
def reset_moved_bools(inp): """Reset the third value in our character tuples, which tracks whether they've moved in a round""" for rowI,row in enumerate(inp): for colI,col in enumerate(row): if col[0] in ["G","E"]: char_tup = (col[0],col[1],False) inp[ro...
def pick_wm_class_2(tissue_class_files): """ Returns the white matter tissue class file from the list of segmented tissue class files Parameters ---------- tissue_class_files : list (string) List of tissue class files Returns ------- file : string Path to segment_seg...
def lower(xs): """returns lowercase for sequence of strings""" # """performs lowercasing on string or sequence of strings""" # if isinstance(xs, str): # return xs.lower() return [x.lower() for x in xs]
def dyn_mean(val, prev_mean, n): """Dynamic mean: computes the mean based on a previous mean plus a new value. Useful when mean is built incrementally, it saves the usage of huge arrays. Keyword arguments: val -- new val to add to the mean prev_mean -- previous mean value n -- number of total e...
def calculate_checksum(data: bytes) -> int: """ Checksum calculation, as per MH-Z19B datasheet, section C. Calibrate and calculate. ``data`` are either command or response, including the original/expected checksum as last byte. Link: https://www.winsen-sensor.com/d/files/infrared-gas-sensor/mh-z19b-co2...
def lmap(f,l): """ given a function and a list maping the function on the list return the mapped list """ return list(map(f,l))
def spacer(value) -> str: """Adds leading space if value is not empty""" return ' ' + str(value) if value is not None and value else ''
def to_sec(v): """ Convert millisecond, microsecond or nanosecond to second. Args: v: timestamp in int, long, float or string. It can be a timestamp in second, millisecond(10e-3), microsecond(10e-6) or nanosecond(10e-9). Returns: int: timestamp in second. R...
def vowels_set(word): """Vowels set: Given a string representing a word, write a set comprehension that produces a set of all the vowels in that word. >>> vowels_set('mathematics') set(['a', 'i', 'e']) """ lst = set([w for w in word if w == 'a' or w == 'e' or w == 'i' or w == 'o' or w ==...
def cross(p1, p2): """ Cross product of two vectors """ x = p1[1] * p2[2] - p1[2] * p2[1] y = p1[2] * p2[0] - p1[0] * p2[2] z = p1[0] * p2[1] - p1[1] * p2[0] return x, y, z
def format_translation_changes(old, new): """ Return a comment stating what is different between the old and new function prototype parts. """ changed = False result = '' # normalize C API attributes oldargs = [x.replace('struct _', '') for x in old['args']] oldretval = old['retval'].replace('struc...
def is_overlap_1d(start1: float, end1: float, start2: float, end2: float) -> bool: """Return whether two 1D intervals overlaps""" assert start1 <= end1 assert start2 <= end2 return not (start1 > end2 or end1 < start2)
def decimalToBinaryv2(decimal): """assumes decimal is an int, representing a number in base 10 returns an int, representing the same number in base 2 """ digits = [] reminder = decimal while reminder > 0: digits.append(str(reminder % 2)) reminder = reminder // 2 return "".joi...
def array_contains_tracking_data(array_to_check): """ Returns True if the array contains some tracking data. """ result = False if array_to_check is not None: number_of_items = len(array_to_check) if number_of_items > 0: found_none = False for i in range(0, nu...
def magnitude2cps(magnitude, magnitude_zero_point): """ converts an apparent magnitude to counts per second The zero point of an instrument, by definition, is the magnitude of an object that produces one count (or data number, DN) per second. The magnitude of an arbitrary object producing DN counts in ...
def flatten(a): """ Flattens list of lists with arbitrary depth into a 1-D list. Parameters ---------- l : list list to be flattened Returns ------- flat_l : list flattened list """ flat_l = [] for el in a: if isinstance(el, list): fl...
def cmdline_remove_npools(cmdline): """Remove all options related to npools in the `settings.cmdline` input. The cmdline setting is a list of strings that typically looks something like: cmdline = ['-nk', '4', '-ntg', '8'] This function will remove all occurrences of '-nk', '-npool', '-npools', w...
def get_intersections(path1, path2): """returns a list of the intersection points between the two paths Args: path1: one path (list of tuples with consecutive integer x, y coords) path2: second path (see above) Returns: a list of all overlapping tuples from the two paths ""...
def err(error_dictionary): """ Formats the error response as wanted by the Flask app :param error_dictionary: name of the error dictionary :return: tuple of error message and error number """ return {'error': error_dictionary['body']}, error_dictionary['number']
def isintlike(value): """ Checks if an object can be converted to an integer. @param value: {object} @return {bool} """ try: int(value) return True except (TypeError, ValueError): return False
def comparison_bool(str1, str2, reverse=False): """idk why I need to write a tag for this, it returns a bool""" if reverse: return str1 != str2 return str1 == str2
def read_lines(file_name): """ Read all the lines in a given file Shortcut to avoid clumping up of many with-blocks Handles the IO exception to return a blank list when no file is present """ lines = [] try: with open(file_name, "r") as f: lines = f.readlines() ...
def convert_to_float(var): """ Tries to convert an number to float. :param var :returns the value of the float or None if it fails """ try: return float(var) except ValueError: return None
def rv12(mjd, hist=[], **kwargs): """cadence requirements for 12-visit RV plates Request: 12 total, ~3 per month, ideally within 1 week mjd: float, or int should be ok hist: list, list of previous MJDs """ # covid 4 plug per night solution return True if len(hist) == 0: retu...
def is_not_logged_in(session): """Returns wether the user is logged in or not""" return 'logged_in' not in session or session['logged_in'] is None
def jaccard_similarity(x, y): """ Returns the Jaccard Similarity Coefficient (Jarccard Index) between two lists. From http://en.wikipedia.org/wiki/Jaccard_index: The Jaccard coefficient measures similarity between finite sample sets, as is defined as the size of the intersection divided by th...
def _get_connect_string(backend, user="openstack_citest", passwd="openstack_citest", database="openstack_citest"): """ Try to get a connection with a very specific set of values, if we get these then we'll run the tests, otherwise they ...
def gen_unknown_filter(skip_unknown = False): """ Generation of a SPARQL Filter clause to exclude unknown edge type Produces something like FILTER( ?controlType = "ACTIVATION"^^xsd:string || ?controlType = "INHIBITION"^^xsd:string) """ if skip_unknown == True: return 'FILTER( ?contr...
def remove_crud(string): """Return string without useless information. Return string with trailing zeros after a decimal place, trailing decimal points, and leading and trailing spaces removed. """ if "." in string: string = string.rstrip('0') string = string.lstrip('0 ') string...
def osc(last, type): """ R=[AG], Y=[CT], K=[GT], M=[AC], S=[GC], W=[AT], and the four-fold degenerate character N=[ATCG] """ if type == "k": if last == "g": return("t") elif last == "t": return("g") return "g" elif type == "m": if last == "...
def find_path(src, target, passable): """ >>> path = find_path((1, 1), (3, 4), lambda: True) >>> len(path) 6 >>> find_path((1, 1), (3, 1), lambda: True) [(1, 1), (2, 1), (3, 1)] :rtype: list or None if not found """ paths = [[src]] visited = {src} # search until target is re...
def info_item_cmp(x,y): """ Comparison function for items (k,v) in the dictionary returned byt the frame_drop_corrector.info_all() function. """ x_num = int(x[0].split('_')[1]) y_num = int(y[0].split('_')[1]) if x_num > y_num: return 1 elif x_num < y_num: return -1 e...
def _locate_qubit_in_address(qubit_map, address): """ Returns the name of a qubit in a pulse address. """ if address is None: raise ValueError("Could not resolve address '{}'".format(address)) for sub_addr in address.split(":"): if sub_addr in qubit_map: return sub_addr ...
def _update_imports(new_imports: list, old_imports: list) -> list: """Update imports. Compare the old imports against the new ones and returns the old imports with the new imports that did not existed previously. :param new_imports: All new imports. :param old_imports: All old imports. :return...
def cubic_hermite_spline(x, p0, m0, p1, m1): """The third order polynomial p(x) with p(0)=p0, p'(0)=m0, p(1)=p1, p'(1)=m1.""" a3 = m0 + m1 + p0 + p0 - p1 - p1 a2 = p1 - a3 - m0 - p0 return p0 + x * (m0 + x * (a2 + x * a3))
def subsequence(first_sequence, second_sequence): """ Returns whether the first sequence is a subsequence of the second sequence. Inputs: first_sequence (list): A sequence. second_sequence (list): Another sequence. Returns: Boolean indicating whether first_sequence is a subsequ...
def _correct_predecessor(reachability_plot, predecessor_plot, ordering, s, e): """Correct for predecessors. Applies Algorithm 2 of [1]_. Input parameters are ordered by the computer OPTICS ordering. .. [1] Schubert, Erich, Michael Gertz. "Improving the Cluster Structure Extracted from ...
def parse_number(string): """Takes a string and attempts to convert it to a number. This function simply removes commas and underscores from the string, and then tries to convert it to an int or a float. >>> parse_number('10') 10 >>> parse_number('1.4') 1.4 >>> parse_number('12,345')...