content
stringlengths
42
6.51k
def c_to_f(celsius): """Converts Celsius to Fahrenheit >>> c_to_f(0) 32.0 >>> c_to_f(5) 41.0 >>> c_to_f(-25) -13.0 """ "*** YOUR CODE HERE ***" a = celsius * 9 / 5 + 32 return a
def calc_time_cost_function_total(natom, nkpt, kmax, niter, nspins=1): """Estimates the cost of simulating a all iteration of a system""" costs = natom**3 * kmax**3 * nkpt * nspins * niter return costs
def bounding_rect(polygon): """takes a polygon and returns a rectangle parallel to the axes""" xs = [q[0] for q in polygon] ys = [q[1] for q in polygon] return [[min(xs), min(ys)], [max(xs), max(ys)]]
def calculate_displacement(src_grammar, tgt_grammar): """Calculate displacement between 2 grammar. E.g: S -> A B C to S -> B C A has displacement of [1 2 0]""" src_grammar_lst = src_grammar.split() tgt_grammar_lst = tgt_grammar.split() src_grammar_lst = src_grammar_lst[src_grammar_lst.index("->")+1:] tgt_grammar_lst = tgt_grammar_lst[tgt_grammar_lst.index("->")+1:] displacement = [] new_words = [] for word in tgt_grammar_lst: try: displacement.append(src_grammar_lst.index(word)) except ValueError: # Resolve ValueError: substring not found # Which indicates this is a new word displacement.append(-1) new_words.append(word) return displacement, new_words
def merge(f_list): """Merge two polynomials into a single polynomial f. Args: f_list: a list of polynomials Format: coefficient """ f0, f1 = f_list n = 2 * len(f0) f = [0] * n for i in range(n // 2): f[2 * i + 0] = f0[i] f[2 * i + 1] = f1[i] return f
def all_pairs(items): """Make all unique pairs (order doesn't matter)""" pairs = [] nitems = len(items) for i, wi in enumerate(items): for j in range(i+1, nitems): pairs.append((wi, items[j])) return pairs
def tab(code, nb_tab=1): """add tabulation for each lines""" space = ' '*4 indent_char = space * nb_tab ret = [] for line in code.splitlines(): ret.append("%s%s" % (indent_char, line)) return '\n'.join(ret)
def hash_string(keyword, buckets): """ Takes as its inputs a string and the number of buckets, b, and returns a number between 0 and b - 1, which gives the position where that string belongs. """ h = 0 for char in keyword: h = (h + ord(char)) % buckets return h
def findRoot(x, power, epsilon): """ Assumes x and epsilon int or float, power an int, epsilon > 0 & power >= 1 Returns float y such that y**power is within epsilon of x. If such a float does not exists, it returns None.""" if x < 0 and power % 2 == 0: return None low = min(-1.0, x) high = max(1.0, x) ans = (high + low) / 2.0 while abs(ans ** power - x) >= epsilon: if ans ** power < x: low = ans else: high = ans ans = (high + low) / 2.0 return print(ans)
def mac_addr(address): """Convert a MAC address to a readable/printable string Args: address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06') Returns: str: Printable/readable MAC address """ return ':'.join('%02x' % ord(b) for b in address)
def _decode_lut_config(raw_lut_string): """Extend a LUT string to one suitable for a 4-LUT. If the input has less than four inputs it will be too sort and must be extended so that no matter what the other inputs are set to, it won't affect the output for the bits that matter. """ # We assume that the logic cell will use LUT inputs associated # with the least significant bits first. lut_string = raw_lut_string * (16 // len(raw_lut_string)) assert len(lut_string) == 16 return int(lut_string, 2)
def _str_list_converter(argument): """ A directive option conversion function that converts the option into a list of strings. Used for 'skip' option. """ if argument is None: return [] else: return [s.strip() for s in argument.split(',')]
def clean_link_text(link_text): """ The link text sometimes contains new lines, or extrananeous spaces, we remove them here. """ return link_text.strip().replace('\n', '').replace('\r', '')
def my_sum(arg): """ Sums the arguments and returns the sum. """ total = 0 for val in arg: total += val return total
def format_input_source(input_source_name, input_source_number): """Format input source for display in UI.""" return f"{input_source_name} {input_source_number}"
def matrixify(string_grid, separator='\n'): """Return a matrix out of string_grid. Args: string_grid (str): A string containing non-whitespace and whitespace characters. separator (str): A whitespace character used in string_grid. Returns: list: Returns list of the strings of string_grid separated at its whitespace. """ return string_grid.split(separator)
def _compare_ranges(range1, range2, epsilon=1e-3): """Returns true if the both range are close enough (within a relative epsilon).""" if not range1[0] or not range2[0]: return False return abs(range1[0] - range2[0]) < epsilon and abs(range1[1] - range2[1]) < epsilon
def bounce(function, *args): """Returns a new trampolined value that continues bouncing on the trampoline.""" return ('bounce', function, args)
def get_mirror_giturl(submod_name): """Gets the submodule's url on mirror server. Retrurn the download address of the submodule on the mirror server from the submod_name. """ mirror_url = 'https://gitee.com/RT-Thread-Mirror/submod_' + submod_name + '.git' return mirror_url
def toDataRange(size, r = all): """Converts range r to numeric range (min,max) given the full array size Arguments: size (tuple): source data size r (tuple or all): range specification, ``all`` is full range Returns: tuple: absolute range as pair of integers See Also: :func:`toDataSize`, :func:`dataSizeFromDataRange` """ if r is all: return (0,size) if isinstance(r, int) or isinstance(r, float): r = (r, r +1) if r[0] is all: r = (0, r[1]) if r[0] < 0: if -r[0] > size: r = (0, r[1]) else: r = (size + r[0], r[1]) if r[0] > size: r = (size, r[1]) if r[1] is all: r = (r[0], size) if r[1] < 0: if -r[1] > size: r = (r[0], 0) else: r = (r[0], size + r[1]) if r[1] > size: r = (r[0], size) if r[0] > r[1]: r = (r[0], r[0]) return r
def get_min_and_max_coords_from_exon_chain(coords): """Gets the minumum and maximum coordinates from exon chain Args: coords ([[int, int]]): [[start,end]] exon coordinate chain Returns: (int, int): start and end coordinates of entire chain """ min_coord = min(map(min, coords)) max_coord = max(map(max, coords)) return min_coord, max_coord
def zigzagLevelOrder(root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] res, temp, stack, flag = [], [], [root], 1 while stack: for i in range(len(stack)): node = stack.pop(0) temp += [node.val] if node.left: stack += [node.left] if node.right: stack += [node.right] res += [temp[::flag]] temp = [] flag *= -1 return res
def _validate_x_and_y(x, y): """ Validate input data. """ if x is None or y is None: raise TypeError("x and y cannot be of NoneType") return x, y
def get_label_yml(label): """Get yml format for label Args: label (dict): dictionnary if labels with keys color, name and description as strings, possibly empty Returns: str: yml formatted dict, as a yml list item """ text = f' - name: "{label["name"]}"\n' text += f' color: "{label["color"]}"\n' text += f' description: "{label["description"]}"\n' return text
def is_cache_enabled(cache_config): # type: (str) -> bool """ Check if the cache is enabled. :param cache_config: Cache configuration defined on startup. :return: True if enabled, False otherwise. And size if enabled. """ if ":" in cache_config: cache, _ = cache_config.split(":") cache = True if cache.lower() == "true" else False else: cache = True if cache_config.lower() == "true" else False return cache
def fact_recur(n): """assumes n >= 0 """ if n <= 1: return 1 else: return n * fact_recur(n - 1)
def float_round(num, n): """Makes sure a variable is a float and round it at "n" decimals Args: num (str, int, float): number we want to make sure is a float n (int): number of decimals Returns: num (float): a float rounded number """ num = float(num) num = round(num, n) return num
def navamsa_from_long(longitude): """Calculates the navamsa-sign in which given longitude falls 0 = Aries, 1 = Taurus, ..., 11 = Pisces """ one_pada = (360 / (12 * 9)) # There are also 108 navamsas one_sign = 12 * one_pada # = 40 degrees exactly signs_elapsed = longitude / one_sign fraction_left = signs_elapsed % 1 return int(fraction_left * 12)
def recur_fibo(n): """Recursive function to print Fibonacci sequence""" if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2))
def parse_program(lines): """Parse program from lines.""" return [[int(num) for num in line.strip().split()] for line in lines.strip().split('\n')]
def cipher(text, shift, encrypt=True): """ Encrypting or deecrpting using Caesar cipher. Parameters ---------- text : str The contents to be encrypted or decrypted shift : int A fixed number of positions that each letter in text is shifted down (positive) or up (negative) encrypt : bool If True, then the text is encrypted; otherwise, the text is decrypted Returns ------- str The encrypted or decrypted text. Examples -------- >>> from cipher_gy2277 import cipher_gy2277 >>> text = "cat" >>> shift = 3 >>> cipher_yuan_gan.cipher(text, shift) 'fdw' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def humanbytes(size): """Input size in bytes, outputs in a human readable format""" if not size: return "" # 2 ** 10 = 1024 power = 2 ** 10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
def parse_rest_create_list_response(resp): """Split the response from the REST API lines into columns Args: resp (string): [description] Returns: [rest_response_object]: [description] """ rest_responses = [] lines = resp.splitlines() del lines[0:2] for line in lines: elements = line.split() rest_response_object = { "id": elements[0], "uri": elements[1], "creation time": str(elements[2] + " " + elements[3]), "state": elements[4], } rest_responses.append(rest_response_object) return rest_responses
def get_steps(length, input_dimension, output_dimension): """Calculates each step along a dimension of the tile. length is the total length of the dimension, model resolution is the detector's expected input length, and padding is the model's required padding (zero if none.) """ steps = [] padding = (input_dimension - output_dimension)//2 remainder = (input_dimension - output_dimension)%2 step_size = output_dimension - remainder current_step = 0-padding steps.append(current_step) current_step += step_size #Iterate until final prediction "falls off" edge of input image while (steps[-1]+(2*step_size+padding)) < length: steps.append(current_step) current_step += step_size #Situation with no overlap on final tile or small length; if current_step+step_size+padding == length or length <= output_dimension: return steps, [step+padding-remainder for step in steps] else: final_step = length - step_size - padding - remainder steps.append(final_step) return steps, [step+padding for step in steps]
def check_long_form(doc, alice_mapping): """ usage: get the mapping b/w long_form: short form for each document input: take the document in output: return the matching short_form: long_form """ try: long_name = alice_mapping[doc] except: long_name = dict() return long_name
def strip_keys(key_list): """ Given a list of keys, remove the prefix and remove just the data we care about. for example: ['defender:blocked:ip:ken', 'defender:blocked:ip:joffrey'] would result in: ['ken', 'joffrey'] """ return [key.split(":")[-1] for key in key_list]
def convert_predictions_to_str_set(predictions): """ Helper method to convert predictions into readable text strings """ return {x.text + "_" + x.label_ for x in predictions}
def ot2bio_ate(ate_tag_sequence): """ ot2bio function for ate task """ n_tags = len(ate_tag_sequence) new_ate_sequence = [] prev_ate_tag = '$$$' for i in range(n_tags): cur_ate_tag = ate_tag_sequence[i] if cur_ate_tag == 'O' or cur_ate_tag == 'EQ': # note that, EQ tag can be incorrectly predicted in the testing phase # when meet EQ, regard it as O new_ate_sequence.append('O') prev_ate_tag = 'O' else: # current ate tag is T if cur_ate_tag == prev_ate_tag: new_ate_sequence.append('I') else: new_ate_sequence.append('B') prev_ate_tag = cur_ate_tag assert len(new_ate_sequence) == len(ate_tag_sequence) return new_ate_sequence
def error_running_file(filename, section, error): """returns a string in log format if a module errors out""" file_error = "ty_error_running_file=%s" % (filename, ) section_error = "ty_error_section=%s" % (section, ) error_message = "ty_error_message=%r" % (error, ) return " ".join([ file_error, section_error, error_message, ])
def pmelt_T_iceIh(T): """ EQ 1 / Melting pressure of ice Ih """ T_star = 273.16 p_star = 611.657E-6 theta = T / T_star a = (0.119539337E7, 0.808183159E5, 0.333826860E4) b = (0.300000E1 , 0.257500E2, 0.103750E3) sum = 0 for i in range(0, 3): sum += a[i] * (1 - theta ** b[i]) pi_melt = 1 + sum return pi_melt * p_star
def partition(f, xs): """ Works similar to filter, except it returns a two-item tuple where the first item is the sequence of items that passed the filter and the second is a sequence of items that didn't pass the filter """ t = type(xs) true = filter(f, xs) false = [x for x in xs if x not in true] return t(true), t(false)
def __filter_assets(catalogs, attachments): """ Separate series from episode assets. :param catalogs: All catalogs :type: list :param attachments: All attachments :type attachments: list :return: Episode catalogs, episode attachments, series catalogs, series attachments :rtype: list, list, list, list """ series_catalogs = [catalog for catalog in catalogs if "series" in catalog.flavor] episode_catalogs = [catalog for catalog in catalogs if catalog not in series_catalogs] series_attachments = [attachment for attachment in attachments if "series" in attachment.flavor] episode_attachments = [attachment for attachment in attachments if attachment not in series_attachments] return episode_catalogs, episode_attachments, series_catalogs, series_attachments
def filter_cmd(cmd): """Remove some non-technical option strings from `cmd`, which is assumed to be a string containing a shell command. """ cmd = cmd.replace(' -outputname /dev/null', '') cmd = cmd.replace(' -q', '') return cmd
def prep_violations(rule, violations): """Default to test rule if code is omitted.""" for v in violations: if "code" not in v: v["code"] = rule return violations
def getOrderedDict(keys,keysid): """Get ordered dict""" from collections import OrderedDict d = OrderedDict() for i in keysid: d[keys[i]] = [] return d
def round_channels(channels, divisor=8): """ Round weighted channel number (make divisible operation). Parameters: ---------- channels : int or float Original number of channels. divisor : int, default 8 Alignment value. Returns ------- int Weighted number of channels. """ rounded_channels = max(int(channels + divisor / 2.0) // divisor * divisor, divisor) if float(rounded_channels) < 0.9 * channels: rounded_channels += divisor return rounded_channels
def check_empty(string: str, delimiter: str = ' '): """Check if string represents dirty data""" string_list = string.split(delimiter) check = 0 for string in string_list: if len(string) < 3: check += 1 if check == len(string_list): string = 'None' else: string = ' '.join(string_list) return string
def jamify(s): """ Convert a valid Python identifier to a string that follows Boost.Build identifier convention. """ return s.replace("_", "-")
def decode_transaction_filter(metadata_bytes): """Decodes transaction filter from metadata bytes Args: metadata_bytes (str): Encoded list of transaction filters Returns: decoded transaction_filter list """ transaction_filter = [] if not metadata_bytes: return None for i in metadata_bytes: transaction_filter.append(int(i)) return transaction_filter
def centerOfMassMotion(*args): """input: [m, vx, vy, vz, vr] variables: m=mass, vx=velocity-along-x, vy=velocity-along-y, vz=velocity-along-z, vr=velocity-along-radius""" mi=0; vxi=1; vyi=2; vzi=3; vri=4 m_total = sum([item[mi] for item in args]) vx = sum([item[mi]*item[vxi] for item in args])/m_total vy = sum([item[mi]*item[vyi] for item in args])/m_total vz = sum([item[mi]*item[vzi] for item in args])/m_total vr = sum([item[mi]*item[vri] for item in args])/m_total return vx,vy,vz,vr
def interval(lower_, upper_): """Build an interval.""" if lower_ <= upper_: return lower_, upper_ return None
def parse_grid(data): """Parses the string representation into a nested list""" return data.strip().split('\n')
def getReverseConnectivity(connectivity): """getReverseConnectivity(connectivity) --> resort connectivity dict with nodes as keys""" reverseConnectivity = {} for el, conn in connectivity.items(): for node in conn: if node not in reverseConnectivity.keys(): reverseConnectivity[node]=[el,] else: reverseConnectivity[node].append(el) return reverseConnectivity
def _strip_object(key): """ Strips branch and version info if the given key supports those attributes. """ if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'): return key.for_branch(None).version_agnostic() else: return key
def first(iterable, default=None, key=None): """ Return first element of `iterable` that evaluates true, else return None (or an optional default value). >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4 """ if key is None: for el in iterable: if el: return el else: for el in iterable: if key(el): return el return default
def pluralize(word, quantity, suffix=None, replacement=None): """Simplistic heuristic word pluralization.""" if quantity == 1: return word if replacement: return replacement if suffix: return '%s%s' % (word, suffix) return '%ss' % word
def get_month(day_str): """ UTILITY FUNCTION takes the day date (str) and returns its month. """ month_dict = {'01':'january', '02':'february', '03':'march', '04':'april', '05':'may', '06':'june', '07':'july', '08':'august', '09':'september', '10':'october', '11':'november', '12':'december'} return month_dict[day_str[5:7]]
def _split_classes_into_list(name): """This dataset provides the classes via a | in the str to signify an or for BCE.""" classes = name.split("|") if len(classes) < 1: return [name] # base case return classes
def extract(data, ids, default=None): """ inputs: data: hierarchical data structure consisting of lists, dicts, and objects with attributes. ids: a list of idices, key names, and attribute names default: optional object output: the value stored at the location indicated by the ids list or default if the location does not exist. Strings in ids are first tried as key name and if no such key name exists, then they are tried as attribute names. To designate that a member of ids should be used as an attribute and not a key name, make it a tuple with the attribute name string as the first member, such as: ('attribute_name',). If you want to make it more explict to the reader, you can add a second member to the tuple, which will not be used, such as ('attribute_name', 'as attribute') """ if len(ids) == 0: return data try: if isinstance(ids[0], tuple): sub_data = getattr(data, ids[0][0]) else: try: sub_data = data[ids[0]] except TypeError: sub_data = getattr(data, ids[0]) except (AttributeError, IndexError, KeyError): return default else: return extract(sub_data, ids[1:], default)
def transcode_bytes(data, encoding): """ Re-encodes bytes to UTF-8. """ return data.decode(encoding).encode()
def wafv2_custom_body_response_content_type(content_type): """validate wafv2 custom response content type""" valid_types = ["APPLICATION_JSON", "TEXT_HTML", "TEXT_PLAIN"] if content_type not in valid_types: raise ValueError('ContentType must be one of: "%s"' % (", ".join(valid_types))) return content_type
def get_class(kls): """ Converts a string to a class. Courtesy: http://stackoverflow.com/q/452969/#452981 """ parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, comp) return m
def _SubtractCpuStats(cpu_stats, start_cpu_stats): """Computes average cpu usage over a time period for different process types. Each of the two cpu_stats arguments is a dict with the following format: {'Browser': {'CpuProcessTime': ..., 'TotalTime': ...}, 'Renderer': {'CpuProcessTime': ..., 'TotalTime': ...} 'Gpu': {'CpuProcessTime': ..., 'TotalTime': ...}} The 'CpuProcessTime' fields represent the number of seconds of CPU time spent in each process, and total time is the number of real seconds that have passed (this may be a Unix timestamp). Returns: A dict of process type names (Browser, Renderer, etc.) to ratios of cpu time used to total time elapsed. """ cpu_usage = {} for process_type in cpu_stats: assert process_type in start_cpu_stats, 'Mismatching process types' # Skip any process_types that are empty. if (not cpu_stats[process_type]) or (not start_cpu_stats[process_type]): continue cpu_process_time = (cpu_stats[process_type]['CpuProcessTime'] - start_cpu_stats[process_type]['CpuProcessTime']) total_time = (cpu_stats[process_type]['TotalTime'] - start_cpu_stats[process_type]['TotalTime']) # Fix overflow for 32-bit jiffie counter, 64-bit counter will not overflow. # Linux kernel starts with a value close to an overflow, so correction is # necessary. if total_time < 0: total_time += 2**32 # Assert that the arguments were given in the correct order. assert total_time > 0 and total_time < 2**31, ( 'Expected total_time > 0, was: %d' % total_time) cpu_usage[process_type] = float(cpu_process_time) / total_time return cpu_usage
def get_snmp_server_config_name(config, name): """ :param config: :param name: :return: """ try: config[name] server_config_name = name except KeyError as exception: server_config_name = 'common' return server_config_name
def get_swagger_version(obj): """ get swagger version from loaded json """ if isinstance(obj, dict): if 'swaggerVersion' in obj: return obj['swaggerVersion'] elif 'swagger' in obj: return obj['swagger'] return None else: # should be an instance of BaseObj return obj.swaggerVersion if hasattr(obj, 'swaggerVersion') else obj.swagger
def zip_check(file_path, compression_type): """ Check if the file suffix or the compression type indicates that it is a zip file. """ if file_path: if file_path.split('/')[-1].split('.')[-1] == 'zip': return True if compression_type == 'zip': return True else: return False
def strip_whitespace(string): """ Converter to strip whitespace from a provided string. """ return string.strip()
def filtra_lista_request_vars(requestvars,clave): """Sirve para limpiar listas que se forman en request.vars con algunas variables que se ponen en el GEt y en el POST devuelve """ if clave in requestvars: if isinstance(requestvars[clave],(list,tuple)): requestvars[clave]=requestvars[clave][0] return requestvars[clave] else: return None
def filter_old_translation_sheets(spreadsheet_names,current_translation_regex,old_translation_regex,languages_to_translate): """ Removes the old translation sheets from the data model. Arguments: spreadsheet_names {[list]} -- [List of the spreadsheet names found in the Translation folder.] current_translation_regex {[string]} -- [String to filter out the sheets to be converted to JSON.] old_translation_regex {[string]} -- [String to filter out the translation sheets not used in data model.] languages_to_translate {[list]} -- [List of lanaguages to translate.] Returns: [list] -- [list of spreadsheets to use for the data model.] """ translation_sheet_names = [ x for x in spreadsheet_names if (current_translation_regex in x) & (old_translation_regex not in x)] return [x for x in translation_sheet_names for y in languages_to_translate if y in x]
def _modcell(cell_in): """Modify the cell""" out = [] for line in cell_in: out.append(line.replace(' C ', ' Si ')) return out
def pKa_mod(resName): """ definitions of min distance """ pKa_mod = {'C- ': 3.20, 'ASP': 3.80, 'GLU': 4.50, 'HIS': 6.50, 'CYS': 9.00, 'TYR':10.00, 'LYS':10.50, 'ARG':12.50, 'N+ ': 8.00} if resName in pKa_mod: return pKa_mod[resName] else: return 20.00
def get_agents_with_name(name, stmts): """Return all agents within a list of statements with a particular name.""" return [ag for stmt in stmts for ag in stmt.agent_list() if ag is not None and ag.name == name]
def _decode_attribute_map_key(key): """This decode a key in an _attribute_map to the actual key we want to look at inside the received data. :param str key: A key string from the generated code """ return key.replace('\\.', '.')
def calc_radiated_power_nadir(radiance_integrated, pixel_resolution_along, pixel_resolution_cross): """ Calculate the power radiated from a ground pixel at Nadir. Returns ------- double : Watts per Sterradian. """ return radiance_integrated * pixel_resolution_along * pixel_resolution_cross
def sort_array_for_min_number(nums): """ :param nums: int list :return: min number string """ from functools import cmp_to_key # def cmp(a, b): # return -1 if a + b < b + a else 1 nums = [str(i) for i in nums] # nums.sort(key = cmp_to_key(cmp)) nums.sort(key = cmp_to_key(lambda a,b:-1 if a + b < b + a else 1)) return ''.join(nums).lstrip('0') or '0'
def clear_low_information_words(message): """ Remove links from messages :param message: :return: message """ output = [] for word in message.split(): # remove links, as they contain no real conversation info and cannot be stemmed if not word.startswith('http'): output.append(word) return str.join(' ', output)
def clean_reg_name(reg, list): """ Clean the name of the registers by removing any characters contained in the inputted list. """ for char in list: reg = reg.replace(char, '') return reg
def module_level_function(param1, param2=None, *args, **kwargs): """Evaluate to true if any paramaters are greater than 100. This is an example of a module level function. Function parameters should be documented in the ``Parameters`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious. This example function calculates if any of the params are greater than a target value of 100, and if so returns True If *args or **kwargs are accepted, they should be listed as ``*args`` and ``**kwargs``. The format for a parameter is:: name : type description The description may span multiple lines. Following lines should be indented to match the first line of the description. The ": type" is optional. Multiple paragraphs are supported in parameter descriptions. Parameters ---------- param1 : int The first parameter. param2 : :obj:`str`, optional The second parameter. *args Variable length argument list. **kwargs Arbitrary keyword arguments. Returns ------- bool True if successful, False otherwise. The return type is not optional. The ``Returns`` section may span multiple lines and paragraphs. Following lines should be indented to match the first line of the description. The ``Returns`` section supports any reStructuredText formatting, including literal blocks:: { 'param1': param1, 'param2': param2 } Raises ------ AttributeError The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError If `param2` is equal to `param1`. ValueError If `param2` is not a string """ if param1 == param2: print(f"param1: {param1}, param2: {param2}") error_message = "param1 may not be equal to param2" print(error_message) raise ValueError(error_message) # Collect the params and find the max value value_list = [] value_list.append(param1) if param2: if not isinstance(param2, str): error_message = "param2 must be a string" print(error_message) raise ValueError(error_message) else: converted_param2 = int(param2) value_list.append(converted_param2) if args: for x in args: if not isinstance(x, int): error_message = "args values must be integers" print(error_message) raise ValueError(error_message) value_list.append(x) if kwargs: print("Metadata content") for key, value in kwargs.items(): print(f"{key}: {value}") if key == "verbose" and value is True: print("Additional verbose output: ......................") # Find max value from the compiled list max_value = max(value_list) print( f"param1: {param1}, param2: {param2}, args: {args}, " f"kwargs: {kwargs}. Max value: {max_value}" ) # Function returns True if any of the params are greater than 100 target_value = 100 if max_value > target_value: return True else: return False
def _add_value_squared_where_missing(row): """Add values `value_squared` where missing.""" value_squared = row[-2] value = row[-3] if value_squared != value_squared: return value else: return value_squared
def _compute_f_pre_rec(beta_square, tp, fn, fp): """ :param tp: int, true positive :param fn: int, false negative :param fp: int, false positive :return: (f, pre, rec) """ pre = tp / (fp + tp + 1e-13) rec = tp / (fn + tp + 1e-13) f = (1 + beta_square) * pre * rec / (beta_square * pre + rec + 1e-13) return f, pre, rec
def state_ocd_id(state): """Get the OCD ID of the state Returns the state OCD ID, which can be used both alone and as a prefix Args: state: state CD (uppercase) Returns: OCD ID of the state string """ if state == 'DC': state_id = 'ocd-division/country:us/district:dc' else: state_id = 'ocd-division/country:us/state:{state}'.format( state=state.lower()) return state_id
def q_prior(q, m=1, gamma=0.3, qmin=0.1): """Default prior on mass ratio q ~ q^gamma """ if q < qmin or q > 1: return 0 C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1))) return C*q**gamma
def calculate_reindeer_run(reindeer, duration): """Calculate distance travelled by reindeer in specified duration""" # get reindeer stats flight_speed = reindeer['flight_speed'] flight_duration = reindeer['flight_duration'] rest_period = reindeer['rest'] # get number of rounds reinder flies and rests rounds = duration // (flight_duration + rest_period) # time spent during rounds time_spent = rounds * (flight_duration + rest_period) # distance covered during rounds distance_covered = rounds * flight_speed * flight_duration # time left after rounds time_left = duration - time_spent # whatever time is left, # fly for a bit (until flight duration or time left runs out) # and add that to the total duration if flight_duration <= time_left: distance_covered += flight_speed * flight_duration else: distance_covered += flight_speed * time_left return distance_covered
def common_start(*strings): """ Returns the longest common substring from the beginning of the `strings` """ if len(strings)==1: strings=tuple(strings[0]) def _iter(): for z in zip(*strings): if z.count(z[0]) == len(z): # check all elements in `z` are the same yield z[0] else: return return ''.join(_iter())
def process_documents(articles): """Process articles and returns it in dictionary format Parameters ---------- articles : list of str List of articles dictionaries Returns ------- dicts_textContent : dict Dictionary containing the required structure used by the models: {"text": article text content "meta": {"name": article title, "uri": article url, "pubDate":publication date (optional)}} """ dicts_textContent = [] for article in articles: # Join text and title as they all provide # interesting information complete_text = ( article["text"] + article["title"] ) # For each of the texts format in form of dictionary dicts_textContent.append( { "text": complete_text, "meta": { "name": article["title"], "uri": article["uri"], "pubDate": article["pubDate"] }, } ) return dicts_textContent
def str_signature(sig): """ String representation of type signature >>> from sympy.multipledispatch.dispatcher import str_signature >>> str_signature((int, float)) 'int, float' """ return ', '.join(cls.__name__ for cls in sig)
def get_first_animal_recordings(all_recordings, animal): """Returns the first animal Recordings instance from a list of Recordings instances :param list all_recordings: list of :py:class:`recording_io.Recordings` instances :param str animal: value to look for in Recordings[0].info['animal'] :return: recording_io.Recordings """ for recordings in all_recordings: if recordings[0].info['animal'] == animal: return recordings
def parse_error_msg(orig_msg): """ Parse "error" message received from backend Format: "error: %s\r\n" """ error = orig_msg[7:] return "error", error
def venus_rot_elements_at_epoch(T, d): """Calculate rotational elements for Venus. Parameters ---------- T: float Interval from the standard epoch, in Julian centuries. d: float Interval in days from the standard epoch. Returns ------- ra, dec, W: tuple (float) Right ascension and declination of north pole, and angle of the prime meridian. """ ra = 272.76 dec = 67.16 W = 160.20 - 1.4813688 * d return ra, dec, W
def check_abc_lec_status(output): """ Reads abc_lec output and determines if the files were equivelent and if there were errors when preforming lec. """ equivalent = None errored = False for line in output: if "Error: The network has no latches." in line: errored = True if line.startswith("Networks are NOT EQUIVALENT"): equivalent = False elif line.startswith("Networks are equivalent"): equivalent = True # Returns None if could not determine LEC status return equivalent, errored
def psc(x, size_ratio, ref_cost): """ Returns: Cost of a power-sizing model estimate as per the formula: tcost = ( size_ratio)^x * ref_cost """ return ref_cost * size_ratio ** x
def _get_iterator_device(job_name, task_id): """ Returns the iterator device to use """ if job_name != 'learner': return None return '/job:%s/task:%d' % (job_name, task_id)
def calculate_tax(income_tax_spec, taxable_income): """Calculate household tax payments based on total household taxable income weekly""" tax_base = taxable_income - income_tax_spec[0] if taxable_income < income_tax_spec[0]: tax_rate = 0 elif (taxable_income >= income_tax_spec[0]) and ( taxable_income < income_tax_spec[1] ): tax_rate = ( (income_tax_spec[3] - income_tax_spec[2]) / (income_tax_spec[1] - income_tax_spec[0]) / 2 ) * tax_base ** 2 + income_tax_spec[2] * tax_base else: tax_rate = ( (income_tax_spec[3] + income_tax_spec[2]) * (income_tax_spec[1] - income_tax_spec[0]) / 2 ) + income_tax_spec[3] * (taxable_income - income_tax_spec[1]) tax = (tax_rate * taxable_income / (tax_base + 0.0001)) * (1 + income_tax_spec[4]) return tax
def dictvals(dictionary): """ Returns the list of elements in a dictionary, unpacking them if they are inside a list :param dictionary: the dictionary to be unpacked :returns :[list] """ try: return [x[0] for x in dictionary.values()] except IndexError: return list(dictionary.values()) except TypeError: return list(dictionary.values())
def ref_seq_nt_output(in_seq_name, in_ref_name, nt, ext): """ Generate output file name :param in_seq_name: treatment name (str) :param in_ref_name: reference name (str) :param nt: aligned read length (int) :param ext: extension (ie. csv or pdf) :return: output filename (str) """ return "{0}_{1}_{2}.{3}".format(in_ref_name, in_seq_name, str(nt), ext)
def get_display_name(user): """ Tries to return (in order): * ``user.profile.display_name`` * ``user.username`` """ if user is None: return None profile = user.profile if profile.display_name: return profile.display_name return user.username
def above_threshold(student_scores, threshold): """Determine how many of the provided student scores were 'the best' based on the provided threshold. :param student_scores: list - of integer scores. :param threshold: int - threshold to cross to be the "best" score. :return: list - of integer scores that are at or above the "best" threshold. """ above = [] for score in student_scores: if score >= threshold: above.append(score) return above
def flatten_index(index: tuple, shape: tuple) -> int: """ Unravel index Convert flatten index into tuple index. Parameters ---------- index: tuple index (x, y) shape: tuple shape of matrix the flatten index is about Returns ------- index: int64 flatten index """ return index[0] * shape[0] + index[1]
def get_board_config(json_data: dict) -> str: """Return boardconfig of said device""" return json_data["boardconfig"]
def ShardedFilePatternToGlob(file_pattern): """Converts a file pattern path@shards to path-?????-of-shards.""" if ',' in file_pattern: raise ValueError( 'ShardedFilePatternToGlob does not support multiple file patterns.') if '@' not in file_pattern: return file_pattern path, shards = file_pattern.split('@') if shards == '*': return f'{path}-?????-of-*' return f'{path}-?????-of-{int(shards):05}'