content
stringlengths
42
6.51k
def _check_dimensions_objects(R): """ :param R: dictionary from (type, type) to relational matrix :return: dictionary string to int (dimension of that type) """ print(R) dimensions = {} for r in R: t1, t2 = r for l in range(len(R[r])): if dimensions.get(t1) is not None: if R[r][l].shape[0] != dimensions[t1]: raise ValueError("Object type " + t1 + " has" "mismatching dimensions") else: dimensions[t1] = R[r][l].shape[0] if dimensions.get(t2) is not None: if R[r][l].shape[1] != dimensions[t2]: raise ValueError("Object type " + t2 + " has" "mismatching dimensions") else: print(R[r][l].shape) dimensions[t2] = R[r][l].shape[1] return dimensions
def beta_mean(x,y): """Calculates the mean of the Beta(x,y) distribution Args: x (float): alpha (shape) parameter y (float): beta (scale) parameter Returns: float: A float that returns x/(x+y) """ output = x / (x+y) return output
def _pick_geographic_location(parameters_json: dict) -> list: """ Sometimes, curate has an array, and sometimes an array within an array, where the inner-most array will have strings. We need to accommodate both. """ """ placeOfCreation has this format: ["Ani, Kars Province, Turkey", " +40.507500+43.572777.", "Ani"]. We will choose the first one that contains a comma""" if 'placeOfCreation' not in parameters_json: return [] for place_string in parameters_json.get("placeOfCreation", []): if isinstance(place_string, list): if len(place_string) == 0: return [] place_string = place_string[0] if ',' in place_string: return [{"display": place_string}] return []
def generate_level_sequence(nested_list,root_rank=0): """ Return a level sequence representation of a tree or subtree, based on a nested list representation. """ level_sequence = [root_rank] for child in nested_list: level_sequence += generate_level_sequence(child,root_rank=root_rank+1) return level_sequence
def compare(a, b): """ Constant time string comparision, mitigates side channel attacks. """ if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0
def escape_colons(string_to_escape): """ Escape the colons. This is necessary for secure password stanzas. """ return string_to_escape.replace(":", "\\:")
def remove_non_breaking_space(string): """replace non breaking space characters""" return string.replace("\xc2\xa0", "").replace("\xa0", "") if string else ""
def site_email_prefix(request, registry, settings): """Expose website URL from ``tm.site_email_prefix`` config variable to templates. This is used as the subject prefix in outgoing email. E.g. if the value is ``SuperSite`` you'll email subjects:: [SuperSite] Welcome to www.supersite.com """ return settings["tm.site_email_prefix"]
def fib2(n): """ return Fibonacci series up to n """ result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
def calInitVec(tag_tag_n, tags_n): """ It is a function to calculate init vector. :param tag_tag_n: Tag-tag type and its number :param tags_n: Tag type and its number :return: init vec """ # Calculate sum of tag_tag_n sum_tag = sum(list(tag_tag_n.values())) init_vec = [tags_n[value] / sum_tag for value in tags_n] return init_vec
def flows_from_generic(flows): """SequenceCollection from generic seq x pos data: seq of seqs of chars. This is an InputHandler for SequenceCollection. It converts a generic list (each item in the list will be mapped onto an object using seq_constructor and assigns sequential integers (0-based) as names. """ names = [] info = [] for f in flows: if hasattr(f, 'Name'): names.append(f.Name) else: names.append(None) if hasattr(f, 'header_info'): info.append(f.header_info) else: info.append(None) return flows, names, info
def listify(x): """ allow single item to be treated same as list. simplifies loops and list comprehensions """ if isinstance(x, tuple): return list(x) if not isinstance(x, list): return [x] return x
def create_coco_refs(data_ref): """Create MS-COCO human references JSON.""" out = {'info': {}, 'licenses': [], 'images': [], 'type': 'captions', 'annotations': []} ref_id = 0 for inst_id, refs in enumerate(data_ref): out['images'].append({'id': 'inst-%d' % inst_id}) for ref in refs: out['annotations'].append({'image_id': 'inst-%d' % inst_id, 'id': ref_id, 'caption': ref}) ref_id += 1 return out
def Secant(f, x_minus2, x_minus1, epsilon = 1.0E-4, N = 10000): """ Uses the Secant method to solve for f(x) = 0 given the values to start at x_-2 and x_-1. returns a 3-tuple of x, n, and f(x) """ x = x_minus2 n = 0 while abs(f(x)) > epsilon and n <=N: n+= 1 temp = x x = x_minus1 - ( (f(x_minus1)*(x_minus1 - x_minus2))/(f(x_minus1) - f(x_minus2)) ) x_minus2 = x_minus1 x_minus1 = temp return x, n, f(x)
def get_lesion_size_ratio(corners, patch_shape): """Compute bbox to patch size ratio Args: corner_resize: tightest bbox coord of lesion (xmin, ymin, xmax, ymax) patch_shape: in the order of (y_size, x_size) Returns: lesion_size_ratio: sqrt(lesion_area / patch_area) """ xmin, ymin, xmax, ymax = corners h, w = patch_shape lesion_size_ratio = ((xmax - xmin) * (ymax - ymin) / (h * w)) ** 0.5 return lesion_size_ratio
def factorial(num): """Calculates the factorial for a given number""" total = 1 for i in range(2, (num + 1)): total *= i return total
def language_check(message ,texts): """ check if the input is a correct language """ if message not in texts: return False return True
def calculate_change(start: float, end: float) -> float: """Use Yahoo Finance API to get the relevent data.""" return round(((end - start) / start) * 100, 2)
def dumps_requirement_options( options, opt_string, quote_value=False, one_per_line=False, ): """ Given a list of ``options`` and an ``opt_string``, return a string suitable for use in a pip requirements file. Raise Exception if any option name or value type is unknown. """ option_items = [] if quote_value: q = '"' else: q = "" if one_per_line: l = "\\\n " else: l = "" for opt in options: if isinstance(opt, str): option_items.append(f"{l}{opt_string}={q}{opt}{q}") elif isinstance(opt, list): for val in sorted(opt): option_items.append(f"{l}{opt_string}={q}{val}{q}") else: raise Exception( f"Internal error: Unknown requirement option {opt!r} " ) return " ".join(option_items)
def numToHex(n): """Convert integer n in range [0, 15] to hex.""" try: return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"][n] except: return -1
def sum_of_digits(number): """ What comes in: An integer. What goes out: Returns the sum of the digits in the given integer. Side effects: None. Example: If the integer is 83135, this function returns (8 + 3 + 1 + 3 + 5), which is 20. """ # ------------------------------------------------------------------ # Students: # Do NOT touch the above sum_of_digits function - it has no TO DO. # Do NOT copy code from this function. # # Instead, ** CALL ** this function as needed in the problems below. # ------------------------------------------------------------------ if number < 0: number = -number digit_sum = 0 while True: if number == 0: break digit_sum = digit_sum + (number % 10) number = number // 10 return digit_sum
def text_length(text): """ Get text length """ text = text.decode('utf-8') return len(text)
def get_dict_keys(d): """Return keys of a dictionary""" return [key for key in d]
def fib(n: int) -> int: """Calculate n-th Fibonacci number recursively, long version.""" assert n >= 0 if n in [0, 1]: return 1 else: return fib(n - 1) + fib(n - 2)
def _kbase_log_name(name): """Smarter name of KBase logger.""" # no name => root if not name: return "biokbase" # absolute name if name.startswith("biokbase."): return name # relative name return "biokbase." + name
def gendot(adj): """ Return a string representing the graph in Graphviz DOT format with all p->q edges. Parameter adj is an adjacency list. """ dot = "digraph g {\n" dot += " rankdir=LR;\n" # fill in dot += "}\n" return dot
def set_query_string_parameter(page: int, data_order: str="") -> str: """ Create the query string to add at the end of the request url. :param page: Page number to extract the data :param data_order: Order of the data :return: Query string parameter """ # Data is returned in ascending (oldest first, newest last) order. # Use the ?order=desc query parameter to reverse this order order_parameter = lambda order: 'order=desc'if 'desc' in order else '' # By default, the api return 100 results at a time. You have to use ?page=2 to list through the results page_parameter = 'page={}'.format(page) query_string_parameter = '?' + page_parameter + '&' + order_parameter(data_order) return query_string_parameter
def round_tat(num): """Changes the turnaround time from a float into natural language hours + minutes.""" remain = num%1 if num.is_integer(): if int(num) == 1: return str(int(num)) + " hour." else: return str(int(num)) + " hours." else: if num < 1: return str(int(remain*60)) + " minutes." elif num-remain == 1: return str(int(num-remain)) + " hour and " + \ str(int(remain*60)) + " minutes." else: return str(int(num-remain)) + " hours and " + \ str(int(remain*60)) + " minutes."
def _fully_qualified_typename(cls): """Returns a 'package...module.ClassName' string for the supplied class.""" return '{}.{}'.format(cls.__module__, cls.__name__)
def unquote(s): """Kindly rewritten by Damien from Micropython""" """No longer uses caching because of memory limitations""" res = s.split('%') for i in range(1, len(res)): item = res[i] try: res[i] = chr(int(item[:2], 16)) + item[2:] except ValueError: res[i] = '%' + item return "".join(res)
def reverse(x): """ :type x: int :rtype: int """ new_str = str(x) i = 1 rev_str = new_str[::-1] if rev_str[-1] == "-": rev_str = rev_str.strip("-") i = -1 if (int(rev_str)>=2**31): return 0 return (int(rev_str)) * i
def cloudfront_public_lookup(session, hostname): """ Lookup cloudfront public domain name which has hostname as the origin. Args: session(Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed hostname: name of api domain or auth domain. Ex: api.integration.theboss.io Returns: (string|None) : Public DNS name of cloud front or None if it could not be located """ if session is None: return None client = session.client('cloudfront') response = client.list_distributions( MaxItems='100' ) items = response["DistributionList"]["Items"] for item in items: cloud_front_domain_name = item["DomainName"] if item["Aliases"]["Quantity"] > 0: if hostname in item["Aliases"]["Items"]: return cloud_front_domain_name return None
def mixrange(s): """ Expand a range which looks like "1-3,6,8-10" to [1, 2, 3, 6, 8, 9, 10] """ r = [] for i in s.split(","): if "-" not in i: r.append(int(i)) else: l, h = list(map(int, i.split("-"))) r += list(range(l, h + 1)) return r
def flatten_list(obj): """ Given a set of embedded lists, return a single, "flattened" list. :param obj: :return: """ if not isinstance(obj, list): return [obj] else: ret_list = [] for elt in obj: ret_list.extend(flatten_list(elt)) return ret_list
def d(a, b, N): """Wrapped distance""" if b < a: tmp = a a = b b = tmp return min(b - a, N - (b - a))
def fizzbuzz(num: int) -> str: """For the given number, returns the correct answer in the Fizzbuzz game. Args: num: An integer number > 0 Returns: A string corresponding to the game answer. """ if num % 3 == 0 and num % 5 == 0: return f"{ num } - FizzBuzz" elif num % 3 == 0: return f"{ num } - Fizz" elif num % 5 == 0: return f"{ num } - Buzz" else: return f"{ num }"
def ratio(num, denom, max_val, MAX_MULTIPLIER=2): """ function to define ratio and handle o denominator """ if denom == 0: return float(max_val * MAX_MULTIPLIER) else: return float(num / denom)
def concatenate_list_into_string(alist): """ Given a list like alist = ["ada", "subtract", "divide", "multiply"] the aim is to concatentate the to have a string of the form: "adasubstractdividemultiply" :param alist: list [list of items] :return: str """ string = "" for item in alist: string += f'{item}' return string
def unpack_meta(*inputs, **kwinputs): """Update ``kwinputs`` with keys and values from its ``meta`` dictionary.""" if 'meta' in kwinputs: new_kwinputs = kwinputs['meta'].copy() new_kwinputs.update(kwinputs) kwinputs = new_kwinputs return inputs, kwinputs
def steering2(course, power): """ Computes how fast each motor in a pair should turn to achieve the specified steering. Input: course [-100, 100]: * -100 means turn left as fast as possible, * 0 means drive in a straight line, and * 100 means turn right as fast as possible. * If >100 power_right = -power * If <100 power_left = power power: the power that should be applied to the outmost motor (the one rotating faster). The power of the other motor will be computed automatically. Output: a tuple of power values for a pair of motors. Example: for (motor, power) in zip((left_motor, right_motor), steering(50, 90)): motor.run_forever(speed_sp=power) """ if course >= 0: if course > 100: power_right = 0 power_left = power else: power_left = power power_right = power - ((power * course) / 100) else: if course < -100: power_left = 0 power_right = power else: power_right = power power_left = power + ((power * course) / 100) return (int(power_left), int(power_right))
def is_starter(index, reason=None): """Takes index and reason column, returns either S, R or DNP. Used on boxscore df. Reason is either Nan or 'Did Not Play'. Keyword arguments: index -- Used to define if starter or not reason -- Used to define if DNP or not """ # Any reason converted to DNP if type(reason) == str: return 'DNP' elif index <= 4: return 'S' else: return 'R'
def serialize_class(cls): """ Serialize Python class """ return '{}:{}'.format(cls.__module__, cls.__name__)
def _IsInstanceShutdown(instance_info): """Determine whether the instance is shutdown. An instance is shutdown when a user shuts it down from within, and we do not remove domains to be able to detect that. The dying state has been added as a precaution, as Xen's status reporting is weird. """ return instance_info == "---s--" \ or instance_info == "---s-d"
def clamp(val, valmin, valmax): """Simple clamping function, limits to [min, max]""" if val < valmin: return valmin if val > valmax: return valmax return val
def calc_loop_steps(n, step_size, offset=0): """Calculates a list of 2-tuples for looping through `n` results with steps of size `step_size`. """ steps = (n - offset) // step_size remainder = (n - offset) % step_size moves = [ (offset + (step_size * s), offset + (step_size * (s + 1))) for s in range(steps) ] if remainder > 0: moves.append( (offset + (step_size * steps), (step_size * steps) + remainder + offset) ) return moves
def _wick_length(close, low, open, high, upper): """ :param close: :param low: :param open: :param high: :return: """ if close > open: top_wick = high - close bottom_wick = open - low else: top_wick = high - open bottom_wick = close - low if upper: return top_wick else: return bottom_wick
def _dict_to_strings(kwds): """Convert all values in a dictionary to strings.""" ot = {} assert isinstance(kwds, dict) for k, v in kwds.items(): ot[k] = str(v) return ot
def efficientnet_params(model_name): """ Map EfficientNet model name to parameter coefficients. """ params_dict = { # Coefficients: width,depth,res,dropout 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 'efficientnet-b6': (1.8, 2.6, 528, 0.5), 'efficientnet-b7': (2.0, 3.1, 600, 0.5), } return params_dict[model_name]
def abreArquivos(arquivo): """ :param arquivo: arquivo que ira ser aberto :return: palavras separas em lista """ palavrasArquivo = list () with open (str (arquivo), 'r') as arquivoCriptografado: for linha in arquivoCriptografado: if linha.strip ('\n') != '': for palavra in linha.strip ('\n').split (" "): palavrasArquivo.append (palavra) return palavrasArquivo
def next_instruction_is_function_or_class(lines): """Is the first non-empty, non-commented line of the cell either a function or a class?""" for i, line in enumerate(lines): if not line.strip(): # empty line if i > 0 and not lines[i - 1].strip(): return False continue if line.startswith('def ') or line.startswith('class '): return True if line.startswith(('#', '@', ' ')): continue return False return False
def average(lst): """Averages a list, tuple, or set of numeric values""" return sum(lst) / len(lst)
def omt_check(grade_v, grade_i, grade_j): """ A check used in omt table generation """ # A_r ^ B_s = <A_r B_s>_|r+s| return grade_v == (grade_i + grade_j)
def get_merged_jobs_steps(jobs, processed_cfg): """ Merge and filter steps from all jobs """ blocked_steps = ['persist_to_workspace', 'attach_workspace', 'store_artifacts'] merged_steps = [] for jname in jobs: steps = processed_cfg['jobs'][jname]['steps'] merged_steps += list(filter(lambda step: list(step)[0] not in blocked_steps, steps)) return merged_steps
def tzy_flatten(ll): """ Own flatten just for use of this context. Expected outcome: > flatten([1, 2, [3, 4], [5]]) [1, 2, 3, 4, 5] Only goes 1 depth so should be O(n) time, but also O(n) space """ ret = [] for item in ll: if isinstance(item, list): for subitem in item: ret.append(subitem) else: ret.append(item) return ret
def give_color_to_direction_static(dir): """ Assigns a color to the direction (static-defined colors) Parameters -------------- dir Direction Returns -------------- col Color """ direction_colors = [[-0.5, "#4444FF"], [-0.1, "#AAAAFF"], [0.0, "#CCCCCC"], [0.5, "#FFAAAA"], [1.0, "#FF4444"]] for col in direction_colors: if col[0] >= dir: return col[1]
def bus_resolve(bus_descriptor: str): """ >>> bus_resolve('bus2.3.1.2') ('bus2', (3, 1, 2)) >>> bus_resolve('bus2.33.14.12323.2.3.3') ('bus2', (33, 14, 12323, 2, 3, 3)) """ bus_descriptor.replace('bus.', '') tkns = bus_descriptor.split('.') bus = tkns[0] terminals = tuple(int(x) for x in tkns[1:]) return bus, terminals
def err_msg(_format, _type, path): """Assertion error message.""" return "while testing format={}, data type={} saved as {}.".format( _format, _type, path )
def FindApprovalValueByID(approval_id, approval_values): """Find the specified approval_value in the given list or return None.""" for av in approval_values: if av.approval_id == approval_id: return av return None
def helloworld(name): """Testando Multiplas linhas Args: name (string): parametro entrada nome Returns: string: parametro saida nome """ print("Hello World!") print(name) return name
def get_contours_points(found, contours): """ get contour's all inner points :param found: :param contours: :return: contour's all inner points """ contours_points = [] for i in found: c = contours[i] for sublist in c: for p in sublist: contours_points.append(p) return contours_points
def parse_metadata_json(data): """ Function to parse the json response from the metadata or the arxiv_metadata collections in Solr. It returns the dblp url. docs is a list of one result, so this is obtained by docs[0].get('url')""" # docs contains authors, title, id generated by Solr, url docs = data['response']['docs'] # NOTE: there are records without authors and urls. This is why the # get method is always used to get the value instead of getting the value # by applying the [] operator on the key. if docs == []: # Return None if not found. return None dblp_url = docs[0].get('url') return dblp_url
def get_positions_at_time(positions, t): """ Return a list of positions (dicts) closest to, but before time t. """ # Assume positions list is already sorted. # frame is a list of positions (dicts) that have the same timestamp. frame = [] frame_time = 0.0 for pos in positions: # If we passed the target time t, return the frame we have if pos["time"] > t: break # If this positions is part of the current frame, add it if pos["time"] == frame_time: frame.append(pos) # If current frame is over, make a new frame and add this position to it else: frame = [] frame.append(pos) frame_time = pos["time"] return frame
def get_snapshots_from_text(query_output): """ Translate expanded snapshots from `cali-query -e` output into list of dicts Takes input in the form attr1=x,attr2=y attr1=z ... and converts it to `[ { 'attr1' : 'x', 'attr2' : 'y' }, { 'attr1' : 'z' } ]` """ snapshots = [] for line in query_output.decode().splitlines(): snapshots.append( { kv.partition('=')[0] : kv.partition('=')[2] for kv in line.split(',') } ) return snapshots
def to_query_str(params): """Converts a dict of params to a query string. Args: params (dict): A dictionary of parameters, where each key is a parameter name, and each value is either a string or something that can be converted into a string. If `params` is a list, it will be converted to a comma-delimited string of values (e.g., "thing=1,2,3") Returns: str: A URI query string including the "?" prefix, or an empty string if no params are given (the dict is empty). """ if not params: return '' # PERF: This is faster than a list comprehension and join, mainly # because it allows us to inline the value transform. query_str = '?' for k, v in params.items(): if v is True: v = 'true' elif v is False: v = 'false' elif isinstance(v, list): v = ','.join(map(str, v)) else: v = str(v) query_str += k + '=' + v + '&' return query_str[:-1]
def get_starting_chunk(filename, length=1024): """ :param filename: File to open and get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode try: with open(filename, 'rb') as f: chunk = f.read(length) return chunk except IOError as e: print(e)
def decimalRound(toRound, numDec): """ decimalRound Function used to round numbers to given decimal value with the following rules: -should add zeroes if numDec > current number of decimal places -should round up/down properly -numDec = 0 should return an int @param toRound << number to round @param numDec << number of decimal places wanted @return correctDec << correctly rounded number """ correctDec = round(toRound, numDec) return correctDec
def do_pick(pick_status : int): """ This function takes one integer type argument and returns a boolean. Pick Status = Even ==> return True (user's turn) Pick Status = Odd ==> return False (comp's turn) """ if (pick_status % 2) == 0: return True else: return False
def save(level, save_type): """ Calculate a character's saves based off level level: character's level save_type: "good" or "poor" returns a number representing the current base save """ if save_type == "good": return int(round(level/2)) + 2 else: return int(round(level/3))
def roundup_20(x): """ Project: 'ICOS Carbon Portal' Created: Tue May 07 09:00:00 2019 Last Changed: Tue May 07 09:00:00 2019 Version: 1.0.0 Author(s): Karolina Description: Function that takes a number as input and rounds it up to the closest "20". Input parameters: Number (var_name: 'x', var_type: Integer or Float) Output: Float """ #Import module: import math import numbers #Check if input parameter is numeric: if(isinstance(x, numbers.Number)==True): #for positive numbers, multiples of 20.0: if((x>=0)&(((x/10.0)%20)%2 == 0)): return int(math.ceil(x / 10.0)) * 10 +20 #for positive numbers with an even number as 2nd digit: elif((x>0)&(int(x/10.0)%2==0)): return int(math.ceil(x / 10.0)) * 10 +10 #for positive and negative numbers, whose 2nd digit #is an odd number (except for i in [-1,-9]): elif(int(x/10.0)%2!=0): return int((x / 10.0)) * 10 +10 #for negative numbers, whose 1st or 2nd digit is an even number: elif((x<-10) & (int(x)%2==0)): return int((x / 10.0)) * 10 +20 else: return 0 #If input parameter is NOT numeric, prompt an error message: else: print("Input parameter is not numeric!")
def is_point_on_border( point_x, point_y, margin_x=0, margin_y=0 ): """Tell if a point is on the border of a rectangular area. Arguments +++++++++ :param int point_x: point's x coordinate :param int point_y: point's y coordinate Keyword arguments +++++++++++++++++ :param int margin_x: margin on x coordinate :param int margin_y: margin on y coordinate return: bool """ return (point_x < margin_x) or (point_y < margin_y)
def _imf_salpeter(x): """ Compute a Salpeter IMF Parameters ---------- x : numpy vector masses Returns ------- imf : numpy vector unformalized IMF """ return x ** (-2.35)
def as_frozen(x): """Return an immutable representation for x.""" if isinstance(x, dict): return tuple(sorted((k, as_frozen(v)) for k, v in x.items())) elif isinstance(x, (list, tuple)): return tuple(as_frozen(y) for y in x) else: return x
def get_name_length(name): """ Returns the length of first name. Parameters: ------ name: (str) the input name Returns: ------- length of name: (float) """ if name == name: return len(name) else: return 0
def fruit_into_baskets(fruits): """Find the maximum contiguous fruits that can be picked with two baskets. Time: O(n) Space: O(1) >>> fruit_into_baskets(['A', 'B', 'C', 'A', 'C']) 3 >>> fruit_into_baskets(['A', 'B', 'C', 'B', 'B', 'C', 'A']) 5 """ fruit_counts = {} max_fruits = 0 win_start = 0 for win_end in range(len(fruits)): last_fruit = fruits[win_end] fruit_counts[last_fruit] = fruit_counts.get(last_fruit, 0) + 1 if len(fruit_counts) > 2: first_fruit = fruits[win_start] fruit_counts[first_fruit] -= 1 if fruit_counts[first_fruit] == 0: del fruit_counts[first_fruit] win_start += 1 max_fruits = max(max_fruits, win_end - win_start + 1) return max_fruits
def getDecile(type): """ Return decile in either string or numeric form """ if type == 'numeric': return [0.05, 0.15, 0.25, 0.35, 0.45, 0.50, 0.55, 0.65, 0.75, 0.85, 0.95] elif type == 'string': return ['5p','15p','25p','35p','45p','50p','55p','65p','75p','85p','95p'] else: raise ValueError
def _NormalizedScript(script): """Translates $PYTHON_LIB in the given script. Returns the translation.""" if script: return script.replace('$PYTHON_LIB/', '') return script
def clean_name(name: str) -> str: """Clean a name to a ticker Parameters ---------- name : str The value to be cleaned Returns ---------- str A cleaned value """ return name.replace("beta_", "").upper()
def _safe(key, dic): """Safe call to a dictionary. Returns value or None if key or dictionary does not exist""" if dic is not None and key in dic: return dic[key] else: return None
def byte_to_megabyte(byte): """ Convert byte value to megabyte """ return byte / (1024.0**2)
def kewley_agn_oi(log_oi_ha): """Seyfert/LINER classification line for log([OI]/Ha).""" return 1.18 * log_oi_ha + 1.30
def squeeze_whitespace(text): """Remove extra whitespace, newline and tab characters from text.""" return ' '.join(text.split())
def find_exml(val, attrib=False): """Test that the XML value exists, return value, else return None""" if val is not None: if attrib: # it's an XML attribute return val else: # it's an XML value return val.text else: return None
def lerp(a, b, t): """lerp = linear interpolation. Returns a value between a and b, based on the value of t When t=0, a is returned. When t=1, b is returned. When t is between 0 and 1, a value mixed between a and b is returned. For example, lerp(10,20,0.5) will return 15. Note the result is not clamped, so if t is less than 0 or greater than 1 then the value is extrapolated beyond a or b. """ return a + (b - a) * t
def filter_attributes(resource_type): """Returns a list of attributes for a given resource type. :param str resource_type: type of resource whose list of attributes we want to extract. Valid values are 'adminTask', 'task', 'adminVApp', 'vApp' and 'adminCatalogItem', 'catalogItem'. :return: the list of attributes that are relevant for the given resource type. :rtype: list """ attributes = None if resource_type in ['adminTask', 'task']: attributes = ['id', 'name', 'objectName', 'status', 'startDate'] elif resource_type in ['adminVApp', 'vApp']: attributes = [ 'id', 'name', 'numberOfVMs', 'status', 'numberOfCpus', 'memoryAllocationMB', 'storageKB', 'ownerName', 'isDeployed', 'isEnabled', 'vdcName' ] elif resource_type in ['adminCatalogItem', 'catalogItem']: attributes = [ 'id', 'name', 'catalogName', 'storageKB', 'status', 'entityType', 'vdcName', 'isPublished', 'ownerName' ] return attributes
def _test_pgm(h): """PGM (portable graymap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r': return 'pgm'
def is_counting_line_passed(point, counting_line, line_orientation): """ To check if the point passed the counting line by the x coord if it left/right or y coord if it bottom/top. :param point: the object location. :param counting_line: the coordinates list of the area. :param line_orientation: the string of the orientation of the line.need to be top, bottom, left, right. :return: True if the point passed the line , False if the point didnt pass the line. """ if line_orientation == 'top': return point[1] < counting_line[0][1] elif line_orientation == 'bottom': return point[1] > counting_line[0][1] elif line_orientation == 'left': return point[0] < counting_line[0][0] elif line_orientation == 'right': return point[0] > counting_line[0][0]
def format_resource_id(resource_type, resource_id): """Format the resource id as $RESOURCE_TYPE/$RESOURCE_ID. Args: resource_type (str): The resource type. resource_id (str): The resource id. Returns: str: The formatted resource id. """ return '%s/%s' % (resource_type, resource_id)
def normalize_to_list(obj, lst): """Returns a matching member of a Player or Card list, if possible. Assumes names of objects in the list are unique, for match by name. Arguments: obj -- a Player, Card, or a name (string) representing one lst -- a list of Players or Cards Returns: a Player or Card from the list, matching obj """ if obj in lst: return obj try: my_obj = next(o for o in lst if o.name == obj) except(StopIteration): raise ValueError("No such Player/Card {} in list {}".format( obj, lst)) return my_obj
def rgb_to_hex(rgb): """Receives (r, g, b) tuple, checks if each rgb int is within RGB boundaries (0, 255) and returns its converted hex, for example: Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0""" hash_ = "#" for i in rgb: if i not in range(0, 256): raise ValueError ("Not in range") else: hash_ += f"{str(hex(i))[2:].upper():0>2}" return hash_
def clog2(x): """Ceiling log 2 of x. >>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4) (0, 0, 1, 2, 2) >>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9) (3, 3, 3, 3, 4) >>> clog2(1 << 31) 31 >>> clog2(1 << 63) 63 >>> clog2(1 << 11) 11 """ x -= 1 i = 0 while True: if x <= 0: break x = x >> 1 i += 1 return i
def solutionClosed(n: int, p: float) -> float: """ A closed-form solution to solutionRecursive's recurrence relation. Derivation: Let q = (-2p + 1). h[0] = 1, h[n] = q h[n-1] + p. By iterating, h[1] = q + p, h[2] = q (q + p) + p = q^2 + pq + p, h[3] = q (q^2 + pq + p) + p = q^3 + pq^2 + pq + p, h[n] = q^n + p(q^(n-1) + q^(n-2) + ... + q^0). Because the term p(q^(n-1) + q^(n-2) + ... + q^0) is a geometric series, h[n] = q^n + p(1 - q^n)/(1 - q). Substituting q = (-2p + 1) and simplifying, h[n] = ((-2p + 1)^n + 1)/2. """ return ((-2*p + 1)**n + 1)/2
def with_apostroves_if_necessary(str_in: str) -> str: """ Returns the same string, surrounded with apostrophes, only if it contains whitespaces. """ if str_in.find(' ') == -1: return str_in else: return '"' + str_in + '"'
def convert_dataset_name(store_name): """Parse {dataset}-{split} dataset name format.""" dataset, *split = store_name.rsplit('-') if split: split = split[0] else: split = None return dataset, split
def tuple_multiply(t, k): """ Multiplies the tuple `t` by the scalar `k` Example >>> t = (1, 2, 3) >>> tuple_multiply(t, -1) (-1, -2, -3) """ return tuple(k * t_i for t_i in t)
def level_validation(user_level, all_data_info): """ Check if the level selected by the user exists in the database. Returns the level number entered by the user, if it exists. If the level entered doesn't exist, it returns an error message and exits the program. Params: 1) user_level - This is the input received from the user 2) all_data_info - This is the list containing all the information from the database Examples: valid_level = level_validation(chosen_level, all_data) > valid_level = level_validation("1", all_data) > valid_level = "1" valid_level = level_validation(chosen_level, all_data) > valid_level = level_validation("100192", all_data) > "You chose an invalid level, please try again", exit() """ count = 0 for data in all_data_info: if data["level"] == user_level: count = count + 1 else: pass if count == 0: return print("You chose an invalid level, please try again"), exit() else: return user_level
def symbols_db(db): """ return dictionary like version of database""" return db if type(db) is dict else {symbol.name: symbol for symbol in db}
def _couple_exists(dict_, a, b): """Check if couple exists in a dict""" if a in dict_: if dict_[a] == b: return True if b in dict_: if dict_[b] == a: return True return False
def _convert_pandas_csv_options(pandas_options, columns): """ Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header. Args: pandas_options (dict): pandas options like {'header': None}. columns (list): list of column name. """ _columns = pandas_options.pop("names", columns) header = pandas_options.pop("header", None) pandas_options.pop("encoding", None) if header == "infer": header_line_number = 0 if not bool(_columns) else None else: header_line_number = header return _columns, header_line_number
def get_t_demand_list(temp_curve, th_curve): """ Sorts thermal energy demand based on values of ambient temperatures. Parameters ---------- temp_curve : list of ambient temperatures for one year th_curve : list of thermal energy demand for one year Returns ------- t_demand_curve : thermal energy curve sorted based on ambient temperature values """ return [th_demand for _, th_demand in sorted(zip(temp_curve, th_curve))]
def get_modules_for_includes(included_files, include_file_index): """ given a set of included files return the set of modules that contain these files, as well as the set of include files which were not found in any module """ included_modules = set() unknown_includes = set() for included_file in included_files: mods = include_file_index.get_modules_containing(included_file) if len(mods) > 1: print("WARNING: {} is present in multiple modules: {}".format( included_file, mods)) if len(mods) == 0: unknown_includes.add(included_file) included_modules = included_modules.union(mods) return (included_modules, unknown_includes)