content
stringlengths
42
6.51k
def unlistify(x): """ remove list wrapper from single item. similar to function returning list or item """ return x[0] if len(x)==1 else x
def absorption_spectrum(spectrum, wave_len, wave_len_min, wave_len_max): """ Determines wavelength of emitted bundle based upon the phosphor absorption spectrum (approximates the spectrum of sunlight) The normalized intensity per wavelength is called from excel and a random cumulative intensity is used to select a wavelength. Input: spectrum = normalized absorption spectrum Output: wave_len = incident wavelength of bundle """ probability = 0 # initialize probability of absorption if wave_len >= wave_len_min and wave_len <= wave_len_max: probability = spectrum.__call__(wave_len) return probability
def recursive_any(l: list, fn) -> bool: """Returns True if callback function fn returns True given any element from list l. Otherwise, False.""" if not l: return False if fn(l[0]): return True return recursive_any(l[1:], fn)
def generate_oa_dfs(in_a_measurements_df, in_b_measurements_df, oa_band_mutations, oa_plot_measurements, prepare_and_filter, plan): """Prepare other/additional attributes (OAs) and write the DataFrames used to name matched data files.""" # Note that B(b) is not used yet, as only GA supported for now. oa_temp_a_df = None oa_temp_b_df = None if in_a_measurements_df is not None and len(oa_band_mutations) > 0: oa_temp_a_df, oa_temp_b_df, oa_temp_c_df = prepare_and_filter.prepare_ab_data( in_a_measurements_df, in_a_measurements_df, None, plan.get('band_col'), oa_band_mutations[0][0], oa_band_mutations[0][1], None, plan.get('in_a_measurements_min_valid_pixel_percentage'), plan.get('in_a_measurements_min_valid_pixel_percentage'), None, oa_plot_measurements[0][0], plan.get('sr_measurements_date_filtering'), plan) # Remove duplicate data set to prevent plotting; # occurs when single OA only. if oa_band_mutations[0][0] == oa_band_mutations[0][1]: oa_temp_b_df = None return (oa_temp_a_df, oa_temp_b_df)
def G(S, K): """the payoff function of put option. Nothing to do with barrier""" return max(K-S, 0)
def extract_arguments(start, string): """ Return the list of arguments in the upcoming function parameter closure. Example: string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' arguments (output): '[{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, {'start': 17, 'end': 19}, {'start': 20, 'end': 53}]' """ arguments = [] closures = { "<": 0, "(": 0 } current_position = start argument_start_pos = current_position + 1 # Search for final parenthesis while current_position < len(string): if string[current_position] == "(": closures["("] += 1 elif string[current_position] == ")": closures["("] -= 1 elif string[current_position] == "<": closures["<"] += 1 elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0: closures["<"] -= 1 # Finished all arguments if closures["("] == 0 and closures["<"] == 0: # Add final argument arguments.append({"start": argument_start_pos, "end": current_position}) break # Finished current argument if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",": arguments.append({"start": argument_start_pos, "end": current_position}) argument_start_pos = current_position + 1 current_position += 1 return arguments
def _get_names_from_list_of_dict(rows): """Return list of column names if ``rows`` is a list of dict that defines table data. If rows is not a list of dict then return None. """ if rows is None: return None names = set() for row in rows: if not isinstance(row, dict): return None names.update(row) return list(names)
def count(grid, char): """Counts the occurrences of [char] in the grid.""" res = 0 for line in grid: res += sum(1 for c in line if c == char) return res
def count_ones_iter(n): """Using Brian Kernighan's Algorithm. (Iterative Approach)""" count = 0 while n: n &= n - 1 count += 1 return count
def convert_age_units(age_unit): """ Simple function to convert proband age units to cgap standard Args: age_unit (str): proband age unit Return: str: cgap age unit """ convert_dict = { "d": "day", "w": "week", "m": "month", "y": "year" } return convert_dict[age_unit.lower()]
def minSize(split, mined): """ Called by combineCheck() to ensure that a given cleavage or peptide is larger than a given minSize. :param split: the cleavage or peptide that is to have its size checked against max size. :param mined: the min size that the cleavage or peptide is allowed to be. :return bool: False if the split is shorter than mined, True if it is longer. """ if len(split) < mined: return False return True
def get_maximum_contexts (dict_context) : """Get the number of sentences before and after to take""" max_before_context=0 for pronoun in dict_context : if max_before_context <dict_context[pronoun]["sentences_before"] : max_before_context=dict_context[pronoun]["sentences_before"] max_after_context = 0 for pronoun in dict_context: if max_after_context < dict_context[pronoun]["sentences_after"]: max_after_context = dict_context[pronoun]["sentences_after"] return max_before_context,max_after_context
def shorten(text, width, placeholder='...'): """ >>> shorten('123456789', width=8) '12345...' >>> shorten('123456789', width=9) '123456789' """ if not text: return text if len(text) <= width: return text return text[: max(0, width - len(placeholder))] + placeholder
def findChIndex(c, str_in): """ Version 2: Using built-in methods. Write a python function that returns the first index of a character 'c' in string 'str_in'. If the character was not found it returns -1. Ex: findChIndex('a', 'dddabbb') will return 3 findChIndex('f', 'ddddabbb') will return -1 """ return_val = str_in.find(c) return return_val
def get_mlt_query(like_these, minimum_should_match): """ Perform a More Like This elasticsearch query on a given collection of documents """ return { "query": { "more_like_this": { "fields": [ "title", "abstract" ], "like": like_these, # "min_term_freq": 0., # "min_doc_freq": 0, "minimum_should_match": minimum_should_match } } }
def f(_a, _c): """Get first flattening. Parameters ---------- _a : float Semi-major axis _c : float Semi-minor axis """ return 1 - _c / _a
def cartesian_product(list1, list2): """Returns the cartesian product of the lists.""" ret = [] for i in list1: ret.append([(i, j) for j in list2]) return ret
def request_to_jsonable(request): """Get a request object and return a dict with desired key, value pairs that are to be encoded to json format """ return dict( (k, request[k]) for k in ( 'id', 'user', 'watchers', 'state', 'repo', 'branch', 'revision', 'tags', 'conflicts', 'created', 'modified', 'title', 'comments', 'reviewid', 'description' ) )
def strip_checkpoint_id(checkpoint_dir): """Helper function to return the checkpoint index number. Args: checkpoint_dir: Path directory of the checkpoints Returns: checkpoint_id: An int representing the checkpoint index """ checkpoint_name = checkpoint_dir.split('/')[-1] return int(checkpoint_name.split('-')[-1])
def number(lst, prefix, start=0): """ Number the items in the lst :lst: contains items to number :returns: a dict with item as the key and its number as the value """ return {item: '{0}{1}'.format(prefix, itemId) for itemId, item in enumerate(sorted(lst), start=start)}
def area_of_polygon(x, y): """Area of an arbitrary 2D polygon given its verticies """ area = 0.0 for i in range(-1, len(x)-1): area += x[i] * (y[i+1] - y[i-1]) return abs(area) / 2.0
def miller_rabin_test(n): """Statistically test the primality of a number using the Miller-Rabin algorithm. """ k, m = 0, n - 1 while True: if m % 2 != 0: break else: k += 1 m /= 2 b = 2**m % n if (b - n) == -1 or b == 1: return True b = b**2 % n if (b - n) == -1: return True for _ in range(2, k): b = b**2 % n if (b - n) == -1: return True if b == 1: return False return False
def string_to_bool(s, default=False): """ Turns a string into a bool, giving a default value preference. """ if len(str(s).strip()) == 0: return default if default: if s[0].upper() == "F": return False else: return True else: if s[0].upper() == "T": return True else: return False
def _is_constant_mapping(val_dict): """ @param val_dict: Defines the mapping, by defining an output value for each row of constrains. Each row is defined by a dictionary of operand names to operand values. @type val_dict: [ ([ dict(opname:string -> opval:string) ], value:string) ] The return type of gen_lookup_dict function @return bool: True if mapping defined by val_dict always returns same value. And hence we can define a constant function, not dependent on parameters. This is relevant for ONE() NT that has same IMM_WIDTH output operand value for several different index values. A good question is why it was defined that way. """ #check if we have same output values for all rows, #then we should generate a constant function, independent from parameters #This happens in ONE() NT for IMM_WIDTH #ONE() seems to be pretty useless NT. (_first_indices, first_output) = val_dict[0] all_same = True for _indices,out_val in val_dict[1:]: if out_val != first_output: all_same = False break return all_same
def string2bool(input_string): """ Converts string to boolena by checking if texts meaning is True, otherwise returns False. """ return input_string in ['true', 'True', 'Yes', '1']
def get_ascii_character_for_key(key): """Map a key to ASCII character.""" if not key: return None value = key.value if value > 255: return None return chr(value)
def isInstalled(name): """Check whether `name` is in the PATH. """ from distutils.spawn import find_executable return find_executable(name) is not None
def flatten(lists): """ Return a new (shallow) flattened list. :param lists: list: a list of lists :return list """ return [item for sublist in lists for item in sublist]
def threshold(suffix, config_dict): """Determines null percent thresholds for categories based on suffix.""" if suffix in config_dict: t1 = config_dict[suffix]['cat1'] t2 = config_dict[suffix]['cat2'] t3 = config_dict[suffix]['cat3'] else: t1 = config_dict['Categories']['cat1'] t2 = config_dict['Categories']['cat2'] t3 = config_dict['Categories']['cat3'] return t1, t2, t3
def forcefully_read_lines(filename, size): """Return lines from file. Ignore UnicodeDecodeErrors. """ input_file = open(filename, mode='rb') try: return input_file.read(size).decode('utf-8', 'replace').splitlines() finally: input_file.close() return []
def desi_proc_joint_fit_command(prow, queue=None): """ Wrapper script that takes a processing table row (or dictionary with NIGHT, EXPID, OBSTYPE, PROCCAMWORD defined) and determines the proper command line call to process the data defined by the input row/dict. Args: prow, Table.Row or dict. Must include keyword accessible definitions for 'NIGHT', 'EXPID', 'JOBDESC', and 'PROCCAMWORD'. queue, str. The name of the NERSC Slurm queue to submit to. Default is None (which leaves it to the desi_proc default). Returns: cmd, str. The proper command to be submitted to desi_proc_joint_fit to process the job defined by the prow values. """ cmd = 'desi_proc_joint_fit' cmd += ' --batch' cmd += ' --nosubmit' cmd += ' --traceshift' if queue is not None: cmd += f' -q {queue}' descriptor = prow['OBSTYPE'].lower() night = prow['NIGHT'] specs = str(prow['PROCCAMWORD']) expids = prow['EXPID'] expid_str = ','.join([str(eid) for eid in expids]) cmd += f' --obstype {descriptor}' cmd += ' --cameras={} -n {} -e {}'.format(specs, night, expid_str) return cmd
def jolt_differences( data ): """ To the given data, add the jolts of the charging outlet at the start and jolt of the device to the end of the adapters list. Since all the adapters have to be used, the difference between the sorted adapters are computed. The 1's and 3's are counted and their multiple is returned. """ adapters = [0] + data + [ max(data)+3 ] differences = [ adapters[i+1] - adapters[i] for i in range(len(adapters)-1) ] return differences.count(1) * differences.count(3)
def get_sources(results): """ Get sources from hits, sorted by source id Args: results (dict): Elasticsearch results Returns: list of dict: The list of source dicts """ sorted_hits = sorted(results['hits'], key=lambda hit: hit['_source']['id']) return [hit['_source'] for hit in sorted_hits]
def ranks_to_acc(found_at_rank, fid=None): """ Computes top-1-accuracy from list of ranks :param found_at_rank: List of ranks. :param fid: File identifier. :return accs: top-N-accuracies """ def fprint(txt): print(txt) if fid is not None: fid.write(txt + '\n') tot = float(len(found_at_rank)) fprint('{:>8} \t {:>8}'.format('top-n', 'accuracy')) accs = [] for n in [1, 3, 5, 10, 20, 50]: accs.append(sum([r <= n for r in found_at_rank]) / tot) fprint('{:>8} \t {:>8}'.format(n, accs[-1])) return accs
def was_preemptible_vm(metadata, was_cached): """ Modified from: https://github.com/broadinstitute/dsde-pipelines/blob/develop/scripts/calculate_cost.py """ # if call cached, not any type of VM, but don't inflate nonpreemptible count if was_cached: return None elif ( "runtimeAttributes" in metadata and "preemptible" in metadata["runtimeAttributes"] ): pe_count = int(metadata["runtimeAttributes"]["preemptible"]) attempt = int(metadata["attempt"]) return attempt <= pe_count else: # we can't tell (older metadata) so conservatively return false return False
def get_max_prime_factor_less_than( n, ceil ): """ Helper function for recursive_seed_part. Returns the largest prime factor of ``n`` less than ``ceil``, or None if all are greater than ceil. """ factors = [] i = 2 while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) if len(factors) == 0: return 1 m = [i for i in factors if i <= ceil] if m == []: return None return int(max(m))
def fmt_point(point): """Format a 2D point.""" assert len(point) == 2 return f"({point[0]},{point[1]})"
def purge(li): """renvoie la liste avec uniquement les chiffres""" return [i for i in li if type(i) == int or type(i) == float]
def get_list_of(key, ch_groups): """ Return a list of values for key in ch_groups[groups] key (str): a key of the ch_groups[groups] dict ch_groups (dict): a group-name-indexed dict whose values are dictionaries of group information (see expand_ch_groups) Example: get_list_of('system', ch_groups) If ch_groups is the one specified in the json in the expand_ch_groups example, this will return the list [ 'geds', 'spms', 'auxs' ] """ values = [] for ch_info in ch_groups.values(): if key in ch_info and ch_info[key] not in values: values.append(ch_info[key]) return values
def remove_markdown(body): """Remove the simple markdown used by Google Groups.""" return body.replace('*', '')
def select_packages(packages, categories): """ Select packages inside the chosen categories Parameters ---------- packages : dict Dictionary with categories and their corresponding packages as lists. categories : list List containing the chosen categories Returns ------- packages_selection : list List of packages that belong to the chosen categories """ packages_selection = [] for category in categories: packages_selection.extend(packages[category]) return packages_selection
def getarg(args, index): """ Helper to retrieve value from command line args """ return args[index] if index < len(args) else None
def sortedMerge(list1, list2): """assumes list1 and list2 are lists returns a list of tuples, from the elements of list1 and list2""" # zip lists combo_list = list(zip(list1, list2)) # sort list by 2nd elem combo_list = sorted(combo_list, key=lambda a: a[1]) return combo_list
def mod_type_to_string(mod_type): """ Prints module type in readable form """ out = '(' # type if (mod_type & 0xf) == 0: out += ' builtin' elif (mod_type & 0xf) == 1: out += ' loadable' # Module that may be instantiated by fw on startup if ((mod_type >> 4) & 0x1) == 1: out += ' auto_start' # Module designed to run with low latency scheduler if ((mod_type >> 5) & 0x1) == 1: out += ' LL' # Module designed to run with edf scheduler if ((mod_type >> 6) & 0x1) == 1: out += ' DP' out += ' )' return out
def pluralize(value): """ Add an 's' or an 'ies' to a word. We've got some special cases too. """ plural = value if value[-1] == 'y': plural = '%sies' % value[:-1] else: plural += 's' return plural
def _get_widget_selections(widgets, widget_selections): """Return lists of widgets that are selected and unselected. Args: widgets (list): A list of widgets that we have registered already. widget_selections (dict): A dictionary mapping widgets (:py:class:`reviewboard.admin.widgets.Widget`) to whether or not they are selected (as a :py:class:`unicode`). Returns: tuple of list: A 2-tuple containing a list of selected widgets (to display on the dashboard) and a list of the unselected widgets. """ selected_widgets = [] unselected_widgets = [] if widget_selections: for widget in widgets: if widget_selections.get(widget.widget_id) == "1": selected_widgets.append(widget) else: unselected_widgets.append(widget) else: selected_widgets = widgets unselected_widgets = None return selected_widgets, unselected_widgets
def clean_filename(filename): """ Remove leading path and ending carriage return from filename. """ return filename.split('/')[-1].strip()
def get_fold_val(fold_test, fold_list): """ Get the validation fold given the test fold. Useful for cross-validation evaluation mode. Return the next fold in a circular way. e.g. if the fold_list is ['fold1', 'fold2',...,'fold10'] and the fold_test is 'fold1', then return 'fold2'. If the fold_test is 'fold10', return 'fold1'. Parameters ---------- fold_test : str Fold used for model testing. fold_list : list of str Fold list. Returns ------- str Validation fold. """ N_folds = len(fold_list) fold_test_ix = [k for k, v in enumerate(fold_list) if v == fold_test][0] # sum(divmod(fold_test_ix+1,N_folds)) fold_val_ix = (fold_test_ix+1) % N_folds fold_val = fold_list[fold_val_ix] return fold_val
def get_fly_energy(weight, distance): """ Calculate E_f. """ m_d = weight # v_d is in m/s v_d = 5.70 * (m_d ** 0.16) # convert to m L_d = distance * 1000 # convert to hours temp_time = L_d / v_d / 60 / 60 E_v = 300 / 4.184 E_f = m_d * E_v * temp_time return E_f
def get_command_name(value): """ Gets command name by value :param value: value of Command :return: Command Name """ if value == 1: return 'CONNECT' elif value == 2: return 'BIND' elif value == 3: return 'UDP_ASSOCIATE' else: return None
def subtract(coords1, coords2): """ Subtract one 3-dimensional point from another Parameters coords1: coordinates of form [x,y,z] coords2: coordinates of form [x,y,z] Returns list: List of coordinates equal to coords1 - coords2 (list) """ x = coords1[0] - coords2[0] y = coords1[1] - coords2[1] z = coords1[2] - coords2[2] return [x,y,z]
def ndvi(nir, red): """Compute Normalized Difference Vegetation Index from NIR & RED images.""" return (nir - red) / (nir + red)
def dot_product(u, v): """Computes dot product of two vectors u and v, each represented as a tuple or list of coordinates. Assume the two vectors are the same length.""" output = 0 for i in range(len(u)): output += (u[i]*v[i]) return output
def remove_last_syllable(phon: str) -> str: """Remove the last syllable boundary in a phonetic string. Example: Turn `fa:-n` (stem of `fa:-n@`) into `fa:n`. """ # Find the last hyphen marking a syllable boundary and remove it. i = phon.rfind("-") j = i + 1 return phon[:i] + phon[j:]
def branch(path): """ Builds a tuple containing all path above this one. None of the returned paths or the given paths is required to actually have a corresponding Node. Expample: >>> branch("/a/b/c/") ('/', '/a/', '/a/b/', '/a/b/c/') """ li = tuple(p for p in path.split('/') if p) return ('/',)+tuple('/'+'/'.join(li[:c])+'/' for c in range(1,len(li)+1))
def convert_to_numbers(string_to_convert): """Converts A-Z strings to numbers.""" numbers_from_string = [] for letter in string_to_convert: numbers_from_string.append(ord(letter)-64) #numbers_from_string.append(keystream.letters_to_keys_list[letter]) return numbers_from_string
def parse_to_tuples(command_strs): """ Parse commands into a tuple list """ tuples = [] for command in command_strs: cmd, arg = command.split(" ") cmd = cmd.strip() arg = int(arg.strip()) tuples.append((cmd, arg)) return tuples
def format_tag_endings(tag, punct_value, endings=[]): """Format punctuation around a tag. Normalizes in case of irregularity. For instance, in the cases of both words.</> words</>. the tags will be normalized to either an in/exclusive order. """ if punct_value == 'inclusive': return endings + [tag] elif punct_value == 'exclusive': return [tag] + endings else: raise Exception(f'INVALID punct_value supplied: {punct_value}')
def get_name(node): """Return name of node.""" return node.get('name')
def get_comparments(list_trans): """ Getting a list of transtions, return the compartments """ l = [] for trans in list_trans: if trans.from_comp not in l: l.append(trans.from_comp) if trans.to_comp not in l and trans.to_comp != 'zero': l.append(trans.to_comp) return l
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) u'1,000' >>> format_currency(100) u'100' >>> format_currency(999.95) u'999.95' >>> format_currency(99.95) u'99.95' >>> format_currency(100000) u'100,000' >>> format_currency(1000.00) u'1,000' >>> format_currency(1000.41) u'1,000.41' >>> format_currency(23.21, decimals=3) u'23.210' >>> format_currency(1000, decimals=3) u'1,000' >>> format_currency(123456789.123456789) u'123,456,789.12' """ number, decimal = ((u'%%.%df' % decimals) % value).split(u'.') parts = [] while len(number) > 3: part, number = number[-3:], number[:-3] parts.append(part) parts.append(number) parts.reverse() if int(decimal) == 0: return u','.join(parts) else: return u','.join(parts) + u'.' + decimal
def compute_hashes(to_compute): """ """ hasharr = [] for arr in to_compute: hashval = hash(bytes(arr)) hasharr.append(hashval) return hasharr
def eval_print_fn(val, print_fn): """Evaluate a print function, and return the resulting string.""" # The generated output from explain contains the string "\n" (two characters) # replace them with a single EOL character so that GDB prints multi-line # explains nicely. pp_result = print_fn(val) pp_str = str(pp_result).replace("\"", "").replace("\\n", "\n") return pp_str
def shaping_by_fields(fields: list) -> str: """ Creating a shaping for the request which is from the fields and seperated by comma's Args: fields: List of fields that would be part of the shaping. Returns: str of the shaping. """ shaping = 'hd_ticket all' for field in fields: shaping += f',{field} limited' return shaping
def format_schedule(sched): """ Formats a schedule (as list of Operations) for printing in HTML """ s = '' for op in sched: if op.type!='READ' and op.type!='WRITE': s += '<b>'+str(op)+' </b>' else: s += str(op)+' ' return s+'\n'
def remove_prefix(text, prefix): """ If a particular prefix exists in text string, This function removes that prefix from string and then returns the remaining string """ if text.startswith(prefix): return text[len(prefix):] return text
def bool_converter(value): """Simple string to bool converter (0 = False, 1 = True).""" return value == "1"
def sig_indicator(pvalue): """Return a significance indicator string for the result of a t-test. Parameters ---------- pvalue: float the p-value Returns ------- str `***` if p<0.001, `**` if p<0.01, `*` if p<0.05, `ns` otherwise. """ return ( '***' if pvalue < 0.001 else '**' if pvalue < 0.01 else '*' if pvalue < 0.05 else 'ns' )
def sediment_delivery_ratio(area_sq_km): """ Calculate Sediment Delivery Ratio from the basin area in square km Original at [email protected]:9334-9340 """ if area_sq_km < 50: return (0.000005 * (area_sq_km ** 2) - (0.0014 * area_sq_km) + 0.198) else: return 0.451 * (area_sq_km ** (0 - 0.298))
def list_to_str(seq, sep="-"): """Transform the input sequence into a ready-to-print string Parameters ---------- seq : list, tuple, dict Input sequence that must be transformed sep : str Separator that must appears between each `seq` items Returns ------- str Printable version of input list """ return sep.join(str(i) for i in seq)
def _format_return_message(results): """ Formats and eliminates redundant return messages from a failed geocoding result. :param results: the returned dictionary from Geoclient API of a failed geocode. :return: Formatted Geoclient return messages """ out_message = None if 'message' in results: out_message = results['message'] if 'message2' in results: if out_message: if out_message != results['message2']: out_message = "{} {}".format(out_message, results['message2']) else: return results['message2'] return out_message
def trim(item, max_len=75): """Return string representation of item, trimmed to max length.""" string = str(item) string = string[:max_len] + '...' if len(string) > max_len else string return string
def get_format_invocation(f, clang_format_binary): """Gets a command line for clang-tidy.""" start = [clang_format_binary, "-i", f] return start
def low_pass_filter(X_room_act: float, X_filt_last: float): """ This function is a low pass filter for data pretreatment to filter out the high frequency data :param X_room_act: float: current absolute humidity (mixing ratio kg_moisture/kg_dry-air) :param X_filt_last: float: last filtered value of absolute humidity (mixing ratio kg_moisture/kg_dry-air) :return float: filtered values of current absolute humidity (mixing ratio kg_moisture/kg_dry-air) """ # time step in seconds t_step = 60 # filtering time constant Tf = 4000 X_filt_act = ((t_step/Tf)*X_room_act + X_filt_last)/(1+(t_step/Tf)) return X_filt_act
def edgeList(G): """convert list-of-sets graphs representation to a list of edges""" V = len(G) E = [] for v in range(V): for u in G[v]: if v < u and v != 0 and u != 0: E += [(v, u)] return E
def count_nt(string): """Count A, T, C, G""" string = string.upper() counts = [] for nt in ['A', 'C', 'G', 'T']: counts.append(string.count(nt)) s_counts = " ".join([str(x) for x in counts]) return s_counts
def heredoc(s, inputs_dict): """ Use docstrings to specify a multi-line string literal. Args: s (str): docstring with named placeholders for replacement. inputs_dict (dict): dict with keys corresponding to placeholders in docstring `s` and values to insert. Returns: str: string with placeholders replaced with corresponding values and any linebreaks preserved. """ import textwrap s = textwrap.dedent(s).format(**inputs_dict) return s[1:] if s.startswith('\n') else s
def parStringToIntList(parString): """ Convert a space delimited string to a list of ints """ return [int(x) for x in parString.split()]
def to_word(word: int) -> int: """ >>> hex(to_word(0x1234ABCD)) '0xabcd' >>> hex(to_word(0)) '0x0' This size should never happen! >>> hex(to_word(0x12345678ABCD)) '0xabcd' Masks the given value to the size of a word (16 bits) :param word: :return: """ assert isinstance(word, int), 'Argument is not of type int' return word & 0xFFFF
def get_index(refname, indices, max_order): """Get the index of a monomial.""" if refname == "interval": return indices[0] if refname == "triangle": return sum(indices) * (sum(indices) + 1) // 2 + indices[1] if refname == "quadrilateral": return indices[1] * (max_order + 1) + indices[0] if refname == "tetrahedron": return (sum(indices) * (sum(indices) + 1) * (sum(indices) + 2) // 6 + sum(indices[1:]) * (sum(indices[1:]) + 1) // 2 + indices[2]) if refname == "hexahedron": return indices[2] * (max_order + 1) ** 2 + indices[1] * (max_order + 1) + indices[0] if refname == "prism": return ((max_order + 2) * (max_order + 1) * indices[2] // 2 + sum(indices[:2]) * (sum(indices[:2]) + 1) // 2 + indices[1])
def weed_out_short_notes(pairs, **kwargs): """Remove notes from pairs whose duration are smaller than the threshold""" duration_threshold = kwargs.get('duration_threshold', 0.25) return [(n, d) for (n, d) in pairs if d > duration_threshold]
def merge(left, right): """ Merge helper Complexity: O(n) """ arr = [] left_cursor, right_cursor = 0,0 while left_cursor < len(left) and right_cursor < len(right): # Sort each one and place into the result if left[left_cursor] <= right[right_cursor]: arr.append(left[left_cursor]) left_cursor+=1 else: arr.append(right[right_cursor]) right_cursor+=1 # Add the left overs if there's any left to the result if left: arr.extend(left[left_cursor:]) if right: arr.extend(right[right_cursor:]) return arr
def last_index(L, value): """ Find the final occurrence of value in L. """ val = next(iter( filter(lambda x: x[1] == value, reversed(list(enumerate(L)))))) if val: return(val[0]) else: raise(ValueError("{} is not in the list.".format(value)))
def _async_unique_id_to_mac(unique_id: str) -> str: """Extract the MAC address from the registry entry unique id.""" return unique_id.split("_")[0]
def expected_headers(auth_token='my-auth-token'): """ Return an expected set of headers, given an auth token """ return { 'content-type': ['application/json'], 'accept': ['application/json'], 'x-auth-token': [auth_token], 'User-Agent': ['OtterScale/0.0'] }
def getWorldRegion(regionID): """ Creates a array of all the world regions """ world_region = { 0: "us", #US West 1: "use", #US East 2: "eu", #Europe 3: "jp" #Japan } return world_region[regionID - 1]
def p3sat_h(h): """ *4.2 Region 3. pSat_h & pSat_s Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) & T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water & Steam 2004 Section 4 Boundary Equations psat(h) & psat(s) for the Saturation Lines of Region 3 Se pictures Page 17, Eq 10, Table 17, Page 18 """ Ii = [0, 1, 1, 1, 1, 5, 7, 8, 14, 20, 22, 24, 28, 36] Ji = [0, 1, 3, 4, 36, 3, 0, 24, 16, 16, 3, 18, 8, 24] ni = [0.600073641753024, -9.36203654849857, 24.6590798594147, -107.014222858224, -91582131580576.8, -8623.32011700662, -23.5837344740032, 2.52304969384128E+17, -3.89718771997719E+18, -3.33775713645296E+22, 35649946963.6328, -1.48547544720641E+26, 3.30611514838798E+18, 8.13641294467829E+37] hs = h / 2600 ps = 0 # for i = 1:14 for i in range(0, 14): ps += ni[i] * (hs - 1.02) ** Ii[i] * (hs - 0.608) ** Ji[i] _p3sat_h = ps * 22 return _p3sat_h
def factorizable(n, factors, sort_factors=True): """ Check if there is a way to factorize n by the factors passed as a second argument. Factors could be non-prime. As the factors could be non-prime, we can't just divide by all the factors one by one until there are no factors left or we got 1. We have to check all possible orders of factorization. We'll try to divide N by all the factors, store all the quotients in the list and then try to check all numbers in that list in the same manner until we run out of possible factors or get 1. """ if not factors: return False if sort_factors: factors = sorted(set(factors)) fs = [n] # The initial list of numbers to check contains only n while fs: # If there are no numbers left to check, there is no way to fully factorize n by factors sub = [] # A list to store all the quotients from the division of n by factors for n in fs: # Try to factorize further for f in factors: if n == f: # Fully factorized! return True elif f <= n: # A possible factor if n % f == 0: # n is divisible by f. Let's check if n/f is in turn factorizable by factors sub.append(n/f) else: # This, and, consequently, all subsequent factors are too large for n to be divisible by them break # We are still here, so we still don't know if n is fully divisible by factors. # Let's check all the quotients in the same way fs = sub return False
def get_tags_asset(tag_assets): """ Iterate over tag assets list from response and retrieve details of tag assets :param tag_assets: List of tag assets from response :return: List of detailed elements of tag assets :rtype: list """ return [{ 'ID': tag_asset.get('id', ''), 'Name': tag_asset.get('name', ''), 'Category': tag_asset.get('category', ''), 'Created': tag_asset.get('created', ''), 'Updated': tag_asset.get('updated', ''), 'Color': tag_asset.get('color', ''), 'Description': tag_asset.get('description', '') } for tag_asset in tag_assets]
def slice(seq, indices): """Performs a Perl-style slice, substituting None for out-of-range indices rather than raising an exception. """ sliced = [] for index in indices: try: sliced.append(seq[int(index)]) except IndexError: sliced.append(None) return sliced
def _dotted_path(segments): """Convert a LUA object path (``['dir/', 'file/', 'class#', 'instanceMethod']``) to a dotted style that Sphinx will better index.""" segments_without_separators = [s[:-1] for s in segments[:-1]] segments_without_separators.append(segments[-1]) return '.'.join(segments_without_separators)
def read_file(file_path): """ Open the file and return the contents Parameters ---------- file_path : str The path of the file. Returns ---------- file_data : str Data in the file """ try: with open(file_path, 'r', encoding="utf-8_sig") as target_file: file_data = target_file.read() except FileNotFoundError: file_data = None print('File not Found!') return file_data
def perm2cycles_without_fixed(perm): """ Convert permutation in one-line notation to permutation in cycle notation without fixed points :param perm: Permutation in one-line notation :type perm: list :return: Returns permutation in cycle notation without fixed points :rtype: list """ cycles = [] used = [] for x in range(1, max(perm) + 1): if x in used: continue temp = [] temp.append(x) used.append(x) i = x while True: i = perm[i - 1] if i == x: break temp.append(i) used.append(i) if len(temp) > 1: cycles.append(temp) return cycles
def get_non_digit_prefix(characters): """ Return the non-digit prefix from a list of characters. """ prefix = [] while characters and not characters[0].isdigit(): prefix.append(characters.pop(0)) return prefix
def get_empty_cells(grid): """Return a list of coordinate pairs corresponding to empty cells.""" empty = [] for j,row in enumerate(grid): for i,val in enumerate(row): if not val: empty.append((j,i)) return empty
def between(bound_min, bound_max, value): """Checks whether the value is between the min and max values, inclusive.""" return bound_min <= value and value <= bound_max
def remove_key(dictionary, key): """Remove specified key from dictionary, do nothing if it does not exist.""" if key in dictionary: del dictionary[key] return dictionary
def split_data(x, y): """ Split data into training and validation set :return: """ training_percent = 0.7 split_idx = round(training_percent * len(y)) x_train = x[:split_idx] x_val = x[split_idx:] y_train = y[:split_idx] y_val = y[split_idx:] return x_train, y_train, x_val, y_val
def find_deltas(arr): """ Creates a new array that is the differences between consecutive elements in a numeric series. The new array is len(arr) - 1 """ return [j-i for i, j in zip(arr[:-1], arr[1:])]
def sanitize(d): """Sanitize sensitive information, preventing it from being logged Given a dictionary, look up all keys that may contain sensitive information (eg. "authtoken", "Authorization"). Returns a dict with the value of these keys replaced with "omitted" Arguments: d (dict): dictionary containing potentially sensitive information Returns: (dict): sensitive information removed from dict """ sanitize_keys = [ "authtoken", "Authorization" ] r = d.copy() sanitized = {k: "omitted" for k in sanitize_keys if k in r.keys()} r.update(sanitized) return r