content
stringlengths
42
6.51k
def get_special_case_tol(dataset, tree_type, method, default_tol=1e-5): """ Special cases for `leaf_inf` and `leaf_refit`. Input dataset: str, dataset. tree_type: str, tree-ensemble model. method: str, explainer. default_tol: float, original tolerance. Return - Tolerance (float). """ tol = default_tol if method in ['leaf_inf', 'leaf_refit', 'leaf_infLE', 'leaf_refitLE']: if tree_type == 'lgb' and dataset == 'flight_delays': tol = 1e-1 elif tree_type == 'cb': if dataset == 'bean': tol = 0.5 elif dataset == 'naval': tol = 1e-4 return tol
def isThumb(frame): """ Check Thumb flag from CPSR """ try: regs = frame.GetRegisters()[0] # general purpose registers cpsr = [reg for reg in regs if reg.GetName()=='cpsr'][0] thumb_bit = int(cpsr.GetValue(), 16) & 0x20 if thumb_bit >> 5 != 0: return True except: pass return False
def init_admin_chat_ids(admin_chat_id: str): """load the admin_chat_ids saved in api_config to list for faster access Returns: list: A List containing all chat id's allowed to exchange admin-messages with the bot """ admin_chat_list = [] admin_chat_id_split = admin_chat_id.split(',') for admin_id in admin_chat_id_split: admin_chat_list.append(int(admin_id)) return admin_chat_list
def get_subplot_size(lenx, i): """ Gets the subplot size as a tuple depending on the number of datasets passed. This is used for creating henry regime subplots. :param lenx: int Number of datasets :param i: Iterator :return: tuple of shape (x, y, z) """ if lenx <= 4: return 2, 2, i + 1 if 9 >= lenx > 4: return 3, 3, i + 1 if 16 >= lenx > 9: return 4, 4, i + 1
def get_italic_token(token): """Apply italic formatting to a given token. https://api.slack.com/docs/message-formatting#message_formatting Args: token (str): String sequence with a specific definition (for parser). Returns: str: bold formatted version of a token. """ return "_{}_".format(token)
def find_sympts(lines): """ Given the contents of a Gnuplot script find the symmetry points To draw the band structure the symmetry points along the path of k-points is needed. The GW code stores this information in the Gnuplot script that draws the band structure. Hence this routine parses the Gnuplot script and returns the symmetry points as a list of tuples, where every tuple contains ( symmetry_point_label, x-coord) where symmetry_point_label is a string representing the name of the symmetry point, and x-coord is a floating point value representing a distance along the k-point path in arbitrary units. Note that in the Gnuplot script the symmetry points are stored as '" G " 0.0000', which means that the split command on a single point returns ['"','G','"','0.00000'] so we want to extract elements 1 and 3. """ path = [] for line in lines: if 'xtics' in line: begin = line.index('(') end = line.index(')') points = line[begin+1:end] points = points.split(',') for point in points: point = point.split() path.append((point[1],float(point[3]))) return path
def find_between(s, first, last): """Find string.""" try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return ""
def check_range(value, mode=0): """ Validate ranges of column (mode=1) or row (mode=0) """ if not isinstance(value, int): value = int(value) bound = 16384 if mode else 1048756 value %= bound return value
def geo_features(geo): """extracts a list of features, for multiple types of input""" features = geo try: features = geo.__geo_interface__ except AttributeError: pass try: features = features['features'] except TypeError: pass return features
def _kwargs_sq_processor(kwargs): """ Converts all values within a provided dictionary to string values @param kwargs: @return: """ if not isinstance(kwargs, dict): raise TypeError for k in kwargs.keys(): if isinstance(kwargs[k], str): kwargs[k] = f'\'{kwargs[k]}\'' else: kwargs[k] = f'{kwargs[k]}' return kwargs
def rindex(l, v): """Like list.index(), but go from right to left.""" return len(l) - 1 - l[::-1].index(v)
def _get_master(cluster_spec, task_type, task_id): """Returns the appropriate string for the TensorFlow master.""" if not cluster_spec: return '' # If there is only one node in the cluster, do things locally. jobs = cluster_spec.jobs if len(jobs) == 1 and len(cluster_spec.job_tasks(jobs[0])) == 1: return '' # Lookup the master in cluster_spec using task_type and task_id, # if possible. if task_type: if task_type not in jobs: raise ValueError( '%s is not a valid task_type in the cluster_spec:\n' '%s\n\n' 'Note that these values may be coming from the TF_CONFIG environment ' 'variable.' % (task_type, cluster_spec)) addresses = cluster_spec.job_tasks(task_type) if task_id >= len(addresses) or task_id < 0: raise ValueError( '%d is not a valid task_id for task_type %s in the ' 'cluster_spec:\n' '%s\n\n' 'Note that these value may be coming from the TF_CONFIG environment ' 'variable.' % (task_id, task_type, cluster_spec)) return 'grpc://' + addresses[task_id]
def isNoisyComponent(labels, signalLabels=None): """Given a set of component labels, returns ``True`` if the component is ultimately classified as noise, ``False`` otherwise. :arg signalLabels: Labels which are deemed signal. If a component has no labels in this list, it is deemed noise. Defaults to ``['Signal', 'Unknown']``. """ if signalLabels is None: signalLabels = ['signal', 'unknown'] signalLabels = [l.lower() for l in signalLabels] labels = [l.lower() for l in labels] noise = not any([sl in labels for sl in signalLabels]) return noise
def feature_list(collection): """get features list from collection""" return collection['features']
def _x_orientation_rep_dict(x_orientation): """Create replacement dict based on x_orientation.""" if x_orientation.lower() == 'east' or x_orientation.lower() == 'e': return {'x': 'e', 'y': 'n'} elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n': return {'x': 'n', 'y': 'e'} else: raise ValueError('x_orientation not recognized.')
def first_non_repeating_character(string): """ One way to do this is to have two dictionaries one which keeps the count of character, other dictionary will keep the first appearance of the character (index). After a traversal. Look in first dictionary for characters occurring once and output the one which has the first appearance as per second dictionary. Since in this case we have special constraint in mind. We will go with a cleverer way by reducing more stack space. """ n = len(string) occurrence = [n]*26 for i in range(len(string)): index = ord(string[i])-ord('a') if index < 0 or index > 25: return ("Invalid") if occurrence[index] == n: occurrence[index] = i else: occurrence[index] += n return string[min(occurrence)] if min(occurrence) < n else -1
def _sanitize_identifier(identifier_pattern): """Sanitizes a substance identifier so it can be used in a file name. Parameters ---------- identifier_pattern: str The identifier to sanitize. Returns ------- str The sanitized identifier. """ identifier_pattern = identifier_pattern.replace("\\", "\\\\") identifier_pattern = identifier_pattern.replace("#", "\\#") escaped_string = f"\\seqsplit{{{identifier_pattern}}}" escaped_string.replace("~", r"\textasciitilde") return escaped_string
def calculate(a: int, operator: str, b: int) -> int: """ Simple calculator. >>> calculate(a = 3, operator = "+", b = 4) 7 >>> calculate(a = 3, operator = "-", b = 4) -1 >>> calculate(a = 3, operator = "*", b = 4) 12 >>> calculate(a = 3, operator = "/", b = 4) 0 >>> calculate(a = 3, operator = "!", b = 4) Traceback (most recent call last): ... ValueError: Invalid operator """ if operator == "+": return a + b elif operator == "-": return a - b elif operator == "*": return a * b elif operator == "/": return a // b else: raise ValueError("Invalid operator")
def strip_word(word): """Converts a word to lowercase and strips out all non alpha characters.""" stripped = "" word = word.lower() for char in word: ascii = ord(char) if ascii >= 97 and ascii <= 122: stripped += char return stripped
def is_prime(n: int) -> bool: """ Returns True if n is prime, else returns False. :param n: int :return: bool """ if n <= 1: return False if n == 2: return True if not n & 1: # This is bitwise and. n & 1 is true for all odd numbers. return False # I avoid dependency on math package but math.sqrt() is actually a little faster. for k in range(3, int(n**0.5) + 1): if not n % k: # "if not n%k" is much less explicit but also measurably faster than "if n%k == 0" return False return True
def _get_mappings(field_spec, lookup_key): """ retrieve the field aliasing for the given key, refs or fields """ mappings = field_spec.get(lookup_key, []) if isinstance(mappings, list): mappings = {_key: _key for _key in mappings} return mappings
def attr_or_key(obj, k): """Get data for `k` by doing obj.k, or obj[k] if k not an attribute of obj >>> d = {'a': 1, 2: 'b', '__class__': 'do I win?'} >>> attr_or_key(d, 'a') 1 >>> attr_or_key(d, 2) 'b' >>> attr_or_key(d, '__class__') <class 'dict'> That last one shows that `attr_or_key` will also look in attributes to find the data of `k`. In fact, it looks there first, before using [k]. That's why we got the dict type returned, and not the 'do I win?' string. Because `d` has an attribute called `__class__` (like... well... all python objects do). """ if isinstance(k, str) and hasattr(obj, k): return getattr(obj, k) else: return obj.__getitem__(k)
def format_dict_as_lines(action_data): """Given a dictionary, format it as list of lines for presentation in tikibar. """ data = [] for key in sorted(action_data): data.append('{key}:{value}'.format(key=key, value=action_data[key])) return '\n'.join(data)
def inteiro_positivo(x): """ -Verifica se o argumento = numero inteiro e positivo (ou zero) Input: -x: elemento a ser testado Output: -Booleano Funcoes externas ao Python usadas: -- Nota:usada no tipo Posicao (construtor e reconhecedor) """ if isinstance(x, int) and x>=0: return True else: return False
def _get_state(inspect_results): """ Helper for deriving the current state of the container from the inspect results. """ if inspect_results.get("State", {}).get("Paused", False): return "paused" elif inspect_results.get("State", {}).get("Running", False): return "running" else: return "stopped"
def _read(f): """ Reads in the content of the file. :param f: the file to read :type f: str :return: the content :rtype: str """ return open(f, 'rb').read()
def RetriveUserIds(json_obj): """Get all user ids in a list of Tweet objects.""" rst_set = set() def _helper(current_obj): if 'entities' in current_obj: if 'user_mentions' in current_obj['entities']: if current_obj['entities']['user_mentions']: for user_obj in current_obj['entities']['user_mentions']: rst_set.add(user_obj['id']) if 'user' in current_obj: rst_set.add(current_obj['user']['id']) if 'retweeted_status' in current_obj: _helper(current_obj['retweeted_status']) for tweet_obj in json_obj: _helper(tweet_obj) return list(rst_set)
def bin_to_int(bits, bpw): """ Convert a list of bits to an integer """ sign_limit = 2**(bpw-1)-1 conv = (2**bpw) value = 0 for bit in reversed(bits): value = (value << 1) | bit if value > sign_limit: value -= conv return value
def link(href, text): """Generate a link""" return '<a href="' + href + '">' + text + '</a>'
def parse_id_list(id_list) -> str: """ Converts a list of IDs to a comma-delimited string """ if type(id_list) is list: returned = "" for s in id_list: if len(returned) > 1: returned += "," returned += str(s) return returned else: return id_list
def set_tags(config, tags): """ set gloabal tags setting in config """ config['tags'] = tags return True
def normalize_chord_case(word: str) -> str: """ Normalizes the case of a chord. Example: >>> normalize_chord_case('gM#') 'Gm#' """ ret = '' if len(word) > 1: return word[0].upper() + word[1:].lower() else: return word.upper()
def _remove_complex_types(dictionary): """ junos-eznc is now returning some complex types that are not serializable by msgpack. Kill those. """ for k, v in dictionary.items(): if isinstance(v, dict): dictionary[k] = _remove_complex_types(v) elif hasattr(v, "to_eng_string"): dictionary[k] = v.to_eng_string() return dictionary
def pipeline(*functions): """ Construct a filter pipeline from a list of filter functions Given a list of functions taking an iterable as their only argument, and which return a generator, this function will return a single function with the same signature, which applies each function in turn for each item in the iterable, yielding the results. That is, given filter functions ``a``, ``b``, and ``c``, ``pipeline(a, b, c)`` will return a function which yields ``c(b(a(x)))`` for each item ``x`` in the iterable passed to it. For example: >>> def a(iterable): ... for item in iterable: ... yield item + ':a' ... >>> def b(iterable): ... for item in iterable: ... yield item + ':b' ... >>> pipe = pipeline(a, b) >>> data_in = ["foo", "bar"] >>> data_out = pipe(data_in) >>> [x for x in data_out] ['foo:a:b', 'bar:a:b'] """ head = functions[0] tail = functions[1:] if tail: def _fn(iterable): for i in pipeline(*tail)(head(iterable)): yield i return _fn else: return head
def legal(a, b): """ Returns True if the given index is on the board - that is, both indices in the range 0 -> 7 """ return a in range(8) and b in range(8)
def configUnmapped(func, param: str): """ Helper to determine if a parameter mapping was set to None. :param func: The function to check. :param param: The parameter name to check. :return: True if the parameter mapping was set to none. """ return hasattr(func, '__cfgMap__') and param in func.__cfgMap__ and func.__cfgMap__[param] is None
def model_cropheatflux(netRadiationEquivalentEvaporation = 638.142, soilHeatFlux = 188.817, potentialTranspiration = 1.413): """ - Name: CropHeatFlux -Version: 1.0, -Time step: 1 - Description: * Title: CropHeatFlux Model * Author: Pierre Martre * Reference: abModelling energy balance in the wheat crop model SiriusQuality2: Evapotranspiration and canopy and soil temperature calculations * Institution: INRA/LEPSE Montpellier * Abstract: It is calculated from net Radiation, soil heat flux and potential transpiration - inputs: * name: netRadiationEquivalentEvaporation ** min : 0 ** default : 638.142 ** max : 10000 ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** variablecategory : auxiliary ** datatype : DOUBLE ** inputtype : variable ** unit : g m-2 d-1 ** description : net Radiation Equivalent Evaporation * name: soilHeatFlux ** min : 0 ** default : 188.817 ** max : 1000 ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** variablecategory : rate ** datatype : DOUBLE ** inputtype : variable ** unit : g m-2 d-1 ** description : soil Heat Flux * name: potentialTranspiration ** min : 0 ** default : 1.413 ** max : 1000 ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** variablecategory : rate ** datatype : DOUBLE ** inputtype : variable ** unit : g m-2 d-1 ** description : potential Transpiration - outputs: * name: cropHeatFlux ** min : 0 ** variablecategory : rate ** max : 10000 ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** datatype : DOUBLE ** unit : g m-2 d-1 ** description : crop Heat Flux """ cropHeatFlux = netRadiationEquivalentEvaporation - soilHeatFlux - potentialTranspiration return cropHeatFlux
def cli_repr(obj): """ Variant of standard `repr` that returns string suitable for using with a Command Line Interface, like the one enforced by `bash`. This is designed to get a `str`. Other input can be incompatible. """ # Replace ' with " because it is for CLI mostly (bash) # and there is no difference for Python. # Also `repr` replaces ' with \' because it wraps result in '. # This function re-wraps result in ", so the replacement must be reverted. return '"' + repr(obj).replace('"', r'\"').replace(r"\'", "'")[1:-1] + '"'
def max_produkt(n): """vrednost produkta najvecjih n-mestnih st""" return (10**(n) - 1) * (10**(n) - 1)
def part_1(puzzle_input): """Function which calculates the solution to part 1 Arguments --------- Returns ------- """ puzzle_input = int(puzzle_input) recipe_scores = [3, 7] elf_1 = 0 elf_2 = 1 while len(recipe_scores) < (puzzle_input + 10): score_sum = recipe_scores[elf_1] + recipe_scores[elf_2] if score_sum >= 10: recipe_scores.append(1) recipe_scores.append(score_sum % 10) else: recipe_scores.append(score_sum) elf_1 = (elf_1 + recipe_scores[elf_1] + 1) % len(recipe_scores) elf_2 = (elf_2 + recipe_scores[elf_2] + 1) % len(recipe_scores) return ''.join([f'{n}' for n in recipe_scores[puzzle_input:puzzle_input+10]])
def find_block_end(row, line_list, sentinal, direction=1): """ Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs """ import re row_ = row line_ = line_list[row_] flag1 = row_ == 0 or row_ == len(line_list) - 1 flag2 = re.match(sentinal, line_) if not (flag1 or flag2): while True: if (row_ == 0 or row_ == len(line_list) - 1): break line_ = line_list[row_] if re.match(sentinal, line_): break row_ += direction return row_
def _is_simple_mask(mask): """A simple mask is ``(2 ** n - 1)`` for some ``n``, so it has the effect of keeping the lowest ``n`` bits and discarding the rest. A mask in this form can produce any integer between 0 and the mask itself (inclusive), and the total number of these values is ``(mask + 1)``. """ return (mask & (mask + 1)) == 0
def vader_output_to_label(vader_output): """ map vader output e.g., {'neg': 0.0, 'neu': 0.0, 'pos': 1.0, 'compound': 0.4215} to one of the following values: a) positive float -> 'positive' b) 0.0 -> 'neutral' c) negative float -> 'negative' :param dict vader_output: output dict from vader :rtype: str :return: 'negative' | 'neutral' | 'positive' """ compound = vader_output['compound'] if compound < 0: return 'negative' elif compound == 0.0: return 'neutral' elif compound > 0.0: return 'positive'
def merge_dicts(samples_dict_1, samples_dict_2): """merge dicts of pairs so {sample: [1.r1, 1.r2, 2.r1, 2.r2]""" samples_dict_new = {} for key in samples_dict_1: samples_dict_new[key] = samples_dict_1[key] + samples_dict_2[key] return samples_dict_new
def split_dishes2val_test(dishes): """splist_dishes2train_val :param dishes: :return (train_content: list, val_content: list) """ val_content = [] test_content = [] for i, dish in enumerate(dishes): if i % 2: val_content += dish else: test_content += dish return val_content, test_content
def _b(strs): """ Convert a list of strings to binary UTF8 arrays. """ if strs is None: return None if isinstance(strs, str): return strs.encode('utf8') return list([s.encode('utf8') if s is not None else None for s in strs])
def average_error_to_weight(error): """ Given the average error of a pollster, returns that pollster's weight. The error must be a positive number. """ return error ** (-2)
def keyfr(frame=0, duration=1000, **kwargs): """ Returns a single keyframe with given parameters :param frame: name or number of image for this keyframe :param duration: time in milliseconds for this keyframe :param angle: degrees of clockwise rotation around a center origin :param flipx: set True to flip image horizontally :param flipy: set True flip image vertically :param color: (r,g,b) triplet to shift color values :param alpha: alpha transparency value :param scale: scaling multiplier where 1.0 is unchanged :param pos: optional (x,y) pair or Vector2 to set sprite position :param velocity: optional (x,y) or Vector2 for sprite to move measured in pixels per second :param rotation: optional degrees of clockwise rotation per second :param scaling: optional amount to scale per second where 0 = None :param fading: optional int to subract from alpha value per second :param coloring: (r,g,b) triplet to shift each color value per second """ kwargs.update(frame=frame, duration=duration) return(kwargs)
def quadratic_vertex_derivative_b(x, a, b, c): """The partial derivative with respect to parameter {@code b} for vertex form of quadratic function :param x: independent variable :param a: coefficient {a} of quadratic function :param b: the x coordinates of the vertex :param c: the y coordinates of the vertex :return:-2 * a * (x - b) """ return -2 * a * (x - b)
def index_based(index,value,input_list): """ only create a state if the eigenvalue is in the index list. """ if index in input_list: return True else: return False
def trailing_stop_loss_switch(value): """enable/disable trailing stop loss settings""" if "trailingstoploss" in value: return False, False return True, True
def removeAmbiguousBases(seq): """ Converts ambiguous bases to - as required by PhyML""" new_seq = "" for char in seq: if char not in ["A", "T", "C", "G"]: char = "-" new_seq += char return new_seq
def extract_doc_type(image_annotation): """ This function extracts the document type from the annotation performed on the Identity Documents :param image_annotation: the annotation from the annotated image :return: the document type """ recto_verso = "" type = "" for annotation in image_annotation["annotations"][0]["result"]: if annotation["from_name"] == "R/V": recto_verso = '_'.join(annotation["value"]["text"]) if annotation["from_name"] == "Type": type = '_'.join(annotation["value"]["text"]) #in case there are several annotation return type
def sizeof_fmt(num, suffix='B'): """ Human-readable string for a number of bytes. http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1000.0 return "%.1f%s%s" % (num, 'Y', suffix)
def f_value_with_digit_sum(n): """ Build the smallest number which digit sum is n. """ n9, d = divmod(n, 9) if d == 0: return '9' * n9 else: return str(d) + '9' * n9
def GPE_gpemgh(mass,gravity,height): """Usage: Find gravitational potential energy from mass, gravity and height""" result=mass*gravity*height return result
def hass_to_wilight_saturation(value): """Convert hass saturation 0..100 to wilight 1..255 scale.""" return min(255, round((value * 255) / 100))
def simple_interest(P,r,t): """ P = Principal Amount I = Interest Amount r = Rate of Interest per year in decimal """ I = P*r*t A = P + I return A
def get_filename_pair(filename): """ Given the name of a SPAR data file (e.g. /home/me/foo.sdat) or parameters file (e.g. c:/stuff/xyz.spar), returns a tuple of (parameters_filename, data_filename). It doesn't matter if the filename is a fully qualified path or not. This is a little shaky on case sensitive file systems since I assume that the file extensions are either all upper or all lower case. If, for instance, the data file is foo.sdat and the param file is FOO.SPAR, this code won't generate the correct name. """ # filenames are the same except for the last three letters. parameters_filename = data_filename = filename[:-3] if filename[-1:].isupper(): data_filename += 'DAT' parameters_filename += 'PAR' else: data_filename += 'dat' parameters_filename += 'par' return (parameters_filename, data_filename)
def convert_string_to_list(value, delimiter): """ Splits a string using the provided delimiter. Parameters: value (str): string to be split. delimiter (str): delimiter used to split the string. Returns: list: a string converted to a list. """ try: return value.split(delimiter) except AttributeError: return value
def metric_slug(value): """Given a redis key value for a metric, returns only the slug. Applying this filter to the keys for each metric will have the following results: * Converts ``m:foo:<yyyy-mm-dd>`` to ``foo`` * Converts ``m:foo:w:<num>`` to ``foo`` * Converts ``m:foo:m:<yyyy-mm>`` to ``foo`` * Converts ``m:foo:y:<yyyy>`` to ``foo`` """ return value.split(":")[1]
def inside(x, a, b): """ test x \in (a, b) or not """ l = 0 # if not torch.isreal(x): # return l if a <= b: if x >= a and x <= b: l = 1 else: if x >= b and x <= a: l = 1 return l
def refine_MIDDLEWARE_CLASSES(original): """ Django docs say that the LocaleMiddleware should come after the SessionMiddleware. Here, we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position. Be careful with the order when refining the MiddlewareClasses with following features. :param original: :return: """ try: session_middleware_index = original.index('django.contrib.sessions.middleware.SessionMiddleware') original.insert(session_middleware_index + 1, 'django.middleware.locale.LocaleMiddleware') return original except ValueError: raise LookupError('SessionMiddleware not found! Please make sure you have enabled the \ SessionMiddleware in your settings (django.contrib.sessions.middleware.SessionMiddleware).')
def fce2array(sr, pat): """Converts functions into arrays """ se = "".join(sr) so = "" ln = len(se) while ln > 0: # find pattern pos = se.find(pat) if pos < 0: break # position just behind the pattern pos += len(pat) sl = list(se) # exchange ( for [ if sl[pos] == "(": sl[pos] = "[" se = "".join(sl) # save everything in front of the pattern so += se[0:pos] se = se[pos:ln] # find clossing braket pos2 = se.find(")") # echange ) for ] sl = list(se) if sl[pos2] == ")": sl[pos2] = "]" se = "".join(sl) ln = len(se) so += se return so
def warning(expression, string, font=None): """ Error for command prompt Count=If count is needed, then you have to change countError to something else than None: assign countError to variable put before loop, which equals 1. After the warning you have to implement the incrementation of this variable """ txt = "" if not expression: # WARNING ERROR??? txt = u"\n [**WARNING**]> {}\n\n".format(string) if font != None: txt += u"\\\\\\\\\\\\\\\ *FILE NAME: {}*\n".format( font.path.split("/")[-1]) return txt
def is_float(s): """ Return True if this is a float with trailing zeroes such as `1.20` """ try: float(s) return s.startswith('0') or s.endswith('0') except: return False
def is_phrasal(subtree): """True if this treebank subtree is not a terminal or a preterminal node.""" return isinstance(subtree, list) and \ (len(subtree) == 1 or isinstance(subtree[1], list))
def filter_results(results, skip_list): """ Remove results for methods on the skip list. """ result = [] for method, res in results: include = True for skip in skip_list: if skip in method: include = False break if include: result.append((method, res)) return result
def dss_bundle_to_dos(dss_bundle): """ Converts a fully formatted DSS bundle into a DOS bundle. :param dss_bundle: :return: """ dos_bundle = {} dos_bundle['id'] = dss_bundle['uuid'] dos_bundle['version'] = dss_bundle['version'] dos_bundle['data_object_ids'] = [x['uuid'] for x in dss_bundle['files']] return dos_bundle
def compute_protein_mass(protein_string): """ Return the mass of a protein string as a float >>> compute_protein_mass("SKADYEK") 821.392 """ mass_table = {"A" : 71.03711, "C" : 103.00919, "D" : 115.02694, "E" : 129.04259, "F" : 147.06841, "G" : 57.02146, "H" : 137.05891, "I" : 113.08406, "K" : 128.09496, "L" : 113.08406, "M" : 131.04049, "N" : 114.04293, "P" : 97.05276, "Q" : 128.05858, "R" : 156.10111, "S" : 87.03203, "T" : 101.04768, "V" : 99.06841, "W" : 186.07931, "Y" : 163.06333, } mass = 0 for i in protein_string: mass = mass + mass_table[i] return mass
def change_extension(filename, extension): """Change file extenstion to @extension. >>> change_extension('file_name.py', 'html') 'file_name.html' >>> change_extension('file_name.with.dots.html', 'py') 'file_name.with.dots.py' """ return '.'.join(filename.split('.')[:-1] + [extension])
def get_docomo_post_data(number, hidden_param): """Returns a mapping for POST data to Docomo's url to inquire for messages for the given number. Args: number: a normalized mobile number. Returns: a mapping for the POST data. """ return {'es': 1, 'si': 1, 'bi1': 1, 'ep': hidden_param, 'sm': number}
def no_progress_count_plane(no_progress, n=8): """ :param int no_progress: Integer value denoting the number of total no-progress moves made. :param int n: Chess game dimension (usually 8). :return: An n x n list containing the same value for each entry, the no_progress number. :rtype: list[list[int]] This function computes the n x n no progress count plane. """ return [[no_progress for _ in range(n)] for _ in range(n)]
def GCD(a , b): """ define a function GCD which takes two integer inputs and return their common divisor""" com_div =[1] i =2 while i<= min(a,b): if a % i == 0 and b % i ==0: com_div.append(i) i = i+1 return com_div[-1]
def to_datetime(timestamp): """converts a timestamp to a Sheets / Excel datetime""" EPOCH_START = 25569 # 1970-01-01 00:00:00 SECONDS_IN_A_DAY = 86400 return timestamp / SECONDS_IN_A_DAY + EPOCH_START
def _asciizToStr(s): """Transform a null-terminated string of any length into a Python str. Returns a normal Python str that has been terminated. """ i = s.find('\0') if i > -1: s = s[0:i] return s
def oc_to_vlan_range(value): """ Converts an industry standard vlan range into a list that can be interpreted by openconfig. For example: ["1", "2", "3..10"] -> "1, 2, 3-10" """ return ",".join(["{}".format(s).replace("..", "-") for s in value])
def quintic_ease_in_out(p): """Modeled after the piecewise quintic y = (1/2)((2x)^5) ; [0, 0.5) y = (1/2)((2x-2)^5 + 2) ; [0.5, 1] """ if p < 0.5: return 16 * p * p * p * p * p else: f = (2 * p) - 2 return (0.5 * f * f * f * f * f) + 1
def _create_groups(together: list): """Returns unions of pairs Args: together (list): Pairs of individuals who should be together Returns: list: Nested list of groups, ordered largest to smallest Example: >>> together = [["a", "b"], ["a", "e"], ["d", "g"]] >>> _create_groups(together) [["a", "b", "e"], ["d", "g"]] """ groups = [] if together is None: return groups for pair in together: if groups == []: groups.append(pair) continue bool_union = False for group in groups: intersect = list(set(pair) & set(group)) if intersect != []: union = list(set(pair) | set(group)) groups.remove(group) groups.append(union) bool_union = True break if not bool_union: groups.append(pair) groups.sort(key=len, reverse=True) return groups
def get_image_parameters( particle_center_x_list=lambda : [0, ], particle_center_y_list=lambda : [0, ], particle_radius_list=lambda : [3, ], particle_bessel_orders_list=lambda : [[1, ], ], particle_intensities_list=lambda : [[.5, ], ], image_half_size=lambda : 25, image_background_level=lambda : .5, signal_to_noise_ratio=lambda : 30, gradient_intensity=lambda : .2, gradient_direction=lambda : 0, ellipsoidal_orientation=lambda : [0, ], ellipticity=lambda : 1): """Get image parameters. Inputs: particle_center_x_list: x-centers of the particles [px, list of real numbers] particle_center_y_list: y-centers of the particles [px, list of real numbers] particle_radius_list: radii of the particles [px, list of real numbers] particle_bessel_orders_list: Bessel orders of the particles [list (of lists) of positive integers] particle_intensities_list: intensities of the particles [list (of lists) of real numbers, normalized to 1] image_half_size: half size of the image in pixels [px, positive integer] image_background_level: background level [real number normalized to 1] signal_to_noise_ratio: signal to noise ratio [positive real number] gradient_intensity: gradient intensity [real number normalized to 1] gradient_direction: gradient angle [rad, real number] ellipsoidal_orientation: Orientation of elliptical particles [rad, real number] ellipticity: shape of the particles, from spherical to elliptical [real number] Note: particle_center_x, particle_center_x, particle_radius, particle_bessel_order, particle_intensity, ellipsoidal_orientation must have the same length. Output: image_parameters: list with the values of the image parameters in a dictionary: image_parameters['Particle Center X List'] image_parameters['Particle Center Y List'] image_parameters['Particle Radius List'] image_parameters['Particle Bessel Orders List'] image_parameters['Particle Intensities List'] image_parameters['Image Half-Size'] image_parameters['Image Background Level'] image_parameters['Signal to Noise Ratio'] image_parameters['Gradient Intensity'] image_parameters['Gradient Direction'] image_parameters['Ellipsoid Orientation'] image_parameters['Ellipticity'] """ image_parameters = {} image_parameters['Particle Center X List'] = particle_center_x_list() image_parameters['Particle Center Y List'] = particle_center_y_list() image_parameters['Particle Radius List'] = particle_radius_list() image_parameters['Particle Bessel Orders List'] = particle_bessel_orders_list() image_parameters['Particle Intensities List'] = particle_intensities_list() image_parameters['Image Half-Size'] = image_half_size() image_parameters['Image Background Level'] = image_background_level() image_parameters['Signal to Noise Ratio'] = signal_to_noise_ratio() image_parameters['Gradient Intensity'] = gradient_intensity() image_parameters['Gradient Direction'] = gradient_direction() image_parameters['Ellipsoid Orientation'] = ellipsoidal_orientation() image_parameters['Ellipticity'] = ellipticity() return image_parameters
def _flip(r, u): """Flip `r` if `u` is negated, else identity.""" return -r if u < 0 else r
def decoder(permutation): """ decoder takes a permutation array and returns the corresponding depermutation array necessary to decode a permuted string """ depermutation = [] for x in range (0, len (permutation)): depermutation.append (permutation.index(x)) return depermutation
def _interval_contains_close(interval, val, rtol=1e-10): """ Check, inclusively, whether an interval includes a given value, with the interval expanded by a small tolerance to admit floating point errors. Parameters ---------- interval : (float, float) The endpoints of the interval. val : float Value to check is within interval. rtol : float, default: 1e-10 Relative tolerance slippage allowed outside of the interval. For an interval ``[a, b]``, values ``a - rtol * (b - a) <= val <= b + rtol * (b - a)`` are considered inside the interval. Returns ------- bool Whether *val* is within the *interval* (with tolerance). """ a, b = interval if a > b: a, b = b, a rtol = (b - a) * rtol return a - rtol <= val <= b + rtol
def case2args(case): """ Parse case and Convert case into pod-compatible string """ s = case.split(" ") s = [q for q in s if q] # remove empty strings s[0] += ".json" return s
def unliteral(lit_type): """ Get base type from Literal type. """ if hasattr(lit_type, '__unliteral__'): return lit_type.__unliteral__() return getattr(lit_type, 'literal_type', lit_type)
def _content_parse(value: str): """ :param value: :return: """ try: res = int(value) except ValueError: try: res = float(value) except ValueError: res = value return res
def swap(string, nameA, nameB): """ Swap all occurances of nameA with nameB and vice-versa in the string. Parameters ---------- string : str The string to modify. nameA : str The substring to replace with `nameB`. nameB : str The substring to replace with `nameA`. Returns ------- str The modified string. Examples -------- >>> qosy.swap('A Up B Dn', 'Up', 'Dn') # 'A Dn B Up' >>> qosy.swap('X X A', 'X', 'Y') # 'Y Y A' >>> qosy.swap('1 2 3', '1', '3') # '3 2 1' """ result = string.replace(nameA, '({})'.format(nameA)) result = result.replace(nameB, nameA) result = result.replace('({})'.format(nameA), nameB) return result
def extended_gcd(a, b): """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb""" # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made positive mod b or a respectively # Iterateive Version is faster and uses much less stack space x = 0 y = 1 lx = 1 ly = 0 oa = a # Remember original a/b to remove ob = b # negative values from return results while b != 0: q = a // b (a, b) = (b, a % b) (x, lx) = ((lx - (q * x)), x) (y, ly) = ((ly - (q * y)), y) if lx < 0: lx += ob # If neg wrap modulo orignal b if ly < 0: ly += oa # If neg wrap modulo orignal a return a, lx, ly
def fsnative2glib(path): """Convert file system to native glib format""" assert isinstance(path, bytes) return path
def _ExtStorageEnvironment(unique_id, ext_params, size=None, grow=None, metadata=None, name=None, uuid=None, snap_name=None, snap_size=None, exclusive=None): """Calculate the environment for an External Storage script. @type unique_id: tuple (driver, vol_name) @param unique_id: ExtStorage pool and name of the Volume @type ext_params: dict @param ext_params: the EXT parameters @type size: integer @param size: size of the Volume (in mebibytes) @type grow: integer @param grow: new size of Volume after grow (in mebibytes) @type metadata: string @param metadata: metadata info of the Volume @type name: string @param name: name of the Volume (objects.Disk.name) @type uuid: string @param uuid: uuid of the Volume (objects.Disk.uuid) @type snap_size: integer @param snap_size: the size of the snapshot @type snap_name: string @param snap_name: the name of the snapshot @type exclusive: boolean @param exclusive: Whether the Volume will be opened exclusively or not @rtype: dict @return: dict of environment variables """ vol_name = unique_id[1] result = {} result["VOL_NAME"] = vol_name # EXT params for pname, pvalue in ext_params.items(): result["EXTP_%s" % pname.upper()] = str(pvalue) if size is not None: result["VOL_SIZE"] = str(size) if grow is not None: result["VOL_NEW_SIZE"] = str(grow) if metadata is not None: result["VOL_METADATA"] = metadata if name is not None: result["VOL_CNAME"] = name if uuid is not None: result["VOL_UUID"] = uuid if snap_name is not None: result["VOL_SNAPSHOT_NAME"] = snap_name if snap_size is not None: result["VOL_SNAPSHOT_SIZE"] = str(snap_size) if exclusive is not None: result["VOL_OPEN_EXCLUSIVE"] = str(exclusive) return result
def get_temp_disk_for_node_agent(node_agent: str) -> str: """Get temp disk location for node agent :param node_agent: node agent :return: temp disk location """ if node_agent.startswith('batch.node.unbuntu'): return '/mnt' elif node_agent.startswith('batch.node.windows'): return 'D:\\batch' else: return '/mnt/resource'
def convertStr(s): """Convert string to either int or float.""" if s is None: return None try: ret = int(s) except ValueError: ret = None return ret
def next_quarter(year, quarter, num=1): """return next quarter for Gregorian calendar""" if quarter not in range(1, 5): raise ValueError("invalid quarter") quarter -= 1 # for mod, div quarter += num year += quarter / 4 quarter %= 4 quarter += 1 # back return year, quarter
def findFractionOfPixelWithinCircle(xmin, xmax, ymin, ymax, r, cx = 0.0, cy = 0.0, ndiv = 16): """ Find the fraction of a pixel that is within a hard circular mask. Arguments: xmin -- left edge xmax -- right edge ymin -- lower edge ymax -- upper edge r -- radius of circle Keyword arguments: cx -- x position of centre of circle (default 0.0) cy -- y position of centre of circle (default 0.0) ndiv -- number sub-divisions (default 16) Note: This function is crying out for FORTRAN+OpenMP. """ # Import special modules ... try: import numpy except: raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None # Create nodes relative to the centre of the circle ... xaxis = numpy.linspace(xmin, xmax, num = ndiv + 1) - cx yaxis = numpy.linspace(ymin, ymax, num = ndiv + 1) - cy # Convert the nodes to centroids ... # NOTE: https://stackoverflow.com/a/23856065 xaxis = 0.5 * (xaxis[1:] + xaxis[:-1]) yaxis = 0.5 * (yaxis[1:] + yaxis[:-1]) # Find out the distance of each centroid to the centre of the circle ... dist = numpy.zeros((ndiv, ndiv), dtype = numpy.float64) for ix in range(ndiv): for iy in range(ndiv): dist[iy, ix] = numpy.hypot(xaxis[ix], yaxis[iy]) # Return answer ... return float((dist <= r).sum()) / float(ndiv * ndiv)
def compute_num_cells(max_delta_x, pt_0_y, pt_1_y): """compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber) Args: max_delta_x (double): User defined maximum grid spacing. pt0x (double): x-coordinate of bottom LHS cookstove combustion chamber pt1x (double): x-coordinate of bottom RHS cookstove combustion chamber Returns: num_cells_int (int): number of cells to be written to the openfoam blockmesh file for entire domain num_cells_double (double): number of cells to be written to the openfoam blockmesh file for entire domain BEFORE INT ROUNDING num_cells_int_str (str): number of cells to be written to the openfoam blockmesh file for entire domain, converted to string type for f.write num_cells_int_str_concat (str): cells formatted for OF """ max_space = abs(pt_1_y-pt_0_y) # maximum spatial step in domain defined by coordinates num_cells_double = max_space/max_delta_x # unrounded number of cells per block num_cells_int = int(round(num_cells_double)) # round to integer value num_cells_int_str = str(num_cells_int) num_cells_int_str_concat = "(" + num_cells_int_str + " " + num_cells_int_str + " " + num_cells_int_str + ")" print("num cells int") print(num_cells_int) print("num cells int converted to str") print(num_cells_int_str) print("num cells int str concat") print(num_cells_int_str_concat) return num_cells_int, num_cells_double, num_cells_int_str, num_cells_int_str_concat
def gwh_to_twh(gwh): """Convert GWh to TWh Arguments --------- gwh : float GWh Returns ------- twh : str TWh """ twh = gwh / 1000.0 return twh
def padded_text(word, max_length, centered): """ Returns padded text with spaces (centered or not) """ word_str = str(word) len_word = len(word_str) if centered: len_pad = max_length - len_word if len_pad % 2 == 0: pad = int(len_pad / 2) l, r = pad, pad else: l = int(len_pad / 2) r = len_pad - l return (" " * l) + word_str + (" " * r) return " " + word_str + " " * (max_length - len_word - 1)
def vis85(n): """ OOO OO OOO OO OOOO OOOOOO OO OOO OOOO OOO OOOO OOOO Number of Os: 4 12 24 """ result = '' if n == 1: result = 'OO\nOO' return result result = (' ' * n) + 'O' * n + '\n' result += 'O' * (n * 2) + '\n' for i in range(n): result += 'O' * (n + 1) + '\n' return result
def stripdefaults(target, removeempty=list(), removeexact=dict()): """ Make output dicts smaller by removing default entries. Keys are removed from `target` in place Args: target (dict): dictionary to remove entries from removeempty (list): Remove keys in this list from target if the key tests as false (None, "", [], {}, etc) removeexact (dict): Remove keys in this dict from target if the correspondong values are equal Returns: target with the keys removed """ for key in removeempty: # if val is an np.array, `not` raises an exception try: if not target.get(key, True): del target[key] except Exception: pass for key, val in removeexact.items(): if target.get(key) == val: del target[key] return target
def subsentence_comma(sentence): """ delete ',' or changed on ';' Input=sentence Output=sentence """ # init i = 0 while i < len(sentence): if sentence[i] == ',': sentence[i] = ';' # We delete it if it is at the end of the sentence if i == len(sentence) - 1: sentence = sentence[:i] elif sentence[i + 1] == '?' or sentence[i + 1] == '!' or sentence[i + 1] == '.': sentence = sentence[:i] + sentence[i + 1:] i += 1 return sentence