content
stringlengths
42
6.51k
def list_as_comma_sep(lst: list) -> str: """Gets a list and returns one single string with elements separated by a comma""" return ",".join(lst)
def mysql_connection(run_services, mysql_socket): """The connection string to the local mysql instance.""" if run_services: return 'mysql://root@localhost/?unix_socket={0}&charset=utf8'.format(mysql_socket)
def uniform_cdf(x: float) -> float: """Uniform cumulative distribution function (CDF)""" """Returns the probability that a uniform random variable is <= x""" if x < 0: return 0 # Uniform random is never less than 0 elif x < 1: return x # e.g. P(X <= 0.4) = 0.4 else: return 1
def _rgb_to_hex(tup): """Convert RGBA to #AARRGGBB """ tup = tuple(tup) if len(tup) == 3: return '#%02x%02x%02x' % tup elif len(tup) == 4: return '#%02x%02x%02x%02x' % (tup[3], tup[0], tup[1], tup[2]) else: raise ValueError("Array or tuple for RGB or RGBA should be given.")
def binary_digits_to_places(binary_string): """Given a string representing a binary value, return a list of the decimal values of the places for which the bit is on. 0011 -> [1, 2]""" reversed_bits = reversed(binary_string) place_values = [ 2**exp for exp, digit in enumerate(reversed_bits) if digit == "1"] return place_values
def from_iob_to_io(sentences): """ Transforms the IOB tags in sentences (output of create_sentences_out_of_dataframe) to IO tags :param sentences: (list of list of tuples) :return: (list of list of tuples) """ clean_sentences=[] for desc in sentences: sublist=[] for x in desc: l = list(x) tag = l[1] if 'B-' in tag: tag = tag.replace('B-', '') elif 'I-' in tag: tag = tag.replace('I-', '') elif 'b-' in tag: tag = tag.replace('b-', '') elif 'i-' in tag: tag = tag.replace('i-', '') t = tuple([l[0], tag]) sublist.append(t) clean_sentences.append(sublist) return clean_sentences
def quaternion_to_xaxis_yaxis(q): """Return the (xaxis, yaxis) unit vectors representing the orientation specified by a quaternion in x,y,z,w format.""" x = q[0] y = q[1] z = q[2] w = q[3] xaxis = [ w*w + x*x - y*y - z*z, 2*(x*y + w*z), 2*(x*z - w*y) ] yaxis = [ 2*(x*y - w*z), w*w - x*x + y*y - z*z, 2*(y*z + w*x) ] return xaxis, yaxis
def repeat(phrase, num): """Return phrase, repeated num times. >>> repeat('*', 3) '***' >>> repeat('abc', 2) 'abcabc' >>> repeat('abc', 0) '' Ignore illegal values of num and return None: >>> repeat('abc', -1) is None True >>> repeat('abc', 'nope') is None True """ if type(num) != int: return None elif int(num) < 0: return None return phrase * num
def product(xs): """Return the product of the elements in an iterable.""" accumulator = 1 for x in xs: accumulator *= x return accumulator
def r(n): """venn2 can't show specified values, so round the values instead""" return round(n, 3)
def escape_suite_name(g: str) -> str: """ format benchmark suite name for display """ c = g.split('-') if c[0] == "amd" or c[0] == "nvidia": return c[0].upper() + " SDK" if c[0] == "npb" or c[0] == "shoc": return c[0].upper() elif c[0] == "parboil" or c[0] == "polybench" or c[0] == "rodinia": return c[0].capitalize() else: raise LookupError
def long2str(x): """ Convert long integer x to a bytes string. """ l = ( x & 0xff, (x >> 8) & 0xff, (x >> 16) & 0xff, (x >> 24) & 0xff) return ''.join([chr(x) for x in l])
def uniform(n: int) -> int: """Generates a binary number with alternating ones and zeros in decimal format""" # input: 1, 2, 3, 4, 5, ... # output: 2, 5, 10, 21, 42, ... bits = 2 for i in range(n - 1): bits *= 2 if not i % 2: bits += 1 return bits
def _from_url(url: str): """ Returns data from paste url. """ server = url.split('?')[0] paste_id, key = (url.split('?')[1]).split('#') return server, paste_id, key.encode('utf-8')
def toggle_trigger_measure_button_label(measure_triggered, mode_val, btn_text): """change the label of the trigger button""" if mode_val == "single": return "Single measure" else: if measure_triggered: if btn_text == "Start sweep": return "Stop sweep" else: return "Start sweep" else: return "Start sweep"
def validPalindrome(s): """ :type s: str :rtype: bool """ if s[::-1]==s: return True i=0 j=len(s)-1 while(i<j): if s[i] != s[j]: sA=s[:i]+s[i+1:] sB=s[:j]+s[j+1:] if sA==sA[::-1] or sB==sB[::-1]: return True else: return False i+=1 j-=1
def _qtp_ids(tests): """Return IDs for QueryTime params tests.""" return ["-".join(item[0].keys()) for item in tests]
def best_model(vals): """Decide on the best model according to an Information Criterion.""" if vals[0] is not None and vals[0] == min(x for x in vals if x is not None): return 1 elif vals[1] is not None and vals[1] == min(x for x in vals if x is not None): return 2 elif vals[2] is not None and vals[2] == min(x for x in vals if x is not None): return 3 else: return 0
def swap_http_https(url): """Get the url with the other of http/https to start""" for (one, other) in [("https:", "http:"), ("http:", "https:")]: if url.startswith(one): return other+url[len(one):] raise ValueError("URL doesn't start with http: or https: ({0})".format(url))
def add(*args): """ :param args: This represents the group of ints that are to be added :return: This returns the total sum of all numbers that were added """ total = 0 for arg in args: if type(arg) is int: total += arg return total
def compute_energy_from_density(density, x_dimension, y_dimension, chemical_potential): """Computes energy from energy density.""" return (x_dimension * y_dimension) * (density - chemical_potential)
def to_arg(flag_str: str) -> str: """ Utility method to convert from an argparse flag name to the name of the corresponding attribute in the argparse Namespace (which often is adopted elsewhere in this code, as well) :param flag_str: Name of the flag (sans "--") :return: The name of the argparse attribute/var """ return flag_str.replace("-", "_")
def wrap(item): """Wrap a string with `` characters for SQL queries.""" return '`' + str(item) + '`'
def calculate_i(condition) -> int: """Return 0 or 1 based on the truth of the condition.""" if condition(): return 1 return 0
def make_sentiment(value): """Return a sentiment, which represents a value that may not exist. >>> positive = make_sentiment(0.2) >>> neutral = make_sentiment(0) >>> unknown = make_sentiment(None) >>> has_sentiment(positive) True >>> has_sentiment(neutral) True >>> has_sentiment(unknown) False >>> sentiment_value(positive) 0.2 >>> sentiment_value(neutral) 0 """ assert value is None or (value >= -1 and value <= 1), 'Illegal value' "*** YOUR CODE HERE ***" sentiment = {} if value is None: sentiment["type"] = 0 sentiment["value"] = 0 else: sentiment["type"] = 1 sentiment["value"] = value return sentiment
def nulls(data): """Returns keys of values that are null (but not bool)""" return [k for k in data.keys() if not isinstance(data[k], bool) and not data[k]]
def delegate(session_attributes, fulfillment_state, message): """Build a slot to delegate the intent""" response = { 'sessionAttributes': session_attributes, 'dialogAction': { 'type': 'Delegate' } } return response
def tuple_cont_to_cont_tuple(tuples): """Converts a tuple of containers (list, tuple, dict) to a container of tuples.""" if isinstance(tuples[0], dict): # assumes keys are correct return {k: tuple(dic[k] for dic in tuples) for k in tuples[0].keys()} elif isinstance(tuples[0], list): return list(zip(*tuples)) elif isinstance(tuples[0], tuple): return tuple(zip(*tuples)) else: raise ValueError("Unkown conatiner type: {}.".format(type(tuples[0])))
def get_area_from_bbox(bbox): """ bbox: [x1,y1,x2,y2] return: area of bbox """ assert bbox[2] > bbox[0] assert bbox[3] > bbox[1] return int(bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
def encode(number, base): """Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= 36, 'base is out of range: {}'.format(base) # Handle unsigned numbers only for now assert number >= 0, 'number is negative: {}'.format(number) encoded_val = "" while number > 0: #Modulo always returns a value less than the base number, remainder = divmod(number, base) #convert numbers 10 or higher to letters if remainder >= 10: encoded_val += chr(remainder + 87) else: encoded_val += str(remainder) return encoded_val[::-1]
def _decimal_to_binary(decimal): """Convert decimal to binary""" return int("{0:b}".format(decimal))
def skip_chars(chars, text, i): """ syntax """ while i < len(text): if text[i] not in chars: return i i += 1 return None
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['id'], "location": met['location'], "starttime": met['sensingStart'], "endtime": met['sensingStop'], }
def _legacy_mergeOrderings(orderings): """Merge multiple orderings so that within-ordering order is preserved Orderings are constrained in such a way that if an object appears in two or more orderings, then the suffix that begins with the object must be in both orderings. For example: >>> _mergeOrderings([ ... ['x', 'y', 'z'], ... ['q', 'z'], ... [1, 3, 5], ... ['z'] ... ]) ['x', 'y', 'q', 1, 3, 5, 'z'] """ seen = set() result = [] for ordering in reversed(orderings): for o in reversed(ordering): if o not in seen: seen.add(o) result.insert(0, o) return result
def build_grid_refs(lats, lons): """ This function takes latitude and longitude values and returns grid reference IDs that are used as keys for raster grid files Parameters: Two iterables containing float values. The first containing latitudes, and the second containing longitudes. Return value: A numpy array of grid reference ID strings. """ grid_refs = [] for i in range(len(lons)): if lats[i] > 0.0 and lons[i] < 0.0: val = str(int(abs(lons[i])) + 1) if len(val) < 3: val = '0' + val grid_refs += ['n' + str(int(abs(lats[i])) + 1) + 'w' + val] else: grid_refs += ['0'] return grid_refs
def yaml_formatter(data, **kwargs): """Method returns parsing results in yaml format.""" try: from yaml import dump except ImportError: import logging log = logging.getLogger(__name__) log.critical( "output.yaml_formatter: yaml not installed, install: 'python -m pip install pyyaml'. Exiting" ) raise SystemExit() return dump(data, default_flow_style=False)
def get_first_k_words(text: str, num_words: int) -> str: """ Returns the given text with only the first k words. If k >= len(text), returns the entire text. :param text: The text to be limited in the number of words (String). :param num_words: The value of k (int). Should be >= 0. :return: The given text with only the first k words. """ words = text.split() if num_words >= len(text): return text return ' '.join(words[:num_words])
def test_deprecated_args(a, b, c=3, d=4): """ Here we test deprecation on a function with arguments. Parameters ---------- a : int This is the first argument. b : int This is the second argument. c : int, optional This is the third argument. d : int, optional This is the fourth argument. Returns : int This is the return value. """ return a + b + c + d
def escape(c): """Convert a character to an escape sequence according to spec""" return "&#{};".format(ord(c))
def jaccard(a, b): """Compute the jaccard index between two feature sets """ return 1.*len(set(a).intersection(set(b)))/len(set(a).union(set(b)))
def add(*args): """Add a list of numbers""" sum = 0.0 for arg in args: sum += arg return sum
def _default_list(length: int) -> list: """ Returns a list filled with None values. """ return [None for _ in range(length)]
def check_deceased(path, name): """Check if the patient at the given path is deceased""" return "In Memoriam" in path
def validate_window_size(s): """Check if s is integer or string 'adaptive'.""" try: return int(s) except ValueError: if s.lower() == "adaptive": return s.lower() else: raise ValueError(f'String {s} must be integer or string "adaptive".')
def ngramsplit(word, length): """ ngramsplit("google", 2) => {'go':1, 'oo':1, 'og':1, 'gl':1, 'le':1} """ grams = {} for i in range(0, len(word) - length + 1): g = word[i:i + length] if not g in grams: grams[g] = 0 grams[g] += 1 return grams
def trim_and_lower(string): """Trims and lowers a string.""" return string.strip().lower()
def make_device(**kwargs): """fixture factory for mocking a device for current tests we only need the fields below and we can add more as needed """ device_data = {"id": 5883496, "is_running__release": {"__id": 1234}} device_data.update(kwargs) return device_data
def insertion_sort(array, begin=1, end=None): """ Sorting is done by splitting the array into a sorted and an unsorted part. Values from the unsorted part are selected and moved to their correct position in the sorted part. """ # None is initiated to be used in Introsort implementation if end == None: end = len(array) # Loop through the array for slot in range(begin, end): # Select the element to position in its correct place current_value = array[slot] # Initialize a variable for finding the correct position of # the current value position = slot # Loop through the array and find the correct position # of the element referenced by current_value while position > 0 and array[position-1] > current_value: # Shift the value to the left and reposition position # to point to the next element (from right to left) array[position] = array[position-1] position -= 1 # When shifting is finished, # position the current_value in its correct location array[position] = current_value return array
def names_cleaner(name): """ Helper function to clean up string from 'thml' symbols """ # pylint: disable=W1402 return name.replace('\u202a', '').replace('\u202c', '').strip()
def _make_header_wsgi_env_key(http_header: str) -> str: """Convert HTTP header to WSGI environ key format. HTTP_ Variables corresponding to the client-supplied HTTP request headers (i.e., variables whose names begin with "HTTP_"). See https://www.python.org/dev/peps/pep-3333/ for more details >>> print(_make_header_wsgi_env_key("X-USERNAME")) HTTP_X_USERNAME """ return "HTTP_" + http_header.replace("-", "_").upper()
def formatNumber(number, billions="B", spacer=" ", isMoney = False): """ Format the number to a string with max 3 sig figs, and appropriate unit multipliers Args: number (float or int): The number to format. billions (str): Default "G". The unit multiplier to use for billions. "B" is also common. spacer (str): Default " ". A spacer to insert between the number and the unit multiplier. Empty string also common. isMoney (bool): If True, a number less than 0.005 will always be 0.00, and a number will never be formatted with just one decimal place. """ if number == 0: return "0%s" % spacer absVal = float(abs(number)) flt = float(number) if absVal >= 1e12: # >= 1 trillion return "%.2e" % flt if absVal >= 10e9: # > 10 billion return "%.1f%s%s" % (flt/1e9, spacer, billions) if absVal >= 1e9: # > 1 billion return "%.2f%s%s" % (flt/1e9, spacer, billions) if absVal >= 100e6: # > 100 million return "%i%sM" % (int(round(flt/1e6)), spacer) if absVal >= 10e6: # > 10 million return "%.1f%sM" % (flt/1e6, spacer) if absVal >= 1e6: # > 1 million return "%.2f%sM" % (flt/1e6, spacer) if absVal >= 100e3: # > 100 thousand return "%i%sk" % (int(round(flt/1e3)), spacer) if absVal >= 10e3: # > 10 thousand return "%.1f%sk" % (flt/1e3, spacer) if absVal >= 1e3: # > 1 thousand return "%.2f%sk" % (flt/1e3, spacer) if isinstance(number, int): return "%i" % number if absVal >= 100: return "%i%s" % (flt, spacer) if absVal >= 10: if isMoney: return "%.2f%s" % (flt, spacer) # Extra degree of precision here because otherwise money looks funny. return "%.1f%s" % (flt, spacer) # Extra degree of precision here because otherwise money looks funny. # if absVal > 1: # return "%.2f%s" % (absVal, spacer) if absVal > 0.01: return "%.2f%s" % (flt, spacer) if isMoney: return "0.00%s" % spacer return ("%.2e%s" % (flt, spacer)).replace("e-0", "e-")
def _is_composite(b, d, s, n): """_is_composite(b, d, s, n) -> True|False Tests base b to see if it is a witness for n being composite. Returns True if n is definitely composite, otherwise False if it *may* be prime. >>> _is_composite(4, 3, 7, 385) True >>> _is_composite(221, 3, 7, 385) False Private function used internally by the Miller-Rabin primality test. """ assert d*2**s == n-1 if pow(b, d, n) == 1: return False for i in range(s): if pow(b, 2**i * d, n) == n-1: return False return True
def not_empty_string(s): """A string that can't be empty.""" return isinstance(s, str) and len(s) > 0
def unique (inn): """ Removes duplicate entries from an array of strings. Returns an array of strings, also removes null and blank strings as well as leading or trailing blanks. * inn = list of strings with possible redundancies """ # Make local working copy and blank redundant entries linn = [] for item in inn: sitem = item.strip() if len(sitem)>0: linn.append(sitem) # Remove duplicates from the end of the list n = len(linn) for jj in range(0,n): j = n-jj-1 for i in range (0,j): if (linn[j]==linn[i]): linn[j] = "" break; # end loops # Copy to output string outl = [] for item in linn: if len(item)>0: outl.append(item) return outl
def format(message): """Formats the message into bytes""" return bytes(message, "utf-8")
def htons(x): """Convert 16-bit positive integers from host to network byte order.""" return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF)
def get_ws_url_private(account_id: int) -> str: """ Builds a private websocket URL :param account_id: account ID :return: a complete private websocket URL """ return f"wss://ascendex.com:443/{account_id}/api/pro/v1/websocket-for-hummingbot-liq-mining"
def dec_to_bin(n): """ :param n: decimal number :return: decimal converted to binary """ return bin(int(n)).replace("0b", "")
def isqrt(n): """Calculate the floor of the square root of n, using Newton's method. Args ---- n : int Integer to use. Returns ------- n_isqrt : int Floor of the square root of n. """ n_isqrt = n y = (n_isqrt + 1) // 2 while y < n_isqrt: n_isqrt = y y = (n_isqrt + n // n_isqrt) // 2 return n_isqrt
def calculate_speed_of_sound(t, h, p): """ Compute the speed of sound as a function of temperature, humidity and pressure Parameters ---------- t: float temperature [Celsius] h: float relative humidity [%] p: float atmospheric pressure [kpa] Returns ------- Speed of sound in [m/s] """ # using crude approximation for now return 331.4 + 0.6 * t + 0.0124 * h
def frequency(lst, search_term): """Return frequency of term in lst. >>> frequency([1, 4, 3, 4, 4], 4) 3 >>> frequency([1, 4, 3], 7) 0 """ return lst.count(search_term)
def canonify_slice(s, n): """ Convert a slice object into a canonical form to simplify treatment in histogram bin content and edge slicing. """ if isinstance(s, int): return canonify_slice(slice(s, s + 1, None), n) start = s.start % n if s.start is not None else 0 stop = s.stop % n if s.stop is not None else n step = s.step if s.step is not None else 1 return slice(start, stop, step)
def raw(string): """ Escapes a string into a form which won't be colorized by the ansi parser. """ return string.replace('{', '{{')
def none2empty_filter(val): """Jinja2 template to convert None value to empty string.""" if not val is None: return val else: return ''
def is_percent(val): """Checks that value is a percent. Args: val (str): number string to verify. Returns: bool: True if 0<=value<=100, False otherwise. """ return int(val) >= 0 and int(val) <= 100
def calculate_enrichment_score(gene_set, expressions, omega): """ Given a gene set, a map of gene names to expression levels, and a weight omega, returns the ssGSEA enrichment score for the gene set as described by *D. Barbie et al 2009* :requires: every member of gene_set is a key in expressions :param gene_set: a set of gene_names in the set :type gene_set: set :param expressions: a dictionary mapping gene names to their expression values :type expressions: dict :param omega: the weighted exponent on the :math:`P^W_G` term. :type omega: float :returns: an array representing the intermediate Enrichment Scores for each step along the sorted gene list. To find the total enrichment score, take the sum of all values in the array. """ #first sort by absolute expression value, starting with the highest expressed genes first keys_sorted = sorted(expressions, key=expressions.get, reverse=True) #values representing the ECDF of genes in the geneset P_GW_numerator = 0 P_GW_denominator = 0 #determining denominator value i = 1 #current rank stepping through listing of sorted genes for gene in keys_sorted: if gene in gene_set: P_GW_denominator += i ** omega i += 1 P_GW = lambda : P_GW_numerator / P_GW_denominator #values representing the ECDF of genes not in the geneset P_NG_numerator = 0 P_NG_denominator = len(expressions) - len(gene_set) P_NG = lambda : P_NG_numerator / P_NG_denominator #integrate different in P_GW and P_NG i = 1 #current index in the traversal of sorted genes scores = [] for gene in keys_sorted: if gene in gene_set: P_GW_numerator += i ** omega else: P_NG_numerator += 1 scores.append(P_GW() - P_NG()) i += 1 return sum(scores)
def lintrans(x,inboundtuple,outboundtuple): """ Purpose: make a linear transformation of data for enhancing contrast. Suppose, the input data is x which lies in [x1,x2], we want to transform it into range [y1,y2] by a linear way. Arguments: inboundtuple --> the original bound tuple (x1,x2) outboundtuple --> the transformed bound tuple (y1,y2) Example: >>> import mathex.lintrans as lintrans >>> lintrans(3,(2,4),(4,8)) >>> plt.plot(np.arange(2,5),lintrans(np.arange(2,5),(2,4),(4,10))) >>> plt.hlines(y=lintrans(3,(2,4),(4,10)),xmin=0,xmax=3,linestyles='dashed',color='r') >>> plt.vlines(x=3,ymin=0,ymax=lintrans(3,(2,4),(4,10)),linestyles='dashed',color='r') >>> plt.plot(3,lintrans(3,(2,4),(4,10)),'ro') >>> plt.show() """ x1,x2=inboundtuple y1,y2=outboundtuple y=(float(y2-y1)/(x2-x1))*(x-x1)+y1 return y
def left_top_of_center(angle): """ True, if angle leads to point left top of center """ return True if 180 <= angle < 270 else False
def race_transform(input_str): """Reduce values to White, Black and Other.""" result = "Other" if input_str == "White" or input_str == "Black": result = input_str return result
def create_group_name(permissions): """Create group name based on permissions.""" formatted_names = [perm.name.rstrip(".").lower() for perm in permissions] group_name = ", ".join(formatted_names).capitalize() return group_name
def _get_sources_with_sink(node_str, connections): """Returns the source nodes that are connected to the sink node with the given string representation. Args: node_str: a string representation of a PipelineNode connections: a list of PipelineConnection instances Returns: a list of PipelineNodes that are connected to the given sink node. """ return [c.source for c in connections if c.sink.is_same_node_str(node_str)]
def geo_db_path(type): """ Returns the full path of a specific GeoLite2 database Args: type (str): The type of database path to retrieve (ASN, City, Country) Raises: ValueError: An invalid database type has been provided Returns: str: The absolute path to the specified database. """ if type not in ['ASN', 'City', 'Country']: raise ValueError( "Invalid GeoLite2 Database type provided.\n" "Type must be: 'ASN', 'City' or 'Country'" ) else: return f'/usr/local/share/GeoIP/GeoLite2-{type}.mmdb'
def strip_qualifiers(typename): """Remove const/volatile qualifiers, references, and pointers of a type""" qps = [] try: while True: typename = typename.rstrip() qual = next(q for q in ['&', '*', 'const', 'volatile'] if typename.endswith(q)) typename = typename[:-len(qual)] qps.append(qual) except StopIteration: pass try: while True: typename = typename.lstrip() qual = next(q for q in ['const', 'volatile'] if typename.startswith(q)) typename = typename[len(qual):] qps.append(qual) except StopIteration: pass return typename, qps[::-1]
def pack_bitflags(*values): # type: (*bool) -> int """ Pack separate booleans back into a bit field. """ result = 0 for i, val in enumerate(values): if val: result |= (1 << i) return result
def _allocation_type(action) -> tuple: """Get details of child policy""" allocation = '---' action_type = '---' if action.get("action-type",{}) == 'shape': if 'bit-rate' in action.get('shape',{}).get('average',{}): allocation = str(round(int(action.get("shape",{}).get("average",{}).get("bit-rate",{})) / 1e+6)) + " Mbps" elif 'percent' in action.get('shape',{}).get('average'): allocation = str(action.get("shape",{}).get("average",{}).get("percent",{})) + "%" elif action.get("action-type",{}) == 'bandwidth': if 'kilo-bits' in action.get('bandwidth', {}): allocation = str(round(int(action.get("bandwidth",{}).get("kilo-bits",{})) * 1000 / 1e+6)) + " Mbps" elif 'percent' in action.get('bandwidth', {}): allocation = str(action.get("bandwidth",{}).get("percent",{})) + '%' if action.get("action-type",{}) == 'service-policy': action_type = 'service-policy' elif action.get("action-type",{}) == 'fair-queue': action_type = 'fair-queue' return allocation, action_type
def dtrunc (x: float) -> float: """ Truncar un numero float """ k = int(x) x = float(k) # numero float sin parte decimal return x
def format_smashgg_url(url): """Converts bracket url to api url, if necessary.""" if "api.smash.gg" not in url: url = "http://api.smash.gg/phase_group/" + url.split("/")[-1] api_string = "?expand[0]=sets&expand[1]=entrants" if api_string not in url: url += api_string return url
def climbing_stairs(n): """ n, the number of stairs O(2**n) time and space """ if n < 2: return 1 if n == 2: return 2 return climbing_stairs(n-1) + climbing_stairs(n-2)
def list_to_scalar(input_list): """ This is a helper function, that turns a list into a scalar if its length is 1. """ if len(input_list) == 1: return input_list[0] else: return input_list
def _fabric_xmlrpc_uri(host, port): """Create an XMLRPC URI for connecting to Fabric This method will create a URI using the host and TCP/IP port suitable for connecting to a MySQL Fabric instance. Returns a URI. """ return 'http://{host}:{port}'.format(host=host, port=port)
def sequence_of_bst(postorder): """ :param postorder: LRD of binary search tree :return: bool """ if len(postorder) <= 1: return True root = postorder[-1] # right_child = postorder.filter(lambda x: x > root, postorder) # left_child = postorder.filter(lambda x: x < root, postorder) count = 0 for node in postorder[:-1]: if node < root: count += 1 else: break right_child = postorder[count:-1] left_child = postorder[:count] for node in right_child: if node < root: return False if left_child: left = sequence_of_bst(left_child) else: return True if right_child: right = sequence_of_bst(right_child) else: return True return left and right
def bitwise_list_comparator(x, y): """ Uses the first element in the list for comparison """ return (1 - x[0]) * y[0]
def UnionFindSet(m, edges): """ :param m: :param edges: :return: union number in a graph """ roots = [i for i in range(m)] rank = [0 for i in range(m)] count = m def find(member): tmp = [] while member != roots[member]: tmp.append(member) member = roots[member] for root in tmp: roots[root] = member return member for i in range(m): roots[i] = i # print ufs.roots for edge in edges: print(edge) start, end = edge[0], edge[1] parentP = find(start) parentQ = find(end) if parentP != parentQ: if rank[parentP] > rank[parentQ]: roots[parentQ] = parentP elif rank[parentP] < rank[parentQ]: roots[parentP] = parentQ else: roots[parentQ] = parentP rank[parentP] -= 1 count -= 1 return count
def equal(a: int, b: int, c: int): """Return the number of equal values in (a,b,c).""" test_equality = set([a, b, c]) length = len(test_equality) count = int(length % 3) number_of_equal_values = 3 if count is 1 else count return number_of_equal_values
def get_prompt_save_file_name(name: str) -> str: """ Derives a file name to use for storing default prompt values. Args: name (str): The unique identifier of the file-name. Returns: str: The file name. """ return f"{name}.sav"
def get_image_details(dynamodb_obj, image_id_list): """Get the image details of all the images provided by the image ID list""" try: image_id_list = list(set(image_id_list)) image_id_query = [{ 'id': item } for item in image_id_list] response = dynamodb_obj.batch_get_item( RequestItems={ 'image_details': { 'Keys': image_id_query, 'ConsistentRead': True } }, ReturnConsumedCapacity='TOTAL' ) except Exception as e: print(str(e)) else: items = response['Responses'] if items["image_details"]: return items["image_details"]
def compute_avg_headway(headways): """ Compute the average headways from the sum of all trips with the specified headways. :param headways: (list of int) list of headways """ if not headways: return 0 frequency = sum([1 / headway for headway in headways]) return 1 / frequency
def _xList(l): """ """ if l is None: return [] return l
def _is_string_like(obj): """ Check whether obj behaves like a string. """ try: obj + "" except (TypeError, ValueError): return False return True
def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False
def str_to_bool(value: str): """Convert a string to bool. Arguments --------- value : str A string representation of a boolean. Returns ------- A bool. Exceptions ---------- Raise a ValueError if the string is not recognized as a boolean's string representation. """ if value.lower() in ["true", "on", "1", "yes"]: return True if value.lower() in ["false", "off", "0", "no"]: return False raise ValueError("Not recognized as a bool: {}".format(value))
def return_operations(*sets): """Sa se scrie o functie care primeste un numar variabil de seturi. Returneaza un dictionar cu urmatoarele operatii dintre toate seturile doua cate doua: reuniune, intersectie, a-b, b-a. Cheia va avea urmatoarea forma: "a op b". """ output = {} for i in range(0, len(sets)): for j in range(i + 1, len(sets)): set1 = sets[i] set2 = sets[j] key = str(set1) + ' | ' + str(set2) value = set1 | set2 output[key] = value key = str(set1) + ' & ' + str(set2) value = set1 & set2 output[key] = value key = str(set1) + ' - ' + str(set2) value = set1 - set2 output[key] = value key = str(set2) + ' - ' + str(set1) value = set2 - set1 output[key] = value return output
def get_groupers(groupers): """ Get default groupers if the input is None Args: groupers (sequence of str or None): groupers for calc and plot functions Returns: list: groupers for calc and plot functions """ if groupers is None: groupers = ["ALL", "time.season", "time.month"] return groupers
def to_list(value): """ Returns ``value`` as a list if it is iterable and not a string, otherwise returns ``value`` in a list. >>> to_list(('foo', 'bar', 'baz')) ['foo', 'bar', 'baz'] >>> to_list('foo bar baz') ['foo bar baz'] """ if hasattr(value, '__iter__') and not isinstance(value, str): return list(value) return [value]
def largest_divisor_five(x=120): """Find which is the largest divisor of x among 2,3,4,5.""" largest = 0 if x % 5 == 0: largest = 5 elif x % 4 == 0: #means "else, if" largest = 4 elif x % 3 == 0: largest = 3 elif x % 2 == 0: largest = 2 else: # When all other (if, elif) conditions are not met return "No divisor found for %d!" % x # Each function can return a value or a variable. return "The largest divisor of %d is %d" % (x, largest)
def recursive_circus_v1(circuits): """Recursive Circus.""" programs = {} for name in circuits.keys(): programs[name] = 0 for circuit in circuits.values(): if 'children' in circuit: for child in circuit['children']: programs[child] += 1 for name, count in programs.items(): if count == 0: return name raise ValueError('No bottom program found!')
def rivers_with_station(stations): """Returns a set of names of rivers with a monotoring station""" rivers = [] for x in stations: if x.river not in rivers: rivers += [x.river] return sorted(rivers)
def get_line_ending(line: bytes) -> bytes: """ Return line ending. Note: this function should be somewhere else. """ non_whitespace_index = len(line.rstrip()) - len(line) if not non_whitespace_index: return b"" else: return line[non_whitespace_index:]
def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ Updates the learning rate using inverse time decay in numpy alpha is the original learning rate decay_rate is the weight used to determine the rate at which alpha will decay global_step is the number of passes of gradient descent that have elapsed decay_step is the number of passes of gradient descent that should occur before alpha is decayed further Returns: the updated value for alpha """ return alpha / (1 + decay_rate * (global_step // decay_step))
def pop_path_info(environ): """Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAME`: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' .. versionadded:: 0.5 :param environ: the WSGI environment that is modified. """ path = environ.get('PATH_INFO') if not path: return None script_name = environ.get('SCRIPT_NAME', '') # shift multiple leading slashes over old_path = path path = path.lstrip('/') if path != old_path: script_name += '/' * (len(old_path) - len(path)) if '/' not in path: environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path return path segment, path = path.split('/', 1) environ['PATH_INFO'] = '/' + path environ['SCRIPT_NAME'] = script_name + segment return segment