content
stringlengths
42
6.51k
def part_two(data): """Part two""" in_garbage = False garbage = 0 i = 0 while i < len(data): if data[i] == "!": i += 1 elif data[i] == "<" and not in_garbage: in_garbage = True elif data[i] == ">" and in_garbage: in_garbage = False ...
def get_addr(local_addr): """ :param local_addr: :return: """ head = "https://commoncrawl.s3.amazonaws.com/" url = head + local_addr return url
def GetDataForExistingElements(list, ref_dict): """ gets a smaller list of type <Atom_Data> only for the present elements """ d = {} for element in list: if ref_dict.get(element): d[element] = ref_dict.get(element) return d
def parse_floats(s): """parse_floats :param s: """ if isinstance(s, str): if "/" in s: # parse a ratio to its float value num, den = s.split("/") return [float(num) / float(den)] elif "," in s: # parse a csv variable into multiple new colu...
def _default_error_handler(err: Exception) -> Exception: """Since the server runs in its own thread context, it can't simply raise an error for the caller to catch. The caller can provide an error handler as a callback when exceptions are raised, this is the default handler that simp...
def _get_versions(json_entry): """ Return version labels ranked from the most recent to the earliest one """ versions = [] if "versions" in json_entry: for version in json_entry["versions"]: # time indicated by "created" attribute versions.insert(0, version["version"]...
def recursive_lookup(lookup, index_list): """ Takes in indexes `index_list` in the form of a list of keys, and iteratively look through those keys in `lookup` until you reach the end of the list. For example, if given the list ['inventory', 'wood'] this method returns lookup['inventory']['wood']...
def _convStorageIdToDocId(doc): """ Function convert doc to storageId. """ if (not doc): return None if '_id' in doc: doc["id"] = doc["_id"] del doc["_id"]
def light_numspec_to_ordinal(spec: str) -> int: """Turn a lighting specification into a light number. The MPF documentation says that FAST lights should be given by serial number only, but at least one example uses channel-index notation like for switches, and it seems to be accepted by the rest of MPF, ...
def is_polygon(point_list): """Takes a list of tuples and determines if it is a polygon""" return (len(point_list) > 1 and point_list[0] == point_list[len(point_list)-1])
def blobdir_name(config): """Generate blobdir name.""" name = config["assembly"]["prefix"] if "revision" in config and config["revision"] > 0: name = "%s.%d" % (name, config["revision"]) return name
def mask_to_cidr(netmask): """Convert netmask in dot-notation to decimal CIDR notation""" return sum(bin(int(x)).count('1') for x in netmask.split('.'))
def get_element_type(_list, dimens): """ Given the dimensions of a nested list and the list, returns the type of the elements in the inner list. """ elem = _list for _ in range(len(dimens)): elem = elem[0] return type(elem)
def breadth_first_search(graph, start, end): """ Breadth First Search Algorithm. """ queue = [] queue.append(start) visited = set() visited.add(start) while queue: current = queue.pop(0) if current == end: return True for node in graph[current]: ...
def get_seat_id(row, column): """Get seat id from row and column.""" return row * 8 + column
def set_dict_value(adict, key, value, prefix=None, splitter='.'): """Used to set value in hierarhic dicts in python with params with dots as splitter""" if prefix is None: prefix = key.split(splitter) if len(prefix) == 1: if type(adict) == type({}): adict[prefix[0]] = value ...
def to_camel(string: str) -> str: """Convert string to camel format.""" if '_' not in string or string.startswith('_'): return string return ''.join([ x.capitalize() if i > 0 else x for i, x in enumerate(string.split('_')) ])
def threshold(threshold, utilization): """ The static CPU utilization threshold algorithm. :param threshold: The threshold on the CPU utilization. :type threshold: float,>=0 :param utilization: The history of the host's CPU utilization. :type utilization: list(float) :return: The decision o...
def genericNonNegativeIntValidator(value): """ Generic. (Added at version 3.) """ if not isinstance(value, int): return False if value < 0: return False return True
def stirling_numbers_1(n,k): """Stirling Numbers of the First Kind""" if n == k: return 1 if n == 0 and k == 0: return 1 if n == 0 or k == 0: return 0 return (n-1)*stirling_numbers_1(n-1,k) + stirling_numbers_1(n-1,k-1)
def lit2str(literals): """For debugging, formats the given literals as a string matching smodels format, as would be input to gringo.""" return ', '.join(map(lambda x: 'v' + str(x) if x > 0 else 'not v' + str(-x), literals))
def _look_for_array_in_array(array1, array2): """ Examples -------- >>> _look_for_array_in_array([1, 2], [2, 3, 4]) 2 >>> _look_for_array_in_array([1, 2], [3, 4, 5]) is None True """ for a1 in array1: if a1 in array2: return a1 return None
def change_sql_sub_obj_into_dic(obj): """change sql sub object into a dictionary""" if obj: obj_info = obj.__dict__ remove = [] for key in obj_info: if str(key)[0] == '_': remove.append(key) for key in remove: del obj_info[key] return obj_inf...
def is_list_like(obj, allow_sets: bool = True): """Whether ``obj`` is a tuple or list :param obj: object to check """ if allow_sets: return isinstance(obj, (set, tuple, list)) else: return isinstance(obj, (tuple, list))
def is_valid_header(val): """Header must have these values.""" return (isinstance(val, dict) and all(x in val for x in ['schema', 'homepage', 'map_name', 'map_id', 'map_description']))
def get_attributes(obj): """ Fetches the attributes from an object. :param obj: The object. :type obj: object :returns: A dictionary of attributes and their values from the object. :rtype: dict """ return {k: getattr(obj, k) for k in dir(obj) if not k.startswith("__")}
def _gen_find(subseq, generator): """Returns the first position of `subseq` in the generator or -1 if there is no such position.""" if isinstance(subseq, bytes): subseq = bytearray(subseq) subseq = list(subseq) pos = 0 saved = [] for c in generator: saved.append(c) if le...
def _generate_root_manifest_content(label, input_files): """Generates the contents for a root manifest for a manifest bundle. Args: label: the BUILD rule that generated the bundle, e.g. //a/b:c input_files: File objects for all the input files in the bundle. """ content = ["// Root manifes...
def generate500response(error: str) -> dict: """ A function that generates a '500-Internal Server Error' message and returns it as a dict """ return { "status": 500, "message": "Internal Server Error", "error": error }
def is_num(str_token): """Numeric token ?""" try: float(str_token) return True except ValueError: return False
def _merge_palettes(palettes): """Build unified palette using all colors.""" unified = {} for palette in palettes: for item in palettes[palette]: unified.update({item: palettes[palette][item]}) palettes.update({'all': unified}) return palettes
def my_min(t): """Compute the minimum of a non empty list.""" current_min = t[0] for v in t: if current_min > v: current_min = v return current_min
def get_ffmpeg_quality(quality_percent): """Convert a value between 0-100 to an ffmpeg quality value (2-31). Note that this is only applicable to the mjpeg encoder (which is used for jpeg images). mjpeg values works in reverse, i.e. lower is better. """ if not 0 <= quality_percent <= 100: r...
def pythonify_metrics_json(metrics): """Converts JSON-style metrics information to native Python objects""" metrics = metrics.copy() for key in metrics.keys(): if key.endswith("_histogram") or key.endswith("_series"): branch = metrics[key] for sub_key in branch.keys(): ...
def GetQueryFields(referenced_fields, prefix): """Returns the comma separated list of field names referenced by the command. Args: referenced_fields: A list of field names referenced by the format and filter expressions. prefix: The referenced field name resource prefix. Returns: The comma sep...
def date_to_iso_8601(d): """Format a datetime.date as an iso 8601 string - YYYY-MM-DD.""" if d: return d.isoformat() else: return None
def add_empty(data, conditions): """ Collected behavioral data may not include (empty) jitter periods. This function corrects for that, adding zero-filled rows to data when conditions is zero. <conditions> shouls be an integer sequence of trial events. '0' indicates a jitter period. In ...
def get_activation_shapes(model, activation_names): """Gets intermediate activation shapes of the model. Args: model: a tf.keras model. activation_names: a list of layer names of `model`. Returns: A list of shapes corresponding to `activation_names`. """ # first dimension is batch size activat...
def _process_nugget(nugget): """ Take raw nugget input and convert to a value and a string :param nugget: Input nugget. Can be a float (fixed nugget) or a string (nugget is inferred via fitting) :type nugget: float or str :returns: Tuple containing nugget value (float) and nu...
def member(value, arg): """Returns html div with the given user's groups Keyword arguments value -- list of dictionaries, containing users, groups and roles arg -- a user """ html = '' groups = [] for group in value.get(arg): html += '<div>' + group + '</div>' groups.ap...
def compareMAC(p, q): """Compare two MAC addresses""" pa = p.split(":") qa = q.split(":") if len(pa) != len(qa): if p > q: return 1 else: return -1 for i in range(len(pa)): n = int(pa[i], 0x10) - int(qa[i], 0x10) if n > 0: return ...
def sieve_public_notes(notes, user_id): """Getting all notes that are public or yours or (shared with you)""" sieved_notes = [] for note in notes: if not note.private: sieved_notes.append(note) elif note.user_id == int(user_id): sieved_notes.append(note) return s...
def roll_right(x): """ Circularly shifts a list to the right [1,2,3] -> [3,1,2] """ new_list = x[:] first = new_list.pop() new_list.insert(0, first) return new_list
def create_cluster_info(cluster_names, sub_keys, values): """ Convenience method for preparing the input parameters cluster_labels and metrics of `create_default_environment()`. The sub-keys can for example be thought of as metric names (and `values` their weights) or cluster label names (and `...
def compute_recall_at_k(real_gains, predicted_gains, k=5): """This function computes recall-at-k, i.e. the proportion of relevant items found in the top-k recommendations. """ relevant_documents = [elem[0] for elem in real_gains] retrieved_documents = [elem[0] for elem in sorted(predicted_gains, key = lambda...
def sort_restaurant(lst, attr=None, order=None): """ """ if attr is None: attr = "avg_score" if order is None or order == "desc": return sorted(lst, key=lambda rest: (-rest[attr], -rest["avg_score"])) else: return sorted(lst, key=lambda rest: (rest[attr], -rest["avg_score"])...
def get_highlight_colour(orig_colour): """ Keep same colour but switch foreground with background. Reference https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters """ return orig_colour.replace("0", "7")
def htid_to_filename(htid): """ Convert a given HTID into a valid filename, performing substitutions on characters that can cause problems in various filesystems and URI schemes. This is a surprisingly subtle process because it needs to be reversible -- that is, we need to generate a filename that c...
def is_substr(s0: str, s1: str): """returns if s0 is a substring of s1""" return (s1.find(s0) > 0)
def cronify(string): """Prepare normal commands for cron""" return string.replace('%', '\%')
def all_the_same(pointer, length, id_list): """ :param pointer: starting from that element the list is being checked for equality of its elements :param length: :param id_list: List mustn't be empty or Null. There has to be at least one element :return: returns the first encountered element if start...
def value_sorted(dic): """ Return dic.items(), sorted by the values stored in the dictionary. """ l = [(num, key) for (key, num) in dic.items()] l.sort(reverse=True) l = [(key, num) for (num, key) in l] return l
def _count_amplicons(amplicon_information, min_depth=0): """ Count number of HaloPlex amplicons for each strand that have fulfilled the minimum read depth. :param amplicon_information: (string) a jSNPmania generate amplicon information string. SNV example: chr1:162722740-162...
def coerce_to_str(x: str) -> str: """Strip outer quotes if we have them.""" if x.startswith("'") and x.endswith("'"): return x[1:-1] elif x.startswith('"') and x.endswith('"'): return x[1:-1] else: return x
def mix_two_grains(grains): """ :param grains: An array of encoded grains of the same size :type grains: array(2) :returns: A single grain :rtype: array """ grain = (grains[0] + grains[1]) / 2.0 return grain
def subdomain_sorting_key(hostname): """Sorting key for subdomains This sorting key orders subdomains from the top-level domain at the right reading left, then moving '^' and 'www' to the top of their group. For example, the following list is sorted correctly: [ 'example.com', 'www...
def _cln(s): """ Clean a string of comments, newlines """ return s.split("!")[0].strip()
def element_of(seq): """ >>> element_of([1, 2, 3]) 1 >>> element_of([[1, 2], [3, 4]]) 1 """ while isinstance(seq, list) and seq: seq = seq[0] return seq
def get_num_le(bytearr): """translate a set of bytes into a number in the little endian format""" num_le = 0 for i in range(len(bytearr)): num_le += bytearr[i] * pow(256, i) return num_le
def largest(upper, lower): """Returns largest of the two values.""" val = max(upper, lower) return val, val
def generate_early_stop_file_path(experiment_path_prefix, net_number): """ Given an 'experiment_path_prefix', return an early-stop-file path with 'net_number'. """ return f"{experiment_path_prefix}-early-stop{net_number}.pth"
def to_gb(byte_value): """Convert the given byte value to GB.""" return "{:.2f}".format(int(byte_value)/1073741824)
def column_value_int(item, args): """Return the value stored in a column cast to an int. YAML usage: outputs: outcol: function: identity arguments: [col(KEYCOL)] value: column_value_int value_arguments: [col(VALUECOL)] ...
def make_param_name_multiple_index(param_parts): """ Make the key name from param parts. For example, ("param", "tag", "2", "1") -> ("param2", "1"). """ return (param_parts[0] + param_parts[-2], param_parts[-1])
def offset_loc(loc, ofs): """ Adds offset to a location represented as a tuple of two ints. """ return (loc[0] + ofs[0], loc[1] + ofs[1])
def getlink(tag): """ Get the hyperlink and title from a tag. Return None tuple if there isn't a link. """ if not tag or isinstance(tag, str): return None, None if "href" not in tag.attrs: return None, None return tag["href"], tag["title"]
def get_html_citeas(authors_bib_style, art_year, art_title, art_pep_sourcetitle_full, art_vol, art_pgrg): """ NOT CURRENTLY USED in OPAS (2020-09-14) """ ret_val = f"""<p class="citeas"><span class="authors">{authors_bib_style}</span> (<span class="year">{art_year}</span>) <span class="title">{art_title...
def _normalize_int_key(key, length, axis_name=None): """ Normalizes an integer signal key. Leaves a nonnegative key as it is, but converts a negative key to the equivalent nonnegative one. """ axis_text = '' if axis_name is None else axis_name + ' ' if key < -length o...
def exploit(p, p_other_lag, p_own_lag, rounder_number): """ Return 1 if the prices correspond to the price cycle used if a player uses the exploit strategy and zero else. """ # p_other_lag always mirrored for algos state = (p_other_lag, p_own_lag) if p == 3 and state == (1,1): r...
def box_contains_point(bx, by, bw, bh, px, py): """ Check if a box contains a point. :param bx: :param by: :param bw: :param bh: :param px: :param py: :return: """ return bx <= px <= (bx + bw) and by <= py <= (by + bh)
def calcAverage (theList): """Calculates the average of a list of values. :param theList: The list of which the average is to be found. :type theList: list :return: The average of the values of theList :rtype: float """ sum = 0 numValues = 0 for value in theList: sum += valu...
def is_close(a, b, rel_tol=1e-09, abs_tol=0.0): """ See PEP 485, added here for legacy versions. >>> is_close(0.0, 0.0) True >>> is_close(1, 1.0) True >>> is_close(0.01, 0.001) False >>> is_close(0.0001001, 0.0001, rel_tol=1e-02) True >>> is_close(0.0001001, 0.0001) Fals...
def strip_version_constraints(requirement): """Strip version constraints and extras from a requirement. >>> strip_version_constraints('zope.foo') 'zope.foo' >>> strip_version_constraints('zope.foo ==4.0.0') 'zope.foo' >>> strip_version_constraints('zope.foo >=4.0.0, <4.1.0...
def blocks_slice_to_chunk_slice( blocks_slice: slice, chunk_shape: int, chunk_coord: int ) -> slice: """ Converts the supplied blocks slice into chunk slice :param blocks_slice: The slice of the blocks :param chunk_shape: The shape of the chunk in this direction :param chunk_coord: The coordinat...
def infer_ensembl_isotype(gene_name): """ Infer e.g., E from IGHE """ if len(gene_name) <= 3: return None return gene_name[3:]
def count_occupied(locations): """Count occupied locations """ occupied = 0 for location in locations: if location == '#': occupied += 1 return occupied
def calc_strike(dip_direction: float) -> float: """ Calculate strike from dip direction. Right-handed rule. E.g.: >>> calc_strike(50.0) 320.0 >>> calc_strike(180.0) 90.0 :param dip_direction: The direction of dip. :return: Converted strike. """ strike = dip_direction - 90...
def is_variable(s: str) -> bool: """Checks if the given string is a variable name. Parameters: s: string to check. Returns: ``True`` if the given string is a variable name, ``False`` otherwise. """ return s[0] >= 'u' and s[0] <= 'z' and s.isalnum()
def collinear(points): """ Returns true, if the given points are all collinear which means, they are on the same line. If the function is called with less than 3 points, it will always return true. """ if (len(points) < 3): return True if (len(points) == 3): return (poi...
def is_northern(lat): """ Determine if it is northern hemisphere. Arguments: lat: float Latitude, in degrees. Northern: positive, Southern: negative. Returns: 1: northern, 0: southern. """ if lat < 0.0: return 0 else: return 1
def kwargs_safe_get(input_dict, key, default_value): """Helper function for managing None in keyword arguments""" result = input_dict.get(key, default_value) if result is None: result = default_value return result
def decompress_amount(x): """ Decompresses the Satoshi amount of a UTXO stored in the LevelDB. Code is a port from the Bitcoin Core C++ source: https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L161#L185 :param x: Compressed amount to be decompressed. :type x: int :return: T...
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ count=0 for i in hand: if hand[i]>0: count=count+hand[i] return count
def full_name(family, style): """ Build the full name of the font from ``family`` and ``style`` names. Names are separated by a space. If the ``style`` is Regular, use only the ``family`` name. """ if style == 'Regular': full_name = family else: full_name = family + ' ' + style...
def partition_by_adjacent_tiles(tile_ids, dimension=2): """ Partition a set of tile ids into sets of adjacent tiles. For example, if we're requesting a set of four tiles that form a rectangle, then those four tiles will become one set of adjacent tiles. Non-contiguous tiles are not grouped together....
def params_fields_lookup(amod, fields): """ Look up all keys mentioned in 'fields' in the module parameters and return their values. :param fields: a list of keys to extract from module params :type fields: list :param amod: the Ansible module to query :type amod: AnsibleModule :return: dict...
def positive_int(value): """Check that the value is an integer greater or equal to 0.""" # An exception will be raised if value is not an int number = int(value) if number < 0: raise ValueError(f"invalid value: '{value}'") return number
def cubic_approx_control(t, p0, p1, p2, p3): """Approximate a cubic bezier curve with a quadratic one. Returns the candidate control point.""" _p1 = p0 + (p1 - p0) * 1.5 _p2 = p3 + (p2 - p3) * 1.5 return _p1 + (_p2 - _p1) * t
def add_empty_space(degrees) -> list: """ A degree like "Dipl.agr.biol." has no empty spaces between the grade of the degree (Dipl.) and its specification (agr. biol.). To make sure that both ways of writing are covered, the degree will be replicated as "Dipl. agr. biol.". """ degrees_w_emp...
def find_insert_spot(relation, model1, coordinates): """helper function for the model_insert function. iterates over the x or y axis to find the first free coordinates in the model1 to satisfy the relation that is given. The function starts with the given coordinates which should be the coordinates ...
def roc_auc_preprocess(positives, negatives, roc_auc): """ROC AUC analysis must be preprocessed using the number of positive and negative instances in the entire dataset and the AUC itself. Args: positives (int): number of positive instances in the dataset negatives (int): number of negativ...
def notamTfrFcn(table, doc): """Create and return partial key for NOTAM-TFR messages. Args: table (str): Database table. doc (dict): Message from database. Returns: str: With partial key for ``vectorDict``. """ return 'NOTAM-TFR~' + doc['_id']
def is_hidden_file(filename): """Does the filename start with a period?""" return filename[0] == '.'
def _to_str_elements(values): """Converts the inner list elements to strings.""" if isinstance(values, list): return [_to_str_elements(value) for value in values] else: return str(values).encode("utf-8")
def _is_spec_data(spec, spectype): """ Checks to see if the spec is data only :return: true if only data, false if it is a spec """ if spec == 'nested' or spectype == 'nested': return False # if it is not a dictionary, then it is definitely not a spec if not isinstance(spec, dict): ...
def get_intersection_set(group): """ Task 2: gets intersection set of all questions in a group. Make a set for every declaration and return the intersection. :param group: list of strings """ declarations = [] for declaration in group: questions = set() for question in declarati...
def nersc_machine(name, queue): """Return the properties of the specified NERSC host. Args: name (str): the name of the host. Allowed values are: edison, cori-haswell, and cori-knl. queue (str): the queue on the machine (regular, debug, etc) Returns: dict: properties ...
def karatsuba(a: int, b: int) -> int: """ Alternative karatsuba implementation for integers instead of lists. This is similar to the actual Python implempentation of multiplication. """ len_a, len_b = len(str(a)), len(str(b)) if len_a == 1 or len_b == 1: return a * b m1 = max(len_a,...
def time_to_sec(time): """ time is tuple of (minutes:seconds) """ return time[0] * 60 + time[1]
def _row_formatter(values): """ tasks a list of value and formats them as a string for .par files """ s = [] for v in values: v = float(v) if v < 1.0: s.append(' ' + '{0:.2f}'.format(v)[1:]) elif v < 10.0: s.append(' {0:.2f}'.format(v)) elif v...