content
stringlengths
42
6.51k
def load_log(log_file): """Reads the processed posts log file and creates it if it doesn't exist. Returns ------- list A list of Reddit posts ids. """ try: with open(log_file, "r", encoding="utf-8") as temp_file: return temp_file.read().splitlines() except FileNotFoundError: with open(log_file, "a", encoding="utf-8") as temp_file: return []
def parse_instruction(instruction): """Deprecated""" sint = str(instruction).zfill(5) parm3 = bool(int(sint[0])) parm2 = bool(int(sint[1])) parm1 = bool(int(sint[2])) op = int(sint[-2:]) return op, parm1, parm2, parm3
def ParseList(List): """Parse lists (e.g. 0,1,3-8,9)""" Res = list() if ( str(List).isdigit() ): Res.append(int(List)) else: for Element in List.split(','): if '-' in Element: x1,x2 = Element.split('-') Res.extend(list(range(int(x1), int(x2)+1))) else: Res.append(int(Element)) return Res
def is_json_schema(data): """ :param dict data: JSON data :returns: whether the JSON data is a JSON Schema :rtype: bool """ return '$schema' in data or 'definitions' in data or 'properties' in data
def getWhiteSpaceLessStringMap(string): """ Map the characters in a string from which whitespace has been removed to their indices in the original string. """ map = {} whiteSpaceLessPos = 0 for originalPos in range(len(string)): if not string[originalPos].isspace(): map[whiteSpaceLessPos] = originalPos whiteSpaceLessPos += 1 return map
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ if not input_list: return -1 if len(input_list) == 1: if input_list[0] == number: return 0 else: return -1 start, end = 0, len(input_list) - 1 while start + 1 < end: mid = (end - start) // 2 + start # mid = (start + end) // 2 if input_list[mid] >= input_list[start]: if input_list[start] <= number <= input_list[mid]: end = mid else: start = mid else: if input_list[mid] <= number <= input_list[mid]: start = mid else: end = mid if input_list[start] == number: return start if input_list[end] == number: return end return -1
def genomic_dup2_free_text(dmd_gene_context): """Create test fixture containing params for genomic dup VD.""" params = { "id": "normalize.variation:TSC2%20g.2137939_2137949dup", "type": "VariationDescriptor", "variation_id": "", "variation": dict(), "molecule_context": "transcript", "structural_type": "SO:1000035", "vrs_ref_allele_seq": "TAGA", "gene_context": dmd_gene_context } return params
def AddFlagPrefix(name): """Add the flag prefix to a name, if not present.""" if name.startswith('--'): return name # Does not guarantee a valid flag name. return '--' + name
def convert_to_float(str_list): """ Return a list of floats """ values = [] for value in str_list: values.append(float(value)) return values
def load_data(file_handle, element, element_size): """Read element_size bytes of binary data from file_handle into element""" if element_size == 0: return element, True if element is None: element = file_handle.read(element_size) else: read_size = element_size - len(element) element += file_handle.read(read_size) return element, len(element) == element_size
def multiply_matrices(m_1: list, m_2: list) -> list: """ Parameters ---------- m_1 : list of lists => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] m_2 : list of lists => [[10, 11, 12], [13, 14, 15], [17, 18, 19]] Returns ------ transformation : list of lists => [[ 87, 93, 99], [207, 222, 237], [327, 351, 375]] """ if len(m_1[0]) != len(m_2): raise ValueError("Size mismatch: m_1 columns do not match m_2 rows") transformation = [[] for _ in m_1] for column_idx, _ in enumerate(m_2[0]): for i, m1_row in enumerate(m_1): m_2_column = [m2_row[column_idx] for m2_row in m_2] positional_sum = sum(a * b for a, b in zip(m1_row, m_2_column)) transformation[i].append(positional_sum) return transformation
def safe_str(s: str) -> str: """A lowercase string with some special characters replaced.""" for char in "[]()'": s = s.replace(char, "") s = s.replace(" ", "-") s = s.replace(".", ",") return s.lower()
def sort_key(item): """Sort list by the first key.""" if len(item) != 1: item = item[0] return (list(item.keys())[0],)
def get_trunc_hour_time(obstime): """Truncate obstime to nearest hour""" return((int(obstime)/3600) * 3600)
def string_to_list(str_): """ Returns a list from the given string >>> string_to_list(['1', '2', '3']) >>> # ['1', '2', '3'] :param str_: :return: list """ str_ = '["' + str(str_) + '"]' str_ = str_.replace(' ', '') str_ = str_.replace(',', '","') return eval(str_)
def readout_tbexec(line, tbexeclist, tbinfo, goldenrun): """ Builds the dict for tb exec from line provided by qemu """ split = line.split('|') # generate list element execdic = {} execdic['tb'] = int(split[0], 0) execdic['pos'] = int(split[1], 0) return execdic
def is_subsub(q, ts): """ check is `q is a subset of any subset in set `ts """ iok = False for tsi in ts: if set(q) <= tsi: iok = True; break return iok
def compute_variance_by_mode(n_EOF, singular_val, cov=True): """Compute variance contained in any mode (EOF). Based on Beckers and Rixen 2001 """ tot_variance = 0 variance = [] # singular values of field matrix X are the square roots # of the eigenvalues of Xt*X if not cov : singular_val *= singular_val for i in range(0, len(singular_val)): tot_variance += singular_val[i] return [100*((singular_val[i])/tot_variance) for i in range(0, n_EOF)]
def chunks(chunkable, n): """ Yield successive n-sized chunks from l. """ chunk_list = [] for i in range(0, len(chunkable), n): chunk_list.append( chunkable[i:i+n]) return chunk_list
def makeListFromCommaSepString(s): """ Reads in comma-separated list and converts to list of successive keyword,value pairs. """ if s.count(",") % 2 == 0: raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s) l = [] items = s.split(",") while len(items) > 0: l.append((items[0], items[1])) items = items[2:] return l
def part2(data): """ >>> part2([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 5 >>> part2(read_input()) 1618 """ count = 0 for i in range(1, len(data) - 2): previous = sum(data[i - 1:i + 2]) value = sum(data[i:i + 3]) if value > previous: count += 1 return count
def get_evening_cars(morning_cars,requested,returned,max_cars): """ compute #cars avaiable in the evening, given #cars in the morning, #returned and #requests during the day """ return min(max(morning_cars - requested,0) + returned, max_cars)
def linear(n): """Trivial linear tweening function. Copied from pytweening module. """ if not 0.0 <= n <= 1.0: raise ValueError('Argument must be between 0.0 and 1.0.') return n
def fuzzyCompareDouble(p1, p2): """ compares 2 double as points """ return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2))
def tweetstyle(tweets_polarity, i,default=False): """ Determines the colour of a tweet based on its polarity. :param tweets_polarity: the array of polarities :param i: the position of the tweet polarity in the array :param default: default flag, True if section is in default :return style: dict """ if default: style = { 'background-color' : 'rgba(250, 192, 0,0.5)', 'border-radius' : '5px', 'margin-top':'1%' } if tweets_polarity[i] < 33: style = { 'background-color' : 'rgba(164, 19, 3,0.5)', 'border-radius' : '5px', 'margin-top' : '1%' } if tweets_polarity[i] > 66: style = { 'background-color' : 'rgba(3, 164, 3, 0.5)', 'border-radius' : '5px', 'margin-top' : '1%' } return style if tweets_polarity[i] == "None": style = { 'background-color' : 'white', 'border-radius' : '5px', 'margin-top' : '1%' } return style style = { 'background-color' : 'rgba(250, 192, 0,0.5)', 'border-radius' : '5px', 'margin-top':'1%' } if tweets_polarity[i] < -0.3: style = { 'background-color' : 'rgba(164, 19, 3,0.5)', 'border-radius' : '5px', 'margin-top' : '1%' } if tweets_polarity[i] > 0.3: style = { 'background-color' : 'rgba(3, 164, 3, 0.5)', 'border-radius' : '5px', 'margin-top' : '1%' } return style
def scan_alias(toks): """Scan the index of 'as' and build the map for all alias""" as_idxs = [idx for idx, tok in enumerate(toks) if tok == 'as'] alias = {} for idx in as_idxs: alias[toks[idx+1]] = toks[idx-1] return alias
def _convert(msg): """Convert a graphite key value string to pickle.""" path, timestamp, value = msg.split(' ') m = (path, (timestamp, value)) return m
def bit_not(n: int, numbits: int=32) -> int: """Return the bitwise NOT of 'n' with 'numbits' bits.""" return (1 << numbits) - 1 - n
def encode_string_text(text): """Replace special symbols with corresponding entities or magicwords.""" text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") text = text.replace("[", "&#91;") text = text.replace("]", "&#93;") text = text.replace("{", "&#123;") text = text.replace("}", "&#125;") text = text.replace("|", "{{!}}") return text
def get_id(element) -> str: """ Return the ID of an event or series. :param element: event or series :type element: dict :return: ID of element :rtype: str """ if "id" in element: return element["id"] elif "identifier" in element: return element["identifier"] else: raise ValueError("Element has no ID")
def convert_to_seconds(millis, return_with_seconds=True): """ Converts milliseconds to seconds. Arg: 'return_with_seconds' defaults to True and returns string ' sekunder' after the seconds """ if return_with_seconds: return (millis/1000) % 60 + " sekunder" else: return (millis/1000) % 60
def fn2Test(pStrings, s, outputFile): """ Function concatenates the strings in pStrings and s, in that order, and writes the result to the output file. Returns s. """ with open(outputFile, 'w') as fH: fH.write(" ".join(pStrings) + " " + s) return s
def boolean_string(s): """ https://stackoverflow.com/questions/44561722/why-in-argparse-a-true-is-always-true :param s: :return: """ if s.lower() not in {'false', 'true'}: raise ValueError('Not a valid boolean string') return s.lower() == 'true'
def min_max_prod(minimums, maximums): """ returns the smallest and largest products achievable by interweaving maximums and minimums >>> min_max_prod((3,6,0,1,6),(-4,3,-5,-4,0)) (-2880, 2160) """ assert len(maximums) == len(minimums) ret_min, ret_max = 1, 1 for op_min, op_max in zip(minimums, maximums): cands = (op_min * ret_min, op_min * ret_max, op_max * ret_min, op_max * ret_max) ret_min = min(cands) ret_max = max(cands) return ret_min, ret_max
def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, list) or isinstance(element, tuple): append.extend(element) else: append.append(element) else: return element
def clean_hostname(hostname): """ Remove the .local appendix of a hostname. """ if hostname: return hostname.replace('.local', '').replace('.lan', '')
def normalize(tensor, stats): """Normalize a tensor using a running mean and std. Parameters ---------- tensor : tf.Tensor the input tensor stats : RunningMeanStd the running mean and std of the input to normalize Returns ------- tf.Tensor the normalized tensor """ if stats is None: return tensor return (tensor - stats.mean) / stats.std
def not_(column: str) -> str: """ >>> not_("col") 'NOT col' """ return f"NOT {column}"
def as_list(string_members): """Returns a string of comma-separated member addresses as a list""" ml = [] for m in string_members.split(","): ml.append(m.strip()) return ml
def linear_search_iterative(array, item): """Return the index of the targeted item""" # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None
def f(x): """does some math""" return x + x * x
def match_parantheses(data): """ Makes sure the parantheses in data are correctly closed. Returns: True if the parantheses are correctly closed. """ parantheses = ['[', ']', '(', ')'] matches = { '[': ']', '(': ')' } stack = [] for char in data: if char in parantheses: isOpening = char in matches.keys() isClosing = char in matches.values() if isOpening: stack.append(char) if isClosing: opened = stack.pop() if matches[opened] != char: return False if len(stack) != 0: return False return True
def in_sh(argv, allstderr=True): """ Provides better error messages in case of file not found or permission denied. Note that this has nothing at all to do with shell=True, since quoting prevents the shell from interpreting any arguments -- they are passed straight on to shell exec. """ # NB: The use of single and double quotes in constructing the call really # matters. call = 'exec "$@" >&2' if allstderr else 'exec "$@"' return ["/bin/sh", "-c", call, "sh"] + argv
def monomial_pow(A, n): """Return the n-th pow of the monomial. """ return tuple([ a*n for a in A ])
def clean_phonological_groups(groups, liaison_positions, liaison_property): """Clean phonological groups so their liaison property is consistently set according to the the liaison positions :param groups: Phonological groups to be cleaned :param liaison_positions: Positions of the liaisons :param liaison_property: The liaison type (synaeresis or synalepha) :return: Cleaned phonological groups :rtype: dict """ clean_groups = [] for idx, group in enumerate(groups): if liaison_property in group: clean_groups.append({ **group, liaison_property: bool(liaison_positions[idx]) }) else: clean_groups.append(group) return clean_groups
def check_data(data_converter, data): """Store class method returns `None` in case the reaktor call returns `void`. For empty result (<> void), the data converter is still run because the backend omits empty and null attributes for bandwidth efficiency. In case of data being an array, a collection of items is assumed and each item is converted using the provided `data_converter`. """ if isinstance(data, list): return [data_converter(d) for d in data] if data is not None: return data_converter(data)
def U32(i): """Return i as an unsigned integer, assuming it fits in 32 bits. If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: i += 1 << 32 return i
def is_blank(s: str) -> bool: """Checks if a string is blank or not""" return not bool(s and not s.isspace())
def rm_empty_by_copy(list_array): """copy the last non-empty element to replace the empty ones""" for idx in range(len(list_array)): if len(list_array[idx]) == 0: list_array[idx] = list_array[idx-1] return list_array
def div(a,b): """``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10 """ res, fail = divmod(a,b) if fail: raise ValueError("%r does not divide %r" % (b,a)) else: return res
def collect_reducer_set(values): """Return the set of values >>> collect_reducer_set(['Badger', 'Badger', 'Badger', 'Snake']) ['Badger', 'Snake'] """ return sorted(list(set(values)))
def argmax(l,f=None): """http://stackoverflow.com/questions/5098580/implementing-argmax-in-python""" if f: l = [f(i) for i in l] return max(enumerate(l), key=lambda x:x[1])[0]
def make_full_path(path, name): """ Combine path and name to make full path""" # path = make_bytes(path) #py3, this added for python3, path must be bytes, not unicode # import pdb; pdb.set_trace() name = name.decode('utf-8') #py3, added name will be byte string and combine_messages is always expecting unicode if path == "/": #py3, added b # full_path = b"/" + name #py3, added b full_path = "/%s" % name #py3, use format instead of + else: # assert not path.endswith(b'/'), "non-root path ends with '/' (%s)" % path #py3, added b assert not path.endswith('/'), "non-root path ends with '/' (%s)" % path # assert not path[-1] == '/', "non-root path ends with '/' (%s)" % path #py3, change to check last char # full_path = path + b"/" + name #py3, added b full_path = "%s/%s" % (path, name) #py3, use format instead of + # remove any duplicate slashes, should be unnecessary # full_path = re.sub(r'//+',r'/', full_path) # print ("path=%s, name=%s, full_path=%s" % (path, name, full_path)) # import pdb; pdb.set_trace() return full_path
def zip_values(x_vals: list, y_vals: list) -> list: """Returns a list of the specified X and Y values packaged together in tuples, with X at index 0 of the tuple.""" return [(x_vals[_], y_vals[_]) for _ in range(len(x_vals))]
def ordinal(num: int) -> str: """ Returns the ordinal representation of a number Examples: 11: 11th 13: 13th 14: 14th 3: 3rd 5: 5th :param num: :return: """ return f"{num}th" if 11 <= (num % 100) <= 13 else f"{num}{['th', 'st', 'nd', 'rd', 'th'][min(num % 10, 4)]}"
def unique(seq, idfun=repr): """ Function to remove duplicates in an array. Returns array with duplicates removed. """ seen = {} return [seen.setdefault(idfun(e), e) for e in seq if idfun(e) not in seen]
def get_path_to_sfr_dir(name: str, data_directory: str) -> str: """Get the path to the directory where the star formation data should be stored Args: name (str): Name of the galaxy data_directory (str): dr2 data directory Returns: str: Path to SFR dir """ return f"{data_directory}/sfr/{name}"
def noise_eliminate(lines, coordinates, flag): """ # delete the noise lines which are defined as the close lines. :param lines: list. lines saved as endpoints coordinates, eg:[[(x_0, y_0), (x_1, y_1), 'v'],[(x_2, y_2), (x_3,y_3), 'h'],...] :param coordinates: list. [x1, x2, x3,...] or [y1, y2, y3,..] is the coordinates of lines endpoints. Based on these points to judge whether the lines are close. :param flag: 'v' or 'h' noted as horizon or vertical represented the lines direction. :return: lists, the filtered lines """ # default the noise lines will have the similar length threshold = max(abs((coordinates[0] - coordinates[-1]) / 25), 10) filter_list = [] ## as for vertical lines ## save the longest line and filte whose surrounded lines close to it if flag == 'v': # initialize longest_line = lines[0] max_length = abs(longest_line[0][1] - longest_line[1][1]) for i in range(len(coordinates) - 1): if abs(coordinates[i] - coordinates[i + 1]) < threshold: # whether it is the close lines # update the longest line if max_length < abs(lines[i + 1][0][1] - lines[i + 1][1][1]): longest_line = lines[i + 1] max_length = abs(lines[i + 1][0][1] - lines[i + 1][1][1]) else: # save the filtered lines filter_list.append(longest_line) # initialized longest_line = lines[i + 1] max_length = abs(lines[i + 1][0][1] - lines[i + 1][1][1]) # the last line filter_list.append(longest_line) # for horizon lines elif flag == 'h': longest_line = lines[0] max_length = abs(longest_line[0][0] - longest_line[1][0]) for i in range(len(coordinates) - 1): if abs(coordinates[i] - coordinates[i + 1]) < threshold: if max_length < abs(lines[i + 1][0][0] - lines[i + 1][1][0]): longest_line = lines[i + 1] max_length = abs(lines[i + 1][0][0] - lines[i + 1][1][0]) else: filter_list.append(longest_line) longest_line = lines[i + 1] max_length = abs(lines[i + 1][0][0] - lines[i + 1][1][0]) filter_list.append(longest_line) else: print('Error for the key argument') return filter_list
def sorted_unique(iterable): """Sort and uniquify elements to construct a new list. Parameters ---------- iterable : collections.Iterable[any] The collection to be sorted and uniquified. Returns ------- list[any] Unique elements as a sorted list. """ return sorted(set(iterable))
def legal_input(input_w): """ :param input_w: string, row. :return: True, if all are legal format. """ if len(input_w) != 7: return False for i in range(len(input_w)): if i % 2 == 0: if not input_w[i].isalpha(): return False elif i % 2 != 0: if input_w[i] != ' ': return False if i == len(input_w)-1: return True
def _indent(input_str: str, indentation: int = 2) -> str: """Indents a string by the specified number of spaces, defaulting to 2.""" spaces = " " * indentation lines = input_str.split("\n") # Prepend spaces to each non-empty line. lines = [f"{spaces}{line}" if len(line) else line for line in lines] return "\n".join(lines)
def el(tag_type, *content): """ Returns a list of strings that represents an HTML element. If the first argument passed to *content is a dict, then the dict is unpacked into attribute pairs for the element. >>> el('div', {'class' : 'navbar'}, "This is my Navbar!") ['<div class="navbar">', 'This is my Navbar!', '</div>'] """ result = [] try: # if content exsists if isinstance(content[0], dict): attrs_dict, content = content[0], content[1:] attrs_pairs = [] for key in attrs_dict: attrs_pairs.append('%s="%s"' % (key, attrs_dict[key])) attrs_string = " ".join(attrs_pairs) open_tag = "<%s %s>" % (tag_type, attrs_string) else: open_tag = "<%s>" % tag_type except IndexError: # if content is empty open_tag = "<%s>" % tag_type close_tag = "</%s>" % tag_type result.append(open_tag) for item in content: result.append(item) result.append(close_tag) return result
def nature_validation(nature): """ Decide if the nature input is valid. Parameters: (str): A user's input to the nature factor. Return: (str): A single valid string, such as "1", "0" or "-5" and so on. """ while nature != "5" and nature != "4" and nature != "3" and nature != "2" and nature != "1" and nature != "0" and nature != "-1" and nature != "-2" and nature != "-3" and nature != "-4" and nature != "-5" : print("\nI'm sorry, but " + nature + " is not a valid choice. Please try again.") nature = input("\nHow much do you like nature? (-5 to 5)" + "\n> ") return nature
def check_time(time, min, max): """ Check time submitted by user to make sure time is correct and follows a correct format :param time: time requested by user :param min: min possible value :param max: max possible value :return: """ if int(time) >= min and int(time) <= max: return True else: return False
def circle_bbox(coordinates, radius=5): """the bounding box of a circle given as centriod coordinate and radius""" x = coordinates[0] y = coordinates[1] r = radius return (x - r, y - r, x + r, y + r)
def vec2spec_dict(n_bins, vec, spectra): """Take a vector of power spectra and return a power spectra dictionnary. vec should be of the form [spectra[0], spectra[1], ... ]. For example [cl_TT,cl_TE,cl_ET, ...., cl_BB] Parameters ---------- n_bins: int the number of bins per spectrum vec: 1d array an array containing a vector of spectra spectra: list of strings the arrangement of the spectra for example: ['TT','TE','TB','ET','BT','EE','EB','BE','BB'] """ return {spec: vec[i * n_bins:(i + 1) * n_bins] for i, spec in enumerate(spectra)}
def validate_input_json(data, expected): """Validates json recieved from request Args: data (): json recieved from request expected (dict): json format expected from request Returns: bool: state of validity, True if good request str: reason for validity int: request status code """ # Validates input json is as expected # Initialize response assuming all correct valid = True message = "Input json is valid." code = 200 # OK # Ensure type data is dict if type(data) != dict: valid = False message = "Data entry is not in dictionary format." code = 400 # Bad Request return valid, message, code # Ensure keys in data are same as expected for key in data: if key not in expected: valid = False message = "Dictionary keys are not in correct format." code = 400 # Bad Request return valid, message, code for key in expected: if key not in data: valid = False message = "Dictionary does not have enough " \ "information. Missing keys." code = 400 # Bad Request return valid, message, code # Ensure value types in data are same as expected for key in expected: if type(data[key]) not in expected[key]: valid = False message = "Dictionary values are not correct. Invalid data types." code = 400 # Bad Request return valid, message, code return valid, message, code
def get_cookie_value(cookies, cookie_name): """Gets a cookies value Arguments: cookies {request.cookies/dict} -- dictionary of cookies cookie_name {str} -- the cookies to retreive Returns: [str] -- returns the value of the item if the cookies exists else returns empty string """ try: return cookies[cookie_name] except: return ""
def addbreaks(text): """:addbreaks: Any text. Add an XHTML "<br />" tag before the end of every line except the last. """ return text.replace('\n', '<br/>\n')
def callable(object: object) -> bool: """callable.""" return hasattr(object, '__call__')
def generate_definition_list(op, prefix): """Generate a definition listing.""" ret = [] if isinstance(op, (list, tuple)): for ii in op: ret += [prefix + ii] elif isinstance(op, str): ret += [prefix + op] else: raise RuntimeError("weird argument given to definition list generation: %s" % (str(op))) return ret
def sec2hms(x, precision=0, mpersist=True): """ CONVERTS decimal seconds to hours : minutes : seconds """ out = '' if x > 60: if x > 3600: h = int(x / 3600) out = '%d:' % h x = x - 3600 * h m = int(x / 60) out += '%d:' % m x = x - 60 * m elif mpersist: out = '0:' if precision == None: fmt = '%g' elif precision == 0: fmt = '%d' else: fmt = '%%.%df' % precision s = fmt % x if (x < 10) and mpersist: s = '0' + s out += s return out
def cdpro_input_header(firstvalue, lastvalue, factor): """ :returns: Multiline string mimicking cdpro output """ firstvalue = '{:0.4f}'.format(firstvalue) lastvalue = '{:0.4f}'.format(lastvalue) header = ("# \n" "# PRINT IBasis \n" " 1 0\n" "# \n" "# ONE Title Line \n" " Title\n" "# \n" "# WL_Begin WL_End Factor \n" " {first} {last} 1.0000\n" "# \n" "# CDDATA (Long->Short Wavelength; 260 - 178 LIMITS \n" ).format(first=lastvalue, last=firstvalue) return header
def state_to_props(state): """Map state to props relevant to component""" return state.get("colorbar", None)
def afla_pasul(mesaj): """ Afla pasul encodarii """ first_letter = 'a' my_letter = mesaj[0] return ord(my_letter) - ord(first_letter)
def set_swfac(name: str) -> float: """ name is cfmt.vocalfont.name :param name: :return: """ swfac = 1.0 if name == "Times-Roman": swfac = 1.00 if name == "Times-Bold": swfac = 1.05 if name == "Helvetica": swfac = 1.10 if name == "Helvetica-Bold": swfac = 1.15 return swfac
def record_pct(A): """ Input: list (list of tuples) - list of tuples of record percents Returns: record_pct (integer) - record percentage """ middle = list() for i in range(len(A)): possible = 1 for j in range(len(A[i])): possible *= A[i][j] middle.append(possible) record_pct = 0 for i in range(len(middle)): record_pct += middle[i] return record_pct
def to_file_descriptor(fobj): """ Converts an object to a file descriptor. The given object can be either: - An integer file descriptor - An object with a ``fileno()`` method. :raises ValueError: If the given object cannot be converted. >>> class Descriptable: ... def fileno(self): ... return 42 ... >>> to_file_descriptor(Descriptable()) 42 >>> to_file_descriptor(42) 42 >>> try: ... to_file_descriptor(object()) ... except ValueError: ... print('Failure') ... Failure """ if isinstance(fobj, int): return fobj elif hasattr(fobj, 'fileno'): return fobj.fileno() else: raise ValueError( '{} cannot be converted to a file descriptor'.format(fobj))
def adder_function(args): """Dummy function to execute returning a single float.""" loc, scale = args return loc + scale
def convert_mwh_bbtu(value: float) -> float: """converts energy in MWh to energy in billion btu. :param value: value in megawatt-hours of energy :type value: float :return: value in bbtu """ bbtu = value * 0.003412 return bbtu
def moment_from_muad(mu, A, d): """moment = mu * A * d :param mu: shear modulus, in Pa :type mu: float :param A: area, in m^2 :type A: float :param d: slip, in m :type d: float :returns: moment, in Newton-meters :rtype: float """ return mu*A*d;
def clean_alphanumeric(text): """ If text has any non-alphanumeric characters, replace them with a hyphen. """ text_clean = '' for charc in text: text_clean += charc if charc.isalnum() else '-' return text_clean
def represents_int(string: str): """Checks if a `string can be turned into an integer Args: string (str): String to test Returns: bool """ try: int(string) return True except ValueError: return False
def minimum_tls_version(supported_protocols): """Returns the minimum supported TLS version""" result = None tls_versions = ['ssl2', 'ssl3', 'tls10', 'tls11', 'tls12', 'tls13'] tls_versions_pretty = ['sslv2', 'sslv3', 'tls 1.0', 'tls 1.1', 'tls 1.2', 'tls 1.3'] for i, v in enumerate(tls_versions): if supported_protocols[v] == "1": result = tls_versions_pretty[i] break return result
def format_number(number): """Format numbers for display. if < 1, return 2 decimal places if <10, return 1 decimal places otherwise, return comma formatted number with no decimal places Parameters ---------- number : float Returns ------- string """ if number == 0: return "0" if number < 0.01: return "< 0.01" if number < 1: round1 = int(number * 10) / 10 if round1 == number: return f"{round1:.1f}" else: number = int(number * 100) / 100 return f"{number:.2f}" if number < 10: if int(number) == number: return f"{number:.0f}" number = int(number * 10) / 10 if int(number) == number: return f"{number:.0f}" return f"{number:.1f}" return f"{number:,.0f}"
def say_hello(name: str = "World"): """ This is the docstring to the 'say_hello' function """ return "Hello {}".format(name)
def is_valid_seq(seq, max_len=2000): """ True if seq is valid for the babbler, False otherwise. """ l = len(seq) valid_aas = "MRHKDESTNQCUGPAVIFYWLO" if (l < max_len) and set(seq) <= set(valid_aas): return True else: return False
def detect_entry_fold(entry, folds): """Detect entry fold. Args: entry (str): Entry string folds (int): Number of folds Returns: int: Entry fold index """ entry_id = entry.split("[")[0] for i in range(len(folds)): if entry_id in folds[i]: return i return None
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] return hp, cp, ro == 'ro' else: hp, cp = parts[0], parts[1] return hp, cp, False else: return None, v, False result = {} if volumes: for vol in volumes: host_path, container_path, read_only = parse_volume(vol) if host_path: result[host_path] = { 'bind': container_path, 'ro': read_only } return result
def _pdbcls_callback(x): """Validate the debugger class string passed to pdbcls.""" message = "'pdbcls' must be like IPython.terminal.debugger:TerminalPdb" if x in [None, "None", "none"]: x = None elif isinstance(x, str): if len(x.split(":")) != 2: raise ValueError(message) else: x = tuple(x.split(":")) else: raise ValueError(message) return x
def reinsertList(lst,selection,insert_row,current_index=0): """ Generic implementation for reinserting a set of elements. lst : a list of items (data type not important) selection : list/set of indices of elements in lst insert_row : an integer index into lst current_index : index of the current song, optional returns the new list, actual insert row, number of selected items and the updated current index. selects the set of items in selection in the order in which they appear in lst. These items are then insert at insert_row. removal / insertion may change the actual index of insert_row and current_index so these values will be recalculated accordingly """ lsta = [] lstb = [] idx = 0; insert_offset = 0; # for updating current idx new_index = -1; for item in lst: if idx in selection: # if we need to update the current idx after drop if idx == current_index: insert_offset = len(lstb) # if the selection effects insert row if idx < insert_row: insert_row -= 1 lstb.append(item) else: if (idx == current_index): new_index = len(lsta) lsta.append(item) idx += 1; # insert row must be in range 0..len(lsta) insert_row = min(insert_row, len(lsta)) if new_index < 0: new_index = insert_row + insert_offset; elif insert_row <= new_index: new_index += len(lstb) if insert_row < len(lsta): lsta = lsta[:insert_row] + lstb + lsta[insert_row:] else: lsta = lsta + lstb return (lsta, insert_row, insert_row+len(lstb), new_index)
def get_machine_type(machine_type, accelerator_count): """Get machine type for the instance. - Use the user-specified machine_type if it is not None - Otherwise, use the standard type with cpu_count = 8 x accelerator_count if user-specified accelerator_count > 0 - Otherwise, use the standard type with 8 cpu Args: machine_type: machine_type specified by the user accelerator_count: accelerator count Returns: the machine type used for the instance """ if machine_type: return machine_type cpu_count = max(accelerator_count, 1) * 8 return 'n1-standard-{}'.format(cpu_count)
def adcStr_to_dict(args, curr_cfg=None): """Handler for `adcCfg`""" if curr_cfg: cfg = curr_cfg else: cfg = {} if int(args[1]) == 1: cfg['isComplex'] = True cfg['image_band'] = False #print('[NOTE] Complex 1x mode, Only Real IF Spectrum is filtered and sent to ADC, so if Sampling rate\n' # ' is X, ADC data would include frequency spectrum from 0 to X.') elif int(args[1]) == 2: cfg['isComplex'] = True cfg['image_band'] = True #print('[NOTE] Complex 2x mode, both Imaginary and Real IF spectrum is filtered and sent to ADC, so\n' # ' if Sampling rate is X, ADC data would include frequency spectrum from -X/2 to X/2.') else: raise ValueError("Real Data Type Not Supported") return cfg
def _make_split_name(prefix, num, neededChars): """ Construct a split name from a prefix, a number, and the number of characters needed to represent the number. :param prefix: the prefix or None. :param num: the zero-based index. :param neededChars: the number of characters to append before the file extension. :returns: a file path. """ if prefix is None: prefix = './' suffix = '.tif' for _ in range(neededChars): suffix = chr((num % 26) + 97) + suffix num //= 26 return str(prefix) + suffix
def define_a_plot_name(plot_idx): """Define unique plot name""" return f"PP" + str(plot_idx).zfill(8)
def _utf8_decode(b): """Decode (if needed) to str. Helper for type conversions among DataObjStr and DataObjBytes. """ if isinstance(b, bytes): return b.decode(encoding="utf-8") elif isinstance(b, str): return b else: raise TypeError("Argument must be 'bytes' or 'str'")
def phugoid_rating(phugoid_damping, ph_t2): """ Give a rating of the phugoid mode : Level1 Level2 or Level 3 according to MILF-8785C Args: phugoid_damping (float) : [-] ph_t2 (float): phugoid time to double amplitude [s] Returns: 1 one 2 or 3 corresponding to the flight level """ if 0.04 < phugoid_damping : ph_rate = 1 elif 0 < phugoid_damping < 0.04 : ph_rate = 2 elif 55 <= ph_t2 : ph_rate = 3 else: ph_rate = None return ph_rate
def string_response(s, encoding='utf-8'): """Convert string to WSGI string response.""" return [bytes(s, encoding)]
def two_bounce(alphas, x0, xp0, x1, z1, x2, z2, z3): """ Calculates the x position of the beam after bouncing off two flat mirrors. Parameters ---------- alphas : tuple Tuple of the mirror pitches (a1, a2) in radians x0 : float x position of the source in meters xp0 : float Pitch of source in radians x1 : float x position of the first mirror in meters z1 : float z position of the first mirror in meters x2 : float x position of the second mirror in meters z2 : float z position of the second mirror in meters z3 : float z position of imager """ result = 2*alphas[0]*z1 - 2*alphas[0]*z3 - 2*alphas[1]*z2 + \ 2*alphas[1]*z3 + z3*xp0 - 2*x1 + 2*x2 + x0 return result
def solve(ver1, op1, ver2, op2): """Solve conflicts.""" ver1_t = tuple(ver1.split(".")) ver2_t = tuple(ver2.split(".")) if op1 == "==": if op2 == "==": return ver1_t == ver2_t, f"{ver1} != {ver2}" if op2 == ">=": return ver1_t >= ver2_t, f"{ver1} < {ver2}" return True, ""