content
stringlengths
42
6.51k
def parseRgbString(rgbString): """ Parses string in the form 'rgb(x,y,z)' where x, y and z are integers. Returns (x, y, z) tuple. """ return [int(s) for s in rgbString[4:-1].split(',', 3)]
def bits_required(integer_value): """ Return the number of bits required to store the given integer. """ assert type(integer_value) == int and integer_value >= 0, "The given number must be an integer greater than or equal to zero." # The bin built-in function converts the value to a binary string, but adds an '0b' prefix. # Count the length of the string, but subtract 2 for the '0b' prefix. return len(bin(integer_value)) - 2
def _nih_checkdigit(h): """Luhn mod N algorithm in base 16 (hex) according to RFC6920_ .. _RFC6920: https://www.ietf.org/rfc/rfc6920 """ ## Adopted from https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm ## pseudocode factor = 2 total = 0 base = 16 digits = len(h) # 0 if digits has even length, 1 if odd # (as we start doubling with the very last digit) parity = digits % 2 for x in range(digits): digit = int(h[x], 16) if x % 2 != parity: # double every second digit digit *= 2 # slight less efficient, but more verbose: # if > 16: # total += digit - 16 + 1 # else: # total + digit total += sum(divmod(digit, 16)) else: # Not doubled, must be <16 total += digit # checkdigit that needs to be added to total # to get 0 after modulus remainder = (16-total) % 16 # Return as hex digit return "%x" % remainder
def _force_dict(value): """If the value is not a dict, raise an exception.""" if value is None or not isinstance(value, dict): return {} return value
def comparator(x, y): """ default comparator :param x: :param y: :return: """ if x < y: return -1 elif x > y: return 1 return 0
def rebalance_A_to_B(A, B, target_relative_weight, transfer_fee): """ Say you want to rebalance two investments A and B so that the relative weight of A to B is the target_relative_weight and transfering the money has a transfer fee proportional to the amount to transfer with fixed rate transfer_fee If transfer is the amount to move from A to B, we want to solve: (A - transfer) / (A - transfer + B + transfer * (1 - transfer_fee)) = target_relative_weight which can be algebraicely written into the equivalent: transfer = (A - target_relative_weight * (A + B)) / (1 - target_relative_weight * transfer_fee) :param A: float, value of A :param B: float, value of B :param target_relative_weight: what A / (A + B) should be after rebalancing :param transfer_fee: a percentage taken from the transfer of value from A to B :return: the amount to transfer from A to B to achieve the target_relative_weight A and B are already balanced, nothing must be taken from A >>> rebalance_A_to_B(10, 10, 0.5, 0) 0.0 For A to be 25% of the total, we need to move 5 unit from A to B (assuming no transfer fee) >>> rebalance_A_to_B(10, 10, 0.25, 0) 5.0 On the other hand, we need to GIVE to A to make A 0.75% of the total (still assuming no transfer fee) >>> rebalance_A_to_B(10, 10, 0.75, 0) -5.0 Example including a transfer fee, here we need to transfer a little more to cover for the fee >>> a, b = 10, 10 >>> target_ratio = 0.25 >>> fee_percent = 0.01 >>> transfer_amount = rebalance_A_to_B(a, b, target_ratio, fee_percent) >>> print(transfer_amount) 5.012531328320802 >>> new_a = a - transfer_amount >>> new_b = b + transfer_amount * (1 - fee_percent) # a portion of the transferred money is lost due to the fees >>> new_ratio = new_a / (new_a + new_b) >>> assert new_ratio == target_ratio >>> print(new_ratio) 0.25 """ return (A - target_relative_weight * (A + B)) / ( 1 - target_relative_weight * transfer_fee )
def rescale_score_by_abs(score, max_score, min_score): """ Normalize the relevance value (=score), accordingly to the extremal relevance values (max_score and min_score), for visualization with a diverging colormap. i.e. rescale positive relevance to the range [0.5, 1.0], and negative relevance to the range [0.0, 0.5], using the highest absolute relevance for linear interpolation. """ # CASE 1: positive AND negative scores occur -------------------- if max_score > 0 and min_score < 0: if max_score >= abs(min_score): # deepest color is positive if score >= 0: return 0.5 + 0.5 * (score / max_score) else: return 0.5 - 0.5 * (abs(score) / max_score) else: # deepest color is negative if score >= 0: return 0.5 + 0.5 * (score / abs(min_score)) else: return 0.5 - 0.5 * (score / min_score) # CASE 2: ONLY positive scores occur ----------------------------- elif max_score > 0 and min_score >= 0: if max_score == min_score: return 1.0 else: return 0.5 + 0.5 * (score / max_score) # CASE 3: ONLY negative scores occur ----------------------------- elif max_score <= 0 and min_score < 0: if max_score == min_score: return 0.0 else: return 0.5 - 0.5 * (score / min_score)
def get_collected_details(event): """Gets collected details if the technology's poller already described the given asset""" return event['detail'].get('collected')
def sort_terms(facets): """Sort terms lexicographically instead of by the number of results returned. This will only sort 'terms' type facets.""" for facet in facets: if facet['type'] == 'terms' and facet.get('buckets'): facet['buckets'].sort(key=lambda x: x['value']) return facets
def create_short_names(wells, products, reactions, barrierless): """ Create a short name for all the wells, all the bimolecular products and all the transition states """ # short names of the wells # key: chemid # value: short name well_short = {} # short names of the products # key: sorted chemids with underscore # value: short name pr_short = {} # short names of the fragments # key: chemid # value: short name fr_short = {} # short name of the ts's # key: reaction name (chemid, type and instance) # value: short name ts_short = {} # short name of the barrierless reactions # key: reaction number # value: reaction number nobar_short = {} for well in wells: if well not in well_short: short_name = 'w_' + str(len(well_short) + 1) well_short[well] = short_name for prod in products: if prod not in pr_short: short_name = 'pr_' + str(len(pr_short) + 1) pr_short[prod] = short_name for frag in prod.split('_'): if frag not in fr_short: short_name = 'fr_' + str(len(fr_short) + 1) fr_short[frag] = short_name for rxn in reactions: if rxn[1] not in ts_short: short_name = 'rxn_' + str(len(ts_short) + 1) ts_short[rxn[1]] = short_name n = 1 for rxn in barrierless: nobar_name = 'nobar_' + str(n) nobar_short[nobar_name] = nobar_name n = n + 1 return well_short, pr_short, fr_short, ts_short, nobar_short
def get_alignment_identities(A, B): """ This function returns the number of identities between a pair of aligned sequences {A} and {B}. If {A} and {B} have different lengths, returns None. @input: A {string} aligned sequence A (with residues and gaps) B {string} aligned sequence B (with residues and gaps) @return: {int} or None """ if len(A) == len(B): return len([i for i in range(len(A)) if A[i] == B[i]]) return None
def find_index(items, condition_fn): """Return the index of the first item whose condition_fn is True.""" for index, item in enumerate(items): if condition_fn(item): return index return None
def _extract_mime_types(registry): """ Parse out MIME types from a defined registry (e.g. "application", "audio", etc). """ mime_types = [] records = registry.get("record", {}) reg_name = registry.get("@id") for rec in records: mime = rec.get("file", {}).get("#text") if mime: mime_types.append(mime) else: mime = rec.get("name") if mime: hacked_mime = reg_name + "/" + mime mime_types.append(hacked_mime) return mime_types
def check_ship(coord, length, v): """ (tuple, int, str) -> bool Function checks if certain ship can be placed on blank field """ if v == "horizontal": if ord(coord[0])+length > 74: return False else: if coord[1]+length > 10: return False return True
def try_parse_int64(string): """Converts the string representation of a number to its 64-bit signed integer equivalent. **Args**: * string (str): string representation of a number **Returns**: The 64-bit signed integer equivalent, or None if conversion failed\ or if the number is less than the min value or greater than\ the max value of a 64-bit signed integer. """ try: ret = int(string) except ValueError: return None return None if ret < -2 ** 64 or ret >= 2 ** 64 else ret
def _trim(txt, length): """ Trim specified number of columns from start of line. """ try: newlines = [] for line in txt.splitlines(): newlines.append(line[int(length) :]) return "\n".join(newlines) except ValueError: return txt
def is_data(data): """Return ``True`` if passed object is Data and ``False`` otherwise.""" return type(data).__name__ == 'Data'
def merge_sort(nums: list) -> list: """ It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. :param nums: list of n elements to sort :return: sorted list (in ascending order) """ if type(nums) is not list: raise TypeError("merge sort only takes lists, not {}".format(str(type(nums)))) try: if len(nums) > 1: mid = len(nums) // 2 left_list = nums[:mid] right_list = nums[mid:] # Recursively breakdown the list merge_sort(left_list) merge_sort(right_list) # Perform the merging i = 0 # index into the left_list j = 0 # index into the right_list k = 0 # index into the merge list # While both lists have content while i < len(left_list) and j < len(right_list): if left_list[i] < right_list[j]: nums[k] = left_list[i] i += 1 else: nums[k] = right_list[j] j += 1 k += 1 # If the left_list still has values, add them while i < len(left_list): nums[k] = left_list[i] i += 1 k += 1 # If the right_list still has values, add them while j < len(right_list): nums[k] = right_list[j] j += 1 k += 1 return nums except TypeError: return []
def get_user_summary(out, user): """Extract the summary for a given user""" user_summary = None for summary in out['summary']: if summary.get('user') == user: user_summary = summary if not user_summary: raise AssertionError('No summary info found for user: %s' % user) return user_summary
def get_common_params(rpc_name, mob_api_functions, hmi_api_functions): """Function calculates common parameters from mobile and hmi apis for specified rpc """ hmi_params = hmi_api_functions[rpc_name] mob_params = mob_api_functions[rpc_name] mob_keys = mob_params.keys() hmi_keys = hmi_params.keys() return list(set(mob_keys).intersection(set(hmi_keys)))
def rupeeCommaInsert(num): """Insert indian style comma seperation to prices Args: num (number): input price in integer format Returns: string: returns string after inserting comma """ myList = list(str(num)) i = len(myList) - 3 while(i > 0): myList.insert(i, ',') i -= 2 return ''.join(myList)
def data_has_changed(val,prv,nxt=None,t=300): """ Method to calculate if decimation is needed, any value that preceeds a change is considered a change any time increment above 300 seconds is considered a change """ return (val[1]!=prv[1] or (nxt is not None and nxt[1]!=prv[1]) or val[0]>(prv[0]+t))
def rectangleSelect(x1, y1, x2, y2, ts): """ Returns the coordinates of a rectangle whose edges are snapped to the divisions between tiles. The returned value is in pixel units in the form (x, y, w, h) @type x1: int @param x1: left x-coordinate in tiles @type y1: int @param y1: top y-coordinate in tiles @type x2: int @param x2: right x-coordinate in tiles @type y2: int @param y2: bottom y-coordinate in tiles @type ts: int @param ts: size of tile in pixels """ rx = min(x1, x2) * ts ry = min(y1, y2) * ts rw = (abs(x2 - x1) + 1) * ts rh = (abs(y2 - y1) + 1) * ts return int(rx), int(ry), int(rw), int(rh)
def order_dict(d): """Order dict by its values.""" o = d.items() def _key(x): return (x[1], x[0]) return sorted(o, key=_key)
def gateway_environment(gateway_environment): """Disabled path routing on gateway""" gateway_environment.update({"APICAST_PATH_ROUTING": 0}) return gateway_environment
def get_outliers(all_outliers, window_size, threshold=1): """Return 'common' and 'unique' outliers. """ common, unique = list(), list() for index, outliers in enumerate(all_outliers): common_exec = list() unique_exec = list() for outlier in outliers: other_execs = all_outliers[:index] + all_outliers[(index + 1):] sum_ = 0 for execution in other_execs: if outlier in execution: sum_ += 1 if sum_ >= threshold: common_exec.append(outlier) else: unique_exec.append(outlier) common.append(common_exec) unique.append(unique_exec) return common, unique
def scale_pairs(pairs, scale): """"Scale an array of pairs.""" return [ ((rx * scale[0], ry * scale[1]), (sx * scale[0], sy * scale[1])) for (rx, ry), (sx, sy) in pairs ]
def cleanbeatarray(beatlist): """ Validates the data from the beat array and discards outliers and wrong results including 0, negative entries or timedif entries higher than 2 seconds (sub-30 bpm) are unrealistic and the threshold needs to be somewhere) :param beatarray: A list of beat time differences :return: beatarray: A list of beat time differences with validated info """ newlist = [] for dif in beatlist: if dif > 0.18 and dif <= 2: newlist.append(dif) return newlist
def __part1by1_64(n): """64-bit mask""" n &= 0x00000000ffffffff # binary: 11111111111111111111111111111111, len: 32 n = (n | (n << 16)) & 0x0000FFFF0000FFFF # binary: 1111111111111111000000001111111111111111, len: 40 n = (n | (n << 8)) & 0x00FF00FF00FF00FF # binary: 11111111000000001111111100000000111111110000000011111111, len: 56 n = (n | (n << 4)) & 0x0F0F0F0F0F0F0F0F # binary: 111100001111000011110000111100001111000011110000111100001111, len: 60 n = (n | (n << 2)) & 0x3333333333333333 # binary: 11001100110011001100110011001100110011001100110011001100110011, len: 62 n = (n | (n << 1)) & 0x5555555555555555 # binary: 101010101010101010101010101010101010101010101010101010101010101, len: 63 return n
def remainder(num1: int, num2: int) -> int: """Find the remainder from num1 and num2.""" if all((num1 > 0, num2 >= 1,)): return num1 % num2 raise ValueError("Check number inputs. ")
def months_of_gregorian_calendar(year=0): """Months of the Gregorian calendar. Parameters ---------- year : int, optional (dummy value). Returns ------- out : list of int months of the year. Notes ----- Appropriate for use as 'year_cycles' function in :class:`Calendar`. This module has a built-in calendar with months only: :data:`CalMonthsOnly`. """ return list(range(1, 13))
def sum_digits(n): """Calculate the sum of digits. Parameters: n (int): Number. Returns: int: Sum of digitis of n. Examples: >>> sum_digits(42) 6 """ s = 0 while n: s += n % 10 n //= 10 return s
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) 2 """ # result = max(set(nums), key=nums.count) # return (result) # Other solution: counts = {} for num in nums: counts[num] = counts.get(num, 0) + 1 max_value = max(counts.values()) for (num, freq) in counts.items(): if freq == max_value: return num
def format_string(indices): """Generate a format string using indices""" format_string = '' for i in indices: format_string += ', %s' % (i) return format_string
def underscore_to_camel( text: str, lower_first: bool = True ) -> str: """Convert a string with words separated by underscores to a camel-cased string. Args: text (:obj:`str`): The camel-cased string to convert. lower_first (:obj:`bool`, optional): Lowercase the first character. Defaults to :obj:`True`. :rtype: :obj:`str` Examples: >>> from flutils.strutils import underscore_to_camel >>> underscore_to_camel('foo_bar') 'fooBar' >>> underscore_to_camel('_one__two___',lower_first=False) 'OneTwo' """ out = ''.join([x.capitalize() or '' for x in text.split('_')]) if lower_first is True: return out[:1].lower() + out[1:] return out
def Time2FrameNumber(t, ori_fps, fps=10): """ function to convert segment annotations given in seconds to frame numbers input: ori_fps: is the original fps of the video fps: is the fps that we are using to extract frames from the video num_frames: is the number of frames in the video (under fps) t: is the time (in seconds) that we want to convert to frame number output: numf: the frame number corresponding to the time t of a video encoded at fps """ ori2fps_ratio = int(ori_fps/fps) ori_numf = t*ori_fps numf = int(ori_numf / ori2fps_ratio) return numf
def redact_logical_AND(field): """ If all rules were satisfied, keep this element. Else, redact. Note - field argument must start with `$` (e.g. ""$dist_matches"") """ stage = { "$redact": { "$cond": { "if": { "$setIsSubset": [ ["false"], { "$ifNull": [field, ["true"]] # if field is not set, don't redact } ] }, "then": "$$PRUNE", "else": "$$DESCEND" } } } return stage
def _build_qualifier_filters(options): """ Build a dictionary defining the qualifier filters to be processes from their definitons in the Click options dictionary. There is an entry in the dictionary for each qualifier filter where the key is the association name and the value is True or False depending in the value of the option ('x' or 'no-x' ) """ qualifier_filters = {} if options['association'] is not None: # show_assoc = options['association'] qualifier_filters['Association'] = options['association'] if options['indication'] is not None: qualifier_filters['Indication'] = options['indication'] if options['experimental'] is not None: qualifier_filters['Experimental'] = options['experimental'] return qualifier_filters
def mirror_ho_hidido(distance_image,distance_object,height_image): """Usage: Find height of object using height of image, distance of object and height of object""" neg_di = (-1) * distance_image numerator = height_image * distance_object return numerator / neg_di
def unwrap_output(iterations): """ Subroutine of `nx_Subdue` -- unwraps the standard Subdue output into pure python objects compatible with networkx """ out = list() for iteration in iterations: iter_out = list() for pattern in iteration: pattern_out = list() for instance in pattern.instances: pattern_out.append({ 'nodes': [vertex.id for vertex in instance.vertices], 'edges': [(edge.source.id, edge.target.id) for edge in instance.edges] }) iter_out.append(pattern_out) out.append(iter_out) return out
def set_param(fit_param,param_name,def_val): """Helper function for IB.py to handle setting of fit parameters.""" param = fit_param.get(param_name,def_val) # extract param, def = def_val if param is None: param = def_val # if extracted param is None, use def_val return param
def id_for_cli(val): """Generate an id for a CLI entry.""" if isinstance(val, str): return val return ""
def transListToGraph(list=[]): """ Transforms a List to a Graph in Xaya format""" graph = {} for item in list: graph[str(item)] = [item] return graph # Future -- add explicit type checking if not a list
def lr_schedule_sgd(epoch): """Learning Rate Schedule # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate """ lr = 1e-1 if epoch > 350: lr = 5e-4 elif epoch > 300: lr = 1e-3 elif epoch > 250: lr = 5e-3 elif epoch > 200: lr = 1e-2 elif epoch > 100: lr = 5e-2 print('Learning rate: ', lr) return lr
def evapot_soil_Liu_and_Todini_ETc(Vs0,Vsm,kc,ETr,X): """ The evapotranspiration taken up from the soil: - at the reference crop rate ETc (potential evapotranspiration rate) - without overland runoff infiltration """ #ETr is in mm #From Reference crop evapotranspiration #to crop evapotranspiration ETc=kc*ETr #to actual evapotranspiration ETa=ETc #From mm to m ETa=ETa*1e-3 #Compute the new soil volume Vs1=max(0.,Vs0-ETa*(X**2)) #From m to mm ETa=ETa*1e3 return ETa, Vs1
def openmpi_mpirun_service(mpirun_commandline, image, worker_memory): """ :type mpirun_commandline: str :type worker_memory: int :rtype: dict """ service = { 'name': "mpirun", 'docker_image': image, 'monitor': True, 'required_resources': {"memory": worker_memory}, 'ports': [], 'environment': [], 'volumes': [], 'command': mpirun_commandline, 'total_count': 1, 'essential_count': 1, 'startup_order': 1 } return service
def summation(num: int) -> int: """ A program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. :param num: :return: """ result = 0 for i in range(1, num + 1): result += i return result
def distance_between(agents_row_a, agents_row_b): """ calculate distance between 2 agents """ length = (((agents_row_a[0] - agents_row_b[0])**2) + ((agents_row_a[1] - agents_row_b[1])**2))**0.5 return(length)
def document_fraction_for_viewport_position(document_size, viewport_size, viewport_position): """ We take any point of the viewpoint, and calculate its relative position with respect to the posible positions it can be in (in practice: we use the top of the viewport, and realize that it cannot be lower than a viewport_size from the bottom). +--------------------+ |Document | | | +----------+ <------------lowest possible position of the top of the viewport, a.k.a. 100% |Viewport | | | | | | | | | | | | | | +----------+---------+ """ if document_size <= viewport_size: return None return viewport_position / (document_size - viewport_size)
def statusString(*strs): """Combine multiple status strings, using commas as needed.""" return ', '.join(s for s in strs if s)
def make_tuple(tuple_like): """Creates a tuple if given ``tuple_like`` value isn't list or tuple. Args: tuple_like: tuple like object - list or tuple Returns: tuple or list """ tuple_like = ( tuple_like if isinstance(tuple_like, (list, tuple)) else (tuple_like, tuple_like) ) return tuple_like
def remove_newline(s): """ Remove a trailing newline from the string, if one exists. """ if s.endswith("\n"): return s[:-1] return s
def MakeFindPackage(modules): """ Make a useful find_package command. """ # Print a useful cmake command res = 'find_package(VTK COMPONENTS\n' for module in sorted(modules): res += ' ' + module.replace('VTK::', 'vtk') + '\n' res += ')' return res
def get_cmdline_option(option_list, option_value): """ generate the command line equivalent to the list of options and their corresponding values """ OPTION_MAP = { "passes": lambda vlist: ("--passes " + ",".join(vlist)), "extra_passes": lambda vlist: ("--extra-passes " + ",".join(vlist)), "execute_trigger": lambda v: "--execute", "auto_test": lambda v: "--auto-test {}".format(v), "bench_test_number": lambda v: "--bench {}".format(v), "auto_test_std": lambda _: "--auto-test-std ", "target": lambda v: "--target {}".format(v), "precision": lambda v: "--precision {}".format(v), "vector_size": lambda v: "--vector-size {}".format(v), "function_name": lambda v: "--fname {}".format(v), "output_file": lambda v: "--output {}".format(v), "compute_max_error": lambda v: "--max-error", # discarding target_specific_options "target_exec_options": lambda _: "", } return " ".join(OPTION_MAP[option](option_value[option]) for option in option_list)
def z_to_r(z, a=200., b=1.6): """Conversion from reflectivities to rain rates. Calculates rain rates from radar reflectivities using a power law Z/R relationship Z = a*R**b Parameters ---------- z : float a float or an array of floats Corresponds to reflectivity Z in mm**6/m**3 a : float Parameter a of the Z/R relationship Standard value according to Marshall-Palmer is a=200., b=1.6 b : float Parameter b of the Z/R relationship Standard value according to Marshall-Palmer is b=1.6 Note ---- The German Weather Service uses a=256 and b=1.42 instead of the Marshall-Palmer defaults. Returns ------- output : float a float or an array of floats rainfall intensity in mm/h """ return (z / a) ** (1. / b)
def bcc_coord_test(x, y, z): # dist2 = 3, 4, 8 """Test for coordinate in BCC lattice""" return (x % 2 == y % 2) and (y % 2 == z % 2)
def create_modify_payload(module_params, fabric_id, msm_version): """ payload creation for fabric management in case of create/modify operations :param module_params: ansible module parameters :param fabric_id: fabric id in case of modify operation :param msm_version: msm version details :return: dict """ backup_params = dict([(k, v) for k, v in module_params.items() if v]) _payload = { "Name": backup_params["name"], "Description": backup_params.get("description"), "OverrideLLDPConfiguration": backup_params.get("override_LLDP_configuration"), "FabricDesignMapping": [ ], "FabricDesign": { } } if backup_params.get("primary_switch_service_tag"): _payload["FabricDesignMapping"].append({ "DesignNode": "Switch-A", "PhysicalNode": backup_params["primary_switch_service_tag"] }) if backup_params.get("secondary_switch_service_tag"): _payload["FabricDesignMapping"].append({ "DesignNode": "Switch-B", "PhysicalNode": backup_params["secondary_switch_service_tag"] }) if backup_params.get("fabric_design"): _payload.update({"FabricDesign": {"Name": backup_params["fabric_design"]}}) if msm_version.startswith("1.0"): # OverrideLLDPConfiguration attribute not supported in msm 1.0 version _payload.pop("OverrideLLDPConfiguration", None) if fabric_id: # update id/name in case of modify operation _payload["Name"] = backup_params.get("new_name", backup_params["name"]) _payload["Id"] = fabric_id payload = dict([(k, v) for k, v in _payload.items() if v]) return payload
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 """ min_num = ints[0] max_num = ints[0] for i in ints: if i <min_num: min_num = i elif i >max_num: max_num = i return (min_num, max_num)
def _same_cluster(site_a, site_b, clusters): """ Check if sites are in the same cluster """ a_index = [site_a in cluster for cluster in clusters].index(True) b_index = [site_b in cluster for cluster in clusters].index(True) return a_index == b_index
def triangle_density(x, mode): """Symetric triangle density with given mode and support of 2*mode Note: not normalized, max=1 at x=mode Parameters ---------- x mode : float in [0, 0.5] mode of the density (argmax) Returns ------- density on x : float """ if 0 <= x <= mode: return x / mode elif mode < x <= 2 * mode: return 2 - x / mode else: return 0
def parse_cluster(parse_dict_in, search_cluster=None): """ This is designed to allow someone to parse on a cluster for filtering outputs """ parsed_dict = {} if search_cluster is None: parsed_dict = parse_dict_in return parsed_dict else: for key,val in parse_dict_in.items(): if search_cluster in key.lower(): parsed_dict[key] = val return parsed_dict
def clean_cats(categories): """Change list of categories into a string.""" return ','.join(cat['alias'] for cat in categories)
def filter_dict_none_values(dict_to_filter): """Takes a dictionary and returns a copy without keys that have a None value""" return {key: value for key, value in dict_to_filter.items() if value is not None}
def test_split(index, value, dataset): """This method split a dataset based on an attribute and an attribute value""" left, right = list(), list() for row in dataset: if row[index] < value: left.append(row) else: right.append(row) return left, right
def age_restricted(content_limit, age_limit): """ Returns True iff the content should be blocked """ if age_limit is None: # No limit set return False if content_limit is None: return False # Content available for everyone return age_limit < content_limit
def split(v, lengths): """Split an array along first dimension into slices of specified lengths.""" i = 0 parts = [] for l in lengths: parts.append(v[i:i+l]) i += l if i < len(v): parts.append(v[i:]) return parts
def ignore_filename(fn, include_dotdirs=False): """ Ignores particular file name patterns output by TSK. Detecting new and renamed files becomes difficult if there are 3+ names for an inode (i.e. "dir", "dir/.", and "dir/child/.."). """ return (not include_dotdirs and (fn.endswith("/.") or fn.endswith("/.."))) or fn in set(['$FAT1','$FAT2'])
def fib(x): """assumes x an int >= 0 Returns Fibonacci of x""" assert type(x) == int and x >= 0 if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)
def format_logo(matrix): """ re-arrange the data """ output = [] for res in matrix: score, aa, modelpos = matrix[res].split("_") score = float(score) modelpos = int(modelpos) output.append( {"position": res, "aa": aa, "score": score, "model_position": modelpos} ) return output
def _output_filename(title): """Construct output filename.""" return title + ".html"
def __is_float(value): """Returns True if this value can be cast to a float, else False""" try: float(value) return True except ValueError: return False
def dictify_cookies(cookie_list): """ Turns list of cookies into dictionary where key is name of the cookie and value is list of cookie values. Args: cookie_list: List of CookieJar objects. Returns: Dictionary of cookie names as key and list of cookie values as dictionary value. Example: {"__cfduid":["db37572f9dd1", "d02f7e47ecb5"], "ts":["1380409840349","1380409840992"]} """ dicookie = {} cookies = [] _ = [cookies.extend(i.items()) for i in cookie_list] for name, cookie_val in cookies: if name in dicookie: dicookie[name].append(cookie_val) else: dicookie[name] = [cookie_val] return dicookie
def factorization(x, F): """ @brief Finds all prime factors for number x O(log(x)) @param x Number to be factorized @param F Minimum prime factors for 1 <= k <= n """ primeFactors = [] while (F[x] > 0): primeFactors += [F[x]] x /= F[x] primeFactors += [x] return primeFactors
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map): """Revert k:v to v:k""" return {v: k for k, v in disk_rses_id_name_map.items()}
def xxd(v): """ better than hex(v) because it doesn't put an L at the end """ return "0x{:x}".format(v)
def unsort(sorted_list, oidx): """ Unsort a sorted list, based on the original idx. """ assert len(sorted_list) == len(oidx), "Number of list elements must match with original indices." if len(sorted_list) == 0: return [] _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
def mod(a,b): """Return the modulus of a with respect to b.""" c = int(a/b) result = a - b*c return result
def get_eid_dt_from_eid_device(eid_device, dt, sort_method): """common unvectorized method for transforming SORT2 data into SORT1""" if sort_method == 1: eid = eid_device // 10 #print("SORT1 dt=%s eid_device=%s eid=%s" % (dt, eid_device, eid)) else: eid, dt = dt, eid_device return eid, dt
def find_indices(lst, condition): """ Find the indices of elements in a list `lst` that match a condition. """ return [i for i, elem in enumerate(lst) if condition(elem)]
def fix_fabric_env(input_dict, original_string, secret_name): """ Fix any fabric env in the provided dict. This will replace key paths to the specified path with keys pointing to the specified secret. """ changed = False if 'fabric_env' in input_dict: if 'key_filename' in input_dict['fabric_env']: if input_dict['fabric_env']['key_filename'] == original_string: input_dict['fabric_env'].pop('key_filename') input_dict['fabric_env']['key'] = { 'get_secret': secret_name, } changed = True return changed
def A_int(freqs, delt): """Calculates the Intermediate Amplitude Parameters ---------- freqs: array The frequencies in Natural units (``Mf``, G=c=1) of the waveform delt: array Coefficient solutions to match the inspiral to the merger-ringdown portion of the waveform """ return ( delt[0] + delt[1] * freqs + delt[2] * freqs ** 2 + delt[3] * freqs ** 3 + delt[4] * freqs ** 4 )
def equal_mirror(t, s): """ Returns whether t is the mirror image of s. """ if t is None and s is None: return True if t is None or s is None: return False if t.value != s.value: return False return equal_mirror(t.left, s.right) and equal_mirror(t.right, s.left)
def instanceType(ty): """ Return the type of an object as a string. """ #print(type(ty).__name__) return type(ty).__name__
def get_sample_name(filename): """Extract sample name from filename.""" return filename.split('/')[-1].split('.')[0]
def is_number(str): """ Checks wether a string is a number or not. :param str: String. :type str: string :returns: True if `str` can be converted to a float. :rtype: bool :Example: >>> is_number('10') True """ try: float(str) return True except ValueError: return False
def ConvertToMSIVersionNumberIfNeeded(product_version): """Change product_version to fit in an MSI version number if needed. Some products use a 4-field version numbering scheme whereas MSI looks only at the first three fields when considering version numbers. Furthermore, MSI version fields have documented width restrictions of 8bits.8bits.16bits as per http://msdn.microsoft.com/en-us/library/aa370859(VS.85).aspx As such, the following scheme is used: Product a.b.c.d -> MSI X.Y.Z: X = (1 << 6) | ((C & 0xffff) >> 10) Y = (C >> 2) & 0xff Z = ((C & 0x3) << 14) | (D & 0x3FFF) So eg. 6.1.420.8 would become 64.105.8 This assumes: 1) we care about neither the product major number nor the product minor number, e.g. we will never reset the 'c' number after an increase in either 'a' or 'b'. 2) 'd' will always be <= 16383 3) 'c' is <= 65535 We assert on assumptions 2) and 3) Args: product_version: A version string in "#.#.#.#" format. Returns: An MSI-compatible version string, or if product_version is not of the expected format, then the original product_version value. """ try: version_field_strings = product_version.split('.') (build, patch) = [int(x) for x in version_field_strings[2:]] except: # pylint: disable=bare-except # Couldn't parse the version number as a 4-term period-separated number, # just return the original string. return product_version # Check that the input version number is in range. assert patch <= 16383, 'Error, patch number %s out of range.' % patch assert build <= 65535, 'Error, build number %s out of range.' % build msi_major = (1 << 6) | ((build & 0xffff) >> 10) msi_minor = (build >> 2) & 0xff msi_build = ((build & 0x3) << 14) | (patch & 0x3FFF) return str(msi_major) + '.' + str(msi_minor) + '.' + str(msi_build)
def from_grid_range(x): """from [-1,1] to [0,1]""" return (x + 1) / 2.0
def game_exists(session): """ Returns True if exists, False otherwise """ # Your code goes here return False
def handle_extends(tail, line_index): """Handles an extends line in a snippet.""" if tail: return "extends", ([p.strip() for p in tail.split(",")],) else: return "error", ("'extends' without file types", line_index)
def inflate(mappings_list, root=None, dict_factory=dict): """ Expands a list of tuples containing paths and values into a mapping tree. >>> inflate([('some.long.path.name','value')]) {'some': {'long': {'path': {'name': 'value'}}}} """ root_map = root or dict_factory() for path, value in mappings_list: path = path.split('.') # traverse the dotted path, creating new dictionaries as needed parent = root_map for name in path: #if path.index(name) == len(path) - 1: if path[-1] == name: # this is the last name in the path - set the value! parent[name] = value else: # this is not a leaf, so create an empty dictionary if there # isn't one there already parent.setdefault(name, dict_factory()) parent = parent[name] return root_map
def nthwords2int(nthword): """Takes an "nth-word" (eg 3rd, 21st, 28th) strips off the ordinal ending and returns the pure number.""" ordinal_ending_chars = 'stndrh' # from 'st', 'nd', 'rd', 'th' try: int_output = int(nthword.strip(ordinal_ending_chars)) except Exception as e: raise Exception('Illegal nth-word: ' + nthword) return int_output
def with_prefix(string, prefix): """ Prefix single string with the defined custom data prefix (such as data-field-whatevs). """ return "{}-{}".format(prefix, string)
def pprint_things(l): """Pretty print""" return ''.join("{:20}".format(e) for e in l.split("\t")) + "\n"
def replace_pcell_libname(pcell_script, libname): """Replace {libname} tag with library name Parameters ---------- pcell_script : str Python PCell script. libname : str Library name. Returns ------- str PCell script with the {libname} tag replaced by the library name. """ return pcell_script.replace('{libname}', libname)
def get_class_predict(class_split, ratio): """get predict memory for each class :param class_split: use class split boundary to get class predict :param ratio: ratio for two adjacent class split boundary to generate the predict value. for example, class_split=[300, 800, 1500, 5000], ratio=0.5, then class_predict[0] = class_split[0]*0.5 + class_split[1]*0.5 and class_predict[-1] = class_split[-1], then class_predict = [550, 1150, 3250, 5000] """ class_predict = [] for i in range(len(class_split) - 1): class_predict.append(ratio*class_split[i] + (1-ratio)*class_split[i+1]) class_predict.append(class_split[-1]) return class_predict
def chunks(l, n): """https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks""" n = max(1, n) return [l[i:i+n] for i in range(0, len(l), n)]
def _ibis_sqlite_power(arg, power): """Raise `arg` to the `power` power. Parameters ---------- arg : number Number to raise to `power`. power : number Number to raise `arg` to. Returns ------- result : Optional[number] None If either argument is None or we're trying to take a fractional power or a negative number """ if arg < 0.0 and not power.is_integer(): return None return arg**power
def score_aggregator(fitness_list): """ aggregate the scores :args fitness_list: list of average rolls :returns: aggregate of the scores """ average_value = sum(fitness_list)/len(fitness_list) best_value = min(fitness_list) worst_value = max(fitness_list) score_agg =[best_value, average_value, worst_value] return score_agg
def get_number_mwus_per_word(mwu_counter, min_freq=2): """ :param mwu_counter: dictionary mapping MWUs to their frequency counts :return: dictionary mapping words to the number of MWUs within which they occur """ ret = dict() for mwu, freq in mwu_counter.items(): if freq < min_freq: continue for w in mwu: if w not in ret: ret[w] = 0 ret[w] += 1 return ret
def bert_squad_out_to_emrai(squad_out): """ Convert the SQuAD-type output from our BERT wrapper to the output type the EMR.AI Q&A system has historically used. :param squad_out: :return: """ best = squad_out[0] start, end = best['start_offset'], best['end_offset'] return [[start, end]] if start < end else []