content
stringlengths
42
6.51k
def represent_seconds_in_milliseconds(seconds): """Converts seconds into human-readable milliseconds with 2 digits decimal precision""" return round(seconds * 1000, 2)
def cyclic_sort(nums): """ 0 1 2 3 4 5 [1, 2, 3, 4, 5] ^ [1, 2, 3, 4, 5, 6] ^ """ for i in range(0, len(nums)): while nums[i] != i + 1: j = nums[i] - 1 nums[i], nums[j] = nums[j], nums[i] return nums
def get_size_for_resize(image_size, shorter_size_trg=384, longer_size_max=512): """ Gets a new size for the image. Try to do shorter_side == shorter_size_trg. But we make it smaller if the longer side is > longer_size_max. :param image_size: :param shorter_size_trg: :param longer_size_max: :...
def wyllie(phi, sat=1, vm=4000, vw=1600, va=330): """Return slowness after Wyllie time-average equation.""" return 1./vm * (1-phi) + phi * sat * 1./vw + phi * (1 - sat) * 1./va
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" # You have to code here # REMEMBER: Tests first!!! area = ((base_minor + base_major) / 2) * height return area
def _create_mux_ranges(multiplexer_ids): """ Create a list of ranges based on a list of single values. Example: Input: [1, 2, 3, 5, 7, 8, 9] Output: [[1, 3], [5, 5], [7, 9]] """ ordered = sorted(multiplexer_ids) # Anything but ordered[0] - 1 prev_value = ordered[0] ...
def get_orbit_node(aos_lat, los_lat, oi): """Return the orbit node - ascending or descending, based on time of AOS and LOS latitude """ if (aos_lat > los_lat): print("PASS = descending") node = "descending" else: print("PASS = ascending") node ...
def indent(s: str, count: int, start: bool = False) -> str: """ Indent all lines of a string. """ lines = s.splitlines() for i in range(0 if start else 1, len(lines)): lines[i] = ' ' * count + lines[i] return '\n'.join(lines)
def int_array_to_str(arr): """turn an int array to a str""" return "".join(map(chr, arr))
def consecutives(times): """ Caclulates the number of consecutive interviews (with 15 minute break in between) """ return sum(t + 3 in times for t in times)
def exp_lr_scheduler(optimizer, epoch, lr_change_factor = 0.1, lr_decay_epoch=10): """Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs""" if epoch % lr_decay_epoch: return optimizer for param_group in optimizer.param_groups: param_group['lr'] *= lr_change_fa...
def get_order_fields(request_get, **kwargs): """Determines the ordering of the fields by inspecting the ``order`` passed in the request GET""" available_order = { 'views': ['-views_count', '-created'], 'created': ['-created'], 'votes': ['-votes_count', '-created'], 'default':...
def get_tracks(conf): """ Get a tracks dictionary from the conf. """ return {name.lower(): path for name, path in conf["tracks"].items()}
def get_default_geofence_id(resource_name): """ Helper to ensure consistency when referring to default Geofence by id (name) """ return f"{resource_name}-default-geofence"
def to_camel_case(hyphenated): """ Convert hyphen broken string to camel case. """ components = hyphenated.split('-') return components[0] + ''.join(x.title() for x in components[1:])
def relative(src, dest): """ Return a relative path from src to dest. >>> relative("/usr/bin", "/tmp/foo/bar") ../../tmp/foo/bar >>> relative("/usr/bin", "/usr/lib") ../lib >>> relative("/tmp", "/tmp/foo/bar") foo/bar """ import os.path if hasattr(os.path, "relpath"): ...
def rob(nums): """Calculate max sum of robbing house not next to each other.""" even_sum, odd_sum = 0, 0 for i in range(len(nums)): if i % 2 == 0: even_sum = max(even_sum + nums[i], odd_sum) else: odd_sum = max(even_sum, odd_sum + nums[i]) return max(even_sum, odd...
def strongly_connected_components(graph): """ Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph theory algorithm for finding the strongly connected components of a graph. Graph is a dict mapping nodes to a list of their succesors. Returns a list of tuples Downloaded from http://www.logar...
def __accumulate_range__(trace_events): """ Removes the type and creates a list of the events that appeared. Does NOT include 0. :param trace_events: Events found in the trace (filtered by type). :return: Accumulated trace """ accumulated = [] for line in trace_events: event = l...
def rosenbrock(x): """ Rosenbrock Function :param x: vector of legth 2 :return: float """ return (1 - x[0]) ** 2 + 105 * (x[1] - x[0] ** 2) ** 4
def seq(x, y): """seq(x, y) represents 'xy'.""" return 'seq', x, y
def build_function_header(function_name): """ Build a header for a function. args: function_name: the name of our function. """ function_name = function_name.strip() num_char = len(function_name) header = function_name + '\n' header += "-"*num_char...
def validate_subsequence_while_loop(arr, seq): """ >>> arr = [5, 1, 22, 25, 6, -1, 8, 10] >>> seq = [1, 6, -1, 10] >>> validate_subsequence_for_loop(arr, seq) True >>> arr = [5, 1, 22, 25, 6, -1, 8, 10] >>> seq = [1, 6, 2, 10] >>> validate_subsequence_for_loop(arr, seq) False """...
def get_attribute(attribute_list, name): """Finds name in attribute_list and returns a AttributeValue or None.""" attribute_value = None for attr in attribute_list: if attr.name.text == name and not attr.is_default: assert attribute_value is None, 'Duplicate attribute "{}".'.format(name) attribute...
def get_kmer_dic(k, rna=False): """ Return a dictionary of k-mers. By default, DNA alphabet is used (ACGT). Value for each k-mer key is set to 0. rna: Use RNA alphabet (ACGU). >>> get_kmer_dic(1) {'A': 0, 'C': 0, 'G': 0, 'T': 0} >>> get_kmer_dic(2, rna=True) {'AA':...
def _startswith(search_str, attr_str): """Startswith-operator which is used to find a view""" return attr_str.startswith(search_str)
def ls_remote(arg1): """Function: ls_remote Description: Method stub holder for git.Repo.git.ls_remote(). Arguments: """ if arg1: return True
def get_DiAC_phases(cliffNum): """ Returns the phases (in multiples of pi) of the three Z gates dressing the two X90 pulses comprising the DiAC pulse correspoding to cliffNum e.g., get_DiAC_phases(1) returns a=0, b=1, c=1, in Ztheta(a) + X90 + Ztheta(b) + X90 + Ztheta(c) = Id """ DiAC_table...
def sort_highscore(highscore_list): """Sort player by highscore.""" print(highscore_list) sorted_new_list = sorted(highscore_list, key=lambda x: x[1], reverse=True) print(sorted_new_list) return sorted_new_list
def get_class_name(obj): """ A form of python reflection, returns the human readable, string formatted, version of a class's name. Parameters: :param obj: Any object. Returns: A human readable str of the supplied object's class name. """ return obj.__class__.__name__
def grch38_genomic_insertion_variation(grch38_genomic_insertion_seq_loc): """Create a test fixture for NC_000017.10:g.37880993_37880994insGCTTACGTGATG""" return { "_id": "ga4gh:VA.tCjV190dUsV7tSjdR8qOLSQIR7Hr8VMe", "location": grch38_genomic_insertion_seq_loc, "state": { "seq...
def _get_nested_value(creds_json, env_var_path_list): """ Handle nested values in the credentials json. :param creds_json: e.g. {"performance_platform_bearer_tokens": {"g-cloud": "myToken"}} :param env_var_path_list: e.g. ["performance_platform_bearer_tokens", "g-cloud"] :return: e.g. "myToken" ...
def overlap(a, b): """Count the number of items that appear in both a and b. >>> overlap([3, 5, 7, 6], [4, 5, 6, 5]) 3 """ count = 0 for item in a: for other in b: if item == other: count += 1 return count
def get_seq_middle(seq_length): """Returns relative index for the middle frame in sequence.""" half_offset = int((seq_length - 1) / 2) return seq_length - 1 - half_offset
def niceNum(num, precision=0): """Returns a string representation for a floating point number that is rounded to the given precision and displayed with commas and spaces.""" return format(round(num, precision), ',.{}f'.format(precision))
def BisectPoint(lower_bound, upper_bound): """Returns a bisection of two positive input numbers. Args: lower_bound (int): The lower of the two numbers. upper_bound (int): The higher of the two numbers. Returns: (int): The number half way in between lower_bound and upper_bound, with preferenc...
def _is_compliant_with_reference_json(reference_problem_name: str, reference_graph_type: str, reference_p: int, json): """Validates if a json file contains the same metadata as provided in arguments.""" return reference_problem_name != json["problem_name"] or reference_graph_type != json[ "graph_type"] ...
def filter(repos): """ remove support repos """ not_need = [ 'tmpl', # tempalte repo 'pk3', # this repo 'gh-config', # a config container for maintaining github configs. ] return [x for x in repos if x['name'] not in not_need ]
def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-1234...
def human_format(num, pos=None): """ Format large number using a human interpretable unit (kilo, mega, ...). ---------- INPUT |---- num (int) -> the number to reformat OUTPUT |---- num (str) -> the reformated number """ magnitude = 0 while abs(num) >= 1000: magnit...
def _backend_module_name(name): """ Converts matplotlib backend name to its corresponding module name. Equivalent to matplotlib.cbook._backend_module_name(). """ if name.startswith("module://"): return name[9:] return f"matplotlib.backends.backend_{name.lower()}"
def feature_list_and_dict(features): """ Assign numerical indices to a global list of features :param features: iterable of feature names :return: sorted list of features, dict mapping features to their indices """ feature_list = sorted(features) feature_dict = {feat:i for i, feat in ...
def read_netrc_user(netrc_obj, host): """Reads 'user' field of a host entry in netrc. Returns empty string if netrc is missing, or host is not there. """ if not netrc_obj: return '' entry = netrc_obj.authenticators(host) if not entry: return '' return entry[0]
def isImage(link): """ Returns True if link ends with img suffix """ suffix = ('.png', '.jpg', '.gif', '.tiff', '.bmp', '.jpeg') return link.lower().endswith(suffix)
def nucleotide_frequency(seq): """Count nucleotides in a given sequence. Return a dictionary""" tmpFreqDict = {"A": 0, "C": 0, "G": 0, "T": 0} for nuc in seq: tmpFreqDict[nuc] += 1 return tmpFreqDict # More Pythonic, using Counter # return dict(Counter(seq))
def minute_to_decimal(degree, minute, second): """ Change degree minute second to decimal degree """ return degree + minute / 60 + second / 3600
def _check_pixel(tup): """Check if a pixel is black, supports RGBA""" return tup[0] == 0 and tup[1] == 0 and tup[2] == 0
def tts_version(version): """Convert a version string to something the TTS will pronounce correctly. Args: version (str): The version string, e.g. '1.1.2' Returns: str: A pronounceable version string, e.g. '1 point 1 point 2' """ return version.replace('.', ' point ')
def pv(i,n,fv,pmt): """Calculate the present value of an annuity""" pv = fv*(1/(1+i)**n) - pmt*((1-(1/(1+i)**n))/i) return pv
def overlap(a, b): """check if two intervals overlap. Positional arguments: a -- First interval. b -- Second interval. """ return a[1] > b[0] and a[0] < b[1]
def is_odd(n): """Determines whether `n` is odd """ # odd = n % 2 == 1 odd = bool(n & 1) return odd
def contact_helper(current,points): """ return True if at least one point contacts the cup, return False otherwise Parameter current: the cup Precondition: current is a list Parameter points: infomation of points Precondition: points is a list """ for point in points: ...
def split_email(email): """ Input: string Returns: "username" If the "email = x" argument is provided to the main function, split_email is called. Splits string containing an email address on the '@', returns 0th element. """ username = str.split(email,'@')[0] return...
def rtrd_list2str(list): """Format Route Target list to string""" if not list: return '' if isinstance(list, str): return list return ','.join(list)
def list_as_tuple_hook(x): """Transform all list entries in a dictionary into tuples. This function can be used to load JSON files with tuples instead of lists. :param dict x: A dictionary. :return: The input dictionary, with lists transformed into tuples. """ return {key: tuple(value) ...
def get_conversations(data): """Return dict of unique conversation IDs and their participants.""" convos = {} for conversation in data["conversation_state"]: conversation_id = conversation["conversation_id"]["id"] convo_participants = [] for participant in conversation["conversation...
def left_rotate(n: int, b: int) -> int: """ Left rotate the input by b. :param n: The input. :param b: The rotation factor. :return: The input after applying rotation. """ return ((n << b) | ((n & 0xffffffff) >> (32 - b))) & 0xffffffff
def get_deep(obj, key, key_split='.', default=None, raising=False): """ Get the deep value of the specified key from the dict object :param obj: :param key: :param key_split: :param default: :param raising: :return: """ value = obj try: for key in key.spli...
def b36(number): """ Convert a number to base36 >>> b36(2701) '231' >>> b36(12345) '9IX' >>> b36(None) '0' Keyword arguments: number -- An integer to convert to base36 """ alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' base36 = '' while number: number, i = divmod(number, 36) ...
def build_edge_topic_prefix(device_id: str, module_id: str) -> str: """ Helper function to build the prefix that is common to all topics. :param str device_id: The device_id for the device or module. :param str module_id: (optional) The module_id for the module. Set to `None` if build a prefix for a d...
def _get_change_extent(str1, str2): """ Determines the extent of differences between two strings. Returns a tuple containing the offset at which the changes start, and the negative offset at which the changes end. If the two strings have neither a common prefix nor a common suffix, (0, 0) is re...
def decode_line_y_true(line): """ format path x1,y1,x2,y2,label x1,y1,x2,y2,label... :param line: :return: {'path':str, 'bboxes':list, (x1,y1,x2,y2), 'labels':list } """ items = line.split() path = items[0] items = items[1:] bboxes = [] labels = [] for item in items: ...
def compute_sin2phi(dx, dy, square_radius): """Compute sin 2 phi.""" return 2.0 * dx * dy / square_radius
def findMinIndex(a_list,start_index, verbose=False): """assumes that a_list is a list of numbers assumes start)index is an int, representing the index where to start looking returns a tuple (int,number) the index of the smallest number found between start_index and the end of the list, inclusive, an...
def make_bet(bank, proposed_bet): """ @summary: Make a bet based on a limited bank allocation @param bank: limited bank allocation @param proposed_bet: bet for the forthcoming roulette spin to check against the bank @return final_bet: updated bet based on cash available in bank @return bank: available bank...
def is_repeated_varargs_parameter(parameter: dict): """Whether the parameter is a repeated varargs parameter. This means the parameter follows a specific varargs convention where the user can pass in an arbitrary repetition of fixed arguments. """ return parameter.get("repeated_var_args", False)
def rule(port, action='ACCEPT', source='net', dest='$FW', proto='tcp'): """ Helper to build a firewall rule. Examples:: from fabtools.shorewall import rule # Rule to accept connections from example.com on port 1234 r1 = rule(port=1234, source=hosts(['example.com'])) # Rul...
def rate_limit_from_period(num_ref_data, period): """Generate the QPS from a period (hrs) Args: num_ref_data (int): Number of lambda calls needed period (float): Number of hours to spread out the calls Returns: float: Queries per second """ seconds = period * 60 * 60 qp...
def jaccard_sim(X, Y): """Jaccard similarity between two sets""" x = set(X) y = set(Y) return float(len(x & y)) / len(x | y)
def merge2list(first,second)->list: """ Return the Merge Two Sorted List. """ i=0 j=0 ans=[] while(i<len(first) and j<len(second)): if first[i]>second[j]: ans.append(second[j]) j+=1 else: ans.append(first[i]) i+=1 if(i>=len(first)): while j<len(second): ans.append(second[j]) j+=1 else: ...
def get(dd, kk, default=0): """Get dd[kk], or return default if kk is not in dd.keys() :param dd: Dictionary :type dd: dict :param kk: Any hashable key :type kk: object :param default: The default value to return if kk is not a valid key :type default: object (anything!) :retur...
def from_db(x): """ Convert from decibels to original units. Inputs: - x [float]: Input data (dB) Outputs: - y [float]: Output data """ return 10**(0.1*x)
def get_diff(liste1, liste2): """Renvoie les objets de liste1 qui ne sont pas dans liste2""" return list(set(liste1).difference(set(liste2)))
def _find_nth_substring(haystack, substring, n): """ Finds the position of the n-th occurrence of a substring Args: haystack (str): Main string to find the occurrences in substring (str): Substring to search for in the haystack string n (int): The occurrence number of the substring to b...
def sort_physical_qubits(physical_qubit_profile): """ This method sorts the physical qubits based on the their connectivity strengths https://ieeexplore.ieee.org/document/9251960 https://ieeexplore.ieee.org/document/9256490 Args: Dictionary holding the connectivity strenths of every qubit. ...
def regex_match_lines(regex, lines): """ Performs a regex search on each line and returns a list of matched groups and a list of lines which didn't match. :param regex regex: String to be split and stripped :param list lines: A list of strings to perform the regex on. """ matches = [] b...
def class_identifier(typ): """Return a string that identifies this type.""" return "{}.{}".format(typ.__module__, typ.__name__)
def single2float(x): """Convert a single x to a rounded floating point number that has the same number of decimals as the original""" dPlaces = len(str(x).split('.')[1]) y = round(float(x),dPlaces+2) # NOTE: Alternative method: #y = round(float(x),6) return y
def solution2(arr): """improved solution1 #TLE """ if len(arr) == 1: return arr[0] max_sum = float('-inf') l = len(arr) for i in range(l): local_sum = arr[i] local_min = arr[i] max_sum = max(max_sum, local_sum) for j in range(i + 1, l): local_sum...
def is_right_child(node_index): """ Checks if the given node index is the right child in the binary tree. """ return node_index % 2 == 1
def slivers_poa_sliver_idpost(body, sliver_id): # noqa: E501 """Perform Operational Action Perform the named operational action on the named resources, possibly changing the operational status of the named resources. E.G. &#x27;reboot&#x27; a VM. # noqa: E501 :param body: :type body: dict | by...
def intprod(xs): """ Product of a sequence of integers """ out = 1 for x in xs: out *= x return out
def _get_index(k, size): """Return the positive index k from a given size, compatible with python list index.""" if k < 0: k += size if not 0 <= k < size: raise KeyError('Index out of bound!') return k
def inclusion_no_params_with_context_from_template(context): """Expected inclusion_no_params_with_context_from_template __doc__""" return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']}
def M_TO_N(m, n, e): """ :param: - `m`: the minimum required number of matches - `n`: the maximum number of matches - `e`: the expression t match """ return "{e}{{{m},{n}}}".format(m=m, n=n, e=e)
def contains(string, substring): """Boolean function detecting if substring is part of string.""" try: if string.index(substring) >= 0: return True except ValueError: return False
def calculate_row_checksum(row): """Form the row checksum as the difference between the largest and the smallest row items""" sorted_row = sorted(row)[0] smallest, largest = sorted_row, sorted(row)[-1] return largest - smallest
def get_device_capability(code): """ Determine the device capability data embedded in a device announce packet. Args: code (int): The message code included in the packet. Returns: str: The capability list. """ opts = ("alternate PAN Coordinator", "device type", "power source",...
def is_under(var): """e.g. is_underscore_case""" return '_' in var
def get_suffixes(arr): """ Returns all possible suffixes of an array (lazy evaluated) Args: arr: input array Returns: Array of all possible suffixes (as tuples) """ arr = tuple(arr) return [arr] return (arr[i:] for i in range(len(arr)))
def cool_number(value, num_decimals=1): """ Converts regular numbers into cool ones (ie: 2K, 434.4K, 33M...) """ int_value = int(value) formatted_number = '{{:.{}f}}'.format(num_decimals) if int_value < 1000: return str(int_value) elif int_value < 1000000: return formatted_nu...
def fmtExp(num): """Formats a floating-point number as x.xe-x""" retStr = "%.1e" % (num,) if retStr[-2] == '0': retStr = retStr[0:-2] + retStr[-1] return retStr
def doc_freqs(docs) -> dict: """ Takes in a list of spacy Doc objects and return a dictionary of frequencies for each token over all the documents. E.g. {"Aarhus": 20, "the": 2301, ...} """ res_dict = {} for doc in docs: # create empty list to check whether token appears multiple times ...
def list_validator(lens=[]): """[summary] This method used to chek the input list sould have 9 elements This method is only for saftey check purpose. Args: lens (list, optional): [input element list]. Defaults to []. Returns: [Boolean]: [True or False] """ return Tru...
def human_size(num, suffix='B'): """Converts a byte count to human readable units. Args: num (int): Number to convert. suffix (str): Unit suffix, e.g. 'B' for bytes. Returns: str: `num` as a human readable string. """ if not num: num = 0 for unit i...
def get_change_content(children, when): """Checks every childrens history recursively to find the content of the change. Args: children: children array of the post dict. when: Time of change log dict. Returns: Content of the change in HTML format. """ for child in child...
def standardize_folder(folder: str) -> str: """Returns for the given folder path is returned in a more standardized way. I.e., folder paths with potential \\ are replaced with /. In addition, if a path does not end with / will get an added /. Argument ---------- * folder: str ~ The folder path...
def ldd_to_ddl(ldd): """Args: list of dicts of dicts Returns: dict of dicts of lists """ return { placer_name: { metric_name: [mval[placer_name][metric_name] for mval in ldd] for metric_name in ldd[0][placer_name] } ...
def _get_value(data, tag): """ Returns first value of field `tag` """ # data['v880'][0]['_'] try: return data[tag][0]['_'] except (KeyError, IndexError): return None
def mean(lst): """Helper function to calculate the mean of the values in a list.""" return sum(lst) / len(lst)