content
stringlengths
42
6.51k
def get_parlabel(pid): """Return label for a list of parameter ids Parameter: pid - list of parameter ids""" master = ['log $M_b$', '$a_b$', 'log $M_d$', '$a_d$', '$b_d$', '$V_h$', '$R_h$', '$\phi$', '$q_x$', '$q_y$', '$q_z$', '$a_{1,-1}$', '$a_{1,0}$', '$a_{1,1}$', '$a_{2,-2}$', '$a_{2,-1}$', '$a_...
def pMorphIa( morphology ): """ P(D|Ia) : The probability that one would observe a SN host galaxy to have the given morphology, assuming that the SN is of type Ia Morphology may be specified as a hubble type : [ 'E', 'S0', 'Sa', 'Sb', 'Sbc', 'Sc', 'Scd', 'Irr' ] or using the CANDELS visual ...
def mult2(A, B): """list comprehension method """ m = len(A) n = len(B) q = len(B[0]) return [[sum(A[i][k]*B[k][j] for k in range(n)) for j in range(q)] for i in range(m)]
def find_pattern_in_iter(start_pattern, function, goal = None, n_iter=1000000000): """ Returns when a SPECIFIED pattern has been found from a function If goal = None, then first time the start pattern shows up again is returned Returns steps, pattern """ if not goal: goal = start_pat...
def index(m, val): """Return the indices of all ``val`` in m""" m = list(m) idx = [] if m.count(val) > 0: idx = [i for i, j in enumerate(m) if j == val] return idx
def count_above(obj, n): """ Return tally of numbers in obj, and sublists of obj, that are over n, if obj is a list. Otherwise, if obj is a number over n, return 1. Otherwise return 0. >>> count_above(17, 19) 0 >>> count_above(19, 17) 1 >>> count_above([17, 18, 19, 20], 18) 2 ...
def end_other(a, b): """ Function to compare two strings ending. Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Args: a (String)...
def interval_toggle(swp_on, mode_val, dt): """change the interval to high frequency for sweep""" if dt <= 0: # Precaution against the user dt = 0.5 if mode_val == 'single': return 1000000 else: if swp_on: return dt * 1000 else: return 10000...
def ignore_port(port_num): """Return True if FAUCET should ignore this port. Args: port_num (int): switch port. Returns: bool: True if FAUCET should ignore this port. """ # 0xF0000000 and up are not physical ports. return port_num > 0xF0000000
def _coord_add(tup1, tup2): """add two tuples of size two""" return (tup1[0] + tup2[0], tup1[1] + tup2[1])
def _merge_subdicts(root: dict) -> dict: """ Merge/flatten nested dictionaries into one. """ res = root[0].copy() for sub in root[1:]: res.update(sub) return res
def growth_calculation(val1, val2, t1, t2): """Calculate cumulative annual growth rate with required arguments. Args: val1: float. Current value. val2: float. Value from base year. t1: float. Current year. t2: float. Base year. Returns: float: Growth value. """ ...
def largest_continuous_product(series, adjacent): """ Function returns the largest product of adjacent numbers within the given series. REQ: type(series) == str and int(series) REQ: type(adjacent) == int :param series: {string} series of whole integers within a string :param adjacent: {int} nu...
def cycle_slice(sliceable, start, end): """Given a list, return right hand cycle direction slice from start to end. Usage:: >>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> cycle_slice(array, 4, 7) # from array[4] to array[7] [4, 5, 6, 7] >>> cycle_slice(array, 8, 2) # from arra...
def _version_split(version): """ Split a version string into major, minor, and bugfix numbers (with bugfix optional, defaulting to 0). """ for prerel in ('.dev', 'a', 'b', 'rc'): if prerel in version: version = version.split(prerel)[0] versplit = version.split('.') majo...
def location( authority ): """Extracts the location (host:port).""" end = authority.find('@') if -1 == end: return authority return authority[1+end:]
def count_occurrences(obj_list, params_to_count, output='dict'): """ Count occurrences of each param value for list of dicts :param obj_list: :param params_to_count: :param output: str (list or dict). list - for plots :return: param_counts: dict """ param_counts = {} for obj in obj_...
def get_notes_by_song(song, notes_map): """ Iterate over all labels for a given song to extract notes """ notes = {} for segment in song: # (start,end,(instrument,note,measure,beat,note_value)) if segment[2][1] not in notes_map: continue note = notes_map[segme...
def is_version_equal_or_higher(lowest_version, framework_version): """Determine whether the ``framework_version`` is equal to or higher than ``lowest_version`` Args: lowest_version (List[int]): lowest version represented in an integer list framework_version (str): framework vers...
def virial_temp_HB(mass, z): """Virial temperature from halo mass according to Haiman & Bryan (2006ApJ...650....7). z is the redshift. Units are Msun and kelvin. """ return 1800. * (mass/1e6)**(2./3.) * (1.+z)/21
def to_camel_case(snake_str: str) -> str: """ Convert a snake_case string to camelCase. :param snake_str: The input in snake_case :return: The input, but in camelCase """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the...
def warmup_linear_flat(x, warmup=0.002): """ Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step. After `t_total`-th training step, learning rate is fixed. """ if x < warmup: return x/warmup return 1.0
def clean_javascript(js): """ Remove comments and all blank lines. """ return "\n".join(line for line in js.split("\n") if line.strip() and not line.startswith("//"))
def adjustLearningRate(learning_rate, decay_rate, epoch_num): """ Adjust Learning rate to get better performance :param learning_rate: :param decay_rate: :param epoch_num: :return: """ return learning_rate / (1 + decay_rate * epoch_num)
def time_converter(seconds): """Converts time (in seconds) in more understandable format. Example: time_conversion(131623.456) --> Script execution finished after 1 day, 12 hours and 33 minutes.""" total_seconds = seconds days = seconds // (24 * 3600) seconds = seconds % (24 * 3600) hours = ...
def sizeof_fmt(num, suffix='B'): """ Pretty print storage units. Source: https://stackoverflow.com/questions/1094841/ reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "...
def jaccard_subset_numeric(left: float, right: float) -> float: """ Operates on pre-computed areas to help reduce redundant calculations. Calculates the jaccard distance assuming `right` is a subset of `left`. Parameters ---------- left, right: pandas.Series left, right: float """ return (left - right) / left
def all_appear_lower_not_at_sentence_beginning(word, title, sents): """ If all mentions of the token in the text not at the beginning of the sentence are lower cased >>> title = [u"Feng", u"Chao", u"Liang", u"Blah", u"hehe"] >>> doc = [[u"Feng", u"chao", u"Liang", u"is", u"in", u"Wuhan", u".", u"hehe"]...
def bool_to_int(value: bool): """Turn boolean into 1 or 0.""" if value is True: return 1 else: return 0
def make_sentiment(value): """Return a sentiment, which represents a value that may not exist. >>> positive = make_sentiment(0.2) >>> neutral = make_sentiment(0) >>> unknown = make_sentiment(None) >>> has_sentiment(positive) True >>> has_sentiment(neutral) True >>> has_sentiment(unk...
def wall_to_wall_distance(len0, len1, diag): """Wall to wall distance for a diagonal position .. math:: L = \\min(l_0 - d, l_1) + \\min(d, 0) with :math:`l_0,l_1` being the length of the sequences (i.e ``len0`` and ``len1`` arguments) and :math:`d` the starting diagonal (i.e ``diag`` argum...
def organize_by_source_db(g_summary): """ returns a dictionary of { source_db_name: { 'sourcelabels': { 'targetlabels': { 'edge_type': count } } } } """ organized = {} for item in g_summary: db_name = item['source_db'] db_summary =...
def pathCost(path, g, wt="weight"): """ Compute the cost of the given path in a graph. Parameters ---------- path : list a path given as a node list. g : networkx.Graph a networkx graph or directed graph where links have some type of weight attribute. wt : string (option...
def intervals2positions(intervals, strand, hstart, hstop): """ Turns intervals to positions depending on strand""" positions = [] if strand == "+": for i in intervals: positions.append((hstart + i[0],hstart + i[1])) elif strand == "-": for i in intervals: position...
def _validProbabilities(probabilities, task_responses, trial_responses): """ Takes the list of probabilities, valid responses and possible responses and returns the appropriate probabilities and responses Parameters ---------- probabilities : 1D list or array The probabilities f...
def _check_hdr_version(header): """Check the header version.""" if header == 'Brain Vision Data Exchange Header File Version 1.0': return 1 elif header == 'BrainVision Data Exchange Header File Version 1.0': return 1 elif header == 'Brain Vision Data Exchange Header File Version 2.0': ...
def extract_lsb(n): """Extract thee least significant bit""" byte_string = bin(n) return byte_string[-1]
def interpreted_fact(n): """Computes n!""" if n <= 1: return 1 return n * interpreted_fact(n - 1)
def get_transition_sites(class_sequence): """ given class sequcne, finds transition sites. args: - class_sequence: the sequence of k-means classes. I recommand using the output of [merge_classes] function """ current_class = class_sequence[0] transition_sites = [] transition_sites.ap...
def hms2deg(angle): """Convert sexagesimal HH:MM:SS.sss to decimal degrees""" h, m, s = angle.split(':') hours = float(h) + float(m)/60. + float(s)/3600. return hours / 24. * 360.
def add_source(os_url, kibana_url, default_url, frequency, user_secret, created_By, created_on, volume, service): """ Add _source information """ _source = {} _source["os_url"] = os_url _source["kibana_url"] = kibana_url _source["default_url"] = default_url _source["frequency"] ...
def make_paired_cycle_list(cycle_list): """Pairs up cycles together into tuples of intakes and outakes. Intakes are the first items and outakes are the second items in each cycle tuple. cycle_list is the list of actions that need to be paired up.""" # [::2] are the even-indexed items of the list, ...
def degree_to_n_coeffs(degree): """how many coefficients has a 2d polynomial of given degree""" return int((degree+1)*(degree+2)/2.+0.5)
def is_in_overlapping_region(readpos, contiglength, readlength, regionlength): """Determine if the read is in a location where the searchable region on both tips is .""" return readpos - readlength <= regionlength and readpos >= contiglength - regionlength
def absolute_value(num): """ This function returns the absolute value of the entered number.""" if num >= 0: return num else: return -num
def choose_colour(wtr: int) -> int: """ Choose a colour to represent the wtr :param wtr: the wtr :return: a hex integer of the colour """ if not wtr or wtr < 300: return 0x930D0D elif wtr < 700: return 0xCD3333 elif wtr < 900: return 0xCC7A00 elif wtr < 1000: ...
def pre_cast_integer(probe): """ A str that cannot be casted as integer is set to 0 in MySQL. This Function return None (NULL SQL equivalent) if not castable. :param probe: SQL probe to cast or not. """ return str(probe) if probe.__class__ is int else probe if probe.isnumeric() is True else ...
def determinent3d(x1,y1,z1,x2,y2,z2,x3,y3,z3): """calculate the determinent of 3*3 matrix """ return (x1*y2*z3 + y1*z2*x3 + z1*x2*y3 - x1*z2*y3 - y1*x2*z3 - z1*y2*x3)
def vecMultiplyAdd(inVecA, inVecB, inMM): """returns inVecA + (inMM * inVecB)""" return [inVecA[0] + inMM * inVecB[0], inVecA[1] + inMM * inVecB[1], inVecA[2] + inMM * inVecB[2]]
def calc_upper_diagonal_idx_ij(i, j, n_total_atoms): """ Return the index for the (i, j) pair in a flattened upper diagonal with n_total_atoms sum_i(n-i)) + (j-i-1) Requirement -------------------- i < j < n_total_atoms """ if i > j: i, j = j, i return i * n_total_atoms - i ...
def strikethrough(text: str) -> str: """Get the given text with a strikethrough. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "~~{}~~".format(text)
def none2zero(v): """None -> zero.""" if v is None: return 0 return v
def get_multiples_3_or_5(n): """Get all multiples of 3 or 5 below n""" return [number for number in range(3, n) if (number % 3 == 0) or (number % 5 == 0)]
def _i_need_a_cat(status_code, active, want): """ This function tell you if you need a cat in your response :param status_code: response status_code :param active: activated :param want: want it right now :return: True if you needed, false otherwise """ return status_code > 400 or activ...
def per_mode_mini(x): """Takes Numeric Code and returns String API code Input Values: 1:"Totals", 2:"PerGame" Used in: """ measure = {1: "Totals", 2: "PerGame"} try: return measure[x] except: raise ValueError("Please enter a number between 1 and " + str(len(measure)))
def parse_palette(s): """Parse a palette string with up to 12 hex digits.""" b = bytes.fromhex(s) if len(b) > 6: raise ValueError("too many colors in palette string (%d, more than 6)" % len(b)) p = [b[:3]] if len(b) > 3: p.append(b[3:]) return p
def pad_equal_whitespace(string, pad=None): """Given a multiline string, add whitespaces to every line so that every line has the same length.""" if pad is None: pad = max(map(len, string.split('\n'))) + 1 return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n'))
def _matches_location(price, location): """Return True if the price object matches the location.""" # the price has no location restriction if not price.get('locationGroupId'): return True # Check to see if any of the location groups match the location group # of this price object for g...
def ssh_login_command(host, port=22): """ Return the SSH shell command that can be used to log in to remote machine :param str host: Host to log in to :param int port: Port to connect with :return str ssh_command: An SSH command """ ssh_command = "ssh root@{} -p {} " \ "-oS...
def hamdist(str1, str2): # From http://code.activestate.com/recipes/499304-hamming-distance/ """Count the number of differences between equal length strings str1 and str2""" diffs = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diffs += 1 return diffs
def efficientnet_params(model_name): """Get efficientnet params based on model name, from official code, differ with paper""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate) 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2...
def quote(s): """Returns quoted PO term string, with special PO characters escaped""" assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s return '"%s"' % s.replace('\\','\\\\') \ .replace('"','\\"') \ ...
def add_subplot(plotfig, subrows=1, subcols=1, subno=1, **kwargs): """ Add a new subplot to an existing figure. Matplotlib wrapper. This function allows a caller to create a figure and add subplots to it without needing to import the matplotlib library separately. :Parameters: plotfig...
def merge_config(args, config): """This function merges the args and the config together. The command line arguments are prioritized over the configured values. :param args: command line arguments :type args: dict :param config: option from the config file :type config: dict :return: dict w...
def decimal_rep(a): """ Returns decimal representation of a """ div = 1 stack = list() if a == 0: return '0' while a > 0: rem = a % 2 a = a // 2 stack.append(rem) stack.reverse() return ''.join([str(x) for x in stack])
def ack(m, n): """Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers """ if m == 0: return n + 1 if (m > 0) and (n == 0): return ack(m - 1, 1) if (m > 0) and (n > 0): return ack(...
def parse_assignment(line): """Helper method to parse the lines with assignment(=) operator in them. Args: line (str): Line read from the WiFi configuration file. Returns: tuple: Tuple with name and value strings. """ while True: # Ignore comments. if line.startswit...
def make_header_map(line, separator='\t'): """Returns a dictionary of "column header":index """ header_map = {} if not line: return header_map # split line at separator and populate dictionary (remove double quotes around header) headers = line.split(separator) for i, heade...
def prod(iterable): """Equivalent to :func:`math.prod` introduced in Python 3.8. """ out = 1 for i in iterable: out = out * i return out
def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is longer than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit inte...
def _compare_strings(*args): """ Compare two or more strings. Return True if all equals. """ if not args: return True compared_item = str(args[0]).strip() for item in args[1:]: if compared_item != str(item).strip(): return False return True
def s_bit_cost(v): """ Max bits required to represent up to the given number """ if v>=64: return 7 if v>=32: return 6 if v>=16: return 5 if v>=8: return 4 if v>=4: return 3 if v>=2: return 2 if v>=1: return 1 return 0
def _maybeEncode(someStr): """ Encode `someStr` to ASCII if required. """ if isinstance(someStr, str): return someStr.encode('ascii') return someStr
def parse_results(results): """Break up multiline output from ls into a list of (name, size) tuples.""" return [(line.split()[1], int(line.split()[0])) for line in results.splitlines() if line.strip()]
def earnings(a, b, c): """ >>> earnings(100, 100, 100) 3600 >>> earnings(50, 75, 100) 2550 >>> earnings(0, 1000, 79) 12711 """ return (15 * a) + (12 * b) + (9 * c)
def clean_empty(l): """ >>> clean_empty(["a", "", "c"]) ['a', 'c'] """ return list(filter(lambda x: x != "", l))
def bin_to_hex(bs): """Convert a bit stream into hexadecimal :param bs: the bit stream (list) :returns: an hexadecimal string """ bs = ''.join(bs) tmp = hex(int(bs, 2))[2:].strip('L') pad = ''.join('0' for i in range(len(tmp), len(bs)//4)) tmp = pad + tmp return str(tmp).upper()
def readall(read_fn, sz): """Reads `sz` bytes using `read_fn` Raises `EOFError` if `read_fn` returned the empty byte array while reading all `sz` bytes. """ buff = b'' have = 0 while have < sz: chunk = read_fn(sz - have) have += len(chunk) buff += chunk if l...
def expandtabs(self, tabsize=8): """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return self.replace("\t", " " * tabsize)
def list_codepoints(_astr): """lists the codeponts in string""" result = list() for achar in _astr: result.append('U+{:04X}'.format(ord(achar))) return result
def weektype(weeklyRtn): """This function does something. :param name: The name to use :type name: None :param state: None :type state: None :returns: None :raises: None """ #print('in weektype') if abs(weeklyRtn)<0.015: return 1 elif weeklyRtn>0.015: return 2 else: r...
def cache_name(filebase): """ return name of file in cache (abstracted to allow smarter options for cache configuration in future) Parameters ---------- filebase : string """ return "cache/%s.ttl" % (filebase,)
def any_positive_or_none(*args): """Return None if any argument is negative and the list of its argument otherwise""" for arg in args: if arg < 0: return None return list(args)
def get_client_login_token_string(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login ...
def apply_threshold(weights, goal): """ Returns a set of keywords such that the set is of minimal size, but the goal is met. The goal should be a float from 0 to 1.0 representing the fraction of the total body of keywords that should be represented by the keyword set. Currently weights are a simple frac...
def isinstance_by_name(obj, ref): """IPython reload can make isinstance(Obj(), Obj) fail; won't work if Obj has __str__ overridden.""" def _class_name(obj): name = getattr(obj, '__qualname__', getattr(obj, '__name__', '')) return (getattr(obj, '__module__', '') + '.' + name).lstrip('.') ...
def factorial(number): """ A function to calculate factorial of a number. param number: integer """ if number is None or not isinstance(number , int): raise Exception("Entered number must be of type 'int' ") if number == 0: return 1 result=1 #added for the small numb...
def average(v, state): """ This function is used to output a stream where the n-th value on the output stream is the average of the first n values of the input stream. The state of the input stream is the pair (n,cum). When used to create a stream, n is the number of values received on ...
def freeze(floors): """Freeze floors so they can be hashed.""" return tuple(frozenset(f) for f in floors)
def assert_same_and_get(*args): """ Verifies that all the arguments are the same, and returns this value. For example, assert_same_and_get(5, 5, 5) will return 5, and assert_same_and_get(0, 1) will raise an AssertionError. """ assert len(set(args)) == 1, 'Values are not the same (%s)' % (args,) ...
def knuth_sum(a, b): """Error-free transformation of the sum of two floating point numbers according to D.E. Knuth. The Art of Computer Programming: Seminumerical Algorithms, volume 2. Addison Wesley, Reading, Massachusetts, second edition, 1981. The underlying problem is that the exact sum a+...
def _parse_user_build_input(input): """ Parse user input specification. Used in build for specific parents and input parsing. :param Iterable[Iterable[str], ...] input: user command line input, formatted as follows: [[fasta=txt, test=txt], ...] :return dict: mapping of keys, which are input nam...
def extract_list_item(source_data, item_pos): """Extract specific items from a list of lists. Extracts the item in item_pos from each list within a list of lists and returns a list with just the extracted items. Args: source_data (list): A list of lists. Returns: e...
def conceptnet_create_search_query(input_dict): """ Constructs a Conceptnet search query. """ input_limit = input_dict['limit'] input_offset = input_dict['offset'] input_text = input_dict['text'] input_minweight = input_dict['minweight'] query = "search?" if input_limit != None...
def find_word(string, start=0): """Find the first word starting from `start` position Return the word and the position before and after the word """ while start < len(string) and string[start].isspace(): start += 1 end = start while end < len(string) and not string[end].isspace(): ...
def find_lcs(s1, s2): """find the longest common subsequence between s1 ans s2""" m = [[0 for i in range(len(s2)+1)] for j in range(len(s1)+1)] max_len = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: m[i+1][j+1] = m[i][j]+1 ...
def label_book(book_title): """ converts the book title into an 'expansish' label (replace upper- with lowercase and use "_" instead of whitespace) :param book_title: book title :return: formatted book title """ return ''.join(char.lower() if char.isupper() else char.upper() for char in book_ti...
def bin_to_pc(binary, pcp_size=36): """ Returns the pitch-class of the specified pcp vector. It assumes (bin[0] == pc9) as implemeted in Essentia. """ return int((binary / (pcp_size / 12.0)) + 9) % 12
def similarity(lst1, lst2): """! \details Evaluates similarity as done in intersection function but doesn't return locations of common hashes """ l1h = [h[0] for h in lst1] l2h = [h[0] for h in lst2] l3h = list(set(l1h)&set(l2h)) sim = len(l3h)/min(len(set(l1h)), len(set(l2h))) return sim
def bspline(knots, x, i, n): """ Evaluate the ith nth-order B-spline basis function at x. :param knots: a sequence of knot positions :param x: the position at which to evaluate the spline :param i: the index of the basis function :param n: the order of the spline :returns: float - the value of the spline at x ...