content
stringlengths
42
6.51k
def streams_dict_from_streams(streams): """Convert a list of stream info objects into a source/type mapping. Args: streams (Iterable[pylsl.StreamInfo]): List of stream info objects, typically as returned by `pylsl.resolve_streams()`. Returns: dict[str, dict[str, pylsl.StreamInf...
def list_average(list_in): """List average calculator Calculate the average value of a list of numbers Args: list_in (list): a list of number Returns: float: The average value of a list number """ answer = sum(list_in)/len(list_in) return answer
def is_shared_by(video: dict) -> bool: """ Checks if a video was shared by an account. Returns True if it was shared by another account, False otherwise. """ shared = video.get('sharing') if shared and shared.get('by_external_acct'): return True return False
def cube(x): """return x^3""" return x*x*x
def split(name): """ Splits a string of form firstname lastname into two strings, returning a list containing those names. """ spIn = name.rfind(' ') first = name[ :spIn] last = name[spIn + 1: ] return [first, last]
def getBits(data, offset, bits=1): """ Get specified bits from integer >>> bin(getBits(0b0011100,2)) '0b1' >>> bin(getBits(0b0011100,0,4)) '0b1100' """ mask = ((1 << bits) - 1) << offset return (data & mask) >> offset
def find_max(data): """Return the maximum value in sublist of list.""" return max([max(sublist) for sublist in data])
def url_to_id(url): """Take an url and return the youtube id that it contains.""" return url.split(sep='watch?v=')[1].split('=')[0]
def int_to_uint16(value_in): """ Convert integer to Unsigned 16 bit little endian integer :param value_in: Integer < 65535 (0xFFFF) :return: """ bin_string = '{:016b}'.format(value_in) big_byte = int(bin_string[0:8], 2) little_byte = int(bin_string[8:16], 2) return [little_byte, big...
def format_output(s: str, prefix: str): """ Prepends every line in given string with the given prefix. """ return ''.join([f'{prefix}: {line}' for line in s.splitlines(keepends=True)])
def broken_power_law(x, amp, x_break, alpha_1, alpha_2, delta): """ Smoothly-broken power law continuum model; for use when there is sufficient coverage in near-UV. (See https://docs.astropy.org/en/stable/api/astropy.modeling. powerlaws.SmoothlyBrokenPowerLaw1D.html#astropy.modeling.powerlaws. ...
def sherlock_anagrams2(s): """copied this from hackerrank, and it works""" was = dict() n = len(s) for i in range(n): for j in range(i, n): cur = s[i:j + 1] cur = ''.join(sorted(cur)) was[cur] = was.get(cur, 0) + 1 ans = 0 for x in was: v = w...
def _is_float(float_value): """ Check if a number is actually a float :type float_value: int or float :param float_value: number to check :return True if it is not an integer number """ if int(float_value) != float_value: return True
def atomp(lst): """Tuple items (representing structs) are regarded as atoms.""" return not isinstance(lst, list)
def update_preds_and_labels(pred, labels_matched, image_id, detected_labels, preds, labels, image_ids): """ Convert the matched labels of the prediction bbox to binary label and update all predictions and labels Args: pred: Current prediction score labels_matched: GT labels for which the cur...
def _make_smart_hint(hint_type, hint_content): """ Construct Tips """ return "*****[{}]: {}".format(hint_type, hint_content)
def translate(x, y, dx, dy): """ Translate (x,y) by distance (dx, dy) Arguments --------- x,y : scalar numbers or numpy vectors dx, dy : scalar numbers Returns ------- X,Y : same type and shape as x,y Points (x,y) are translated to points (X,Y). """ return ...
def MapFileExtension(file_name, extension_mapping): """Changes the file extension based on extension_mapping.""" name_parts = file_name.rsplit('.', 1) if len(name_parts) == 1: return file_name name_parts[-1] = extension_mapping.get(name_parts[-1], name_parts[-1]) return '.'.join(name_parts)
def code_to_well_no(code): """A1 -> 1, H12 -> 96""" if len(code) not in (2, 3): raise ValueError("Invalid code") first = ord(code[0]) - ord('A') second = int(code[1:]) return 12 * first + second
def additional_file(remote, local): """ Create step additional file :param remote: the remote file of the additional file :type remote: string :param local: the local file of the additional file :type local: string :return: :rtype map """ return { 'remote': remote, ...
def hamming_no_gap(seq1, seq2): """Calculate pairwise Hamming distance, skipping sites with gaps.""" n, m = 0, 0 for c1, c2 in zip(seq1, seq2): if c1 != '-' and c2 != '-': n += 1 if c1 != c2: m += 1 return m / n
def clean_tool_shed_url( tool_shed_url ): """Return a tool shed URL, eliminating the port if it exists.""" if tool_shed_url.find( ':' ) > 0: # Eliminate the port, if any, since it will result in an invalid directory name. return tool_shed_url.split( ':' )[ 0 ] return tool_shed_url.rstrip( '/...
def change_event_name(event): """ Change event names from json style to html (ex: BLOCKED_SHOT to BLOCK). :param event: event type :return: fixed event type """ event_types = { 'PERIOD_START': 'PSTR', 'FACEOFF': 'FAC', 'BLOCKED_SHOT': 'BLOCK', 'GAME_END...
def offset_from_peak(peak_ind, freq, prepeak): """Compute data offset index from location of first peak. Args: peak_ind (int): location of first peak as index value freq (float): data frequency in Hz prepeak (int/float): desired start point of data stream in s prior to first...
def get_display_name(record): """Get the display name for a record. Args: record A record returned by AWS. Returns: A display name for the security group. """ return str(record["GroupName"]) + " (" + str(record["GroupId"]) + ")"
def reversed_change_dict(change): """ Return the dictionary of genre changes, whereby keys and values have swapped their roles. Parameters: change (dict): Original dictionary of genre changes, with: * key (string): desired genre. * value (list of string): None, or list of genres ...
def get_short_size(size_bytes): """ Get a file size string in short format. This function returns: "B" size (e.g. 2) when size_bytes < 1KiB "KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB "MiB" size (e.g. 7.8M) when size_bytes >= 1MiB size_bytes: File siz...
def get_cardinal(number:int)->str: """ Returns the cardinal thingy for the end of a number. Used for string formatting, ie, 1 --> st 2 --> nd 3 --> rd 4 --> th """ _number = abs(number) if number==0: return "th" elif _number==1: ...
def create_site_url(ip: str, extension: str, port: str) -> str: """:brief Given the url extension after http://ip:, returns the complete url for that site""" url = f"http://{ip}:{port}{extension}" return url
def urlencode(s): """urlencodes a string""" return ''.join(['%%%02x' % ord(c) for c in s])
def remove_empty_dict_items(d): """Returns items from dict without empty values.""" if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (remove_empty_dict_items(v) for v in d) if v] return {k: v for k, v in ((k, remove_empty_dict_items(v)) for k, v in ...
def is_valid_size(dot_width, dot_height, distance, screen_width, screen_height): """takes the dot width and height and make sure it will fit the window :param: dot_width dot width :param: dot_height dot height :param: distance distance between dots :param: screen_width screen height :param:...
def any_(collection, predicate=None): """:yaql:any Returns true if a collection is not empty. If a predicate is specified, determines whether any element of the collection satisfies the predicate. :signature: collection.any(predicate => null) :receiverArg collection: input collection :argType ...
def depth_to_location(depth: float): """ Convert depth (of polyp) to location in colon based on https://training.seer.cancer.gov/colorectal/anatomy/figure/figure1.html :param depth: :return: """ locations = [] if depth <= 4: locations.append('anus') if 4 <= depth <= 17: ...
def get_batch_job_options(job_options: dict) -> dict: """ Returns AWS Batch-specific job options from general job options. """ keys = [ "vcpus", "gpus", "memory", "shared_memory", "role", "retries", "privileged", "job_def_name", "au...
def create_ngram_sentence_list(sentence_list, n_grams): """ Returns a list of lists of n-grams for each sentence """ n_gram_merged_sentence_list = [] for sentence in sentence_list: aux_list = [tuple(sentence[ix:ix+n_grams]) for ix in range(len(sentence)-n_grams+1)] n_gram_merged_sentence_l...
def matching_bounds(original, approx, conf: float, rounding=10) -> bool: """ Checks if 2 bounds match in respect to a confidence interval.""" # sx0 = original[0] - conf <= approx[0] <= original[0] + conf # dx0 = original[1] - conf <= approx[1] <= original[1] + conf # float precision ... sx0 =...
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
def flagged_return(flags, objects): """Return only objects with corresponding True flags. Useful for functions with multiple possible return items.""" if sum(flags) == 1: return objects[0] elif sum(flags) > 1: return tuple([object for flag, object in zip(flags, objects) if flag]) else: ...
def interface_is_in_vlan(vlan_member_table, interface_name): """ Check if an interface is in a vlan """ for _, intf in vlan_member_table: if intf == interface_name: return True return False
def format_variable_assignment(step): """Format an assignment statement.""" asn = step['detail'] lhs, rhs, binary = asn['lhs'], asn['rhs-value'], asn['rhs-binary'] binary = '({})'.format(binary) if binary else '' return '{} = {} {}'.format(lhs, rhs, binary)
def merge(dict1: dict, dict2: dict): """Merge two disjoint dictionaries.""" if dict1 is None or dict2 is None: return None keys1 = dict1.keys() keys2 = dict2.keys() if keys1 & keys2 != set(): raise Exception("Non linear patterns not supported") dict_r = {k: dict1[k] for k in keys...
def add_notebook_container_mount(notebook, container_mount): """ Add the provided container mount (dict V1VolumeMount) to the Notebook's PodSpec. notebook: Notebook CR dict volume: Podvolume dict """ container = notebook["spec"]["template"]["spec"]["containers"][0] if "volumeMounts" not...
def format_as_string(string: str): """ Formats a given string in a different color using ANSI escape sequences (see https://stackoverflow.com/a/287944/5299750) and adds double quotes :param string: to be printed """ ansi_start = '\033[32m' ansi_end = '\033[0m' return f"{ansi_start}\"{str...
def compareTuples(new, old): """Compare two tuples. Return (common_prefix, middle_of_old, middle_of_new, common_suffix) """ first = 0 for oldval, newval in zip(old, new): if oldval != newval: break first += 1 last = 0 for oldval, newval in zip(reversed(old[first:...
def crop_box_right_top(current_size, target_size): """ Returns box coordinates (x1, y1, x2, y2) to crop image to target size from right-top. """ cur_w, cur_h = current_size trg_w, trg_h = target_size assert trg_w <= cur_w assert trg_h <= cur_h x1 = cur_w - trg_w x2 = cur_w y1...
def line(tam=43): """ Returns the number of the argument size. Remembering that the size is in pixels. """ return '-' * tam
def is_valid_window(s): """ test if a value is a valid window. A valid window being an odd int between 3 and 501 """ valid = True try: value = int(s) if not value in [i for i in range(3, 503, 2)]: valid = False except ValueError: valid = False retu...
def validate_tabular_choices(dep_var, cont_inputs, int_inputs): """ Checks to see if user choices are consistent with expectations Returns failure message if it fails, None otherwise. """ if dep_var in cont_inputs: return 'Dependent variable should not be continuous' if dep_var in int_in...
def get_port(line): """Get port number out of a line like "some message: localhost:[port].""" stripped = line.strip() separator_index = stripped.rfind(':') return int(stripped[separator_index+1:])
def pretty_print_rows(data,prepend=False): """Format row-wise data into 'pretty' lines Given 'row-wise' data (in the form of a list of lists), for example: [['hello','A salutation'],[goodbye','The End']] formats into a string of text where lines are newline-separated and the 'fields' are padd...
def skill(A_data, A_ref, A_perf=0): """Generic forecast skill score for quantifying forecast improvement Parameters ========== A_data : float Accuracy measure of data set A_ref : float Accuracy measure for reference forecast A_perf : float, optional Accuracy measure for...
def transfer(x): """ how does the output of the PID relate to change in PV i.e., how does the angle offset of the wings relate to the change in heading currently y = 30(x/135)^3 {-135 <= x <= 135} corresponds to a non-linear curve with max speed 30 degrees/s using 30/10 to run in degree...
def convert_reference_json(reference_json, data_object): """ Converts the reference JSON download from DSS into the DOS message and returns the DOS message. :param reference_json: :param data_object: :return: """ # {u'content-type': u'application/octet-stream', # u'crc32c': u'e2a2bc0...
def is_number(s): """Returns True is string is a number.""" try: float(s) return True except ValueError: return False
def removeprefix(s: str, suffix: str) -> str: """similar to str.removeprefix in Python 3.9+""" return s[len(suffix) :] if suffix and s.startswith(suffix) else s
def get_include_args(args, truth=True): """Get command args that in/exclude based on a value""" include = {} if isinstance(args, str): args = args.split(",") for arg in args: if arg.startswith("~") or arg.startswith("-"): arg = arg[1:] include[arg] = False ...
def linspace(start,stop,num): """Return a list of floats linearly spaced from start to stop (inclusive). List has num elements.""" return [i*(stop-start)/(num-1)+start for i in range(num)]
def build_forms_dict(form_feats_list): """ forms=build_forms_dict(lemma_dict['simples','A']) forms['simples'] [['F', 'PL'], ['F', 'SG'], ['M', 'PL'], ['M', 'SG']] """ forms={} for form,feats in form_feats_list: if not forms.get(form): forms[form]=[feats] else: ...
def get_json_uri(json_line): """Returns the URI of page from JSON data. Args: json_line: dictionary with JSON data. Returns: (current_uri, json_line): the current URI, and the original JSON dictionary. """ try: current_uri = json_line["envelope"]["warc-header-me...
def map_ids_to_names(participants): """Map tournament participants' IDs to their names.""" ids_to_names = {} for p in participants: participant = p['participant'] participant_id = participant['id'] participant_name = participant['name'] ids_to_names[participant_id] = partici...
def get_f_score(prec, rec, beta=1): """ Compute F_beta score. The formula is F_beta = (1+beta**2)*prec*rec/((beta**2)*prec + rec) Args: prec (float): Precision rec (float): Recall beta (float): Weighting of precision Returns: The F_beta score. """ if prec + rec...
def calculate(num_one, num_two): """Return the division result for two numbers. The second number should be greater than the first one. Arguments: num_one -- an integer by which we divide. num_two -- an integer to be divided by 'num_one'. Return values: If the second number is smaller, ret...
def color_coder(grid, current): """Accepts spaceship grid. Returns 0 if current space is black ('.'), and 1 if current space is white ('.')""" if grid[current[0]][current[1]] == '.': return 0 elif grid[current[0]][current[1]] == '#': return 1 else: print("And I oop...color_coder...
def all_unique(seq): """Returns whether all the elements in the sequence ``seq`` are unique. >>> all_unique(()) True >>> all_unique((1, 2, 3)) True >>> all_unique((1, 1, 2)) False Creates a set, so the elements of the sequence must be hashable (and are compared ...
def build_completed_quiz_feedback(actor_name, quiz_name, course_name, score, feedback): """ Build the feedback when an user has completed the quiz and has failed the quiz. :param actor_name: Name of the user that has completed the quiz. :type actor_name: str :param quiz_name: Name of the quiz. ...
def intersect(range_1, range_2): """Return intersection size.""" return min(range_1[2], range_2[2]) - max(range_1[1], range_2[1])
def simple_format(format, *args): """ Returns a formatted string by replacing all instances of %X with Xth argument in args (0...len(args)) e.g. "%0 says hello", "ted" should return "ted says hello" "%1 says hello to %0", ("ted", "jack") should return jack says hello to ted etc. If %X is used a...
def _import_task(taskname): """Looks up a dotted task name and imports the module as necessary to get at the task.""" parts = taskname.split('.') if len(parts) < 2: return None func_name = parts[-1] full_mod_name = ".".join(parts[:-1]) mod_name = parts[-2] try: module = _...
def xoai_contributor(source, *args, **kwargs): """ CZ: EN: """ value = [] for person_role in source: role = person_role["@name"] field = person_role["element"]["field"] if isinstance(field, list): for person in field: value.append( ...
def accumulate(func, a): """ Accumulates the result of a function over iterable a. For example: ''' from collections import namedtuple def square(x): return x**2 coords = namedtuple("coordinates", ["x", "y"]) a = coords(1,2) b = accumulate(square, a) # 5 a = list(a)...
def parse_coordinates(geojson): """Finds the coordinates of a geojson polygon Note: we are assuming one simple polygon with no holes Args: geojson (dict): loaded geojson dict Returns: list: coordinates of polygon in the geojson Raises: KeyError: if invalid geojson type (n...
def power_amplitude(z): """Add redshift evolution to the Gaussian power spectrum.""" return 58.6*pow((1+z)/4.0,-2.82)
def merge(summary, log): """Merges log entries into parent categories based on timestamp. Merges general log entries into parent categories based on their timestamp relative to the summary output timestamp. Note that this function is destructive and will directly modify the nodes within the `summa...
def RPL_TRACEUNKNOWN(sender, receipient, message): """ Reply Code 203 """ return "<" + sender + ">: " + message
def empty_name(got): """ Empty name error. """ return "Expected non-empty name, got {}.".format(repr(got))
def is_package_cs(csname): """ If 'csname' is a package C-state name, returns 'True'. Returns 'False' otherwise (even if 'csname' is not a valid C-state name). """ return csname.startswith("PC") and len(csname) > 2
def reverse_manually(input_string): """Reverse a string slowly """ result = '' for char in input_string: result = char + result return result
def canonical_order(*corners): """return corners of enclosing rectangle in their canonical order (clockwise starting from bottom left). can be used to simply reorder rectangle nodes.""" xmin = min(x[0] for x in corners) xmax = max(x[0] for x in corners) ymin = min(x[1] for x in corners) yma...
def fragment_1(N): """Fragment-1 for exercise.""" ct = 0 for _ in range(100): for _ in range(N): for _ in range(10000): ct += 1 return ct
def replace_leading_trailing(seq): """ Replace leading and trailing Ns with -s :param seq: the sequence :type seq: str :return: the sequence with leading trailing N's replaced :rtype: str """ validbase = {"A", "G", "C", "T"} lastbase = 0 inseq = False newseq = [] for i...
def removeWhitespaceChars(s): """ Removes whitespace characters s: string to remove characters from """ s = s.replace(" ","") s = s.replace("\t","") s = s.replace("\n","") #if this were python3 this would work: #removeWhitespaceTrans = "".maketrans("",""," \t\n") #s = s.translate(removeWhitespaceTrans...
def create_log_json(ep_name, ep_method, in_json): """ create a json for logging """ out_json = {} out_json['ep_building_block'] = "events_building_block" out_json['ep_name'] = ep_name out_json['ep_method'] = ep_method if 'tags' in in_json: out_json['tags'] = in_json['tags'] i...
def _flatten(d, parent_key='', sep='_', int_to_float=False, remove_null=False, flatten_list=False): """ Flatten a nested dictionary to one leve dictionary (recursive function) :param d: dictionary :param parent_key: parent_key used to create field name :param sep: separator of neste...
def interpret_as_filename(textbox_content): """ docs """ FILE_TAG = "." return FILE_TAG in textbox_content
def nice(val): """pretty print""" if val == 'M': return 'M' if val < 0.01 and val > 0: return 'Trace' return '%.2f' % (val, )
def compute_generalized_logw(log_gamma_old, log_gamma_new, log_forward_kernelt, log_backward_kernel_tm1): """ compute a generalized log incremental (unnormalized) weight arguments log_gamma_old : float log unnormalized probability distribution at t-1 (and position x_{t-1}) log_g...
def isnumeric(value): """Return True if `value` can be converted to a float.""" try: float(value) return True except (ValueError, TypeError): return False
def _calc_amount_of_successful_runs(runs): """ If there were no failures while there's any passes, then the run succeeded. If there's no fails and no passes, then the run did not succeeded. """ was_run_successful = lambda x: 1 if x['fail'] == 0 and x['pass'] > 0 else 0 successful_runs = map(was_...
def is_prime(number): """ Find if a number is prime Complexity: O(sqrt(NUMBER)) If n is a non prime integer then there is a prime p that divides n (p | n) and p^2 <= n. We use the same technique to find if n is a prime or not. """ if number == 0 or number == 1: return False ...
def is_quoted_with_backticks(identifier): """Check if the given identifier is quoted with backticks. identifier[in] identifier to check. Returns True if the identifier has backtick quotes, and False otherwise. """ return identifier[0] == "`" and identifier[-1] == "`"
def firstLetterCapitalize(t): """capitalize only the first letter of the string """ if t: return t[0].upper() + t[1:] else: return ""
def form_packet(host): """Form the packets""" # Convert the data to json packet = f"""GET /device HTTP/1.1 Host: {host} Connection: close """ return packet
def _xml_escape_attr(attr, skip_single_quote=True): """Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes. """ escaped = (attr .replace('&', '&amp;') ...
def _is_tag_argument(argument_name): """Return True if the argument is a tagged value, and False otherwise.""" return argument_name.startswith('%')
def angle_difference(b1: float, b2: float): """ To compute the difference between the two angles :param b1: first angle :param b2: second angle :return: difference with direction (sign) """ r = (b2 - b1) % 360.0 # Python modulus has same sign as divisor, which is positive here, # so ...
def compare_values(real_mbit, warn_mbit, crit_mbit): """ compare values and generate exitcode """ if real_mbit < warn_mbit: if real_mbit > crit_mbit: exit_code = 1 return exit_code else: exit_code = 2 return exit_code else: exit_code =...
def get_augmented_coordinate(target_coordinate, strengths): """ Produce a coordinate suitable for use with `xx_region_polytope`. """ *strengths, beta = strengths strengths = sorted(strengths + [0, 0]) interaction_coordinate = [sum(strengths), strengths[-1], strengths[-2], beta] return [*targ...
def subset(s): """construct the set of all subsets, that is, SUBSET S""" sets = [] # sets to be constructed carrier = list(s) nelems = len(carrier) bits = [0] * nelems # the binary vector encodes a set under construction current = set() # a set under cosntruction sets.append(fr...
def parse_text(text): """Parses the string by removing characters before each hash symbol""" stack = [] for char in text: if char != '#': stack.append(char) else: if len(stack) > 0: stack.pop() return ''.join(stack)