content
stringlengths
42
6.51k
def select_min(window): """In each window select the minimum hash value. If there is more than one hash with the minimum value, select the rightmost occurrence. Now save all selected hashes as the fingerprints of the document. :param window: A list of (index, hash) tuples. """ # print window, ...
def calculate_result(expression): """ Calcualte the result for the previous validate expression :reutrn: str """ return str(round(eval(expression), 2))
def str_list(F_list,sep_c=','): """ Get string with representation of list. """ return("["+sep_c.join(map(str,F_list))+"]")
def fix_zip5(zip5): """add leading zeros if they have been stripped by the scorecard db""" if len(zip5) == 4: return "0{0}".format(zip5) if len(zip5) == 3: return "00{0}".format(zip5) else: return zip5[:5]
def pvl(vertex_list): """ Convert a list of vertexes to a string of task names for output. """ return "".join([str(v) for v in vertex_list])
def getCN(dn): """ Get the CN part of a DN """ fields = dn.split('/') for f in fields: if f[0:3] == 'CN=': cn = f[3:] return cn
def int_or_float(x): """Convert `x` to either `int` or `float`, preferring `int`. Raises: ValueError : If `x` is not convertible to either `int` or `float` """ try: return int(x) except ValueError: return float(x)
def distances_from_position(pos, size): """ Returns vector of distances from position in array of size 'size' pos: int size: int returns: list """ result = [] for i in range(size): result.append(i-pos if i-pos >= 0 else i-pos+size) return result
def get_img_path_file(img_id): """ could change the path_root to be transportable folder containing the images """ #path_root='./gtFine/val_images/' path_root='./static/images/' return str(path_root+img_id+'.png')
def CalculateOverlap(intervalls1, intervalls2): """calculate overlap between intervalls. """ if not intervalls1 or not intervalls2: return 0 intervalls1.sort() intervalls2.sort() overlap = 0 x = 0 y = 0 while x < len(intervalls1) and y < len(intervalls2): xfrom, ...
def signal_det(corr_resp, subj_resp): """ Returns an accuracy label according the (modified) Signal Detection Theory. ================ =================== ================= Response present Response absent ================ =================== ================= Stimulus...
def cast_keep_none(obj, dest_type: type): """ Cast ``obj`` to ``dest_type``. If ``obj`` is ``None``, returns ``None``. :param obj: object to be casted :param dest_type: target type to cast `obj` :return: casted `obj` """ if obj is None: return None if issubclass(dest_type,...
def to_bit_array(byte): """Gets 8 bits from a byte.""" arr = [] curr = byte for i in range(8): arr.append(curr % 2) curr = curr // 2 return list(reversed(arr))
def items2list(x): """ x - string of comma-separated answer items """ return [l.strip() for l in x.split(',')]
def _find_concentrations(col): """Finds the concentration of a given array of colors. :arg col: an integer array of the labeling """ Concs=[] tcol= list(col) for i in range(len(tcol)): if tcol[i] != 0: Concs.append(tcol.count(tcol[i])) for j in range(len(tcol)):...
def _extract_col_name(colname:str) -> str: """ Extracts all data before line boudnaries and just returns that as the column header. This allows help text to be placed in the same table cell as a column header, but ignored. """ if not isinstance(colname, str): return "" return colname.split...
def normalize_provider(provider, plan_ids_set): """Flatten provider JSON blobs and filter by plan ID.""" normalized = [] addresses = provider.pop('addresses') plans = provider.pop('plans') specialties = provider.pop('specialty') # this is a list name = provider.pop('name') for plan in plans...
def binary_search(array, other_num, low, high): """Searches for the other number needed to make the target sum. Returns array index, or -1 if not found. low and high - index positions between which we are searchig """ mid = (low + high) // 2 # base case - successful if array[mid] == other_n...
def condense_labels(labels, cluster_map): """ Can be used to "collapse" clusters of similar poses into meta-clusters """ new_labels = labels for l, label in enumerate(labels): if label != -1 and label in cluster_map: new_labels[l] = cluster_map[label] return new_labels
def convert_tag(tag: str) -> str: """Convert nltk pos tag to wodnet tag.""" res = tag[0].lower() if res in ["j"]: res = "a" if res not in ["a", "v", "n", "r"]: res = "n" return res
def _rssify_author(author): """ Convert author from whatever it is to a plain old email string for use in an RSS 2.0 feed. """ if type(author) is dict: try: return author["email"] except KeyError: return None else: if "@" in author and "." in aut...
def average(a, b): """ Decorator ensures that this function can be used in a Tangled graph """ return (a + b) / 2
def numdim(l): """ Returns number or dimensions of the list, assuming it has the same depth everywhere. """ if not isinstance(l, (list, tuple)): return 0 if not isinstance(l[-1], (list, tuple)): return 1 else: return 1 + numdim(l[-1])
def calc_tags(list_tags): """Calculate bot list tags""" # Tag calculation tags_fixed = [] for tag in list_tags.keys(): # For every key in tag dict, # create the "fixed" tag information # (friendly and easy to use data for tags) tags_fixed.append({ "name": ta...
def snake_to_text(x: str) -> str: """Convert snake case to regular text, with each word capitalized.""" return " ".join([w.capitalize() for w in x.split("_")])
def numReactantsProducts(chapter): """Return the number of reactants and products (in particles) for a reaction of ReacLib Chapter type chapter.""" r,p = 1,1 if chapter in [2,5,9,10]: p+= 1 if chapter in [3,6]: p+= 2 if chapter in [7,11]: p+= 3 if chapter > 3 and chapter is not 11: r+= 1 ...
def uint32(value): """Validate a 'unit32' method parameter type""" value = int(value) if value > 4294967295: raise ValueError("{} exceeds upper bound for uint32".format(value)) if value < 0: raise ValueError("{} below lower bound for uint32".format(value)) return value
def keyword_event(callbacks, parameters): """ Custom call for events with keywords (like push, or pull, or turn...). Args: callbacks (list of dict): the list of callbacks to be called. parameters (str): the actual parameters entered to trigger the callback. Returns: A list cont...
def bps2human(n, _format='%(value).1f%(symbol)s'): """Converts n bits per scond to a human readable format. >>> bps2human(72000000) '72Mbps' """ symbols = ('bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps') prefix = {} for i, s in enumerate(symbols[1:]): prefix[s...
def spaces(num_spaces: int) -> str: """ Return a string with the given number of spaces. """ return ' ' * num_spaces
def ifdef_name(filename): """ Generates the ifdef name to use for the given filename""" return filename.replace("/", "_").replace(".", "_").upper() + "_"
def chrome(_os=None, os_bit=None): """ chrome driver info :param _os: system :param os_bit: system bit :return: """ latest_version = '81.0.4044.69' base_download = "https://cdn.npm.taobao.org/dist/chromedriver/%s/chromedriver_%s%s.zip" download = base_download % (latest_version, _os,...
def int_to_roman(input): """ Convert an integer to Roman numerals. Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most recent call last): ValueError: Argument must be between 1 and 399...
def ReadData( offset, arg_type ): """Emit a READ_DOUBLE or READ_DATA call for pulling a GL function argument out of the buffer's operand area.""" if arg_type == "GLdouble" or arg_type == "GLclampd": retval = "READ_DOUBLE( %d )" % offset else: retval = "READ_DATA( %d, %s )" % (offset, arg_type) return retval
def get_scalebin(x, rmin=0, rmax=100, tmin=0, tmax=100, step=10): """ Scale variable x from rdomain to tdomain with step sizes return key, index :param `x`: Number to scale :type `x`: number :param `rmin`: The minimum of the range of your measurement :type `rmin`: number, optional :para...
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
def extract_commit_file_components(commit_files): """ Extract components from individual files to create lists for each component :param commit_files: List of database file objects :return: Dictionary with all the components from the files """ commit_file_components = { 'patches': [], ...
def resolve_url(url): """ >>>resolve_url("127.0.0.1:21337") >>>"127.0.0.1", 21337 >>>resolve_url("http://127.0.0.1:21337") >>>"127.0.0.1", 21337 Args: url (string): {http,ws}://ip:port Returns: (string,int): ip, port """ url = url.split("://")[-1] url = url.st...
def get_dir(xy): """ |NW|N |NE| +--+--+--+ |W |C |E | +--+--+--+ |SW|S |SE| """ if xy == (0, 0): return "NW" elif xy == (0, 1): return "N" elif xy == (0, 2): return "NE" elif xy == (1, 0): return "W" elif xy == (1, 1): return "C" ...
def can_select(_): """ Determines whether user can select a membership from the database Args: editors_role (Role): the role of the member who is selecting the membership """ # All members can read all memberships return True
def convert_stack_to_string(stack): """ convert stack of numbers, brackets, commas to string """ return "".join(stack)
def heat_in_radiator(room_temp, radiator_temp): """ Heat transfer into the room via the radiator. Assume radiator temperature independent of heat transfer. :param room_temp: [C] :param radiator_temp: [C] :return: [J] """ conductance = 25 # thermal conductance [W/K] return (radiator_te...
def add_left_title(ax, title, **kwargs ): """Add a centered title on the left of the selected axis. All :func:`~matplotlib.Axes.annotate` parameters are accessible. :param ax: Target plot axis. :type ax: :class:`~matplotlib.Axes` :param str title: Title text to add. :return: :class:`~matp...
def partition(lis, predicate): """ Splits a list into two lists based on a predicate. The first list will contain all elements of the provided list where predicate is true, and the second list will contain the rest """ as_list = list(lis) true_list = [] false_list = [] for l in as_list: pred_value...
def response_card_login(title, output, endsession): """ create a simple json plain text response """ return { 'card': { 'type': 'LinkAccount', 'title': title, 'text': output }, 'outputSpeech': { 'type': 'SSML', 'ssml': "<speak...
def project(*args, **kwargs): """ Build a projection for MongoDB. Due to https://jira.mongodb.org/browse/SERVER-3156, until MongoDB 2.6, the values must be integers and not boolean. >>> project(a=True) == {'a': 1} True Once MongoDB 2.6 is released, replace use of this function with a simp...
def lookup_zone_by_name(name, interfaces): """Looks for a network by name and returns a list""" zone = [] for inf in interfaces: if isinstance(inf, dict): for listinf in inf: if name in listinf: zone.append({listinf: inf[listinf]}) elif name in...
def create_bcs(Lx, Ly, mesh, enable_NS, enable_EC, **namespace): """ The boundaries and boundary conditions are defined here. """ boundaries = dict() bcs = dict() # Apply pointwise BCs e.g. to pin pressure. bcs_pointwise = dict() if enable_NS: bcs_pointwis...
def validate_rows(board: list): """ checks whether rows of the board comply to the rules of the game """ for row in board: row = row.strip('*').replace(' ', '') if sorted(list(set(row))) != sorted(list(row)): return False return True
def legacy_id_to_url_fn(id: str) -> str: """Generate an arxiv.org/archive URL given a paper ID.""" return 'https://arxiv.org/archive/' + id
def create_jstruct(jstruct, elem_struct, val): """ Create json structure (recursive function) :param jstruct: jstruct to update :param elem_struct: nested field represented as list :param val: value of the nested field :return: json structure created (update...
def is_null_or_empty(obj): """ Checks if a given object is either Null, empty or a length of 0 """ validations = [] validations.append(obj is None) validations.append(obj == "") if isinstance(obj, list) or isinstance(obj, dict): validations.append(len(obj) == 0) return any(val...
def true_function(x): """$t = 5x+x^2-0.5x^3$""" return (5 * x) + x**2 - (0.5 * x**3)
def filter_eliminate_long(data): """Filter out items with too many characters as they are unlikely to represent a technique""" MAX_CHARACTERS = 300 new_data = [] for d in data: if len(d['article']) <= MAX_CHARACTERS: new_data.append(d) data = new_data return data
def flag_monthday(datestr): """a date in this range is likely a month/day entered by a user, but stored as a month/year by Wikidata; check to make sure this isn't the case""" try: y,m,d = [int(x) for x in datestr.split('T')[0].rsplit('-', 2)] # is "year" in the range where it could actually be a...
def sol(arr, n): """ The complexity here is n^2 """ b = [-1]*n prev = -1 for i in range(n-1): if not arr[i]: b[i] = prev continue j = i + 1 mv = -1 m = None while j < n and arr[i] > arr[j]: if arr[j] > mv: ...
def merge_result_dict(result_dicts): """Merge results stored in dict Parameters ---------- result_dicts : List[Dict[key, value]] or Dict[key, value] result dicts to be merged Returns ------- Dict[key, List[value]] merge values into list """ if not isinstance...
def get_main_domain_name(url_str) -> str: """get url domain texts Args: url_str (str): url string Returns: str: domain name of url """ domain_name = url_str.split("/")[2] main_domain_name = domain_name.split(".")[-2] return main_domain_name
def get_tangent_intersect_inner(hloc_0, vloc_0, hloc_1, vloc_1, radius_0, radius_1): """Return Location in 2 Dimensions of the Intersect Point for Inner Tangents. Args: hloc_0: Horizontal Coordinate of Centre of First Arc vloc_0: Vertical Coordinate of Centre of First Arc hloc_1: Horizo...
def calculate(input_): """ Given a string with numbers separated by comma like "+1, -2" calculate the sum of the numbers """ return sum([int(x.strip()) for x in input_.split(",") if x])
def sent_length(sentence): """ Returns sentence length without spaces. """ return sum(1 for c in sentence if c != ' ')
def unsigned2signed(value, width=32): """ convert an unsigned value representing the 2's complement encoding of a signed value to its numerical signed value """ msb = value >> (width - 1) return int(value - msb * 2**width)
def do_box_overlap(coord1, coord2): """Checks if boxes, determined by their coordinates, overlap. Safety margin of 2 pixels""" return ( (coord1[0] - 2 < coord2[0] and coord1[1] + 2 > coord2[0] or coord2[0] - 2 < coord1[0] and coord2[1] + 2 > coord1[0]) and (coord1[2] - 2 < coord2[2] and coor...
def splittexttolines(text, linelength): """ DESCRIPTION: Internal method which splits provided comments into IAGA 2002 conform lines. Returns a list of individual lines which do not exceed the given linelength. EXAMPLE: comment = "De Bello Gallico\nJulius Caesar\nGallia est omnis div...
def merge_dicts(d0, d1): """Create a new `dict` that is the union of `dict`s `d0` and `d1`.""" d = d0.copy() d.update(d1) return d
def _levenshtein_distance(s1, s2): """ :param s1: A list or string :param s2: Another list or string :returns: The levenshtein distance between the two """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for index2, num2 in enumerate(s2): new_dis...
def strictly_increasing(L): """Return True if list L is strictly increasing.""" return all(x < y for x, y in zip(L, L[1:]))
def lookup_beatmap(beatmaps: list, **lookup): """ Finds and returns the first beatmap with the lookup specified. Beatmaps is a list of beatmap dicts and could be used with beatmap_lookup(). Lookup is any key stored in a beatmap from beatmap_lookup(). """ if not beatmaps: return None fo...
def convert_to_iris(dict_): """Change all appearances of `short_name` to `var_name`. Parameters ---------- dict_ : dict Dictionary to convert. Returns ------- dict Converted dictionary. """ dict_ = dict(dict_) if 'short_name' in dict_: dict_['var_name']...
def name_normalizer(name: str) -> str: """Normalize the name of a method.""" return name.lower().replace('_', '')
def choose_LP(masks_OUT): """ Provided a list of [[IN,IN,IN,IN],[IN,IN,IN]], returns the masks common to all the lists of mask. """ x = masks_OUT[0][:] for i in range(1,len(masks_OUT)): x = list(set(x).intersection(masks_OUT[i])) return x
def get_key(x): """Return key. According to standard NODC-PhyChe serie format (YEAR_SHIPC_SERNO). """ return '_'.join(x)
def table(lst): """ Takes a list of iterables and returns them as a nicely formatted table. All values must be convertible to a str, or else a ValueError will be raised. N.B. I thought Python's standard library had a module that did this (or maybe it was Go's standard library), but I'm on an a...
def find_all_subj(sent): """ Find all the subjects that we would like to probe, with corpus-specific heuristic. We cannot use a postagger because most of these sentences in synthetic datasets are garden-path sentences. It is very likely that a postagger will make mistakes. heuristics: (1) all the NPs sho...
def minmax(x, my_min=0, my_max=1): """Restrict float to between a minimum and maximum value Parameters ---------- x : float Value to be restricted between my_min and my_max my_min : float Minimum value accepted (default 0) my_max : float Maximum value accepted (default 1)...
def merge_sort(input_list, left_index, right_index): """ Merge sort """ if right_index - left_index > 1: midpoint = left_index + (right_index - left_index) // 2 left_sorted = merge_sort(input_list, left_index, midpoint) right_sorted = merge_sort(input_list, midpoint, right_index)...
def reduce_axis(pix_in, kernel_size, stride, drop_last=False): """ Calculate output pixels along one axis given input pixels, filter size, and stride. --- IN pix_in: number of pixels along input axis (int) kernel_size: assuming a square filter, pixels on one side (int) stride: pixels per...
def docsitalia_parse_tags(tag_string): """ Parses a string into its tags by preserving spaces and other characters. We just split on commas :see: https://django-taggit.readthedocs.io/page/custom_tagging.html :param tag_string: a delimited string of tags :return: a sorted list of tag strings ...
def add_missing_multiply(token_list): """ pre-processing step, if there is any variable adjacent to a number, add a '*' """ for i in range(len(token_list)): if type(token_list[i]) == list: token_list[i] = add_missing_multiply(token_list[i]) res = [] for i in range(len(token_l...
def centroid(ipgroup): """ takes a group of mz and intensity values and finds the centroid this method results in substantially more error compared to the weighted_average method (~9 orders of magnitude for C61H51IP3Pd) """ return sum(ipgroup[0]) / len(ipgroup[0]), sum(ipgroup[1]) / len(ipgroup[...
def findadjacentdir(a, b): """Gives direction from a to b if they are adjacent(not diagonal), if they are not adjacent returns false""" ax = a['x'] ay = a['y'] bx = b['x'] by = b['y'] xdiff = ax - bx ydiff = ay - by if (xdiff in range(-1, 2) and ydiff == 0) or (ydiff in range(-1, 2) and...
def join(*args): """ Return a string composed of the result of applying str() to each one of the given args, separated by spaced, but only if the item exists. Example: >>> join('Hello', False, 1, True, 0, 'world') 'Hello 1 True world' """ strings = [str(arg) for arg in args if a...
def sl(c, s, l): """ This accountancy function computes straight line depreciation for an asset purchase for cash with a known life span and salvage value. c = historical cost or price paid (1000) s = the expected salvage proceeds at disposal l = expected useful life of the fixed asset Ex...
def curveqa(pyccd_result, ordinal): """ Curve fit information for the segment in which the ordinal intersects with. Defaults to 0 in cases where the given ordinal day to calculate from is either < 1 or it does not intersect with a segment identified in pyccd. Args: pyccd_result: dict r...
def del_none(dictionary): """ Recursively delete from the dictionary all entries which values are None. Args: dictionary (dict): input dictionary Returns: dict: output dictionary Note: This function changes the input parameter in place. """ for key, value in list(dic...
def weighted_average(weighted_list): """calculate weighted average of attributes input: list of (attribute, weight) pairs""" if len(weighted_list) > 0: return sum([val * wgt for val, wgt in weighted_list]) /\ sum([wgt for _, wgt in weighted_list]) else: return 0
def encode_string_for_graph_label(val): """Encodes reserved graphviz characters""" return val.replace('{', '&#123;').replace('|', '&#124;').replace('}', '&#125;').replace('<', '&#60;').replace('>', '&#62;')
def rescale(x, y, coeff, mx, my): """ Rescale x y - axis. Args: x: (todo): write your description y: (todo): write your description coeff: (todo): write your description mx: (todo): write your description my: (todo): write your description """ # Bring the da...
def _deep_flatten(items): # pylint: disable=invalid-name """Returns a list of objects, flattening sublists/subtuples along the way. Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return the list [1, 2, 3, 4, 5, 6, 7, 8]. Args: items: An iterable. If elements of this iterable are lists...
def stripsuffix( glyphname ): """Returns the glyphname without the dot suffix.""" dotindex = glyphname.find(".") return glyphname[:dotindex]
def _pipe(obj, func, *args, **kwargs): """ Apply a function ``func`` to object ``obj`` either by passing obj as the first argument to the function or, in the case that the func is a tuple, interpret the first element of the tuple as a function and pass the obj to that function as a keyword argument ...
def valid_parentheses(parens): """Are the parentheses validly balanced? >>> valid_parentheses("()") True >>> valid_parentheses("()()") True >>> valid_parentheses("(()())") True >>> valid_parentheses(")()") False >>> valid_parentheses("())") ...
def is_int(parser, arg): """ Check if argument is int or auto. """ if arg != "auto": try: arg = int(arg) except parser.error: parser.error('Value {0} is not an int or "auto"'.format(arg)) return arg
def alpha(min_val, max_val, val): """Return 0-1 where 0 val==min_val and 1 val==max_val. Does not clamp.""" return (val-min_val)/(max_val-min_val)
def pdiff(a, b): """Difference between a and b as a fraction of a i.e. abs((a - b)/a) """ return abs((a - b)/a)
def get_available_difficulties(metadata_record): """Gets the difficulty levels that are present for a song in a metadata record.""" levels = [] for key, value in metadata_record['metadata']['difficulties'].items(): if value == True or value == 'True': levels.append(key) return levels
def get_units(x): """ Gets the units of x. Returns None if x has no units """ try: return x.units except AttributeError: return None
def user_url(username): """Get a user's url.""" return "https://instagram.com/%s/" % username
def make_train_state(save_file): """Initializes history state dictionary Args: save_file (str): path to save directory """ return { 'epoch_idx': 0, 'model_save_file': save_file, 'best_joint_acc': 0, 'best_joint_loss': 1e9, 'best_epoch_idx_loss': 0, ...
def get_pdbid_from_pnid(pnid): """Return RCSB PDB ID associated with a given ProteinNet ID. Args: pnid (string): A ProteinNet entry identifier. """ # Try parsing the ID as a PDB ID. If it fails, assume it's an ASTRAL ID. try: pdbid, chnum, chid = pnid.split("_") chnum = int(...