content
stringlengths
42
6.51k
def flatten(lst): """Returns a flattened version of lst. >>> flatten([1, 2, 3]) # normal list [1, 2, 3] >>> x = [1, [2, 3], 4] # deep list >>> flatten(x) [1, 2, 3, 4] >>> x # Ensure x is not mutated [1, [2, 3], 4] >>> x = [[1, [1, 1]], 1, [1, 1]] # deep list >>> flatten(x) [1, 1, 1, 1, 1, 1] >>> x [[1, [1, 1]], 1, [1, 1]] """ "*** YOUR CODE HERE ***" flat = [] for i in lst: if type(i) == type([]): flat += flatten(i) else: flat.append(i) return flat
def parse_host_port(hp, default_port=0): """ Parse host/port from string Doesn't work with IPv6 Args: hp: host/port string to parse default_port: default port if no port is specified (default: 0) Returns: tuple (host, port) """ if hp.find(':') == -1: return (hp, default_port) else: host, port = hp.rsplit(':', 1) return (host, int(port))
def add_underscore(s): """ Makes sure S begins with an underscore. """ return s if s.startswith('_') else u'_%s' % s
def get_list_of_additions(docs): """ Return a list of distinct expanded_content from the additions of all docs in similar_label_docs in the form: [[expanded_content], ...] Parameters: docs (list): list of label docs from MongoDB having the same application_numbers """ return_list = [] for doc in docs: if doc["additions"]: for value in doc["additions"].values(): if value["expanded_content"] not in return_list: return_list.append([value["expanded_content"]]) return return_list
def font_stretch(keyword): """Validation for the ``font-stretch`` descriptor.""" return keyword in ( 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded')
def normalize_reg(a_reg): """Wrap string representing regular expression in brackets. @param a_reg - string representing regular expression @type unicode @return regexp string wrapped in parentheses @type unicode """ return "(?:" + a_reg + ")"
def read_value (fields, name, validate_fn): """Retrieve a value from an epgdb record and validate it. fields: The record dict name: The field name validate_fn: Function used to validate the value (like the function returned by `validate`) Returns the value to use or throws `ValueError`. """ value = fields.get(name) try: return validate_fn(value) except ValueError as e: raise ValueError('found item with unexpected value', {'field': name, 'fields': fields}, *e.args)
def table_delta(first_summary, second_summary): """ A listing of changes between two TableSummarySet objects. :param first_summary: First TableSummarySet object :param second_summary: Second TableSummarySet object :return: Change in number of rows """ differences = [] for first, second in zip(first_summary, second_summary): diff = first.number_of_rows - second.number_of_rows differences.append(diff) return differences
def length(listed): """ return length of list """ count = 0 for item in listed: count += 1 return count
def compute_u_score(entropy, subset_indices, alpha=1.): """ Compute the Uncertainity Score: The point that makes the model most confused, should be preferred. :param final_activations: :param subset_indices: :param alpha: :return: u_score """ if len(subset_indices) == 0: return 0 else: u_score = alpha*entropy[subset_indices] return u_score
def fibonacci(number): """ calculate the fibonacci number """ if number < 2: return 1 return fibonacci(number-1) + fibonacci(number-2)
def subscription_name(project, name): """Get subscription name.""" return 'projects/{project}/subscriptions/{name}'.format( project=project, name=name)
def reverse_lists(lists): """ >>> reverse_lists([[1,2,3], [4,5,6]]) [[3, 2, 1], [6, 5, 4]] """ return list(map(list, map(reversed, lists)))
def get_tree_tweet_edges(tree): """ Input: - tree: recursive tree structure {tweet: "tweet_id", replies: [ .... ]} Output: - list of parent-child tweet_ids """ parent_tweet_id = tree["tweet"] edges_to_children = [] childrens_edges = [] for reply in tree["replies"]: reply_tweet_id = reply["tweet"] # add an edge from the parent to the reply edges_to_children.append((parent_tweet_id, reply_tweet_id)) # recursively get the edges of child childrens_edges += get_tree_tweet_edges(reply) return edges_to_children + childrens_edges
def parse_tool_list(tl): """ A convenience method for parsing the output from an API call to a Galaxy instance listing all the tools installed on the given instance and formatting it for use by functions in this file. Sample GET call: `https://test.galaxyproject.org/api/tools?in_panel=true`. Via the API, call `gi.tools.get_tool_panel()` to get the list of tools on a given Galaxy instance `gi`. :type tl: list :param tl: A list of dicts with info about the tools :rtype: tuple of lists :return: The returned tuple contains two lists: the first one being a list of tools that were installed on the target Galaxy instance from the Tool Shed and the second one being a list of custom-installed tools. The ToolShed-list is YAML-formatted. Note that this method is rather coarse and likely to need some handholding. """ ts_tools = [] custom_tools = [] for ts in tl: # print "%s (%s): %s" % (ts['name'], ts['id'], len(ts.get('elems', []))) for t in ts.get('elems', []): tid = t['id'].split('/') if len(tid) > 3: tool_already_added = False for added_tool in ts_tools: if tid[3] in added_tool['name']: tool_already_added = True if not tool_already_added: ts_tools.append({'tool_shed_url': "https://{0}".format(tid[0]), 'owner': tid[2], 'name': tid[3], 'tool_panel_section_id': ts['id']}) # print "\t%s, %s, %s" % (tid[0], tid[2], tid[3]) else: # print "\t%s" % t['id'] custom_tools.append(t['id']) return ts_tools, custom_tools
def hashable(item): """Determine whether `item` can be hashed.""" try: hash(item) except TypeError: return False return True
def strong(text: str) -> str: """ Return the *text* surrounded by strong HTML tags. >>> strong("foo") '<b>foo</b>' """ return f"<b>{text}</b>"
def is_str(x): """Whether the input is an string instance. Note: This method is deprecated since python 2 is no longer supported. """ return isinstance(x, str)
def make_qdict(key, private): """return a query dict to be passed with all requests""" rv = {} if key: if isinstance(key, list): rv['key'] = key else: rv['key'] = [key] if private: rv['private'] = ['1'] return rv
def get_usans(inlist): """Return the usans at the right threshold.""" return [[tuple([val[0],0.75*val[1]])] for val in inlist]
def jgetonerow(json,sfld,search): """ return a row based on a search """ for row in json: if row[sfld]==search or search == '*': return row
def sleeper_service(sleep_duration): """ :type sleep_duration: int :rtype: dict """ service = { 'name': "sleeper", 'docker_image': 'alpine', 'monitor': True, 'required_resources': {"memory": 1 * 1024 * 1024 * 1024}, # 1 GB 'ports': [], 'environment': [], 'command': 'sleep ' + str(sleep_duration) } return service
def filter_only(keep_list, filter_list): """Filter out items in an iterable not in the keep_list. :param keep_list: list of key names to keep. :type: list of str :param filter_list: iterable to filter. :type: list or dict """ return list( filter( lambda key: key in keep_list, filter_list ) )
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): """ Compute max metric between prediction and each ground truth. From official ReCoRD eval script """ scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) return max(scores_for_ground_truths)
def powerlaw(x, a, b, c): """ Charged particle multiplicity as a function of initial entropy density empirically follows a power law relation. The constant c accounts for missing entropy below the UrQMD switching temperature. This is commonly referred to as the "corona". """ return a*x**b + c
def convert_dec2deg(deg, arcm, arcs): """ Convert measurement of declination in deg arcmin, arcsec to decimal degrees Parameters ---------- deg : int -or- string -or- float degrees value arcm : int -or- string -or- float arc minute value arcs : int -or- string -or- float arc second value Returns ------- result : float declination in degrees """ if isinstance(deg, str): deg = float(deg) if isinstance(arcm, str): arcm = float(arcm) if isinstance(arcs, str): arcs = float(arcs) return deg + arcm / 60. + arcs / 3600.
def RGBtoYCbCr(R, G, B): """ convert RGB to YCbCr color :param R: red value (0;255) :param G: green value (0;255) :param B: blue value (0;255) :return: YCbCr tuple (0;255) """ Y = (R * 0.299) + (G * 0.587) + (B * 0.114) Cb = (R * -0.1687) + (G * -0.3313) + (B * 0.5) + 128.0 Cr = (R * 0.5) + (G * -0.4187) + (B * -0.0813) + 128.0 return tuple(int(i) for i in (Y, Cb, Cr))
def modality(note): """Extract modality from note in booth schedule Args: note (str): The note description Returns: str: The modality of the course """ modality_dict = { "In-Person Only": "IP", "Remote-Only": "R", "Dual Modality": "D", "Faculty In-Person, Dual Modality": "D-FIP", "Faculty Remote, Dual Modality": "D-FR", } if note in modality_dict: return modality_dict[note] else: return ""
def g_inhomo(t, sigma): """ Lineshape function for the inhomogeneous limit: sigma**2*t**2/2 Parameters: ----------- t : array-like float time sigma : float Frequency distribution \Delta \omega """ return 0.5*sigma**2*t**2
def s1_orbit_number(title: str) -> str: """ sentinel competition date extractor extractor from product name """ if not title.startswith(('S1B', 'S1A','S2A','S2B')): raise ValueError("Title should start with ('S1B','S1A')") return title[49:49+6]
def report_metrics(metrics, label_matches=None): """Return metric samples with labels and values in Json format""" metrics_map = {} for metric in metrics.values(): samples = [] for sample in metric.samples: if not label_matches or label_matches.items() <= sample.labels.items(): sample_map = {'labels': sample.labels, 'value': sample.value} samples.append(sample_map) metrics_map[metric.name] = {'samples': samples} return metrics_map
def level_to_criticality(level: int) -> str: """Translate level integer to Criticality string.""" if level >= 4: return "Very Malicious" elif level >= 3: return "Malicious" elif level >= 2: return "Suspicious" elif level >= 1: return "Informational" return "Unknown"
def mkbool(v): """Make bool.""" if isinstance(v, str): v = v.lower() if v in mkbool.true: return True if v in mkbool.false: return False raise ValueError(f'Unknown bool format {v!r}') return bool(v)
def checkIfCoordinateIsValid(x, y): """ Check if board values constitute a valid location on the board """ valid = False odd_values = (1, 3, 5, 7, 9) even_values = (2, 4, 6, 8, 10) if y in even_values: if x in even_values: valid = True elif y in odd_values: if x in odd_values: valid = True if valid: return True else: raise ValueError(("Coordinate is not on the board: " "({0}, {1})").format(x, y))
def extract_end_bits(num_bits, pixel): """ Extracts the last num_bits bits of each value of a given pixel. example for BW pixel: num_bits = 5 pixel = 214 214 in binary is 11010110. The last 5 bits of 11010110 are 10110. ^^^^^ The integer representation of 10110 is 22, so we return 22. example for RBG pixel: num_bits = 2 pixel = (214, 17, 8) last 3 bits of 214 = 110 --> 6 last 3 bits of 17 = 001 --> 1 last 3 bits of 8 = 000 --> 0 so we return (6,1,0) Inputs: num_bits: the number of bits to extract pixel: an integer between 0 and 255, or a tuple of RGB values between 0 and 255 Returns: The last num_bits bits of pixel, as an integer (BW) or tuple of integers (RGB). """ #By looking at pattern, the value of each lsb is given by the pixel or one #of the numbers in the tuple of pixel and the remainder of this with 2 #to the power of num_bits if type(pixel) == int: value = pixel%(2**num_bits) return value else: values = [] #emty list which will have each of the values from each lsb in the #tuple for i in pixel: #after iterating over tuple we do the same procedure as before value = i%(2**num_bits) values.append(value) #use of tuple() to return the desired tuple as this was the original #class of pixel return tuple(values)
def is_list(element): """ Check if element is a Python list """ return isinstance(element, list)
def str_in_list(str, list): """Check if a string is contained in a list Args: str (str): Arbitrary string list (list of str): Arbitrary list of strings Returns: bool: Returns True (False) if (not) str contained in list """ if str in list: return True else: return False
def compare_elementwise_perspective(triple, gold): """ :param triple: triple extracted by the system :param gold: golden triple to compare with :return: number of correct elements in a triple """ correct = 0 for key in triple: if key not in gold.keys(): continue if type(triple[key]) == float and triple[key] != gold[key]: print(f"Mismatch in perspective {key}: {triple[key]} != {gold[key]}") elif type(triple[key]) == float and triple[key]['label'].lower() == gold[key]: print(f"Match triple {key}: {triple[key]} == {gold[key]}") correct += 1 return correct
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ # Indexes to keep track of the last index of low (0), middle (1), and bottom of high (2) values top_of_zero_idx = 0 # top index of 0 one_idx = 0 # index of 1 bottom_of_2_idx = len(input_list) - 1 # bottom index of 2 # Continue to loop while index of 1 is less than bottom index of 2 while one_idx <= bottom_of_2_idx: # if value at 1 index is 0, then swap the value with the value at top of 0 index # also increment top of 0 index and 1 index if input_list[one_idx] == 0: input_list[one_idx], input_list[top_of_zero_idx] = input_list[top_of_zero_idx], input_list[one_idx] top_of_zero_idx += 1 one_idx += 1 # if value at 1 index is 1, nothing to do. Increment 1 index elif input_list[one_idx] == 1: one_idx += 1 # if value at 1 index is 2, swap the value with the value at bottom of 2 index # also decrement bottom of 2 index elif input_list[one_idx] == 2: input_list[one_idx], input_list[bottom_of_2_idx] = input_list[bottom_of_2_idx], input_list[one_idx] bottom_of_2_idx -= 1 return input_list
def PlusEpsilon(x, eps=1e-6): """Element-wise add `eps` to `x` without changing sign of `x`.""" return x + ((x < 0) * -eps) + ((x >= 0) * eps)
def get_schedule_list(schedule_dict, plan_name): """returns list of schedules which are defined for given plan.""" return([scheduel_name for scheduel_name in schedule_dict.keys() if schedule_dict[scheduel_name]["plan"]==plan_name])
def count_ones(s, N): """Count the number of `1` in the binary representation of the state `s`.""" return bin(s).count('1')
def decompose_complex_array(complex_array) -> list: """ Decomposes an NI ComplexSingle[] or ComplexDouble[] into a list of complex numbers. """ # use list comprehension of DecomposeArray so we don't have to identify a type return [complex(iq.Real, iq.Imaginary) for iq in complex_array]
def can_asteroid_see_you(asteroid, other_asteroid, asteroid_layout): """Reads two asteroids (tuples) and an asteroid_map (list). Returns whether or not the asteroids can see each other.""" asteroid_x = asteroid[0] asteroid_y = asteroid[1] other_x = other_asteroid[0] other_y = other_asteroid[1] delta_x = other_x - asteroid_x delta_y = other_y - asteroid_y # Vertical lines have no slope. We check by changing y only if delta_x == 0: min_y = min(asteroid_y, other_y) for i in range(1, abs(delta_y)): if (asteroid_x, min_y + i) in asteroid_layout: return False # Non-vertical lines have slope. We check by chaning by one x and the slope and see if there's an asteroid there. else: slope = delta_y / delta_x # We start with the asteroid on the left if asteroid_x < other_x: min_x = asteroid_x min_x_y = asteroid_y else: min_x = other_x min_x_y = other_y # Checking all the spots along the way for asteroids. for i in range(1, abs(delta_x)): maybe_other = (min_x + i, min_x_y + i*slope) if maybe_other in asteroid_layout: return False return True
def validateFilename(value): """ Validate filename. """ if 0 == len(value): raise ValueError("Name of TimeHistoryDB file must be specified.") try: fin = open(value, "r") except IOError: raise IOError("Temporal database file '{}' not found.".format(value)) return value
def b2s(b): """ Binary to string. """ ret = [] b = b.zfill((len(b) + 7) // 8 * 8) for pos in range(0, len(b), 8): ret.append(chr(int(b[pos:pos + 8], 2))) return "".join(ret)
def sort_hyps(hyps): """Return a list of Hypothesis objects, sorted by descending average log probability""" return sorted(hyps, key=lambda h: h.avg_log_prob, reverse=True)
def validateWavelengths(wavelengths: list, bbl: list): """ Validate wavelengths and bbl. Parameters ---------- wavelengths : list of int List of measured wavelength bands bbl : list of str/int/bool List of bbl values that say which wavelengths are measured in good quality (1) and which are not (0) Returns ------- list of int Validated `wavelengths` list list of int Validated `bbl` list Raises ------ ValueError: Raised if `wavelengths` and `bbl` are of a different length. """ # check for inconsistencies if len(wavelengths) != len(bbl): raise ValueError( "Length of wavelengths ({0}) and bbl ({1}) is not equal.".format( len(wavelengths), len(bbl))) # remove zero-wavelength at the beginning if len(wavelengths) == 139: return wavelengths[1:], bbl[1:] return wavelengths, bbl
def countRectsInGrid(gridWidth, gridHeight, abortLimit=None): """Count how many rectangles fit in a grid with given dimensions. 'abortLimit' is an optional argument to avoid counting beyond a certain limit.""" return gridWidth * (gridWidth + 1) * gridHeight * (gridHeight + 1) // 4
def appears_bnd(content): """Checks if the magic bytes at the start of content indicate that it is a BND3-packed file. """ return content[0:4] == "BND3"
def _validate_shape(*args): """ Helper method for shape based array creation routines. Verifies user specified shape is either int or tuple of ints. Additional work in case of in is to format it for upcoming broadcast. """ if len(args) != 1: raise TypeError('only positional argument should be shape.') shape = args[0] #Special case for non-root ranks/processes if shape is None: return shape if isinstance(shape, int): return (shape,) if isinstance(shape, tuple): if all([isinstance(dim, int) for dim in shape]): return shape raise ValueError('shape must be int or tuple of ints.')
def build_cluster_info(config): """ Construct our cluster settings. Dumps global settings config to each cluster settings, however, does not overwrite local cluster settings. Cluster config takes precedence over global. Use global config for generic info to be applied by default. Note: However, as in the docstring for :func:`send_to_notifiers`, the local settings are not used for anything other than user/pass for getting snapshot information. There's not a need to send notifications to multiple areas at the time of writing. I doubt this will change in the future. Args: config: global settings config Returns: Global settings config, but with each cluster config is updated with global settings. """ global_settings = config['settings'] cluster_settings = config['clusters'] for cluster in cluster_settings: # Set global as settings if not present if 'settings' not in cluster: cluster['settings'] = global_settings continue # Only add/update keys not present in cluster for k, v in global_settings.items(): if k not in cluster['settings']: cluster['settings'][k] = v return config
def subtract_vars(var_seq_1, var_seq_2): """ Subtract one variable sequence from another. """ return [v1 - v2 for v1, v2 in zip(var_seq_1, var_seq_2)]
def identify_known_accounts(account_aliases, account_id): """ Given a known list of account IDs from yaml config, append note about their account if they're known to us. :return: Account description """ # If the accounts custom aliases yaml file does not exist just default to normal behavior if account_aliases: if 'accounts' in account_aliases.keys(): accounts = account_aliases["accounts"] for acct in accounts.keys(): if acct == account_id: return accounts[acct] return "Unidentified" else: return ""
def get_child_object_data(raw_data): """ Returns key/value pairs that describe child objects in raw data Args: raw_data (dict): Returns: dict: """ return {k: v for k, v in raw_data.items() if k.startswith("[")}
def merge_js_dependencies(*chart_or_name_list): """ Merge multiple dependencies to a total list. This will ensure the order and unique in the items. :param chart_or_name_list: :return: A list containing dependency items. """ front_must_items = ['echarts'] # items which must be included. front_optional_items = ['echartsgl'] dependencies = [] fist_items = set() def _add(_items): if _items in front_must_items: pass elif _items in front_optional_items: fist_items.add(_items) elif _items not in dependencies: dependencies.append(_items) for d in chart_or_name_list: if hasattr(d, 'js_dependencies'): for x in d.js_dependencies: _add(x) elif isinstance(d, (list, tuple, set)): for x in d: _add(x) else: _add(d) # items which should be included in front part. fol = [x for x in front_optional_items if x in fist_items] return front_must_items + fol + dependencies
def numWindows(tfmin, deltaT): """ Evaluates the number of windows that will be used given the total time (tot) of a particular induction. """ return int( (tfmin - deltaT) + 2 )
def get_scan_fs_dates(year, all_obs): """Generate a forecast at the time of each observation.""" return sorted(o['date'] for o in all_obs)
def basename(filepath): """Return base filename without directory and extension.""" left = filepath.rfind("/") + 1 filename = filepath[left:] right = filename.find(".") return filename[:right]
def convert_to_dayone_date_string(day_str, hour=10, minute=0, second=0): """ Convert given date in 'yyyy-mm-dd' format into dayone accepted format of iso8601 and adding additional hour, minutes, and seconds if given. """ year, month, day = day_str.split('-') from datetime import datetime now = datetime.utcnow() # FIXME: The current version of day one does not support timezone data # correctly. So, if we enter midnight here then every entry is off by a # day. # Don't know the hour, minute, etc. so just assume midnight date = now.replace(year=int(year), month=int(month), day=int(day), minute=int(minute), hour=int(hour), second=int(second), microsecond=0) iso_string = date.isoformat() # Very specific format for dayone, if the 'Z' is not in the # correct positions the entries will not show up in dayone at all. return iso_string + 'Z'
def cgtpl(cg): """ Takes a cigar string as input and returns a cigar tuple """ for i in "MIDNSHPX=": cg = cg.replace(i, ';'+i+',') return [i.split(';') for i in cg.split(',')[:-1]]
def comment(s: str) -> str: """Single-line comment.""" return f'--{s}\n'
def to_array(input): """ parse strings of data from ajax requests to return """ try: input = input.decode("utf-8") except AttributeError: pass input = input.replace('\r\n', ',') input = input.replace('\n', ',') col0 = [float(x) for x in input.split(',')[0:-1:3]] col1 = [float(x) for x in input.split(',')[1:-1:3]] col2 = [float(x) for x in input.split(',')[2:-1:3]] return list(zip(col0, col1, col2))
def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway. """ return ( hasattr(obj, "__iter__") and not isinstance(obj, str) and not isinstance(obj, tuple) )
def _mutator_no_contributes_extra_field(data): """ Contributions used to be called contributes. Check that an extra field fails. """ data["invalid_extra_name"] = data["contributions"] del data["contributions"] return data
def prefix_split(prefix): """ return tuple(<servername/nick>, <user agent>, <host>) """ server_name = None user = None host = None pos = prefix.find('!') if pos >= 0: server_name, userhost = prefix[:pos], prefix[pos+1:] pos = userhost.find('@') if pos >= 0: user, host = userhost[:pos], userhost[pos+1:] else: host = userhost else: server_name = prefix return server_name, user, host
def split_ldap_common_name(common_name): """Returns firstname, surname tuple filters non alphabetical characters to avoid encoding problems""" namesplit = common_name.split() firstname = namesplit[0] surname = '' if len(namesplit) > 1: surname = namesplit[-1] # Filter nonalphabetical. firstname = ''.join(c for c in firstname if c.isalpha()) surname = ''.join(c for c in surname if c.isalpha()) return (firstname, surname)
def parse_uuid(uuid): """takes a hex-encoded uuid and returns an uuid or None if the uuid is invalid.""" try: # Remove the '-'s at specific points uuidhash = uuid[:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:] if len(uuidhash) != 32: return None x = uuidhash.decode('hex') return uuid except: return None
def de_bruijn(k, n): """ de Bruijn sequence for alphabet k and subsequences of length n. """ alphabet = k k = len(k) a = [0] * k * n sequence = [] def db(t, p): if t > n: if n % p == 0: sequence.extend(a[1:p + 1]) else: a[t] = a[t - p] db(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j db(t + 1, t) db(1, 1) sequence.extend(sequence[:n - 1]) return "".join(alphabet[i] for i in sequence)
def postprocess_descriptor_(descriptor): """ for convenience of indexing descriptor: - add AllowableQualifiersListForIndex with QualifierUIs only - add PharmacologicalActionListForIndex with DescriptorUIs note this mutates the original dict. """ if 'AllowableQualifiersList' in descriptor: descriptor['AllowableQualifiersListForIndex'] = [qual['QualifierReferredTo']['QualifierUI'] for qual in descriptor['AllowableQualifiersList']] if 'PharmacologicalActionList' in descriptor: descriptor['PharmacologicalActionListForIndex'] = [desc['DescriptorReferredTo']['DescriptorUI'] for desc in descriptor['PharmacologicalActionList']] return descriptor
def create_expression_values(item: dict): """ Creates the update expression using the provided dictionary. :param item: Dictionary of the data to use for the expression. :return: String with the expression. """ expression = 'SET ' values = dict() for name in item: expression += '{} = :{}, '.format(name, name) values[':{}'.format(name)] = {'S' if type(item[name]) is str else 'N': str(item[name])} return expression[0:-2], values
def stopwatch_format(ticks): """ Convert tenths of seconds to formatted time """ minutes = ticks // 600 # minutes = ticks // 60 tens_seconds = (ticks // 100) % 6 seconds = (ticks // 10) % 10 tenths = ticks % 10 return str(minutes) + ':' + str(tens_seconds) + \ str(seconds) + '.' + str(tenths)
def isiterable(target): """ From the pysistant library (@author Jay Lee) Check if target object is iterable :param target: :return: True if target is iterable. Otherwise, return False. """ try: iter(target) except: return False else: return True
def distance_constraints_too_complex(wordConstraints): """ Decide if the constraints on the distances between pairs of search terms are too complex, i. e. if there is no single word that all pairs include. If the constraints are too complex and the "distance requirements are strict" flag is set, the query will find some invalid results, so further (slow) post-filtering is needed. """ if wordConstraints is None or len(wordConstraints) <= 0: return False commonTerms = None for wordPair in wordConstraints: if commonTerms is None: commonTerms = set(wordPair) else: commonTerms &= set(wordPair) if len(commonTerms) <= 0: return True return False
def get_all_unicode_chars(): """Get all unicode characters.""" all_unicode_chars = [] i = 0 while True: try: all_unicode_chars.append(chr(i)) except ValueError: break i += 1 return all_unicode_chars
def _split_line(line, id_offset): """ First 10 chars must be blank or contain id info """ if not line or not line.strip(): return None, None # extract id and sequence curr_id = line[0:id_offset].strip() curr_seq = line[id_offset:].strip().replace(" ", "") return curr_id, curr_seq
def array_count(nums: list, target: int) -> int: """Count of target in nums. :return: Integer number of target in nums list/array. """ return len(list(filter(lambda x: x == target, nums)))
def is_blank(x): """Checks if x is blank.""" return (not x) or x.isspace()
def std_var_mean (Spectrum): """Compute mean for standard normal variate""" mean = sum(Spectrum)/len(Spectrum) return mean
def inject_string(string_input, index, injection): """ Inject one string into another at a given index :param string_input: string to accept injections :param index: index where injection will be applied :param injection: string that will be injected :return: string """ return string_input[:index] + str(injection) + string_input[index:]
def is_valid_project_type(type): """ Validates supported project types; currently only maven is supported; hopefully gradle in the future """ if not type: return False if "maven" != type: return False return True
def index2Freq(i, sampleRate, nFFT): """ Return the frequency for a given FTT index. :param i: Index :type i: int :param sampleRate: Numbers of data samples per second :type sampleRate: int :param nFFT: Length of fourier transform :type nFFT: int :return: Frequency at the given FFT index :rtype: int """ return (i * (sampleRate / (nFFT*2)))
def limit_client_trafic_trace(ignore_list, text): """Determine client trafic row that should be ignored.""" for index in range(len(ignore_list)): if text.find(ignore_list[index].ident_text) != -1: return True return False
def getGC(sequence): """ Calculate GC content of a sequence """ GC = 0 for nt in sequence: if nt == "G" or nt == "C": GC = GC + 1 GC = GC / float(len(sequence)) return GC
def rmtfp(para: str) -> str: """" Removes the main term from the paragraph. """ ind = str(para).index("span", str(para).index("span") + 1) return (para[ind + 6 :])
def parse_float(data: str) -> float: """ Parses float from string. If parsing failed, returns 0.0 """ try: return float(data.strip()) except ValueError: return 0.0
def injectlocals(l, skip=['self','args','kwargs'], **kwargs): """Update a dictionary with another, skipping specified keys.""" if 'kwargs' in l: kwargs.update(l['kwargs']) kwargs.update(dict((k, v) for k, v in l.items() if k not in skip)) return kwargs
def _bool_or_string(string): """Helper to interpret different ways of specifying boolean values.""" if string in ['t', 'true', 'True']: return True if string in ['f', 'false', 'False']: return False return string
def hr_size(size): """Returns human readable size input size in bytes """ units = ["B", "kB", "MB", "GB", "TB", "PB"] i = 0 # index while (size > 1024 and i < len(units)): i += 1 size /= 1024.0 return f"{size:.2f} {units[i]}"
def update_label(old_label, exponent_text): """ Update an axis label with scientific notation using LaTeX formatting for the order of magnitude. """ if exponent_text == "": return old_label try: units = old_label[old_label.index("(") + 1:old_label.rindex(")")] except ValueError: units = "" label = old_label.replace("({})".format(units), "") exponent_text = exponent_text.replace(r"$\times$", "") return "{} ({} {})".format(label, exponent_text, units)
def is_point_in_box(point, box): """ Box should be provided as ((xmin, ymin), (xmax, ymax)) """ x, y = point (x1, y1), (x2, y2) = box return x1 <= x and x2 >= x and y1 <= y and y2 >= y
def cu_mask_to_int(cu_mask): """ A utility function that takes an array of booleans and returns an integer with 1s wherever there was a "True" in the array. The value at index 0 is the least significant bit. """ n = 0 for b in reversed(cu_mask): n = n << 1 if b: n |= 1 return n
def first_plus_last(num: int) -> int: """Sum first and last digits of an integer.""" as_string = str(num) return int(as_string[0]) + int(as_string[-1])
def video_time_interval_suggestions(video_duration, max_num_suggestions=4): """ :param video_length: duration of video in seconds :return: array of tuples representing time intervals [(t1_start, t1_end), (t2_start, t2_end), ...] """ assert (video_duration > 3), "video too short to crop (duration < 3 sec)" suggestions = [] if video_duration < 4: margin = (4-video_duration)/2 suggestions.append((margin, 4-margin)) elif video_duration < 5: suggestions.append((1, 4)) else: num_suggestuions = min(max_num_suggestions, int((video_duration-2)//2.5)) left_margin, right_margin= 1, video_duration - 1 for i in range(num_suggestuions): offset = (video_duration-2)/num_suggestuions * i suggestions.append((left_margin + offset, left_margin + offset + 3)) assert len(suggestions) > 0 assert all([t_end <= video_duration and abs(t_end - t_start - 3) < 0.001 for t_start, t_end in suggestions]) return suggestions
def print_to_log(message, log_file): """Append a line to a log file :param message: The message to be appended. :type message: ``str`` :param log_file: The log file to write the message to. :type log_file: ``Path`` """ with open(log_file, "a") as file_handle: message.rstrip() file_handle.write(message+"\n") return 0
def _update_curr_pos(curr_pos, cmd, start_of_path): """Calculate the position of the pen after cmd is applied.""" if cmd[0] in 'ml': curr_pos = [curr_pos[0] + float(cmd[1]), curr_pos[1] + float(cmd[2])] if cmd[0] == 'm': start_of_path = curr_pos elif cmd[0] in 'z': curr_pos = start_of_path elif cmd[0] in 'h': curr_pos = [curr_pos[0] + float(cmd[1]), curr_pos[1]] elif cmd[0] in 'v': curr_pos = [curr_pos[0], curr_pos[1] + float(cmd[1])] elif cmd[0] in 'ctsqa': curr_pos = [curr_pos[0] + float(cmd[-2]), curr_pos[1] + float(cmd[-1])] return curr_pos, start_of_path
def selection(iterable, cmp_function): """ First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, a nd continue in this way until the entire array is sorted. Example: # Sort ascending li = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] def cmp_function(a, b): if a == b: return 0 elif a < b: return -1 else: return 1 li = selection(li, cmp_function) # li is now [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # for descending order use the following cmp_function def cmp_function(a, b): if a == b: return 0 elif a < b: return 1 else: return -1 Input: iterable - list object cmp_function - the function used for comparing Output: list object sorted """ len_iterable = len(iterable) for i in range(0, len_iterable - 1): min_index = i for j in range(i, len_iterable): # element in position j is smaller than element in position min_index if cmp_function(iterable[j], iterable[min_index]) == -1: min_index = j # swap if min_index != i: iterable[i], iterable[min_index] = iterable[min_index], iterable[i] return iterable
def check_input(depth, input_size, filter_size, n_convs): """checks if input is valid for model configuration Args: depth (int): depth of the model input_size (int): shape of model (width or height) filter_size (int): filter size convolutions n_convs (int): number of convolutions per depth """ def is_even(size): return size % 2 == 0 i1 = input_size # encoding for _ in range(depth): # input_size reduced through valid convs i1 -= (filter_size - 1) * n_convs # check if inputsize before pooling is even if not is_even(i1): return False # max pooling i1 /= 2 if i1 <= 0: return False # decoding for _ in range(depth): # input_size reduced through valid convs i1 -= (filter_size - 1) * n_convs # check if inputsize before upsampling is even if not is_even(i1): return False # upsampling i1 *= 2 i1 -= filter_size - 1 if i1 <= 0: return False # check if inputsize is even if not is_even(i1): False i1_end = i1 - (filter_size - 1) * n_convs if i1_end <= 0: return False return True
def get_changed_cell(curr_records, prev_records): """ Parameters ---------- curr_records : list of dicts prev_records : list of dicts Returns ------- row_num : int Index of the changed row. col_name : str Key of the changed column. Notes ----- Assumes at most one cell changed. If no cell changed, return `None, None`. """ records = zip(curr_records, prev_records) for i, (curr_record, prev_record) in enumerate(records): keys = set(list(curr_record.keys()) + list(prev_record.keys())) for key in keys: if curr_record.get(key) != prev_record.get(key): return i, key return None, None
def single_number(nums): """ Find single number in given array :param nums: given array :type nums: list[int] :return: single number :rtype: int """ # Use two bit operator to save three states m1, m2 = 0, 0 # n = 1, change in this order # m1 0 -> 0 -> 1 -> 0 # m2 0 -> 1 -> 0 -> 0 # n = 0, remain it same for n in nums: tmp = m1 m1 = m1 ^ n & (m1 ^ m2) m2 = m2 ^ n & (~tmp) return m2