content
stringlengths
42
6.51k
def readHysteresisDelayfromGUI(delay, timeZero): """ Read and create Hysteresis Delays from GUI. The values are given relative to the timezero (so -20 means 20ps before the set t0). The returned value is the absolute ps Delay for the setting of the stage. :param delay, timeZero: :return: delayV...
def get_readable_file_size(size): """ Returns a human-readable file size given a file size in bytes: >>> get_readable_file_size(100) '100.0 bytes' >>> get_readable_file_size(1024) '1.0 KB' >>> get_readable_file_size(1024 * 1024 * 3) '3.0 MB' >>> get_readable_file_size(1024**3) '...
def hsl2rgb(hsl): """Convert an HSL color value into RGB. >>> hsl2rgb((0, 1, 0.5)) (255, 0, 0) """ try: h, s, l = hsl except TypeError: raise ValueError(hsl) try: h /= 360 q = l * (1 + s) if l < 0.5 else l + s - l * s p = 2 * l - q e...
def z_score(point, mean, stdev): """ Calculates z score of a specific point given mean and standard deviation of data. parameters: point: Real value corresponding to a single point of data mean: Real value corresponding to the mean of the dataset stdev: Real value corresponding to the standard deviation of the...
def is_example_dag(imported_name: str) -> bool: """ Is the class an example_dag class? :param imported_name: name where the class is imported from :return: true if it is an example_dags class """ return ".example_dags." in imported_name
def getDistinctElt(transactions): """ Get the distinct element in a list of transactions. """ distinctSet = set() for transaction in transactions: for elt in transaction: if not(elt in distinctSet): distinctSet.add(elt) return distinctSet
def fibonacci(n): """ accepts fibonacci number, returns nth number """ """ Using the fibonacci number sequence""" if n==1: return 0 elif n==2: return 1 else: return fibonacci(n-1)+fibonacci(n-2)
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints)<= 0: return min_num = ints[0] max_num = ints[0] for i in range(1, len(ints)): if ints[i] ...
def _indexed_tags(tags): """Returns a list of tags that must be indexed. The order of returned tags is from more selective to less selective. """ if not tags: return [] return sorted(set( t for t in tags if t.startswith(('buildset:', 'build_address:')) ))
def get_role_name(session, role_arn): """ Get function role name based on role_arn Parameters ---------- session : :class:`Session` AWS Boto3 Session. See :class:`Session` for creation. role_arn : str Role arn Returns ------- str Role name. Returns N...
def get_details(string): """ input: "sina bakhshandeh 17" output: ["sina" , "bakhshandeh", 17] """ string = string.split() string[2] = int(string[2]) return string
def to_title_ex(text): """ Description: Convert text to title type and remove underscores. ( Exclusive for core json to html conversion process) :param text: raw text :return: Converted text """ return str(text).title().replace('_', ' ')
def dopplerShift(wvl, flux, v): """Doppler shift a given spectrum. Does not interpolate to a new wavelength vector, but does shift it. """ # Shifted wavelength axis wlprime = wvl * (1.0 + v / 299792.458) return flux, wlprime
def gnome_sort(arr): """ Examples: >>> gnome_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> gnome_sort([]) [] >>> gnome_sort([-2, -45, -5]) [-45, -5, -2] """ # first case size = len(arr) if size <= 1: return arr ind = 0 # while loop ...
def reversed_tom(liste: list) -> list: """ Return the reversed list. :param liste: list to be returned :return: returned list """ liste.reverse() return liste
def gen_endpoint_scaling(endpoint_name, scaling_policy_name, scale_config): """ Generate the endpoint scaling resource """ endpoint_scaling = { "ScalingTarget": { "Type": "AWS::ApplicationAutoScaling::ScalableTarget", "Properties": { "MaxCapacity": scale_c...
def fizz_buzz(n): """Returns fizz when divisible by 3 Returns buzz when divisible by 5 and fizzbuzz if divisible by both 3 and 5""" if n % 3 == 0 and n % 5 == 0: return 'fizzbuzz' elif n % 3 == 0: return 'fizz' elif n % 5 == 0: return 'buzz'
def asbool(val): """ Parse string to bool. """ val = str(val.lower()) if val in ('1', 't', 'true', 'on'): return True elif val in ('0', 'f', 'false', 'off'): return False else: raise ValueError()
def generate_reads(read_seq, read_pos, ref_alleles, alt_alleles): """Generate set of reads with all possible combinations of alleles (i.e. 2^n combinations where n is the number of snps overlapping the reads) """ reads = [read_seq] # iterate through all snp locations for i in range(len(read_...
def _detector_from_source(parameter, z): """Return the detector-frame parameter given samples for the source-frame parameter and the redshift """ return parameter * (1. + z)
def __format_datetime_input(datetime_input, language): """Formats the specified datetime input. Args: datetime_input (dict): A datetime input configuration to format. language (dict): A language configuration used to help format the input configuration. Returns: dict: A formatted d...
def sub(proto, *args): """ This really should be a built-in function. """ try: text = proto.format(*args) except: text = "--" #print sub("WARNING: Couldn't sub {} with {}", proto, args) return text
def coords_to_sdss_navigate(ra, dec): """ Get sdss navigate url for objects within search_radius of ra, dec coordinates. Default zoom. Args: ra (float): right ascension in degrees dec (float): declination in degrees Returns: (str): sdss navigate url for objects at ra, dec ""...
def sanitize_cloud(cloud: str) -> str: """ Fix rare cloud layer issues """ if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] != '/': if cloud[3] == 'O': cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003 else: # Move modifiers t...
def palindromeStr(x: str) -> bool: """ Checks whether a `string` is a `Palindrome` or not. After checking returns `True` if a `String` is a `Palindrome` else `False` Args: This function takes exactly one argument. `x:str` : x should be a string data type for the palindrome test """ re...
def find_project(testrun_url): """ Find a project name from this Polarion testrun URL. :param testrun_url: Polarion test run URL :returns: project name eg "CEPH" or "ContainerNativeStorage" """ url_suffix = testrun_url[59:] index = url_suffix.index('/') return url_suffix[:index]
def perpedicular_line(line, p): """ Returns a perpendicular line to a line at a point. Parameters ---------- line : (1x3) array-like The a, b, and c coefficients (ax + by + c = 0) of a line. p : (1x2) array-like The coordinates of a point on the line. Returns ------- ...
def bisect_left(sorted_collection, item, lo=0, hi=None): """ Locates the first element in a sorted array that is larger or equal to a given value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_left . :param sorted_collection: some ascending sorted collection ...
def _normalize_angle(angle, range, step): """Finds an angle that matches the given one modulo step. Increments and decrements the given value with a given step. Args: range: a 2-tuple of min and max target values. step: tuning step. Returns: Normalized value within a given ran...
def _uniq(l): """Removes duplicates from a list, preserving order.""" r = [] for item in l: if item not in r: r.append(item) return r
def compose_base_find_query(user_id: str, administrator: bool, groups: list): """ Compose a query for filtering reference search results based on user read rights. :param user_id: the id of the user requesting the search :param administrator: the administrator flag of the user requesting the search ...
def _parse_seq_arg(arg, arg_name, n_layers): """ Parses args that can be per-layer. """ if type(arg) == str: return [arg] * n_layers try: iter(arg) except TypeError: return [arg] * n_layers if len(arg) == n_layers: return arg else: raise ...
def file_contents_from(path): """ Fetch file contents from a file at path. Returns False if file at path cannot be read. """ try: f = open(path) return f.read() except IOError as e: return False
def hamming_dist(seq1: str, seq2: str) -> int: """Compare hamming distance of two strings""" if len(seq1) != len(seq2): raise ValueError("length of strings are not the same") return sum(c1 != c2 for c1, c2 in zip(seq1, seq2))
def convert_null_to_zero(event, field_or_field_list): """ Converts the value in a field or field list from None to 0 :param event: a dict with the event :param field_or_field_list: A single field or list of fields to convert to 0 if null :return: the updated event Examples: .. code-block:: py...
def straight(ranks): """Return True if the ordered ranks form a 5-card straight. Args: ranks: list of ranks of cards in descending order. """ return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5
def concat(obj, str): """ Concats the the two given strings :param obj: :param str: :return: """ return "%s%s" % (obj, str)
def proton_split(line): """ Split a log line into fields. * allow commas and spaces in quoted strings. * split on ', ' and on ' '. strip trailing commas between fields. * quoted fields must have both quotes :param line: :return: """ result = [] indqs = False pending...
def rigids_mul_rigids(a, b): """Group composition of Rigids 'a' and 'b'.""" c00 = a[0] * b[0] + a[1] * b[3] + a[2] * b[6] c01 = a[3] * b[0] + a[4] * b[3] + a[5] * b[6] c02 = a[6] * b[0] + a[7] * b[3] + a[8] * b[6] c10 = a[0] * b[1] + a[1] * b[4] + a[2] * b[7] c11 = a[3] * b[1] + a[4] *...
def knapsack(capacity, itemList): """I am now a thief, and need to steal the most valuable stuff possible. itemList = [[item1weight, item1val], [item2weight, item2val]] etc. Capacity is amount of weight possible. """ if capacity == 0: return [0, []] if itemList == []: return[0, ...
def binary_search(list_to_search, num_to_find): """ Perform Binary Search on a sorted array of ints. Args: list_to_search (list): The list to search. num_to_find (int): The int to search for. Returns: tuple: (index, value) """ first = 0 last = len(list_to_sear...
def get_dataset_url(hit): """Select dataset url.""" ret_url = None for url in hit["_source"].get("urls", []): if url.startswith("http"): ret_url = url if url.startswith("http") and "amazonaws.com" in url: ret_url = url if url.startswith("http") and "googleapi...
def funcy2(x, a, b, c) : """Quadratic polynomial function to test curve_fit. """ return a*x*x + b*x + c
def lazy_if2(*args): """Return first non-empty argument.""" for a in args: val = a() if val: return val return ''
def doc_to_html(doc): """Makes the doc-string more suitable for html.""" doc = (doc.replace('\\n','<br>') .replace('->','&rarr;') .replace('...', '&#8230;') .replace('\\\\', '\\')) if doc.startswith('"'): doc = doc[1:] if doc.endswith('"'): doc =...
def allowed_file(fn, types): """ validates a filename of allowed types :param fn: :param types: iterable of extensions :return: """ if fn.split(".")[-1] in (x.replace(".", "") for x in types): return True return False
def _getObjectsByTags(objects, tags): """ internal function to return a list of objects with given tags \todo add an explicit option atLeastOneTag, allTags,... """ taggedObjects = list() for obj in objects: if len(obj.tags & tags) > 0: taggedObjects.append(obj) return taggedO...
def get_var_string(vars): """ Turn dictionary of variables into terraform argument string """ args = [] for key, val in vars.items(): current = "-var='{}={}'".format(key, val) args.append(current) return ' '.join(args)
def get_service_name(config): """Get the name of the systemctl service used for the agent""" service_name=config['deploy']['service_name'] return f"{service_name}.service"
def scale_reader(provision_increase_scale, current_value): """ :type provision_increase_scale: dict :param provision_increase_scale: dictionary with key being the scaling threshold and value being scaling amount :type current_value: float :param current_value: the current consumed units or ...
def split_commas(value): """ Splits comma separated values into a list. """ return value.split(',')
def strong(n) -> bool: """Checks whether the given number is Strong Number or not.""" sum = 0 temp = n while(n): i = 1 f = 1 r = n % 10 while(i <= r): f = f*i i = i+1 sum = sum+f n = n//10 if(sum == temp): return True ...
def sortArrayByParity2(A): """ :type A: List[int] :rtype: List[int] """ i, j = 0, len(A) - 1 while i < j: if A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i] if A[i] % 2 == 0: i+=1 if A[j] % 2 == 1: j-=1 return A
def get_named_parent( decl ): """ returns a reference to a named parent declaration @param decl: the child declaration @type decl: L{declaration_t} @return: reference to L{declaration_t} or None if not found """ if not decl: return None parent = decl.parent while parent an...
def stairs(N): """ Produces stairs array of size N """ stairs = [] for i in range(0,N): # step = ''.join([str(N)]*(i+1)) + ''.join([' ']*(N-i-1)) step = '#'*(i+1) + ' '*(N-i-1) stairs.append(step) return stairs
def clamp(image, a, b): """ Clamp the range of intesities of the image from (0, 255) to a custom range (a, b). """ interval_len = b - a return (interval_len / 255.0) * image + a
def _version_difference_str(authority, consensus_versions, vote_versions): """ Provide a description of the delta between the given consensus and vote versions. For instance... moria1 +1.0.0.1-dev -0.0.8.6 -0.0.8.9 """ consensus_versions = set(consensus_versions) vote_versions = set(vote_versions) ...
def Required(field, dictionary): """ When added to a list of validations for a dictionary key indicates that the key must be present. This should not be called, just inserted into the list of validations. # Example: validations = { "field": [Required, Equals(2)] ...
def ra_to_deg(hour: float, minute: float, second: float) -> float: """ Convert RA from (hr, min, sec) -> degree """ return (hour + minute / 60. + second / 3600.) * 15.
def UA_fld_wll_plate(A, s_wll, alpha_fld, lam_wll): """ Calculates the U*A-value for the heat flow to or from a fluid at a plate to or from the ambient. Layers which are considered: fluid, wall material. The reference area must always be the cross section area. Parameters: ----------- A...
def quantile(x, q): """ Return, roughly, the q-th quantile of univariate data set x. Not exact, skips linear interpolation. Works fine for large samples. """ k = len(x) x.sort() return x[int(q * k)]
def twoAdicity(num): """ Description: Computes the 2-adicity order of an integer Input: num - integer Output: Integer - 2-adicity order """ if num % 2 != 0 : return 1 factor = 0 while num % 2 == 0 : num /= 2 factor += 1 return factor
def find_next(p: str) -> int: """ Assuming the last character is a failure next value is returned Note: there is a significantly more efficient method to achieve this this simply follows the 'by-hand' rules provided in the lecture videos. """ if (len(p) == 1): return -1 # Init, answer (retu...
def reverse_in_place(array): """ Array Memory Flip: Given: An Array of Integers. Challenge: We want to reverse the order of the array in memory and you are only allowed the array and 1 integer variable to do this. No pre-canned library calls or frameworks are not allowed. You must do all...
def slope(edge): """Returns the slope of the edge""" return float(edge[0][1] - edge[1][1]) / float(edge[0][0] - edge[1][0])
def user_externalize(user_object): """ Cleanse private/internal data from a user object and make it suitable to serve. """ # only secret value right now is the auth_hash, # but this may change in the future for key in ("auth_hash",): user_object.pop(key) return user_object
def ellipsize(o): """ Ellipsize the representation of the given object. """ r = repr(o) if len(r) < 800: return r r = r[:60] + ' ... ' + r[-15:] return r
def instance_method_wrapper(obj, method_name, *args, **kwargs): """Wraps an object instance method within a static method. This can be used when pickling is needed such as for multiprocessing. Example: from sklearn.externals.joblib import Parallel, delayed pjobs = [delayed(instance_method_wr...
def get_node_value(json_object, parent_node_name, child_node_name=None): """Returns value of given child_node. If child_node is not given, then value of parent node is returned :returns: None If json_object or parent_node is not given, If child_node is not found under parent_node ""...
def is_prime(nb: int) -> bool: """Check if a number is a prime number or not :param nb: the number to check :return: True if prime, False otherwise """ # even numbers are not prime if nb % 2 == 0 and nb > 2: return False # checking all numbers up to the square root of the number ...
def _GetNestedGroup(buf, i, beg, end): """Returns the index in buf of the end of the nested beg...end group. Args: buf: Input buffer. i: The buf[] index of the first beg character. beg: The group begin character. end: The group end character. Returns: The index in buf of the end of the neste...
def before_first_x(text, x): """ before_first_x(str, str) -> str >>> before_first_x("enum class Actions", " ") 'enum' >>> before_first_x("enum Actions : byte", " : ") 'enum Actions' >>> before_first_x("enum Actions : ", " : ") 'enum Actions' """ i = text.find(x) if i > -1: ...
def epj2d(epj): """ Converts Julian epoch to Modified Julian Date. Inputs: - epj Julian epoch Returns: - mjd Modified Julian Date (JD - 2400000.5). Reference: Lieske,J.H., 1979. Astron.Astrophys.,73,282. History: P.T.Wallace Starlink February 1984 2002-07-11 ROwen ...
def merge(*dicts: dict) -> dict: """Deep merges the right most dictionaries into the left most one. Args: *dicts (dict): dictionaries to be merged. Examples: >>> a = {'a': 1, 'b': 2} >>> b = {'b': 3, 'c': {'c1': 4, 'c2': 3}} >>> c = {'a': 3, 'c': {'c1': 3 }} >>> pr...
def sub(I1, I2): """Calculate the substraction of two intervals as another interval Keyword arguments: I1 -- the first interval given as a tuple (a, b) I2 -- the second interval given as a tuple (c, d) """ (from1, to1) = I1 (from2, to2) = I2 return (from1 - max(from2, to2), to1 - min(f...
def wire_plotter(wire_code, current_location): """Accepts code (string) and current location (tuple of two ints). Returns list of new locations (tuples of two ints).""" new_locations = [] if wire_code[0] == 'U': upper_value = int(wire_code[1:]) for i in range(1, upper_value+1): ...
def unescape_text(text): """Unescapes SDF text to be suitable for unit consumption.""" return text.replace("\\\\", "\a").replace("\\n", "\n").replace("\\t", "\t").\ replace("\\r", "\r").replace("\a", "\\\\")
def calculate_percentile(n: list, p: float): """ Find the percentile of a list of values @parameter N - A list of values. N must be sorted. @parameter P - A float value from 0.0 to 1.0 @return - The percentile of the values. """ k = int(round(p * len(n) + 0.5)) return n[k - 1]
def merge_dicts(*args): """Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Args: *args (list(dict)): A list of dictionaries to be merged. Returns: dict: A merged dictionary. """ result = {} for dictiona...
def check_byte(b): """ Clamp the supplied value to an integer between 0 and 255 inclusive :param b: A number :return: Integer representation of the number, limited to be between 0 and 255 """ i = int(b) if i < 0: i = 0 elif i > 255: i = 255 return i
def get_model_names(path_list): """Get model name given list of paths. Args: path_list: Returns: """ res_list = [] for i in path_list: cur_name = i.split('/')[-1] cur_name = cur_name.replace('output_pred_', '').replace('_.pkl', '') res_list.append(cur_name) ...
def combine_rs_and_ps(regular_season, post_season): """Combine Regular Season and Post-Season Data into one table. Args: regular_season: player RS data for table type post_season: player PS data for table type Returns: combined RS and PS table """ total = [] if regular_...
def RemoveRepaya(text): """Replaces all occurrences of repaya with pure ra + al-lakuna.""" # The sequence 0DBB (ra), 0DCA (virama), 200D (ZWJ), 0DBA (ya) is potentially # ambiguous. The first three characters represent repaya; the last three # characters represent yansaya. Per Sri Lanka Standard SLS 1134 : 2011...
def is_length_acceptable(var, length): """Checks if input length is valid""" return len(var) <= length
def add_dicts(d1, d2): """Adds two dicts and returns the result.""" result = d1.copy() result.update(d2) return result
def get_row_col_bounds(level, schema="here"): """ schema "here" [x,y], start from bottom left, go anti-clockwise level 0: 0,0 level 1: 0,0; 1,0 level 2: 0,0; 0,1; 1,0; 1,1; 2,0; 2,1; 3,0; 3,1 """ if schema == "here": nrow = 2 ** (level - 1) if level else 1 ...
def to_list(item): """ If the given item is iterable, this function returns the given item. If the item is not iterable, this function returns a list with only the item in it. :type item: object :param item: Any object. :rtype: list :return: A list with the item in it. """ if ...
def create_freq2opacity(n: int) -> dict: """Create mapping between variant frequency (lower-bound) and opacity level""" freq2opacity = {} for i in range(n): freq2opacity[i] = (1./n)*(i+1) return freq2opacity
def create_instruction(a, b): """ Create a full instruction from the contents of two cells Args: a (str): The string for the first half of the instruction b (str): The string for the second half of the instruction Returns: str: The complete instruction """ completeinstruct...
def make_query_to_get_users_profiles(userIds): """Returns a query to retrieve the profile for the indicated list of user ids Api info: parameter name: user_id values: A comma separated list of user IDs, up to 100 are allowed in a single request. Notes: You are strongly encouraged to ...
def GetLastPathElement(path): """ Similar to basename. Generic utility function. """ return path.rsplit('/', 1)[1]
def _merge_variance(var1, var2): """Merge the variance.""" if var1[0] > 0: if var2[0] > 0: var = [var1[0]+var2[0], var1[1]+var2[1]] else: var = var1 else: var = var2 return var
def is_iterable(inp) -> bool: """ Check if the input is iterable by trying to create an iterator from the input. :param inp: any object :return: `True` if input is iterable, else `False` """ try: _ = iter(inp) return True except TypeError: return False
def determine_rank_order(con): """Determines dynamically rank order based on first input con string""" order = [s.strip()[0] for s in con.split(';')] global RANK_ORDER RANK_ORDER = order return order
def calc_num_metric(predicted_number, actual_number): """ How similar are 2 numbers of references? The difference between the predicted and actual numbers of references as a percentage of the actual number """ # In the case of 0 references (some documents don't have references but do # have...
def add(x, y): """The sum of two bits, mod 2.""" return (x + y) % 2
def weighted_pixel_distance(p1, p2): """straight 3-d euclidean distance (assume RGB)""" return (2*(p1[0] - p2[0])**2 + 4*(p1[1] - p2[1])**2 + 3*(p1[2] - p2[2])**2)**0.5
def sample_interval(hours, minutes, seconds): """Sets the interval between data samples Args: hours - the hours between data samples 0 and 23 minutes - integer between 0 and 59 seconds - integer between 0 and 59 Returns: time interval in seconds. """ if hours == 0 and minutes == 0 ...
def rotate(pattern, k): """ Return a left circular rotation of the given pattern by k.""" if not type(k) == int: raise TypeError("Second argument must be an integer") n = len(pattern) k = k % n return pattern[k:n] + pattern[0:k]
def tune(scale, acceptance): """ Borrowed from PyMC3 """ # Switch statement if acceptance < 0.001: # reduce by 90 percent scale *= 0.1 elif acceptance < 0.05: # reduce by 50 percent scale *= 0.5 elif acceptance < 0.2: # reduce by ten percent scale *= ...