content
stringlengths
42
6.51k
def mu_parameter_mapping(mu,scale_with_mu,**kwargs): """Parameters that are 'replaced' by mu should be fixed to some nominal values using functools.partial, as should the list 'scale_with_mu'""" out_pars = {} for parname, parval in kwargs.items(): if parname in scale_with_mu: out_pars[parname] = mu * parval else: out_pars[parname] = parval return out_pars
def verify_user_prediction(user_inputs_dic: dict, correct_definition_dic: dict): """ Verifies user prediction json against correct json definition returns true if correct format, false if not """ if user_inputs_dic.keys() != correct_definition_dic.keys(): return False for user_key, user_value in user_inputs_dic.items(): possible_values = correct_definition_dic[user_key].keys() if user_value not in possible_values: return False return True
def html_popup(title, comment, imgpath, data): """Format the image data into html. :params title, comment, imgpath, data: strings""" html = """ <h3>TITLE</h3> <img src = IMGPATH style="width:180px;height:128px;" > <p> "COMMENT" </p> <p> DATA </p> """ html = html.replace( "TITLE", title).replace( "COMMENT", comment).replace( "IMGPATH", imgpath).replace( "DATA", data) return html
def convertVCFPhaseset(vcfPhaseset): """ Parses the VCF phaseset string """ if vcfPhaseset is not None and vcfPhaseset != ".": phaseset = vcfPhaseset else: phaseset = "*" return phaseset
def _get_xls_cc_ir_generated_files(args): """Returns a list of filenames generated by the 'xls_cc_ir' rule found in 'args'. Args: args: A dictionary of arguments. Returns: Returns a list of files generated by the 'xls_cc_ir' rule found in 'args'. """ return [args.get("ir_file")]
def income_tax(is_single, income): """ Returns a floating point for estimated income tax :param is_single: boolean that describes filing status :param income: total income in USD :type is_single: bool :type income: int :return: estimated income tax :rtype: float """ if is_single: bracket = { 9325: 0.1, 37950: 0.15, 91900: 0.25, 191650: 0.28, 416900: 0.33, 418400: 0.35, float('inf'): 0.396 } else: bracket = { 18650: 0.1, 75900: 0.15, 153100: 0.25, 233350: 0.28, 416900: 0.33, 470700: 0.35, float('inf'): 0.396 } tax = 0 untaxed_income = income lower_bound = 0 for upper_bound, percent in bracket.items(): if income >= upper_bound: # While the total income is greater than the current bracket # add to the income tax bracket_percent * bracket_range tax += (percent * (upper_bound - lower_bound)) untaxed_income = income - upper_bound # Untaxed income is the income - current lower_bound = upper_bound # Update upper bound for next calculation else: # Once the highest income bracket is reached, # add to the tax the remainder of untaxed_income * bracket_percent tax += (untaxed_income * percent) break return int(tax)
def remove_whitespace(string): """ Parse a string and remove all its whitespace Parameters string Returns string without whitespaces """ return string.replace(" ", "")
def define_mlp(n_classes, n_hidden, dropout_p, activation="relu", l1_reg=0, l2_reg=0): """Shortcut to create a multi-layer perceptron classifier Parameters ---------- n_classes : int Number of classes to calculate probabilities for n_hidden : list of ints Number of units in each hidden layer dropout_p : float or list of floats Dropout fraction for input and each hidden layer. If a single float, this dropout fraction will be applied to every layer. activation : {"relu", "prelu", "sigmoid", "tanh", "abstanh", "linear"} Activation function to use for all layers l1_reg, l2_reg : float, optional L1 and L2 regularization strengths for all layers Returns ------- list Layer definitions suitable for input to a `NNClassifier` Examples -------- >>> layers = define_mlp(10, [400, 400], [0.4, 0.25, 0.25], "prelu", l2_reg=1e-4) >>> print(layers) [['DropoutLayer', {'dropout_p': 0.4, 'name': 'DO-input'}], ['FCLayer', {'activation': 'prelu', 'l1': 0, 'l2': 0.0001, 'n_units': 400, 'name': 'fc0'}], ['DropoutLayer', {'dropout_p': 0.25, 'name': 'DO-fc0'}], ['FCLayer', {'activation': 'prelu', 'l1': 0, 'l2': 0.0001, 'n_units': 400, 'name': 'fc1'}], ['DropoutLayer', {'dropout_p': 0.25, 'name': 'DO-fc1'}], ['ClassificationOutputLayer', {'l1': 0, 'l2': 0.0001, 'n_classes': 10, 'name': 'output'}]] """ try: # Make sure that `n_hidden` is a list. len(n_hidden) except TypeError: n_hidden = [n_hidden] try: # Make sure that `dropout_p` is a list. len(dropout_p) except TypeError: dropout_p = (1 + len(n_hidden)) * [dropout_p] if len(dropout_p) != len(n_hidden) + 1: raise ValueError("Either specify one dropout for all layers or one dropout for " "each layer (inputs + hidden layers).") dropout_p = dropout_p[::-1] # Pops come from the end, so reverse this list. # Start by putting on dropout for the input layer (if any). layer_defs = [] input_do = dropout_p.pop() if input_do: layer_defs.append(["DropoutLayer", {"name": "DO-input", "dropout_p": input_do}]) # Add fully-connected layers. for i_hidden, hidden in enumerate(n_hidden): layer_defs.append(["FCLayer", {"name": "fc{}".format(i_hidden), "n_units": hidden, "activation": activation, "l1": l1_reg, "l2": l2_reg}]) layer_do = dropout_p.pop() if layer_do: layer_defs.append(["DropoutLayer", {"name": "DO-fc{}".format(i_hidden), "dropout_p": layer_do}]) # Put on an output layer. layer_defs.append(["ClassificationOutputLayer", {"name": "output", "n_classes": n_classes, "l1": l1_reg, "l2": l2_reg}]) return layer_defs
def _is_new_kegg_rec_group(prev, curr): """Check for irregular record group terminators""" return curr[0].isupper() and not prev.endswith(';') and \ not curr.startswith('CoA biosynthesis') and not prev.endswith(' and') and \ not prev.endswith('-') and not prev.endswith(' in') and not \ prev.endswith(' type') and not prev.endswith('Bindng') and not \ prev.endswith('Binding')
def _remove_empty_values(dictionary): """ Remove None values from a dictionary. """ return {k: v for k, v in dictionary.items() if v is not None}
def gcd(a, b): """Return the greatest common divisor of a and b. >>> gcd(2, 10) 2 >>> gcd(6, 9) 3 >>> gcd(5, 22) 1 """ if a % b == 0: return b return gcd(b, a % b)
def ball_touch_intent(event_list, team): """Returns intentnional or unintentional if the event is a ball touch""" intent = None for e in event_list[:1]: if e.type_id == 61 and e.outcome == 1 and e.team != team: intent = "Oppo. Intentional Ball Touch" elif e.type_id == 61 and e.outcome == 0 and e.team != team: intent = "Oppo. Unitentional Ball Touch" elif e.type_id == 61 and e.outcome == 1 and e.team == team: intent = "Intentional Ball Touch" elif e.type_id == 61 and e.outcome == 0 and e.team == team: intent = "Unintentional Ball Touch" return intent
def mul(a,b): """Multiply a vector either elementwise with another vector, or with a scalar.""" if hasattr(b,'__iter__'): if len(a)!=len(b): raise RuntimeError('Vector dimensions not equal') return [ai*bi for ai,bi in zip(a,b)] else: return [ai*b for ai in a]
def circle(x, a = 1.0, b = 1.0, r = 1.0): """ Name: Generic circle. """ return (x[0] - a)**2 + (x[1] - b)**2 - r**2
def head_tail(iterable): """ For python2 compatibility """ lst = list(iterable) return lst[0], lst[1:]
def ngrams(s, r, pad=False): """ Takes a list as input and returns all n-grams up to a certain range. :param s: input list :param r: range :param pad: whether to return ngrams containing a "PAD" token :return: dicttionary {id: ngram} """ # add padding S = s + ["<PAD>"] * (r - 1) l = len(S) ng = {} curr_id = 0 seen = set() for i in range(l-1): for j in range(i, i+r): gram = tuple(S[i:j+1]) elements = set(gram) # Don't store ngrams with PAD tokens if "<PAD>" in elements and not pad: continue # Don't store ngrams with only the pad token elif len(elements) == 1 and "<PAD>" in elements: continue elif gram not in seen: seen.add(gram) ng[curr_id] = gram curr_id += 1 return ng
def filter_form_fields(prefix, form_data): """Creates a list of values from a dictionary where keys start with prefix. Mainly used for gathering lists from form data. e.g. If a role form's permissions fields are prefixed with "role-permission-<index>" passing in a prefix if 'role-permission-' will return all of the inputs values as a list. Parameters ---------- prefix: str The key prefix to search for. form_data: Dict The dictionary of form data to search for. Returns ------- list List of all values where the corresponding key began with prefix. """ values = [form_data[key] for key in form_data.keys() if key.startswith(prefix)] return [None if v == 'null' else v for v in values]
def find_ignorespace(text, string): """Return (start, end) for string in start of text, ignoring space.""" ti, si = 0, 0 while ti < len(text) and si < len(string): if text[ti] == string[si]: ti += 1 si += 1 elif text[ti].isspace(): ti += 1 elif string[si].isspace(): si += 1 else: raise ValueError('{} not prefix of {}[...]'.format( string, text[:len(string)])) if si != len(string): raise ValueError('{} not prefix of {}[...]'.format( string, text[:len(string)])) return (0, ti)
def parse_message(error_msg): """This function parses error messages when necessary to prepare them for translation. :param error_msg: The original error message :type error_msg: str :returns: The prepared error message """ split_sequences = ['\n', '\r'] for sequence in split_sequences: if sequence in error_msg: error_msg = error_msg.split(sequence)[0] break return error_msg
def confidence_interval_for_regression_line(yhat, error): """ Get the confidence interval for the predicted value of outcome. > `yhat`: the predicted value of y > `error`: the standard error of estimate Returns ------- The confidence interval for the predicted value yhat. """ low = yhat - error high = yhat + error return (low, high)
def parseArnsString(arnsString=None): """ This function returns a list of arns from the comma-separated arnsString string. If the string is empty or None, an empty list is returned. """ if arnsString is None or arnsString is '': return [] else: return arnsString.split(',')
def get_sym(pair): """ reformats a tuple of (team, rival) so that the first element is smaller than the other (by convention, this is how we represent a match without home-away status). """ if pair[0] > pair[1]: return pair[1], pair[0] else: return pair
def remove_punctuation(s): """ Returns a string with all punctuation removed from input :param s: Any string :return: A string with no punctuation """ # modified from http://www.ict.ru.ac.za/Resources/cspw/thinkcspy3/thinkcspy3_latest/strings.html punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ " # space added s_sans_punct = "" # empty string for letter in s: if letter not in punctuation: s_sans_punct += letter # s_sans_punct = s_sans_punct + letter return s_sans_punct
def count_words(fl): """Reads a file-like and returns the word count. """ words = [] count = {} for row in fl: for word in row.rstrip().split(): word = word.lower() if word not in count: count[word] = 0 words.append(word) count[word] += 1 return count, words
def make_label_index(link_display_label, entries): """Map entry IDs to human-readable labels. :arg link_display_label: Marker, which contains the label. :arg entries: Collection of entries. """ return { entry.id: entry.get(link_display_label, entry.id) for entry in entries}
def dist(x, y): """ Pure python implementation of euclidean distance formula. """ dist = 0.0 for i in range(len(x)): dist += (x[i] - y[i])**2 return dist**0.5
def grid_traveler_rec(m: int, n: int) -> int: """Computes the number of ways of traveling from source to destination. Args: m: The total vertical distance. n: The total horizontal distance. Returns: The number of ways ways you can travel to the goal on a grid with dimensions (m x n). """ if m == 1 and n == 1: return 1 if m == 0 or n == 0: return 0 return grid_traveler_rec(m - 1, n) + grid_traveler_rec(m, n - 1)
def greatest(numbers: list) -> int: """ A function that calculate the largest number within the given list parameter Parameters: ----------- numbers: list Returns: -------- int """ largest_num = 0 # Edit this function so that it return the largest number within the list return largest_num
def get_clustering_level(clustering): """ Returns the numbers of levels in the clustering. Intended to be used as an upper bound for 1-based `max_level` in clustering preprocessing. """ levels = [] for el in clustering: if isinstance(el, dict): levels.append(get_clustering_level(el['references'])) if not levels: return 1 else: return max(levels) + 1
def shortstr(obj, maxl=20) -> str: """Convert an object to string and truncate to a maximum length""" s = str(obj) return (s[:maxl] + "...") if len(s) > maxl else s
def human_readable_stat(c): """ Transform a timedelta expressed in seconds into a human readable string Parameters ---------- c Timedelta expressed in seconds Returns ---------- string Human readable string """ c = int(float(c)) years = c // 31104000 months = c // 2592000 days = c // 86400 hours = c // 3600 % 24 minutes = c // 60 % 60 seconds = c % 60 if years > 0: return str(years) + "Y" if months > 0: return str(months) + "MO" if days > 0: return str(days) + "D" if hours > 0: return str(hours) + "h" if minutes > 0: return str(minutes) + "m" return str(seconds) + "s"
def get_default_bbbp_task_names(): """Get that default bbbp task names and return the binary labels""" return ['p_np']
def value_in_many_any(a, b): """return true if item 'a' is found inside 'b': a list/tuple of many iterators else return false """ for c in b: if a in c: return True return False
def _positive(index: int, size: int) -> int: """Convert a negative index to a non-negative integer. The index is interpreted relative to the position after the last item. If the index is smaller than ``-size``, IndexError is raised. """ assert index < 0 # noqa: S101 index += size if index < 0: raise IndexError("lazysequence index out of range") return index
def script_language(_path): """Returns the language a file is written in.""" if _path.endswith(".py"): return "python" elif _path.endswith(".js"): return "node" elif _path.endswith(".go"): return "go run" elif _path.endswith(".rb"): return "ruby" elif _path.endswith(".java"): return 'javac' # Compile Java Source File elif _path.endswith(".class"): return 'java' # Run Java Class File else: return 'unknown'
def fluid(x): """Function 3""" rho_f = 0.890 rho_o = 0.120 r = 5 return (((rho_f / 3) * x**3) - (r * rho_f * x**2) + ((4 * r**3 * rho_o) / 3))
def init_list_args(*args): """Initialize default arguments with empty lists if necessary.""" return tuple([] if a is None else a for a in args)
def is_range(parser, arg): """ Check if argument is min/max pair. """ if arg is not None and len(arg) != 2: parser.error('Argument must be min/max pair.') elif arg is not None and float(arg[0]) > float(arg[1]): parser.error('Argument min must be lower than max.') return arg
def user_prompt(msg: str, sound: bool = False, timeout: int = -1): """Open user prompt.""" return f'B;UserPrompt("{msg}",{sound:d},{timeout});'.encode()
def derive_mid(angle_start, angle_stop, norm): """Derive mid angle respectng closure via norm.""" angle = (angle_stop + angle_start) / 2.0 if angle_stop < angle_start: angle = (angle_stop + norm + angle_start) / 2.0 return angle
def prod(m, p): """ Computes the product of matrix m and vector p """ return (p[0]*m[0] + p[1]*m[1], p[0]*m[2] + p[1]*m[3])
def stripfile(filedata, listofterms): """ Creates a list with lines starting with strings from a list :param filedata: File Data in list form :param listofterms: list of strings to use as search terms :return: list of file lines starting with strings from list of terms """ datawithterms = [] for line in filedata: if type(line) == str: for i in listofterms: if line.startswith(i): datawithterms.append(line) elif type(line) == list: for i in listofterms: if line[0] == i: datawithterms.append(line) return datawithterms
def jsonify(records): """ Parse asyncpg record response into JSON format """ # print(records) list_return = [] for r in records: itens = r.items() list_return.append({i[0]: i[1].rstrip() if type( i[1]) == str else i[1] for i in itens}) return list_return
def make_mt_exchange_name(namespace, endpoint): """ Method which generate MT name which based on MT namespace and endpoint name. Better see MT documentation for known details :param namespace: MT namespace :param endpoint: MT endpoint name :return: RabbitMQ exchange name needed for pika as string """ return '{}:{}'.format(namespace, endpoint)
def valid_str(x: str) -> bool: """ Return ``True`` if ``x`` is a non-blank string; otherwise return ``False``. """ if isinstance(x, str) and x.strip(): return True else: return False
def vsbyValue(value): """Method to return a simple scalar as a string. Value from grid is multiplied by 100.0""" try: return str(int(round(value*100.))) except: return "999"
def get_label(cplt): """ get cplt and return a label Parameters ---------- cplt : str name of the dimension of interest Returns ------- label : str axis label Examples -------- None yet """ label = cplt if cplt == 'T': label += ' (K)' elif cplt == 'P': label += ' (Pa)' return label
def remove_unknown(sentences, unknown_idx=1): """ remove sentences with unknown word in them :param sentences: a list containing the orig sentences in formant of: [index, sentence indices as list] :param unknown_idx: the index number of unknown word :return: a new list of the filtered sentences """ filter_sent = list() for i in range(len(sentences)): if unknown_idx not in sentences[i][1]: filter_sent.append(sentences[i]) return filter_sent
def print_scientific_double(value: float) -> str: """ Prints a value in 16-character scientific double precision. Scientific Notation: 5.0E+1 Double Precision Scientific Notation: 5.0D+1 """ if value < 0: Format = "%16.9e" else: Format = "%16.10e" svalue = Format % value field = svalue.replace('e', 'D') if field == '-0.0000000000D+00': field = '0.0000000000D+00' #assert len(field) == 16, ('value=%r field=%r is not 16 characters ' # 'long, its %s' % (value, field, len(field))) return field
def get_data_length(data): """Gets the number of entries in the data from the result of a pushshift api call. Args: data (dict): JSON object that is returned from the pushshift api. Returns: int: Length of the data. """ return len(data["data"])
def parse_line_2(bitmap): """converts 2 bytes into 1 byte. Used in 16-color modes""" ba = bytearray() for i in range(len(bitmap) // 2): hi = bitmap[i * 2 + 0] & 0xf lo = bitmap[i * 2 + 1] & 0xf byte = hi << 4 | lo ba.append(byte) return ba
def address_list2address_set(address_list): """ Helper function for parsing and converting address list to addres set """ address_set = set() for address in address_list: address = address.split("/")[2] address_set.add(address) return address_set
def determinant(m): """Compute determinant.""" return ( m[0][0] * m[1][1] * m[2][2] - m[0][0] * m[1][2] * m[2][1] + m[0][1] * m[1][2] * m[2][0] - m[0][1] * m[1][0] * m[2][2] + m[0][2] * m[1][0] * m[2][1] - m[0][2] * m[1][1] * m[2][0] )
def find_target_container(container_wrapper, container_name): """Search through a collection of containers and return the container with the given name :param container_wrapper: A collection of containers in the Google Tag Manager List Response format :type container_wrapper: dict :param container_name: The name of a container to find :type container_name: str :return: A Google Tag Manager containers :rtype: dict """ for container in container_wrapper["container"]: if container["name"] == container_name: return container return None
def write_header(heading, level=1): """ - heading: string, the heading - level: integer, level > 0, the markdown level RETURN: string """ return ("#"*level) + " " + heading + "\n\n"
def pathcombine(path1, path2): """ Note: This is copied from: https://code.google.com/p/pyfilesystem/source/browse/trunk/fs/path.py Joins two paths together. This is faster than `pathjoin`, but only works when the second path is relative, and there are no backreferences in either path. >>> pathcombine("foo/bar", "baz") 'foo/bar/baz' """ if not path1: return path2.lstrip() return '%s/%s' % (path1.rstrip('/'), path2.lstrip('/'))
def get_pypi_urls(name, version): """ Return a mapping of computed Pypi URLs for this package """ api_data_url = None if name and version: api_data_url = f'https://pypi.org/pypi/{name}/{version}/json' else: api_data_url = name and f'https://pypi.org/pypi/{name}/json' repository_download_url = ( name and version and f'https://pypi.org/packages/source/{name[0]}/{name}/{name}-{version}.tar.gz' ) repository_homepage_url = name and f'https://pypi.org/project/{name}' return dict( repository_homepage_url=repository_homepage_url, repository_download_url=repository_download_url, api_data_url=api_data_url, )
def is_none_or_int(obj): """Check if obj is None or an integer. :param obj: Object to check. :type obj: object :return: True if object is None or an integer. :rtype: bool """ return obj is None or (isinstance(obj, int) and obj >= 0)
def _get_base_step(name: str): """Base image step for running bash commands. Return a busybox base step for running bash commands. Args: name {str}: step name Returns: Dict[Text, Any] """ return { 'image': 'busybox', 'name': name, 'script': '#!/bin/sh\nset -exo pipefail\n' }
def frange(start, end, step, rnd = 5): """Generate a range with float values""" result = [] # invert step and change start/end when positions are inverted if start > end: return(frange(end, start, step*-1)) if step > 0: point = start while point <= end: result.append(point) point =round(point + step,rnd) # for negative steps else: point = end while point >= start: result.append(point) point =round(point + step,rnd) return result
def str2bool(s2b): """ Converts String to boolean params: s2b - a string parameter to be converted to boolean Possible inputs: True: true, t, yes, y, 1 False: false, f, no, n, 0 Note: Possible inputs are not case sensitive. returns: True or False """ if s2b == None: return True if s2b.lower() in ('true', 't', 'yes', 'y', '1'): return True if s2b.lower() in ('false', 'f', 'no', 'n', '0'): return False ValueError('Error: Incorrect Compress Value')
def values_match(x, y): """ Compare x and y. This needed because the types are unpredictable and sometimes a ValueError is thrown when trying to compare. """ if x is y: return True # explicit checks for None used to prevent warnings like: # FutureWarning: comparison to `None` will result in an elementwise object comparison in the future. # eq = x==y if x is None: if y is None: return True else: return False if y is None: return False try: eq = x==y except ValueError: # ValueError: shape mismatch: objects cannot be broadcast to a single shape return False if isinstance(eq, bool): return eq return eq.all()
def getCachedValue(cache, bits, generator): """ Return and cache large (prime) numbers of specified number of bits """ if bits not in cache: # populate with 2 numbers cache[bits] = [generator(bits) for _ in range(2)] # rotate, so each call will return a different number a = cache[bits] cache[bits] = a[1:] + a[:1] return cache[bits][0]
def format_money(amnt, precision=2): """ Format output for money values Finac doesn't use system locale, in the interactive mode all numbers are formatted with this function. Override it to set the number format you wish """ # return '{:,.2f}'.format(amnt) return ('{:,.' + str(precision) + 'f}').format(amnt).replace(',', ' ')
def clean_record(raw_string: str) -> str: """ Removes all unnecessary signs from a raw_string and returns it :param raw_string: folder or file name to manage :return: clean value """ for sign in ("'", '(', ')', '"'): raw_string = raw_string.replace(sign, '') return raw_string.replace(' ', '-').replace('--', '-')
def edit_diff(start, goal, limit): """A diff function that computes the edit distance from START to GOAL.""" if start == goal: return 0 if limit == 0: #stop when reach the limit! return 1 if not start: return len(goal) elif not goal: return len(start) elif start[0]== goal[0]: return edit_diff(start[1:], goal[1:],limit) else: add_char = 1 + edit_diff(goal[0]+ start,goal,limit-1) remove_char = 1 + edit_diff(start[1:],goal,limit-1) substitute_char = 1 + edit_diff(goal[0]+ start[1:], goal,limit-1) return min(add_char, remove_char, substitute_char)
def fmt(nbytes): """Format network byte amounts.""" nbytes = int(nbytes) if nbytes >= 1000000: nbytes /= 1000000 return f"{nbytes:.1f}MB" if nbytes > 1000: nbytes /= 1000 return f"{nbytes:.1f}kB" return f"{nbytes}B"
def raise_error(func, args , kwargs): """ This decorator help you to wrap any function to catch any error raised in the function body ## Snippet code ```python >>> from easy_deco import raise_error >>> @raise_error >>> def func(): "Function body" ``` """ try: return func(*args, **kwargs) except Exception as e: raise eval(e.__class__.__name__)(e)
def list_file_by_day(ws,day_list,row_index,patient_detail_row_index,day_number=0): """ Input all recorded file in the given day to the work sheet :param ws: The patient list sheet :param day_list: list of days having the recorded data :param row_index: The current row of the cusor in the patient summary sheet :param patient_detail_row_index: The row of the hyperlink to the patient detail sheet :param day_number: Day of record - Day 1, Day 5 or other Day :return: row_index patient_detail_row_index """ if len(day_list) < 1 and day_number!=0: if day_number !=1: day_number = 5 ws["D" + str(row_index)] = "DAY "+str(day_number) ws["F" + str(row_index)] = "Missing File" row_index = row_index + 1 # return row_index, patient_detail_row_index else: for day_file in day_list: ws["D" + str(row_index)] = day_file.split("/")[3] cell = ws.cell(row_index, 6) cell.value = '=HYPERLINK("#\'Patient Detail\'!A' + str(patient_detail_row_index) + \ '","' + day_file.split("/")[-1] + '")' patient_detail_row_index = patient_detail_row_index + 18 row_index = row_index + 1 return row_index, patient_detail_row_index
def get_image_url_from_soup(soup): """ """ try: image_url = soup.find(id='comic').img['src'] except: image_url = None return image_url
def remove_empty_entities(d): """ Recursively remove empty lists, empty dicts, or None elements from a dictionary. Note. This is extended feature of CommonServerPython.py remove_empty_elements() method as it was not removing empty character x == ''. :param d: Input dictionary. :return: Dictionary with all empty lists, and empty dictionaries removed. """ def empty(x): return x is None or x == {} or x == [] or x == '' if not isinstance(d, (dict, list)): return d elif isinstance(d, list): return [value for value in (remove_empty_entities(value) for value in d) if not empty(value)] else: return {key: value for key, value in ((key, remove_empty_entities(value)) for key, value in d.items()) if not empty(value)}
def _symbol_count_from_symbols(symbols): """Reduce list of chemical symbols into compact VASP notation args: symbols (iterable of str) returns: list of pairs [(el1, c1), (el2, c2), ...] """ sc = [] psym = symbols[0] count = 0 for sym in symbols: if sym != psym: sc.append((psym, count)) psym = sym count = 1 else: count += 1 sc.append((psym, count)) return sc
def lag_entry_table(lag_name): """ :param lag_name: given lag to cast. :return: LAG_TABLE key. """ return b'LAG_TABLE:' + lag_name
def convert_word_index_to_sentence(word_idx, vocab): """Convert word indices to sentence.""" s = "" for ind in range(len(word_idx)): w_idx = word_idx[ind] if w_idx> 0: s += vocab[w_idx-1] if ind < len(word_idx)-1: s+= " " return s
def str2hex(s): """ :param s: '303132' :return: '123' """ return ''.join([chr(c) for c in bytearray.fromhex(s)])
def say_hello(subject:str) -> str: """Say hello to somebody. Args: subject: who to say hello to. Returns: A friendly greeting as a string. """ return f"Hello {subject}!"
def sqrt(n): """http://stackoverflow.com/questions/15390807/integer-square-root-in-python Find the square root of a number for the purpose of determining whether or not it is a whole number.""" x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x
def auto_int(int_arg): """Automatically format integer.""" return int(int_arg, 0)
def _gen_alignment_table(sequence_left: str, sequence_right: str, scoring_matrix: dict, gap_penalty, floor=None, sub_constant_cost=-7, **kwargs): """ Common code to generate alignment table given a matrix :param sequence_left: :param sequence_right: :param scoring_matrix: :param gap_penalty: :param floor: :return: """ alignment_table = {(0, 0): (0, (0, 0))} # Populate initials gap_accum = gap_penalty for i, _ in enumerate(sequence_left): i = i + 1 alignment_table[(i, 0)] = (max(gap_accum, floor) if floor is not None else gap_accum, (i - 1, 0)) gap_accum += gap_penalty gap_accum = gap_penalty for i, _ in enumerate(sequence_right): i = i + 1 alignment_table[(0, i)] = (max(gap_accum, floor) if floor is not None else gap_accum, (0, i - 1)) gap_accum += gap_penalty for i, c1 in list(enumerate(sequence_left)): i = i + 1 for j, c2 in list(enumerate(sequence_right)): j = j + 1 sub_score = scoring_matrix.get((c1, c2), 0.0) + sub_constant_cost alignment_table[(i, j)] = max( [ (alignment_table[(i - 1, j)][0] + gap_penalty, (i - 1, j)), # Gap right (alignment_table[(i, j - 1)][0] + gap_penalty, (i, j - 1)), # Gap up (alignment_table[(i - 1, j - 1)][0] + sub_score, (i - 1, j - 1)), # Accept substitution (or match) ], key=lambda x: x[0] ) if floor is not None: alignment_table[(i, j)] = (max(alignment_table[(i, j)][0], floor), alignment_table[(i, j)][1]) return alignment_table
def epoch_to_timestamp(time_raw): """converts raw time (days since year 0) to unix timestamp """ offset = 719529 # offset between 1970-1-1 und 0000-1-1 time = (time_raw - offset) * 86400 return time
def MAP(P, Y, metric=None): """ Sort solutions according to the MAP decision rule. :param P: probabilities :param Y: support :return: sorted list of triplets (loss, probability, solution) """ return [1 - p for p in P]
def analyse_sample_attributes(sample): """ To find sample attributes Attributes: min_position_value - [index, value] max_position_value - [index, value] up_or_down - up - down - variates """ attributes = { "min_position_value": [0, sample[1]], "max_position_value": [0, sample[1]], "up_or_down": -1, } for index, value in enumerate(sample): if value < attributes["min_position_value"][1]: attributes["min_position_value"] = [index, value] if value > attributes["max_position_value"][1]: attributes["max_position_value"] = [index, value] if attributes["min_position_value"][0] == 0 and attributes["max_position_value"][0] == len(sample)-1: # noqa attributes["up_or_down"] = "up" elif attributes["min_position_value"][0] == len(sample)-1 and attributes["max_position_value"][0] == 0: # noqa attributes["up_or_down"] = "down" else: attributes["up_or_down"] = "variates" return attributes
def angryProfessor(k, a): """ Given the arrival time of each student and a threshold number of attendees, determine if the class is canceled. :param k: int threshold for minimum on time student :param a: array of arrival time of students :return: Class cancel """ count = 0 # counting students on time for s in a: if s <= 0: count += 1 # Class is not canceled if count >= k: return False # Class is canceled else: return True
def _make_divisible( v, divisor, min_value=None, ): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: This implementation is taken from torchvision repositories. """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
def encode_sequence(sequence: str, encoding_scheme: dict): """ Encodes a peptide sequence with values provided by the encoding table/scheme. """ encoded_sequence = [] for aa in sequence: try: value = encoding_scheme.get(aa) except Exception as e: msg = f'{e}' raise KeyError(msg) encoded_sequence.append(value) return encoded_sequence
def _unbool(element, true=object(), false=object()): """A hack to make True and 1 and False and 0 unique for _uniq.""" if element is True: return true elif element is False: return false return element
def make_bits(num, bits): """Constructs a bit string of length=bits for an integer num.""" assert num < (1 << bits) if bits == 0: return '' return '{num:0{bits}b}'.format(num=num, bits=bits)
def flatten(items): """Removes one level of nesting from items Parameters ---------- items : iterable list of items to flatten one level Returns ------- flattened_items : list list of flattened items, items can be any sequence, but flatten always returns a list. Examples -------- >>> from skbio.util import flatten >>> h = [['a', 'b', 'c', 'd'], [1, 2, 3, 4, 5], ['x', 'y'], ['foo']] >>> print(flatten(h)) ['a', 'b', 'c', 'd', 1, 2, 3, 4, 5, 'x', 'y', 'foo'] """ result = [] for i in items: try: result.extend(i) except TypeError: result.append(i) return result
def clean_string(s): """ Get a string into a canonical form - no whitespace at either end, no newlines, no double-spaces. """ s = s.strip().replace("\n", " ").replace(" ", " ") while " " in s: # If there were longer strings of spaces, need to iterate to replace... # I guess. s = s.replace(" ", " ") return s
def count_ways(n): """ Parameters ---------- n : Dimension of chessboard (n x n) Returns ---------- The number of ways to place n queens on the chessboard, such that no pair of queens attack each other """ def backtrack(i, c, l, r): if not i: return 1 ways, mask = 0, ((1 << n) - 1) & ~(l | r | c) while mask: x = -mask & mask mask ^= x ways += backtrack(i - 1, c | x, (l | x) << 1, (r | x) >> 1) return ways return backtrack(n, 0, 0, 0)
def partial_match(first, second, places): """ Returns whether `second` is a marginal outcome at `places` of `first`. Parameters ---------- first : iterable The un-marginalized outcome. second : iterable The smaller, marginalized outcome. places : list The locations of `second` in `first`. Returns ------- match : bool Whether `first` and `second` match or not. """ return tuple(first[i] for i in places) == tuple(second)
def merge_dicts(create_dict, iterable): """ Merges multiple dictionaries, which are created by the output of a function and an iterable. The function is applied to the values of the iterable, that creates dictionaries :param create_dict: function, that given a parameter, outputs a dictionary. :param iterable: iterable, on which the function will be applied. :return: dict, the created dictionary. """ merged_dict = {} for dictionary in map(create_dict, iterable): merged_dict = {**merged_dict, **dictionary} return merged_dict
def _DegreeDict(tris): """Return a dictionary mapping vertices in tris to the number of triangles that they are touch.""" ans = dict() for t in tris: for v in t: if v in ans: ans[v] = ans[v] + 1 else: ans[v] = 1 return ans
def rgb_int2pct(rgbArr): """ converts RGB 255 values to a 0 to 1 scale (255,255,255) --> (1,1,1) """ out = [] for rgb in rgbArr: out.append((rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0)) return out
def extract_Heff_params(params, delta): """ Processes the VUMPS params into those specific to the effective Hamiltonian eigensolver. """ keys = ["Heff_tol", "Heff_ncv", "Heff_neigs"] Heff_params = {k: params[k] for k in keys} if params["adaptive_Heff_tol"]: Heff_params["Heff_tol"] = Heff_params["Heff_tol"]*delta return Heff_params
def parse_port_pin(name_str): """Parses a string and returns a (port-num, pin-num) tuple.""" if len(name_str) < 4: raise ValueError("Expecting pin name to be at least 5 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") if name_str[1] not in ('0', '1'): raise ValueError("Expecting pin port to be in 0 or 1") port = ord(name_str[1]) - ord('0') pin_str = name_str[3:] if not pin_str.isdigit(): raise ValueError("Expecting numeric pin number.") return (port, int(pin_str))
def AzimuthToCompassDirection(azimuth): """ Compass is divided into 16 segments, mapped to N, NNE, NE, NEE, E, SEE, SE, SSE, S, SSW, SW, SWW, W, NWW, NW, and NNW. IMPORTANT: input azimuth must be in radians, NOT degrees. """ compassDirection = "" if azimuth >= 0 and azimuth <= 0.1963350785: compassDirection = "North" if azimuth > 0.1963350785 and azimuth <= 0.5890052356: compassDirection = "North-NorthEast" if azimuth > 0.5890052356 and azimuth <= 0.9816753927: compassDirection = "NorthEast" if azimuth > 0.9816753927 and azimuth <= 1.37434555: compassDirection = "NorthEast-East" if azimuth > 1.37434555 and azimuth <= 1.767015707: compassDirection = "East" if azimuth > 1.767015707 and azimuth <= 2.159685864: compassDirection = "SouthEast-East" if azimuth > 2.159685864 and azimuth <= 2.552356021: compassDirection = "SouthEast" if azimuth > 2.552356021 and azimuth <= 2.945026178: compassDirection = "South-SouthEast" if azimuth > 2.945026178 and azimuth <= 3.337696335: compassDirection = "South" if azimuth > 3.337696335 and azimuth <= 3.730366492: compassDirection = "South-SouthWest" if azimuth > 3.730366492 and azimuth <= 4.123036649: compassDirection = "SouthWest" if azimuth > 4.123036649 and azimuth <= 4.515706806: compassDirection = "SouthWest-West" if azimuth > 4.515706806 and azimuth <= 4.908376963: compassDirection = "West" if azimuth > 4.908376963 and azimuth <= 5.30104712: compassDirection = "NorthWest-West" if azimuth > 5.30104712 and azimuth <= 5.693717277: compassDirection = "NorthWest" if azimuth > 5.693717277 and azimuth <= 6.086387435: compassDirection = "North-NorthWest" if azimuth >= 6.086387435: compassDirection = "North" return compassDirection
def check_number_in_box(data, rect_diag_0, rect_diag_1, counter=0): """ function to retrieve how many points are in a given rectangle :param data: data to check :param rect_diag_0: coordinates of one side of the diagonal :param rect_diag_1: coordinates of the other side of the diagonal :param counter: can possibly start not from 0 :return: counter of how many people are in rectangle + counter """ for elem in data: if rect_diag_0[0] <= elem[0] <= rect_diag_1[0] and rect_diag_1[1] <= elem[1] <= rect_diag_0[1]: counter += 1 return counter
def unescape_path(path: str) -> str: """ Decodes a percent-encoded URL path. @raise ValueError: If the escaping is incorrect. """ idx = 0 while True: idx = path.find("%", idx) if idx == -1: return path # Percent escaping can be used for UTF-8 paths. start = idx data = [] remaining: int = None # type: ignore[assignment] while True: hex_num = path[idx + 1 : idx + 3] if len(hex_num) != 2: raise ValueError('incomplete escape, expected 2 characters after "%"') idx += 3 try: if "-" in hex_num: raise ValueError() value = int(hex_num, 16) except ValueError: raise ValueError( f"incorrect escape: " f'expected 2 hex digits after "%", got "{hex_num}"' ) from None data.append(value) if len(data) > 1: if (value & 0xC0) == 0x80: remaining -= 1 if remaining == 0: path = path[:start] + bytes(data).decode() + path[idx:] break else: raise ValueError( f"invalid percent-encoded UTF8: " f"expected 0x80..0xBF for non-first byte, got 0x{value:02X}" ) elif value == 0x2F: # '/' # Path separator should remain escaped. path = path[:start] + "%2f" + path[idx:] break elif value < 0x80: path = path[:start] + chr(value) + path[idx:] break elif value < 0xC0 or value >= 0xF8: raise ValueError( "invalid percent-encoded UTF8: " f"expected 0xC0..0xF7 for first byte, got 0x{value:02X}" ) elif value < 0xE0: remaining = 1 elif value < 0xF0: remaining = 2 else: assert value < 0xF8, value remaining = 3 if idx == len(path) or path[idx] != "%": raise ValueError( f"incomplete escaped UTF8 character, " f"expected {remaining:d} more escaped bytes" )
def get_roi(shift, dim, gap=(0, 0, 0, 0)): """ find the over-lappying region of the image based on shift top-left (0, 0), x(+) to the right, y(+) goes down :param shift: (shift_x, shift_y) positive integer :param dim: (w , h) positive integer :param gap: (left, right, top, bottom) positive integer :return: ( x1, y1, x2, y2, w, h) x1, y1 top-left corner on original frame x2, y2 top-left corner on shifted frame w width of ROI h height of ROI """ # dimansion of the image w0 = dim[1] h0 = dim[0] # shift of the image sx = int(shift[0]) sy = int(shift[1]) # gap of the ROI to the over-lapped area gl = abs(int(gap[0])) gr = abs(int(gap[1])) gt = abs(int(gap[2])) gd = abs(int(gap[3])) # coordinate and size of ROI w = w0 - abs(sx) - gl - gr h = h0 - abs(sy) - gt - gd w = max(0, w) h = max(0, h) if sx >= 0: x1 = gl + sx x2 = gl else: x1 = gl x2 = gl + abs(sx) if sy >= 0: y1 = gt + sy y2 = gt else: y1 = gt y2 = gt + abs(sy) output = (x1, y1, x2, y2, w, h) return output