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: :return: """ w, h = image_size size = shorter_size_trg # Try [size, size] if min(w, h) <= size: return w, h min_original_size = float(min((w, h))) max_original_size = float(max((w, h))) if max_original_size / min_original_size * size > longer_size_max: size = int(round(longer_size_max * min_original_size / max_original_size)) if (w <= h and w == size) or (h <= w and h == size): return w, h if w < h: ow = size oh = int(size * h / w) else: oh = size ow = int(size * w / h) return ow, oh
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] ranges = [] for value in ordered: if value == prev_value + 1: ranges[-1][1] = value else: ranges.append([value, value]) prev_value = value return ranges
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 = "ascending" oi = 360 - oi return (oi, 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_factor return optimizer
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': ['-is_featured', '-created'], } if kwargs: available_order.update(kwargs) order = request_get.get('order') if order and order in available_order: return available_order[order] return available_order['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"): return os.path.relpath(dest, src) else: destlist = os.path.normpath(dest).split(os.path.sep) srclist = os.path.normpath(src).split(os.path.sep) # Find common section of the path common = os.path.commonprefix([destlist, srclist]) commonlen = len(common) # Climb back to the point where they differentiate relpath = [ os.path.pardir ] * (len(srclist) - commonlen) if commonlen < len(destlist): # Add remaining portion relpath += destlist[commonlen:] return os.path.sep.join(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_sum)
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.logarithmic.net/pfh/blog/01208083168 Allegedly by Dries Verdegem Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm """ index_counter = [0] stack = [] lowlinks = {} index = {} result = [] def strongconnect(node): #print "calling strong connect", node # set the depth index for this node to the smallest unused index index[node] = index_counter[0] lowlinks[node] = index_counter[0] index_counter[0] += 1 stack.append(node) # Consider successors of `node` try: successors = graph[node] except: successors = [] for successor in successors: if successor not in lowlinks: # Successor has not yet been visited; recurse on it strongconnect(successor) lowlinks[node] = min(lowlinks[node],lowlinks[successor]) elif successor in stack: # the successor is in the stack and hence in the current strongly connected component (SCC) lowlinks[node] = min(lowlinks[node],index[successor]) # If `node` is a root node, pop the stack and generate an SCC if lowlinks[node] == index[node]: connected_component = [] while True: successor = stack.pop() connected_component.append(successor) if successor == node: break component = tuple(connected_component) # storing the result result.append(component) for node in graph: if node not in lowlinks: strongconnect(node) return result
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 = line[1] if event != 0: accumulated.append(event) return accumulated
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 + '\n\n' return header
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 """ arr_idx = 0 seq_idx = 0 while arr_idx < len(arr) and seq_idx < len(seq): if arr[arr_idx] == seq[seq_idx]: seq_idx += 1 arr_idx += 1 return seq_idx == len(seq)
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_value = attr.value return attribute_value
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': 0, 'AC': 0, 'AG': 0, 'AU': 0, 'CA': 0, 'CC': 0, 'CG': 0, 'CU': 0, 'GA': 0, 'GC': 0, 'GG': 0, 'GU': 0, 'UA': 0, 'UC': 0, 'UG': 0, 'UU': 0} """ # Check. assert k, "invalid k given" assert k > 0, "invalid k given" # Dictionary. mer2c_dic = {} # Alphabet. nts = ["A", "C", "G", "T"] if rna: nts = ["A", "C", "G", "U"] # Recursive k-mer dictionary creation. def fill(i, seq, mer2c_dic): if i: for nt in nts: fill(i-1, seq+nt, mer2c_dic) else: mer2c_dic[seq] = 0 fill(k, "", mer2c_dic) return mer2c_dic
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 = [ [0, 1, 1], [0.5, -0.5, 0.5], [0, 0, 0], [0.5, 0.5, 0.5], [0, -0.5, 1], [0, 0, 1], [0, 0.5, 1], [0, 1, -0.5], [0, 1, 0], [0, 1, 0.5], [0, 0, 0.5], [0, 0, -0.5], [1, -0.5, 1], [1, 0.5, 1], [0.5, -0.5, -0.5], [0.5, 0.5, -0.5], [0.5, -0.5, 1], [1, -0.5, -0.5], [0, 0.5, -0.5], [-0.5, -0.5, 1], [1, 0.5, -0.5], [0.5, 0.5, 1], [0, -0.5, -0.5], [-0.5, 0.5, 1]] return DiAC_table[cliffNum]
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": { "sequence": "TACGTGATGGCTTACGTGATGGCT", "type": "LiteralSequenceExpression" }, "type": "Allele" }
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" """ if len(env_var_path_list) > 1: return _get_nested_value(creds_json.get(env_var_path_list[0], {}), env_var_path_list[1:]) return creds_json.get(env_var_path_list[0])
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 preference for the lower of the two as the result of treating the result of division as an int. """ assert upper_bound >= 0 assert lower_bound >= 0 assert upper_bound >= lower_bound return lower_bound + (upper_bound - lower_bound) / 2
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"] or reference_p != json["p"]
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(-123456) 6 """ return len(str(abs(n)))
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: magnitude += 1 num /= 1000.0 return '%.1f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
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 enumerate(feature_list)} return feature_list, feature_dict
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: if ((point[0]-current[0])**2+(point[1]-current[1])**2)**0.5<=15: return True return False
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 username
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) if isinstance(value, list) else value for key, value in x.items()}
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_state"]["conversation"][ "participant_data" ]: try: convo_participants.append(participant["fallback_name"]) except KeyError: pass convos[conversation_id] = convo_participants return convos
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.split(key_split): if isinstance(value, dict): value = value[key] continue else: if raising: raise KeyError return default except KeyError: if raising: raise return default else: return value
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) base36 = alphabet[i] + base36 return base36 or alphabet[0]
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 device. :return: The topic prefix, including the trailing slash (`/`) """ if module_id: return "$iothub/{}/{}/".format(device_id, module_id) else: return "$iothub/{}/".format(device_id)
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 returned. """ start = 0 limit = min(len(str1), len(str2)) while start < limit and str1[start] == str2[start]: start += 1 end = -1 limit = limit - start while -end <= limit and str1[end] == str2[end]: end -= 1 return (start, end + 1)
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: if not item: continue x1, y1, x2, y2, label = item.split(',') x1, y1, x2, y2, label = float(x1), float(y1), float(x2), float(y2), float(label) bboxes.append([x1, y1, x2, y2]) labels.append(label) return path, bboxes, labels
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, and the value of this smallest number if there is a tie for smallest valye, returns the 1st occurence """ min_index = start_index min_value = a_list[start_index] for index in range(start_index,len(a_list)): if a_list[index] < min_value: min_index = index min_value = a_list[index] if verbose: print("The index of the minimum value of the subarray starting at index " + str(start_index) +" is " + str(min_index) + "." ) return min_index
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 after bet has been made """ if proposed_bet > bank: final_bet = bank bank = 0 else: final_bet = proposed_bet bank -= proposed_bet return final_bet, 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'])) # Rule to reject outgoing SMTP connections r2 = rule(port=25, action='REJECT', source='$FW', dest='net') """ return { 'action': action, 'source': source, 'dest': dest, 'proto': proto, 'dest_port': port, }
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 qps = num_ref_data / seconds return qps
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: while i<len(first): ans.append(first[i]) i+=1 return ans
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!) :return: dd[kk], or 'default' if kk is not in dd.keys :rtype: object (anything!) """ if kk in dd.keys(): return dd[kk] else: return default
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 be located. n > 0 Returns: int_or_None: Position index of the n-th substring occurrence in the haystack string if found. None if not found. """ parts = haystack.split(substring, n) if n <= 0 or len(parts) <= n: return None else: return len(haystack) - len(parts[-1]) - len(substring)
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. Returns: Sorted list of the physical qubits. """ sorted_physical_qubits = [] for key in physical_qubit_profile.keys(): if sorted_physical_qubits == []: sorted_physical_qubits.append(key) #print(sorted_physical_qubits) continue i = 0 assigned = 'NO' for element in sorted_physical_qubits: if physical_qubit_profile[element] < physical_qubit_profile[key]: sorted_physical_qubits.insert(i,key) assigned = 'YES' break i = i + 1 if assigned == 'NO': sorted_physical_qubits.append(key) #print(sorted_physical_qubits) return sorted_physical_qubits
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 = [] bad_lines = [] for line in lines: match = regex.search(line) if match: matches.append(match.groups()) else: bad_lines.append(line) return matches, bad_lines
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 += arr[j] local_min = min(local_min, arr[j]) max_sum = max([max_sum, local_sum, local_sum - local_min]) return max_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 | bytes :param sliver_id: Sliver identifier as UUID :type sliver_id: str :rtype: Success """ slice_graph = body.decode("utf-8") return 'do some magic!'
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", "receiver on when idle", "R", "R", "security capable", "allocate address") cap_list = "" for i in range(0, 8): if (code & (1 << i)) == (1 << i): if opts[i] == "R": cap_list += "reserved function, " else: cap_list += opts[i] + ", " cap_list = cap_list[0:1].upper() + cap_list[1:-2] return cap_list
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_number.format(int_value / 1000.0).rstrip('0.') + 'K' else: return formatted_number.format(int_value / 1000000.0).rstrip('0.') + 'M'
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 in doc duplicates = [] for token in doc: if token.text not in duplicates: # if token is not in dict; add token as key and 1 as value if token.text not in res_dict: res_dict[token.text] = 1 # if the token is already in dic; add 1 to the value of that token else: res_dict[token.text] += 1 duplicates.append(token.text) return res_dict
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 True if len(lens) == 9 else False
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 in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
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 children: if child.get('updated') == when: return child.get('subject') if child.get('history') is not None: # an answer for hist in child.get('history'): if hist.get('created') == when: return hist.get('content') elif len(child.get('children')) >= 1: found = get_change_content(child['children'], when) if found is not None: return found return None
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 that shall be standardized. """ # Standardize for \ or / as path separator character. folder = folder.replace("\\", "/") # If the last character is not a path separator, it is # added so that all standardized folder path strings # contain it. if folder[-1] != "/": folder += "/" return folder
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] } for placer_name in ldd[0].keys() }
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)