content
stringlengths
42
6.51k
def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> re...
def bytes_to_int_signed(b): """Convert big-endian signed integer bytearray to int.""" return int.from_bytes(b, 'big', signed=True)
def make_PEM_filename(cert_id: str) -> str: """Create a filename for PEM certificate""" return cert_id + '.pem'
def is_safe(value: str) -> bool: """ Evaluate if the given string is a fractional number save for eval() """ return len(value) <= 10 and all(c in "0123456789./ " for c in set(value))
def pt_agent_country(country): """Clean the country""" c = country.strip() if c.lower() == 'unknown': return '' return c
def cut_off_str(obj, max_len): """ Creates a string representation of an object, no longer than max_len characters Uses repr(obj) to create the string representation. If this is longer than max_len -3 characters, the last three will be replaced with elipsis. """ s = repr(obj) if len...
def diamond_coord_test(x, y, z): # dist2 = 3 """Test for coordinate in diamond grid""" return (((x % 2 + y % 2 + z % 2) == 0 and (x//2+y//2+z//2) % 2 == 0) or ((x % 2 + y % 2 + z % 2) == 3 and (x//2+y//2+z//2) % 2 == 0))
def GetBoundaries(n, line): """ Parse and extract a boundary of n+1 elements from a line of text Parameters ---------- n: int Number of elements line: string line containing boundary data Returns ------- Array of n+1 floats representing the boundary...
def to_psychopy_coord(normx, normy): """Transform coordinates from normalized to psychopy-format.""" psychopyx = normx*2-1 psychopyy = 2-normy*2-1 return psychopyx, psychopyy
def is_contained_in(frst, scnd): """ Is the first region contained in the second. :param frst: a tuple representing the first region with chromosome, start, end as the first 3 columns :param scnd: a tuple representing the second region with chr...
def find_key(d: dict, key: str, default: None): """ Search for the first occurence of the given key deeply in the dict. When not found is returned the default value """ if key in d: return d[key] for k, v in d.items(): if isinstance(v, dict): item = find_key(v, key, default)...
def combination(a: int, b: int) -> int: """ Choose b from a. a >= b """ b = min(b, a - b) numerator = 1 dominator = 1 for i in range(b): numerator *= (a - i) dominator *= (b - i) return int(numerator / dominator)
def pdh_signal( ff, power, gamma, finesse, FSR, fpole ): """Laser frequency Pound-Drever-Hall signal response to a cavity in W/Hz. """ pdh = 2 * power * gamma * finesse / FSR / (1 + 1j * ff / fpole) return pdh
def _us_to_s(time_us): """Convert [us] into (float) [s] """ return (float(time_us) / 1e6)
def bytes_to_english(num_bytes): """Converts integers into standard computer byte names, i.e. a kilobyte is NOT 10^3, a kilobyte is 2^10. This function requires a byte size to be ten (10) times a base unit size before it will convert, e.g. a 2,097,152 will NOT convert to "2 megabytes" because it is only two...
def validate_int_or_None(s): """if not None, tries to validate as an int""" if s=='None': s = None if s is None: return None try: return int(s) except ValueError: raise ValueError('Could not convert "%s" to int' % s)
def slice_page(path): """ Function removes proper amount of characters from the end of a given path, so that it can later be appended in an altered form :param path: string (url path with filter and page parameters) :return: string (sliced path) """ index = len(path) - 7 if path.count('&...
def dict2list(data,order=None): """ Converts a dictionary to a list of keys and a list of values Parameters ---------- data : dict dictionary with name, value pairs order : list list of keys representing the order of the data in the saved file ...
def narrow_to_non_space(text, start, end): """ Narrow down text indexes, adjusting selection to non-space characters @type text: str @type start: int @type end: int @return: list """ # narrow down selection until first non-space character while start < end: if not text[start].isspace(): break start ...
def format_time(time_str): """ Properly format a run-time string for the sbatch file Examples: 15 -> 15:00:00 2:30:5 -> 02:30:05 :30 -> 00:30:00 ::30 -> 00:00:30 """ time_str = str(time_str) split = time_str.split(':') hours = sp...
def beta_mode(alpha, beta): """Calculate the mode of a beta distribution. https://en.wikipedia.org/wiki/Beta_distribution When the distribution is bimodal (`alpha`, `beta` < 1), this function returns `nan`. :param alpha: first parameter of the beta distribution :type alpha: float :param be...
def utf8ify(s): """Create a representation of the string that print() is willing to use""" return s.encode("utf8", "replace").decode("utf8")
def padTime(timestring): """ Returns a 12 digit string as time by padding any missing month, day, hour or minute values. """ padder = "000001010000" if len(timestring) < 12: timestring = timestring + (padder[len(timestring):]) return timestring
def get_entry_dictionary(resource, vos, cpus, walltime, memory): """Utility function that converts some variable into an xml pilot dictionary""" # Assigning this to an entry dict variable to shorten the line edict = {} # Entry dict edict["gridtype"] = "condor" edict["attrs"] = {} edict["attrs"]...
def _parent(i): """ Returns the parent node of the given node. """ return (i - 1) // 2
def python_type_name(type_info): """Given a type instance parsed from ast, return the right python type""" # print(type_info) if type_info is None: return "None" type_map = { "void" : "None", "std::string" : "str", } if "unique_ptr" in type_info.name or "shared_ptr" in ty...
def reverse(un_list): """This function aims to reverse a list""" empty_list = [] if un_list == []: return [] else: for i in range(len(un_list)-1,0,-1): empty_list += [un_list[i]] return empty_list + [un_list[0]]
def get_dust_attn_curve_d1(wave,d1=1.0): """ Calculate birth cloud dust attenuation curve Parameters ---------- wave: Float or 1-D Array Wavelengths (Angstroms) at which attenuation curve should be evaluated d1: Float Birth cloud dust optical depth Returns ------- Bi...
def hash_dict(d): """Construct a hash of the dict d. A problem with this kind of hashing is when the values are floats - the imprecision of floating point arithmetic mean that values will be regarded as different which should really be regarded as the same. To solve this problem we hash to 8 signi...
def get_track_id_from_json(item): """ Try to extract video Id from various response types """ fields = ['contentDetails/videoId', 'snippet/resourceId/videoId', 'id/videoId', 'id'] for field in fields: node = item for p in field.split('/'): ...
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in range...
def get_amr_line(infile): """ Read an entry from the input file. AMRs are separated by blank lines. """ cur_comments = [] cur_amr = [] has_content = False for line in infile: if line[0] == "(" and len(cur_amr) != 0: cur_amr = [] if line.strip() == "": if not has_content: continue ...
def create_gitbom_doc_text(infile_hashes, db): """ Create the gitBOM doc text contents :param infile_hashes: the list of input files, with its hashes, essentially a dict :param db: gitBOM DB with {file-hash => its gitBOM hash} mapping """ if not infile_hashes: return '' lines = [] ...
def guess_number(f_guess, f_turns_left): """ Function to obtain player guess Params: f_guess: str f_turns_left: int Returns: int, int or str, int """ try: f_guess = int(f_guess) if f_guess < 1 or f_guess > 9: raise ValueError return f...
def generate_winner_list(winners): """ Takes a list of winners, and combines them into a string. """ return ", ".join(winner.name for winner in winners)
def find_aruba(aps, ap): """ This function is needed to go all over the list of APs comparing their serial numbers to make a match :param aps: a list of objects, that represent the APs that we are looking for :param ap: an object, representing one of the APs found on the controller :return: an inde...
def qbinomial(n, k, q = 2): """ Calculate q-binomial coefficient """ c = 1 for j in range(k): c *= q**n - q**j for j in range(k): c //= q**k - q**j return c
def DebugStructToDict(structure): """Converts a structure as printed by the debugger into a dictionary. The structure should have the following format: field1 : value1 field2 : value2 ... Args: structure: The structure to convert. Returns: A dict containing the values stored in the s...
def _get_message(status, backend, hrsp_5xx_ratio, warning_ratio, critical_ratio, interval): """Return a message conveying the check results. :return: Informational message about the check :rtype: :py:class:`str` """ return ("""{backend} traffic has HTTP 5xx ratio of {hrsp_5xx_ratio:.4f} in the past...
def correct_other_vs_misc(rna_type, _): """ Given 'misc_RNA' and 'other' we prefer 'other' as it is more specific. This will only select 'other' if 'misc_RNA' and other are the only two current rna_types. """ if rna_type == set(["other", "misc_RNA"]): return set(["other"]) return rn...
def second_half(dayinput): """ second half solver: """ suffix = [17, 31, 73, 47, 23] knot = [i for i in range(256)] sub_lengths = [] for x in dayinput: sub_lengths.append(ord(x)) print(sub_lengths) sub_lengths += suffix current = skip = 0 for x in range(64): f...
def tuple_4d(x, y, z, w): """Returns a 4D tuple with x, y, z and w coordinates.""" return [x, y, z, w]
def scale_formula(k, m=5, s_min=0.2, s_max=0.9): """ Scale formula. Args: k: K-th feature map level. m: Number of feature map levels. s_min: Scale factor of the lowest layer. s_max: Scale factor of the highest layer. Returns: Scale value for the k-th feature map. """ ...
def _start_stop_block(size, proc_grid_size, proc_grid_rank): """Return `start` and `stop` for a regularly distributed block dim.""" nelements = size // proc_grid_size if size % proc_grid_size != 0: nelements += 1 start = proc_grid_rank * nelements if start > size: start = size ...
def get_space_packet_header( packet_id: int, packet_sequence_control: int, data_length: int ) -> bytearray: """Retrieve raw space packet header from the three required values""" header = bytearray() header.append((packet_id & 0xFF00) >> 8) header.append(packet_id & 0xFF) header.append((packet_se...
def truecase(word, case_counter): """ Truecase :param word: :param case_counter: :return: """ lcount = case_counter.get(word.lower(), 0) ucount = case_counter.get(word.upper(), 0) tcount = case_counter.get(word.title(), 0) if lcount == 0 and ucount == 0 and tcount == 0: ...
def _package_exists(module_name: str): """Check if a package exists""" mod = __import__(module_name) return mod is not None
def hexify(number): """ Convert integer to hex string representation, e.g. 12 to '0C' """ if number < 0: raise ValueError('Invalid number to hexify - must be positive') result = hex(int(number)).replace('0x', '').upper() if divmod(len(result), 2)[1] == 1: # Padding resul...
def mergelistadd(lst1,lst2): """returns the sum at each index comparing 2 lists""" try: return [lst1[i]+lst2[i] for i in range(len(lst1))] except: print('incompatible lists')
def remove_private_prefix(attr_name: str, prefix: str) -> str: """Return the specified attribute name without the specified prefix.""" return attr_name[len(prefix):]
def sgn(x): """a simple sign function""" if(x < 0): return -1 return 1
def _qt_list(secondary_dict_ptr, secondary_key_list_ptr, cols, key): """ This sub-function is called by view_utils.qt to add keys to the secondary_key_list and is NOT meant to be called directly. """ if cols[key]: if cols[key] not in secondary_key_list_ptr: secondary_key_list_pt...
def parseOneDigit(n): """Given a single digit 1-9, return its name in a word""" if n == 1: return "One " elif n == 2: return "Two " elif n == 3: return "Three " elif n == 4: return "Four " elif n == 5: return "Five " elif n == 6: return "Six " ...
def div(x, y): """ Compute integer division x//y. """ # find largest shift less than x i = 0 s = y while s < x: s <<= 1 i += 1 s >>= 1 i -= 1 d = 0 rem = x while i >= 0: if s < rem: rem -= s d += 1<<i i -= 1 ...
def det(a: list) -> int: """ Calculates the determinant of a 2x2 Matrix, via the shortcut (a*d) - (b*c) :param a: The matrix A. :return: The determinant. """ d= (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]) return d
def sequence_identity(a, b, gaps='y'): """Compute the sequence identity between two sequences. The definition of sequence_identity is ambyguous as it depends on how gaps are treated, here defined by the *gaps* argument. For details and examples, see `this page <https://pyaln.readthedocs.io/en/latest/t...
def linear_full_overlap(dep_t, dep_h): """Checks whether both the head and dependent of the triplets match.""" return (dep_h[0] in dep_t[0]) and (dep_h[2] in dep_t[2])
def min_square_area(x: int, y: int): """ """ smallest_side = min(x, y) longest_side = max(x, y) square_side = 2*smallest_side if square_side < longest_side: square_side = longest_side return square_side * square_side
def weighted_mean(x,w): """ Given equal length vectors of values and weights """ return sum(xi*wi for xi,wi in zip(x,w)) / sum(w)
def get_unique(items): """ Get a list of unique items, even for non hashable items. """ unique_list = [] for item in items: if not item in unique_list: unique_list.append(item) return unique_list
def CSVWriter (iterable, outLoc, header="", ): """ Writes an iterable to a CSV file. :param iterable: List of list :param outLoc: file location. Where to place it. :param header: header of the CSV file :return: 1 """ if not iterable: print ("nothing to write") return 0 ...
def contar_letras (cadena: str, letras: str): """Cuenta la cantidad de letras especificas en la cadena Argumentos: cadena (str) -- cadena sobre la que contar letra (str) -- letra que quiero contar """ cuenta = 0 for caracter in cadena: if caracter == letras: ...
def simple_two_params(one, two): """Expected simple_two_params __doc__""" return "simple_two_params - Expected result: %s, %s" % (one, two)
def _get_date_or_none(panda_date_or_none): """ Projection Null value is a string NULL so if this date value is a string, make it none. Otherwise convert to the python datetime. Example of this being null is when there is no bed shortfall, the shortfall dates is none """ if isinstance(panda_date_or_non...
def Swap(x, **unused_kwargs): """Swap the first two element on the stack.""" if isinstance(x, list): return [x[1], x[0]] + x[2:] assert isinstance(x, tuple) return tuple([x[1], x[0]] + list(x[2:]))
def maxTabCount(edgeLen, width, minDistance): """ Given a length of edge, tab width and their minimal distance, return maximal number of tabs. """ if edgeLen < width: return 0 c = 1 + (edgeLen - minDistance) // (minDistance + width) return max(0, int(c))
def get_extrapolated_flux(flux_ref, freq_ref, spectral_index): """ Computes the flux density at 843 MHz extrapolated from a higher/lower flux density measurement & some assumed spectral index. input: ------ flux_ref: float Reference flux density, usually S400 or S1400 [mJy]. freq_re...
def canonicalize_job_spec(job_spec): """Returns a copy of job_spec with default values filled in. Also performs a tiny bit of validation. """ def canonicalize_import(item): item = dict(item) item.setdefault('in_env', True) if item.setdefault('ref', None) == '': raise...
def max_value(knapsack_max_weight, items): """ Get the maximum value of the knapsack. """ values = [0 for _ in range(knapsack_max_weight+1)] for item in items: for weight in range(knapsack_max_weight, item.weight-1, -1): values[weight] = max(values[weight], values[weight - item.w...
def decifrador(lista, senha=0): """ :param lista: recebe a lista com os elementos separados :param senha: numeros de trocas de letras :return: a lista com as palavras traduzidas """ varTemp = list () stringTemp = '' alfabeto = ['a', 'b', 'c', 'd', 'e', 'f', 'g'...
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' ...
def calculate_mass( mono_mz, charge ): """ Calculate the precursor mass from mono mz and charge """ M_PROTON = 1.00727646687 prec_mass = mono_mz * abs(charge) - charge * M_PROTON return prec_mass
def next_collatz_number(int_value, k=3, c=1): """ This method calculates the next Collatz number for a given int value. :param int_value: The int value to calculate the next Collatz number for. The value must be a natural number > 0. :param k: The factor by which odd numbers are multiplied in t...
def remove_blanks(d): """ Returns d with empty ('' or None) values stripped """ empty_keys = [] for key in d: if d[key]=='' or d[key]==None: # del d[key] raises runtime exception, using a workaround empty_keys.append(key) for key in empty_keys: del d[key] return d
def truncate_response_data(response_data, block_size=4): """ Truncates pagination links. We don't want to show a link for every page if there are lots of pages. This replaces page links which are less useful with an ``...`` ellipsis. :param response_data: Data supposed to be passed to :cla...
def site_url(request, registry, settings): """Expose website URL from ``tm.site_url`` config variable to templates. .. note :: You should not use this variable in web page templates. This variable is intended for cases where one needs templating without running a web server. The correct way to ge...
def parse_by_category(category, data): """ filters database content by category from dumps :param category: accepts string :param data: accepts multi-dimensional iterable data type :return: returns filtered multi-dimensional LIST containing TUPLES """ new_dat = [] for entry in ...
def binary_search(a, key, index=0, iteration=0): """ a (list) : a sorted list """ if len(a) == 1 and a[0] != key: return -1 m = len(a) // 2 # m for middle of the array if a[m] == key: return index + m elif a[m] > key: return binary_search(a[0:m], key, index, iteration + 1) el...
def messpf_inp_str(globkey_str, spc_str): """ Combine various MESS strings together to combined MESSPF """ return '\n'.join([globkey_str, spc_str]) + '\n'
def convert_to_tq_format(topic, question): """creates a string that is uniform in the "T?.Q?.A? format; without the A""" return "T"+str(topic)+".Q"+str(question)
def class_counts(y, n): """ >>> class_counts([2, 1, 1, 0, 1, 2], 3) [1, 3, 2] """ return [len([yj for yj in y if yj == yi]) for yi in range(n)]
def translate_confidence_level(level): """ return confidence level """ if level is None or level == 'LOW': return '-i' if level == 'MEDIUM': return '-ii' if level == 'HIGH': return '-iii' raise ValueError(f'{level} is not a valid confidence level')
def get_gene_name(line): """ Input: A line read in from a txt or csv file from some proteomic data that contains a 'GN=' part before the gene name Output: The gene name pulled out of the line """ gene = "" start = line.find("GN=") while line[start+3] != " ": gene += line[sta...
def two_adjacent_digits_same(number: int) -> bool: """Two adjacent digits are the same (like 22 in 122345).""" previous = None for digit in str(number): if digit == previous: return True previous = digit return False
def integer_to_binary_str(n): """ Returns a string representing the conversion into binary of the integer entered as a parameter. :param: *(int)* :rctype: *str* :UC: n >= 0 :Examples: >>> integer_to_binary_str(0) '0' >>> integer_to_binary_str(8) '1000' >>> integer_to_binary_s...
def summarize_metrics(all_metrics): """ Returns a subset of the metrics dictionary with only f1,f0.5,recall and precision values :param all_metrics: :return: """ metric_names = ['f1', 'recall', 'precision', 'f0.5', 'num_samples','num_metrics'] # The keys to keep return dict((k, all_metrics[...
def parse_accept_header(accept): """ Parse the Accept header *accept*, returning a list with 3-tuples of [(str(media_type), dict(params), float(q_value)),] ordered by q values. If the accept header includes vendor-specific types like:: application/vnd.yourcompany.yourproduct-v1.1+json It w...
def rectangles_intersect(rect1, rect2): """Returns True if two rectangles intersect.""" return all([(rect1[1][i] >= rect2[0][i]) and (rect2[1][i] >= rect1[0][i]) for i in range(2)])
def _get_sstable_proto_dict(*input_values): """Returns table key -> serialized proto map. This function exists because the create_parse_tf_example_fn operates on dequeued batches which could be 1-tuples or 2-tuples or dictionaries. Args: *input_values: A (string tensor,) tuple if mapping from a RecordIO...
def get_color_from_score(score): """Returns color depending on the score""" color = "hsl(184, 77%, 34%)" if score < 20: color = "hsl(360, 67%, 44%)" elif score < 50: color = "hsl(360, 71%, 66%)" elif score < 80: color = "hsl(185, 57%, 50%)" return color
def get_thresholds(points=100, power=3) -> list: """Run a function with a series of thresholds between 0 and 1""" return [(i / (points + 1)) ** power for i in range(1, points + 1)]
def center_x(cell_lower_left_x, cell_width, word_length): """ This function centers text along the x-axis :param cell_lower_left_x: Lower left x-coordinate :param cell_width: Width of cell in which text appears :param word_length: Length of plotted word :return: Centered x-position """ ret...
def remove_prefix(text, prefix): """Removes the prefix `prefix` from string `text` in case it is present.""" return text[len(prefix):] if text.startswith(prefix) else text
def compare_snpchecks(sangerdict, ngsdict): """Compare values from 2 dicts with overlapping keys. NGS-dict contains all keys from sangerdict. Create dict with loci as keys and ok or ERROR as values. Ok when both values are the same, ERROR if not. Return a dict. """ out = dict() for k, v in sange...
def gf_mul_const(f, a, p): """Returns f * a where f in GF(p)[x] and a in GF(p). """ if not a: return [] else: return [ (a*b) % p for b in f ]
def color565(r, g, b): """Return RGB565 color value. Args: r (int): Red value. g (int): Green value. b (int): Blue value. """ return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3
def format_str_strip(form_data, key): """ """ if key not in form_data: return '' return form_data[key].strip()
def sim_max(terms1, terms2, sem_sim): """Similarity score between two term sets based on maximum value """ sims = [] for t1 in terms1: for t2 in terms2: sim = sem_sim(t1, t2) if sim is not None: sims.append(sim) return round(max(sims), 3)
def RGB2YCbCr(RGB): """ This is a fast version, that sometimes differes by 1. It can be easily cythonized. """ R, G, B = RGB Y = ( ( 66 * R + 129 * G + 25 * B + 128) >> 8) + 16 Cb = ( ( -38 * R - 74 * G + 112 * B + 128) >> 8) + 128 Cr = ( ( 112 * R - 94 * G - 18 * B + 128) >> 8) +...
def return_converted_dict(key, *value): """this method create dict from token key and value parameters. It is converted element of list, if parameters of this method get the str. NOTE ---- if you give str to parameters of this method, Dictionary return key will be unexpected Parameters...