content
stringlengths
42
6.51k
def unpack_data(data_str): """Extract the code and message from a received string. Parameters ---------- data_str : str Returns ------- code : str msg : str """ if data_str: data_list = data_str.split(' ', 1) code = data_list[0] msg = None if len(data_list) < 2 else data_list[1] return code, msg return None, None
def reverse_long_words(sentence: str) -> str: """ Reverse all words that are longer than 4 characters in a sentence. >>> reverse_long_words("Hey wollef sroirraw") 'Hey fellow warriors' >>> reverse_long_words("nohtyP is nohtyP") 'Python is Python' >>> reverse_long_words("1 12 123 1234 54321 654321") '1 12 123 1234 12345 123456' """ return " ".join( "".join(word[::-1]) if len(word) > 4 else word for word in sentence.split() )
def normalizer(dataset, colorby): """normalizes dataset using min and max values""" valnorm_lst = [] if colorby not in ["atom_type", "residue_type"]: for val in dataset.values(): val = float(val) # used if all values in the set are the same if max(dataset.values()) == min(dataset.values()): valnorm = 0.0 else: valnorm = ((val-min(dataset.values())) / (max(dataset.values())-min(dataset.values()))) valnorm_lst.append(valnorm) return valnorm_lst
def extract_scalar_reward(value, scalar_key='default'): """ Extract scalar reward from trial result. Parameters ---------- value : int, float, dict the reported final metric data scalar_key : str the key name that indicates the numeric number Raises ------ RuntimeError Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int. """ if isinstance(value, (float, int)): reward = value elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)): reward = value[scalar_key] else: raise RuntimeError('Incorrect final result: the final result should be float/int, ' \ 'or a dict which has a key named "default" whose value is float/int.') return reward
def is_complex(object): """Check if the given object is a complex number""" return isinstance(object, complex)
def _worker_command_line(thing, arguments): """ Create a worker command line suitable for Popen with only the options the worker process requires """ def a(name): "options with values" return [name, arguments[name]] * (arguments[name] is not None) def b(name): "boolean options" return [name] * bool(arguments[name]) return ( ['ckanapi', 'dump', thing, '--worker'] + a('--config') + a('--ckan-user') + a('--remote') + a('--apikey') + b('--get-request') + ['value-here-to-make-docopt-happy'] )
def email_escape_char(email_address): """ Escape problematic characters in the given email address string""" return email_address.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
def detect_graphql(payload): """ """ return "query" in payload
def _truncate_location(location): """ Cuts off anything after the first colon in location strings. This allows for easy comparison even when line numbers change (as they do regularly). """ return location.split(":", 1)[0]
def calculate_roc_points(instances): """From a sorted list of instances, calculate the points that draw the ROC curve.""" # Calculate the number of positives and negatives (the real ones). P = N = 0 for label, score in instances: if label == 'p': P += 1 else: N += 1 # Calculate each point. TP = FP = 0 points = [] for label, score in instances: if label == 'p': TP += 1 else: FP +=1 point = (FP/N, TP/P) points.append(point) return points
def get_sentiment_emoji(sentiment): """Returns an emoji representing the sentiment score.""" if sentiment == 0: return ":neutral_face:" elif sentiment > 0: return ":thumbsup:" else: # sentiment < 0: return ":thumbsdown:"
def moveParameters(target): """ Iterate through all paths and move the parameter types to the schema subsection """ for path in target['paths']: for verb in target['paths'][path]: #Only need to be performed on 'parameters' key if verb == 'parameters': paramtype = target['paths'][path][verb][0].pop('type') target['paths'][path][verb][0]['schema'] = {'type':paramtype} return target
def GenerateAuthProviderCmdArgs(kind, cluster_id, location): """Generates command arguments for kubeconfig's authorization provider. Args: kind: str, kind of the cluster e.g. aws, azure. cluster_id: str, ID of the cluster. location: str, Google location of the cluster. Returns: The command arguments for kubeconfig's authorization provider. """ template = ('container {kind} clusters print-access-token ' '{cluster_id} --location={location}') return template.format(kind=kind, cluster_id=cluster_id, location=location)
def allow_minkowski_specification(value): """Dash callback for enabling/disabling the Minkowski distance input widget for k nearest neighbors. Given a distance metric to use for measuring the distance between neighbors in the k nearest neighbors algorithm, only allow user input of the Minkowski distance if the metric selected is Minkowski. Args: value: Selected k nearest neighbors distance metric from dropdown. Returns: True if the distance metric is not "minkowski" and False otherwise. """ return value.lower() != 'minkowski'
def tree_intersection(tree_one, tree_two): """ Function that takes in two binary trees, and returns a list of all common values in both trees In: 2 parameters - 2 trees Out: List of all common values found in both trees """ if tree_one is None or tree_two is None: return [] seen = set() result = [] def walk_one(node): if node is None: return seen.add(node.value) walk_one(node.left) walk_one(node.right) walk_one(tree_one.root) def walk_two(node): if node is None: return if node.value in seen: result.append(node.value) walk_two(node.left) walk_two(node.right) walk_two(tree_two.root) return result
def factorial(number): """ This method calculates the factorial of the number """ result = 1 for index in range(1,number+1): result *= index return result
def diff(n, l): """ Runtime: O(n) """ occurences = {} count = 0 for i in l: if i in occurences.keys(): occurences[i] += 1 else: occurences[i] = 1 for i in occurences.keys(): if i + n in occurences.keys(): c1 = occurences[i] c2 = occurences[i+n] count += c1 * c2 return count
def normalise_toolshed_url(tool_shed): """ Return complete URL for a tool shed Arguments: tool_shed (str): partial or full URL for a toolshed server Returns: str: full URL for toolshed, including leading protocol. """ if tool_shed.startswith('http://') or \ tool_shed.startswith('https://'): return tool_shed return "https://%s" % tool_shed
def get_track_row(name, performer, time, row_format='raw'): """ function to get track row in specified format """ if row_format == 'csv': return '"{}","{}","{}"\n'.format(name, performer, time) return '{0:<60} - {1:<60}{2:<60}\n'.format(name, performer, time)
def _get_hash(bytestring): """Get sha256 hash of `bytestring`.""" import hashlib return hashlib.sha256(bytestring).hexdigest()
def page_moment(n, na, m): """Return average trace of moment of reduced density matrix for ergodic states. """ if m == 2: return 1/2**na + 1/2**(n-na) if m == 3: return 1/2**(2*na)+1/2**(2*(n-na))+1/2**(2*n)+3/2**n
def addVectors(a, b): """Add two list-like objects, pair-wise.""" return tuple([a[i] + b[i] for i in range(len(a))])
def validate_subnet_mask(subnet_mask): """Checks that the argument is a valid subnet mask. :param str subnet_mask: The subnet mask to check. :return: True if the subnet mask is valid; false if not. :rtype: bool :raises ValueError: if the subnet mask is invalid. .. seealso:: https://codereview.stackexchange.com/questions/209243/verify-a-subnet-mask-for-validity-in-python """ if subnet_mask is not None and subnet_mask.strip(): subnet_mask = subnet_mask.strip() a, b, c, d = (int(octet) for octet in subnet_mask.split(".")) mask = a << 24 | b << 16 | c << 8 | d if mask < 1: raise ValueError("Invalid subnet mask: {0}".format(subnet_mask)) else: # Count the number of consecutive 0 bits at the right. # https://wiki.python.org/moin/BitManipulation#lowestSet.28.29 m = mask & -mask right0bits = -1 while m: m >>= 1 right0bits += 1 # Verify that all the bits to the left are 1"s if mask | ((1 << right0bits) - 1) != 0xffffffff: raise ValueError("Invalid subnet mask: {0}".format(subnet_mask)) return True else: raise ValueError("Invalid subnet mask: {0}.".format(subnet_mask))
def split(s, sep=None, maxsplit=0): """split(str [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is nonzero, splits into at most maxsplit words If sep is not specified, any whitespace string is a separator. Maxsplit defaults to 0. (split and splitfields are synonymous) """ return s.split(sep, maxsplit)
def saml_assertion_to_ldap_style_name(assertion_attributes): """ Return string, approximating a NOAA LDAP-style name for SAML user Keyword Parameters: assertion_attributes -- Dict, representing SAML assertion attributes for a logged in user >>> test_attributes = {'mail': ['Pat.Ng@noaa.gov']} >>> saml_assertion_to_ldap_style_name(test_attributes) 'uid=pat.ng,ou=People,o=noaa.gov' """ # Adapt SAML user email assertion, into a LDAP-style name user_name, user_domain = assertion_attributes['mail'].pop().split('@') generated_ldap_id = 'uid={},ou=People,o={}'.format(user_name.lower(), user_domain) return generated_ldap_id
def weWantThisPixel(col, row): """ a function that returns True if we want # @IndentOk the pixel at col, row and False otherwise """ if col%10 == 0 and row%10 == 0: return True else: return False
def complement(dna): """ This function will return the complement of dna sequence of the input sequence :param dna: (string) original dna :return: (string) complement dna """ ans = '' for base in dna: if base == 'A': ans += 'T' if base == 'T': ans += 'A' if base == 'C': ans += 'G' if base == 'G': ans += 'C' return ans
def is_int(string): """Checks if a string can be converted into an integer""" try: int(string) return True except ValueError: return False
def lowercase_voc(voc): """ In case of conflict take the max of two. """ print("....") vocl = {} for v in voc: vl = v.lower() if vl not in vocl or vocl[vl] < voc[v]: vocl[vl] = voc[v] else: pass return vocl
def get_chess_square_border(size, x, y): """ Returns the coordinates of the square block's border """ return (x * size // 8 + 2, y * size // 8 + 2)
def put_on_device(dev, tensors): """Put arguments on specific device Places the positional arguments onto the user-specified device Parameters ---------- dev : str Device identifier tensors : sequence/list Sequence of torch.Tensor variables that are to be put on the device """ for i in range(len(tensors)): if not tensors[i] is None: tensors[i] = tensors[i].to(dev) return tensors
def split_dirname(dirname): """Splits the capitalized suffix out from the given directories. Looks for the longest suffix that is CamelCased; specifically, where each directory starts with a capitalized letter. See go/haskell-standard-names for the motivation of this scheme. For example: split_dirname("abc/Def/Ghi") == ("abc", "Def/Ghi") split_dirname("abc/def") == ("abc/def", "") Args: dirname: A string; a path of directories separated by "/". Returns: A pair of (prefix, suffix) strings. """ dirs = dirname.split("/") for i in range(len(dirs) - 1, -1, -1): if not dirs[i][0:1].isupper(): # Make sure to exclude symbols return ("/".join(dirs[0:(i + 1)]), "/".join(dirs[(i + 1):])) # Every component is lower-cased: return (dirname, "")
def to_list(collection): """:yaql:toList Returns list built from iterable. :signature: collection.toList() :receiverArg collection: collection to be transferred to list :argType collection: iterable :returnType: list .. code:: yaql> range(3).toList() [0, 1, 2] """ if isinstance(collection, tuple): return collection return tuple(collection)
def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b))
def does_not_compose(left, right): """ Composition error. """ return "{} does not compose with {}.".format(left, right)
def flatten_with_key_paths( d, sep=None, flat_list=True, reverse_key_value=False, condition_fn=None ): """ Example: >>> d = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} >>> flatten_with_key_paths(d, flat_list=False) {('a',): 1, ('c', 'a'): 2, ('c', 'b', 'x'): 5, ('c', 'b', 'y'): 10, ('d',): [1, 2, 3]} >>> flatten_with_key_paths(d, sep='/', flat_list=False) {'a': 1, 'c/a': 2, 'c/b/x': 5, 'c/b/y': 10, 'd': [1, 2, 3]} >>> flatten_with_key_paths(d, sep='/', flat_list=True) {'a': 1, 'c/a': 2, 'c/b/x': 5, 'c/b/y': 10, 'd/0': 1, 'd/1': 2, 'd/2': 3} >>> flatten_with_key_paths(d, sep='/', flat_list=True, reverse_key_value=True) {1: 'd/0', 2: 'd/1', 5: 'c/b/x', 10: 'c/b/y', 3: 'd/2'} >>> flatten_with_key_paths(1, sep='/', flat_list=False) {'': 1} """ res = {} def fetch(prefix, v0): if isinstance(v0, dict): for k, v in v0.items(): fetch(prefix + (k,), v) elif flat_list and isinstance(v0, (tuple, list)): for k, v in enumerate(v0): fetch(prefix + (str(k),), v) else: key = prefix if sep is None else sep.join(prefix) if condition_fn is None or condition_fn(key, v0): if reverse_key_value: res[v0] = key else: res[key] = v0 fetch((), d) return res
def comparable(bytes): """ Helper function to make byte-array output more readable in failed test assertions. """ readables = ["%02x" % v for v in bytes] return " ".join(readables)
def sum_of_lines(line1, line2): """ sum of snailfish lines """ return "[" + line1 + "," + line2 + "]"
def allowed_file(filename, allowed_extensions): """ Check for whether a filename is in the ALLOWED_EXTENSIONS Args: filename (str): filename to check Returns: bool: whether the filename is in allowed extensions """ return '.' in filename and \ filename.rsplit('.', 1)[1] in allowed_extensions
def join_url(*args): # type: (*str) -> str """ Joins given arguments into an url and add trailing slash """ parts = [part[:-1] if part and part[-1] == '/' else part for part in args] parts.append('') return '/'.join(parts)
def calculate_a(sigma1: float, sigma2: float, rho: float) -> float: """Calculates Clark's expression for a (degeneracy condition).""" a2 = sigma1 ** 2 + sigma2 ** 2 - 2 * sigma1 * sigma2 * rho a = a2 ** 0.5 return a
def is_luminous(rgb): """Is an "rgb" value luminous. Notes ----- Determined using the formula at: https://www.w3.org/TR/WCAG20/#relativeluminancedef """ new_color = [] for c in rgb: if c <= 0.03928: new_color.append(c / 12.92) else: new_color.append(((c + 0.055) / 1.055) ** 2.4) L = sum([x * y for x, y in zip([0.2126, 0.7152, 0.0722], new_color)]) return True if L < 0.179 else False
def get_corpus(tokens): """ Combine the list of tokens into a string :return: a long string that combines all the tokens together """ corpus = ' '.join(tokens) return corpus
def bps_to_mbps(value): """Bits per second to Mbit/sec""" return round(int(value) / (1000**2), 3)
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year): """Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database.""" formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthday_of_contact_day + "/" + p_birthday_of_contact_year return formated_birthday_string
def _hemisphere(latitude): """ This function defines the hemisphere from latitude :param latitude: float :return: String 'S' is South 'N' is North """ # if latitude > 0: # min_max hemisphere_lat = 'N' # North else: hemisphere_lat = 'S' # South hemisphere = hemisphere_lat return hemisphere
def buildUpdateFields(params): """Join fields and values for SQL update statement """ return ",".join(['%s = "%s"' % (k, v) for k, v in list(params.items())])
def f_raw(x, a, b): """ The raw function call, performs no checks on valid parameters.. :return: """ return a * x + b
def cast_value(value, requested_type): """ Tries to cast the given value to the given type """ try: if requested_type == "Boolean": return value == "True" if requested_type == "Integer": return int(value) if requested_type == "Float": return float(value) return value except TypeError: print("Value doesnt match with given type")
def normalize_path_for_settings(path, escape_drive_sep=False): """ Normalize a path for a settings file in case backslashes are treated as escape characters :param path: The path to process (string or pathlib.Path) :param escape_drive_sep: Option to escape any ':' driver separator (windows) :return: The normalized path """ if isinstance(path, str): processed = path else: processed = str(path.resolve()) processed = processed.replace('\\', '/') if escape_drive_sep: processed = processed.replace(':', '\\:') return processed
def _check_transform_file_ending(fn, f_format=".sdf"): """Checks if there is sdf(or optional other) file ending. If not it adds a file ending. """ if fn.endswith(f_format): return fn else: return fn + f_format
def amplitude(times, signal, period): """ Computes the mean amplitude of a periodic signal params: - times: instants when the measures were taken - signal: values of the measure - period: period of the signal """ n = len(times) if not len(signal) == len(times): raise ValueError( 'signal and times must have the same length (a measure for each time)' ) points = [] amp_sum = 0 current_max = 0 i = 0 count = 0 for i in range(n): if times[i] < (count + 1)*period: current_max = max(current_max, abs(signal[i])) else: amp_sum += current_max current_max = 0 count += 1 # print('MAX ', max(np.abs(signal))) # print('MEAN', mean_sum/count) return amp_sum/count
def endlToFudgeInterpolation( interpolation ) : """This function converts an endl interpolation value (0 or 2 is lin-lin, 3 is log-lin, 4 is lin-log and 5 is log-log) into a fudge interpolation value (0 is lin-lin, 1 is log-lin, 2 is lin-log and 3 is log-log).""" if( ( interpolation < 0 ) or ( interpolation > 5 ) or ( interpolation == 1 ) ) : raise Exception( "Invalid ENDL interpolation value = %d" % interpolation ) return( ( 0, None, 0, 1, 2, 3 )[interpolation] )
def no_none_get(dictionary, key, alternative): """Gets the value for a key in a dictionary if it exists and is not None. dictionary is where the value is taken from. key is the key that is attempted to be retrieved from the dictionary. alternative is what returns if the key doesn't exist.""" if key in list(dictionary.keys()): if dictionary[key] is not None: return dictionary[key] else: return alternative else: return alternative
def pre_cell(data, html_class='center'): """Formats table <pre> cell data for processing in jinja template.""" return { 'cell_type': 'pre', 'data': data, 'class': html_class, }
def merge_variables(program, node, variables): """Create a combined Variable for a list of variables. The purpose of this function is to create a final result variable for functions that return a list of "temporary" variables. (E.g. function calls). Args: program: A cfg.Program instance. node: The current CFG node. variables: A list of cfg.Variables. Returns: A cfg.Variable. """ if not variables: return program.NewVariable() # return empty var elif len(variables) == 1: v, = variables return v elif all(v is variables[0] for v in variables): return variables[0] else: v = program.NewVariable() for r in variables: v.PasteVariable(r, node) return v
def ife(test, if_result, else_result): """ Utility if-then-else syntactic sugar """ if(test): return if_result return else_result
def two_sum_problem_hash(data, total, distinct=False): """ Returns the pairs of number in input list which sum to the given total. Complexity O(n) Args: data: list, all the numbers available to compute the sums. total: int, the sum to look for. distinct: boolean, whether to accept distinct values when computing sums. Returns: list, of pairs of numbers from data which sum up to total. """ h = {} # Using python's native hash table which is much more performant. for i in data: h[i] = True out = [] for i in data: other = total - i if (other in h) and ((distinct == True and i != other) or (distinct == False)): out.append((i, other)) return out
def nested_dict(dict_, keys, val): """Assign value to dictionary.""" cloned = dict_.copy() if len(keys) == 1: cloned[keys[0]] = val return cloned dd = cloned[keys[0]] for k in keys[1:len(keys) - 1]: dd = dd[k] last_key = keys[len(keys) - 1] dd[last_key] = val return cloned
def actor_phrase_match(patphrase, phrasefrag): """ Determines whether the actor pattern patphrase occurs in phrasefrag. Returns True if match is successful. Insha'Allah... """ ret = False APMprint = False connector = patphrase[1] kfrag = 1 # already know first word matched kpatword = 2 # skip code and connector if APMprint: # debug print( "APM-1", len(patphrase), patphrase, "\nAPM-2", len(phrasefrag), phrasefrag) if len(patphrase) == 2: if APMprint: print("APM-2.1: singleton match") # debug return True, 1 # root word is a sufficient match # <14.02.28>: these both do the same thing, except one handles a string of # the form XXX and the other XXX_. This is probably unnecessary. though it # might be...I suppose those are two distinct cases. if len(patphrase) == 3 and patphrase[2][0] == "": if APMprint: print("APM-2.2: singleton match") # debug return True, 1 # root word is a sufficient match if kfrag >= len(phrasefrag): return False, 0 # end of phrase with more to match while kpatword < len(patphrase): # iterate over the words in the pattern if APMprint: # debug print( "APM-3", kfrag, kpatword, "\n APM Check:", kpatword, phrasefrag[kfrag], patphrase[kpatword][0]) if phrasefrag[kfrag] == patphrase[kpatword][0]: if APMprint: print(" APM match") # debug connector = patphrase[kpatword][1] kfrag += 1 kpatword += 1 # final element is just the terminator if kpatword >= len(patphrase) - 1: return True, kfrag # complete pattern matched else: if APMprint: print(" APM fail") # debug if connector == '_': return False, 0 # consecutive match required, so fail else: kfrag += 1 # intervening words are allowed if kfrag >= len(phrasefrag): return False, 0 # end of phrase with more to match return ( # complete pattern matched (I don't think we can ever hit this) True, len(phrasefrag) )
def _symbolize_path(keypath): """ Take a key path like `gust.version`, and convert it to a global symbol like `GUST_VERSION`, which is usable as, say, an environment variable. """ return keypath.replace(".", "_").upper()
def _max(arr): """Maximum of an array, return 1 on empty arrays.""" return arr.max() if arr is not None and len(arr) > 0 else 1
def create_unimplemented_message(param, method): """Message to tell you request is succeed but requested API is unimplemented. :param param: request param :param method: request method :return: message object """ date = { 'message': 'Request is succeed, but this API is unimplemented.', 'param': param, 'method': method } return date
def index(s, *args): """index(s, sub [,start [,end]]) -> int Like find but raises ValueError when the substring is not found. """ return s.index(*args)
def duration_as_string(years, months): """ Return duration as printable string """ duration_y = '' duration_m = '' if years > 1: duration_y = '{} years'.format(years) elif years == 1: duration_y = '1 year' if months > 1: duration_m = '{} months'.format(months) elif months == 1: duration_m = '1 month' if duration_y and duration_m: return '{}, {}'.format(duration_y, duration_m) return duration_y + duration_m
def combine_english_defs(senses, separator=u', '): """Combines the English definitions in senses. Args: senses: An array with dict elements with English info. Returns: A string of English definitions separated by the separator. """ # Each sense contains a list of English definitions. e.g. [[], [], []] eng_defs_lists = [sense['english_definitions'] for sense in senses if 'english_definitions' in sense] # Combine the inner lists of English definitions into one list. combined_eng_defs = [eng_def for eng_def_list in eng_defs_lists for eng_def in eng_def_list] return separator.join(combined_eng_defs)
def has_same_spaces(plain, cipher): """has same number of spaces in same positions""" if len(plain) != len(cipher): return False if plain.count(' ') != cipher.count(' '): return False for p, c in zip(plain, cipher): if p==' ' and c != p: return False return True
def get_eta_powerlaw_params(param_dict): """ Extract and return parameters from dictionary for powerlaw form """ rScale = param_dict['rScale'] rc = param_dict['rc'] etaScale = param_dict['etaScale'] betaDelta = param_dict['betaDelta'] return rScale, rc, etaScale, betaDelta
def add_database_name(db, name): """Add database name to datasets""" for ds in db: ds['database'] = name return db
def preprocess_txt(input_ids, masks, labels): """ format for tf model """ return {'input_ids': input_ids, 'attention_mask': masks}, labels
def findAnEven(L): """Assumes L is a list of integers Returns the first even number in L Raises ValueError if L does not contain an even number""" for e in L: if e%2 == 0: return e else: e = e raise ValueError('The provided list does not contain an even number') return None
def empty_chunk(n): """ Produce a 2D list of size n x n that is populated with ".". """ return [["." for _ in range(n)] for _ in range(n)]
def index_to_tier(index): """Convert numerical index to named tier""" tier = ("Primary" if index == 1 else "Reserve" if index == 2 else "Index %s" % index) return tier
def get_list(data): """ Return list of data from string. Args: data (str): String to convert to list Raises: None Returns: TYPE: list """ obtained_list = [ele.strip(" ").strip("\n") \ for ele in data.split(",")] return obtained_list
def set_count(items): """ This is similar to "set", but this just creates a list with values. The list will be ordered from most frequent down. Example: >>> inventory = ["apple", "lemon", "apple", "orange", "lemon", "lemon"] >>> set_count(inventory) [("lemon", 3), ("apple", 2), ("orange", 1)] """ item_count = {} for item in items: if not item: continue if item not in item_count: item_count[item] = 0 item_count[item] += 1 items = [(v, k) for k, v in item_count.items()] items.sort() items.reverse() return [(k, v) for v, k in items]
def get_module_description(module_name: str, max_lines=5) -> str: """ Attempt to get the module docstring and use it as description for search results """ desc = "" try: doc = "" name_chunks = module_name.split(".") if len(name_chunks) > 1: tail = name_chunks[-1] mod = __import__(module_name) doc = getattr(mod, tail).__doc__ if not doc: doc = __import__(module_name).__doc__ or "" lines = doc.splitlines()[:max_lines] for line in lines: if not line and desc: return desc desc += "\n" if desc else "" desc += line except Exception: # pylint: disable=broad-except pass return desc
def filter_dict(dictionary, keep_fields): """ Filter a dictionary's entries. :param dictionary: Dictionary that is going to be filtered. :type dictionary: dict :param keep_fields: Dictionary keys that aren't going to be filtered. :type keep_fields: dict or list or set :return: Filtered dictionary. :rtype: dict """ return { key: value for key, value in dictionary.items() if key in keep_fields }
def early_stop(patience, max_factor, vae_loss_val, em_loss_val): """ Manual implementation of https://keras.io/api/callbacks/early_stopping/. :param patience: max number of epochs loss has not decreased :param max_factor: max_factor * current loss is the max acceptable loss :param vae_loss_val: list of vae validation losses :param em_loss_val: list of emulator validation losses :return: boolean, True (keep going) or False (stop early) """ if not len(em_loss_val) > patience: # there is not enough training to compare return True if vae_loss_val is not None: vae_max_loss = vae_loss_val[-(1 + patience)] * max_factor # the max acceptable loss else: vae_max_loss = None em_max_loss = em_loss_val[-(1 + patience)] * max_factor # the max acceptable loss count = 0 while count < patience: if em_loss_val[-(1 + count)] > em_max_loss: if vae_loss_val is None: count += 1 continue elif vae_loss_val[-(1 + count)] > vae_max_loss: count += 1 continue else: break else: break if count == patience: # the last [patience] losses are all too large: stop training print("Early stopping!") return False # keep_going = False, i.e. stop early else: return True
def logical_any_terminal_condition(env, conditions): """A logical "Any" operator for terminal conditions. Args: env: An instance of MinitaurGymEnv conditions: a list of terminal conditions Returns: A boolean indicating if any of terminal conditions is satisfied """ return any([cond(env) for cond in conditions])
def sign(num): """ Determines the sign of a number """ if num >= 0: return 1 else: return -1
def validate(observation): """Make sure the observation table is valid, or raise an error.""" if observation is not None and type(observation) == dict: return observation elif type(observation) == list: return observation else: raise RuntimeError('Must return dictionary from act().')
def selectionsort(arr): """ In each iteration, find the min of arr[lo:hi+1] and swap with arr[lo], then increment lo Invariant: everything to the left of lo is sorted """ lo = 0 hi = len(arr) - 1 while lo <= hi: minval = arr[lo] minindx = lo for curr in range(lo + 1, hi + 1): if arr[curr] < minval: minval = arr[curr] minindx = curr arr[lo], arr[minindx] = arr[minindx], arr[lo] # print(arr) lo += 1 return arr
def ignorefunc(original, ignore): """A function to replace ignored characters to noting :v""" text = str(original) ignore = list(ignore) for ch in ignore: if ch in text: text=text.replace(ch,"") # I don't know why, but text is not a tuple text = text.replace("(", "") text = text.replace(")", "") text = text.replace(",", "") text = text.replace("'", "") return text
def checksum(string): """Fetch string and calculate the checksum. This function is copied from sample code file. Args: :param string: A string of the time in seconds since the epoch. Returns: :return: The value of checksum (integer type). """ csum = 0 count_to = (len(string) // 2) * 2 count = 0 while count < count_to: this_val = string[count + 1] * 256 + string[count] csum = csum + this_val csum = csum & 0xffffffff count = count + 2 if count_to < len(string): csum = csum + string[len(string) - 1] csum = csum & 0xffffffff csum = (csum >> 16) + (csum & 0xffff) csum = csum + (csum >> 16) answer = ~csum answer = answer & 0xffff answer = answer >> 8 | (answer << 8 & 0xff00) return answer
def next_indentation(line, tab_length): """Given a code line, return the indentation of the next line.""" line = line.expandtabs(tab_length) indentation = (len(line) - len(line.lstrip(" "))) // tab_length if line.rstrip().endswith(":"): indentation += 1 elif indentation >= 1: if line.lstrip().startswith(("return", "pass", "raise", "yield")): indentation -= 1 return indentation
def remove_dup(a): """ remove duplicates using extra array """ res = [] count = 0 for i in range(0, len(a)-1): if a[i] != a[i+1]: res.append(a[i]) count = count + 1 res.append(a[len(a)-1]) print('Total count of unique elements: {}'.format(count +1)) return res
def sort_list_by (sorting_key: str, array_to_sort: list) -> list: """ Sort a list of dictionaries by one of the dictionary key values """ return sorted(array_to_sort, key=lambda keyy: keyy[sorting_key], reverse=True)
def convert(number): """ input: a number return: a string """ sound = "" if number % 3 == 0: sound = "Pling" if number % 5 == 0: sound = sound + "Plang" if number % 7 == 0: sound = sound + "Plong" if sound == "": sound = str(number) return sound
def uses_only( word, letters ): """Return True if the word contains only letters in the list. """ for w in word: if w not in letters: return False return True
def nlp_process(search_cond): """ Build structured search criteria from constraints specified in the natural language input string :param search_cond: natural language english input with email search criteria :return: mail_box, gmail mail box to retrieve emails from :return: search_criteria, structured search criteria string """ if search_cond is None: return '[Gmail]/All Mail', 'ALL' mail_box_list = ['INBOX', '[Gmail]', '[Gmail]/All Mail', '[Gmail]/Drafts', '[Gmail]/Important', '[Gmail]/Sent Mail', '[Gmail]/Spam', '[Gmail]/Starred', '[Gmail]/Trash'] mail_type = ['ANSWERED', 'UNANSWERED', 'ALL', 'SEEN', 'UNSEEN', 'RECENT', 'OLD', 'NEW', 'DELETED'] mail_date = {'on': 'SENTON {date}', 'after': 'SENTSINCE {date}', 'before': 'SENTBEFORE {date}'} mail_field = {'from': 'FROM "{search_text}"', 'to': 'TO "{search_text}"', 'subject': 'SUBJECT "{search_text}"', 'body': 'BODY "{search_text}"', 'text': 'TEXT "{search_text}"'} mail_size = {'small': 'SMALLER {size}', 'large': 'LARGER {size}'} or_key = 'OR' and_key = 'AND'
def quote_str(obj): """ Adds extra quotes to a string. If the argument is not a string it is returned unmodified :param obj: Object :type obj: any :rtype: Same as argument For example: >>> import putil.misc >>> putil.misc.quote_str(5) 5 >>> putil.misc.quote_str('Hello!') '"Hello!"' >>> putil.misc.quote_str('He said "hello!"') '\\'He said "hello!"\\'' """ if not isinstance(obj, str): return obj else: return ( "'{obj}'".format(obj=obj) if '"' in obj else '"{obj}"'.format(obj=obj) )
def is_monotonically_increasing(series): """ Check if a given list or array is monotonically increasing. Examples -------- >>> import pandas as pd >>> times = pd.date_range('1980-01-19', periods=10) >>> all(is_monotonically_increasing(times)) True >>> import numpy as np >>> all(is_monotonically_increasing(np.r_[times[-2:-1], times])) False """ return [x < y for x, y in zip(series, series[1:])]
def c_to_f(tempc): """ Parameters Temp (C) Returns Temp (F) """ tempf = tempc * (9./5.) + 32. return tempf
def get_code(file_path: str) -> str: """Gets the source code of the specified file.""" with open(file_path, "r") as file: code = file.read() return code
def get_link_to_osm(lat, lon, zoom=15): """Return link to OSM centered in lat, lon.""" return ('http://openstreetmap.org/?mlat=%(lat)s&mlon=%(lon)s' '&zoom=%(zoom)s' % {'lat': lat, 'lon': lon, 'zoom': zoom})
def cntDivisor(n): """ >>> cntDivisor(14) 4 >>> cntDivisor(140) 12 """ rem = 1 cnt = 2 while 1: rem += 1 num = n / rem if num < rem: break if n % rem == 0: cnt += 2 if num == rem: cnt -= 1 break return cnt
def graph_is_connected(edges, players): """ Test if a set of edges defines a complete graph on a set of players. This is used by the spatial tournaments. Parameters: ----------- edges : a list of 2 tuples players : a list of player names Returns: -------- boolean : True if the graph is connected """ # Check if all players are connected. player_indices = set(range(len(players))) node_indices = set() for edge in edges: for node in edge: node_indices.add(node) return player_indices == node_indices
def string_to_bool(val): """Convert string to bool.""" if val is None: return False if isinstance(val, bool): return val if isinstance(val, str): if val.lower() in ("yes", "true", "t", "y", "1"): return True elif val.lower() in ("no", "false", "f", "n", "0"): return False raise ValueError("Boolean value expected.")
def _HasNewFailures(current_failures, new_failures): """Checks if there are any new failures in the current build.""" if current_failures == new_failures: return False for step, tests in current_failures.iteritems(): if not new_failures.get(step): # New step. return True for test in tests: if not test in new_failures[step]: # New test. return True return False
def position_angle(freq, pa_zero, rm, freq_cen): """ Polarisation position angle as a function of freq.""" c = 2.998e8 # vacuum speed of light in m/s return pa_zero + rm*(((c/freq)**2) - ((c/(freq_cen*1e6))**2))