content
stringlengths
42
6.51k
def prime_factors(n): """Return a list of prime factors for a given number in ascending order.""" factors = [] p = 2 if n < 2: return factors while n >= (p * p): if n % p: p += 1 else: n = n // p factors.append(p) factors.append(n) ...
def insert_newline(matrix): """ Format matrix with newlines adter each sub list """ s_matrix = str(matrix) matrix = s_matrix.replace("], ", "],\n") return matrix
def is_decl(line: str) -> bool: """Whether an XIR line is a declaration or an include statement. Args: line (str): a single line from an XIR script Returns: bool: whether the line is a declaration or an include statement """ if not set(line.split()).isdisjoint({"gate", "out", "obs"...
def parse_msiinfo_suminfo_output(output_string): """ Return a dictionary containing information from the output of `msiinfo suminfo` """ # Split lines by newline and place lines into a list output_list = output_string.splitlines() results = {} # Partition lines by the leftmost ":", use the s...
def generate_conanfile_txt(requires, build_requires, generators) -> str: """Generate contents of a ``conanfile.txt``.""" text = '' if requires: text += '[requires]\n' text += ''.join(f'{line}\n' for line in requires) if build_requires: text += '[build_requires]\n' text +=...
def clean_equivalency_dict(d): """Clean equivalency dict from connected component algorithm.""" for key, val in d.items(): d[key] = d[val] return d
def vels(speed, turn): """ Function to get current velocity (speed and heading direction) :param speed: linear velocity (m/sec) :param turn: heading direction (radians) :return: typeset string useful for displaying current velocity :rtype: string """ return "currently:\tspeed %s\tturn %...
def encode_name(param): """ Encodes the given param description into a valid enum name. :param param: :return: """ sname = param # replace all kind of unwanted chars in a python dictname. sname = sname.strip() for ch in ['/', ' + ', ' ', '#', '&', '-', ',', '+', ]: if ch in s...
def clean_lccn(value): """Following the logic/examples described at: http://lccn.loc.gov/lccnperm-faq.html#n9 http://www.loc.gov/marc/lccn-namespace.html""" # remove all blanks value = value.replace(' ', '') # if there's a forward slash, remove it and all characters to its right if '/' i...
def get_type_default_value(prop_type: str): """ Returns the default value of the given Haxe type. If the type is not supported, `None` is returned: """ if prop_type == "Int": return 0 if prop_type == "Float": return 0.0 if prop_type == "String" or prop_type in ( ...
def adjust_lr(lr, lrd=10, log=None): """ Update learnign rate. :param lr: original learning rate. :param lrd: decrease ratio of learning rate. :param log: if log is not None, print the comments for changing learning rate. :return lr: adjusted learning rate. """ lr = lr / lrd pri...
def format_dictionary_element_name(parent, key): """ Format a string representation dictionary and key formatted as <parent>['<key>'} :param parent: name of dictionary :param key: key to element in dictionary :return: string representation of element """ return str(parent) + '[' + str(key) +...
def convert_special_characters_to_html_entities(value): """ encode special characters HTML encoding to make it a little harder to scrape """ CONVERSION_MAPPING = [ ('@', '&#64;'), ('.', '&#46;'), ('_', '&#95;'), ('-', '&#45;'), ('(', '&#40;'), (')', '&#41;'), ...
def question_answers(conversations): """ Divide the dataset into two sets: questions and answers. """ questions, answers = [], [] for convo in conversations: for index in range(len(convo) - 1): questions.append(convo[index]) answers.append(convo[index + 1]) assert len(que...
def my_sum(iterable): """Calculating a sum""" tot = 0 for i in iterable: tot += i return tot
def effective_col_set(col_set, prev_col_set): """Computes the effective collision set to use given the current collision set and the collision set used to get to the current node Only makes sense when used with recursive M* The purpose of this code is that in recursive M*, you invoke a subp...
def elaborateanswer(question): """ Give an elaborate, realitisc and Michael-Palin-like answer to the question `question`. Examples: --------- >>> elaborateanswer("Do you have some cheddar?") 'No.' >>> elaborateanswer("The camembert is indeed runny.") '<Nods.>' """ if questio...
def _unnesttemplatelist(tree): """Expand list of templates to node tuple >>> def f(tree): ... print(pycompat.sysstr(prettyformat(_unnesttemplatelist(tree)))) >>> f((b'template', [])) (string '') >>> f((b'template', [(b'string', b'foo')])) (string 'foo') >>> f((b'template', [(b'strin...
def TimeToInt( time_string ): """ Function used to convert a time-string into an integer. Args: time_string ( string ): the time-string. Returns: int: the converted time-string into int. Testing: >>> TimeToInt( "2022.03.14 09:20:00.000" ) 20220314092000000 ...
def mean_percentage_error_implementation(y_true, y_pred): """Calculate MPE Arguments: y_true {list} -- real numbers, true values y_pred {list} -- real numbers, predicted values """ # intialize error at 0 error = 0 # loop over alll samples in true and predicted list for yt, y...
def get_health_check(app, portIndex): """Get the healthcheck for the app.""" checks = [] for check in app.get('healthChecks', []): if check.get('port') or check.get('portIndex') == portIndex: checks.append(check) if len(checks) > 0: return checks return None
def getXtitle(input): """ returns paper-ready y axis name """ x_axis_title = { "parallel_requests": "Concurrent Connections", "QPS": "QPS" } return x_axis_title[input]
def get_LZW_dictionnary(L): """This slightly modified version of the LZW compression algorithm return a dictionnay of sequences encountered in L with their count of occurence. :param L: a list where a pattern is hidden :type L: list(int) :return: the dictionnary of patterns with their count of oc...
def empty(level): """ To generate empty space needed for shaping the tree""" s = "" for x in range(level): s += " " return s
def bisect_left(a, x, lo=0, hi=None, key=lambda x: x): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the left...
def _correct_folder(folder: str) -> str: """Ensures the folder follows a standard. Pathlib.parent in the root folder results in '.', whereas in other places we should use '' for the root folder. This function makes sure the root folder is always empty string. Args: folder: the folder to be corrected. ...
def get_rounds(number): """ :param number: int - current round number. :return: list - current round and the two that follow. """ return [number + i for i in range(3)]
def is_valid(line): """verificam daca linia este valida""" line = line.split() if len(line) < 1: return False if line[0] not in ["STANGA", "DREAPTA", "SUS", "JOS"]: return False try: int(line[1]) return True except ValueError: return False return Tru...
def keys_exists(element, *keys): """ Check if *keys (nested) exists in `element` (dict). """ if not isinstance(element, dict): raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError( 'keys_exists() expects at least t...
def my_sum(a: int, b: int, c: int): """ >>> my_sum.cmd("1 2 3") 6 >>> my_sum.cmd(["4", "5", "6"]) 15 >>> my_sum.cmd(["a", "b", "c"]) Traceback (most recent call last): ... SystemExit: 2 """ return a + b + c
def rework_args(args): """Rework args to be able to exclude list of tags (pybot hack)""" # first loop to distinguish between previous, --exclude, and next args prev_args = [] next_args = [] found_next_arg = False parse_next_args = False excluded_tags_string = None for arg in args: ...
def fullwidth(st): """\ Return the fullwidth version of the given string. """ ret = "" if not st: return ret for c in st: i = ord(c) if c == " ": ret += chr(0x3000) elif 0x21 <= i <= 0x7f: ret += chr(i - 0x21 + 0xff01) else: ret...
def dsname(exp='xpptut15', run='0001') : """Returns (str) control file name, e.g. 'exp=xpptut15:run=1' for (str) exp and (str) of (int) run """ if isinstance(run, str) : return 'exp=%s:run=%s' % (exp, run.lstrip('0')) elif isinstance(run, int) : return 'exp=%s:run=%d' % (exp, run) else : return No...
def skip_bits(page, nbits): """ Skip bits for a given page """ # compute relative shifting and complementary shifting values rel_shift = int(nbits%8) comp_shift= int(8 - rel_shift) # skip nbits/8 bytes first page = page[int(nbits//8):] page += bytes([0]) if rel_shift > 0: ...
def intersect_two_lists(list1, list2): """ intersects two lists of np.arrays""" result = [] for item2 in list2: for item1 in list1: if (item2.shape == item1.shape) and (item2 == item1).all(): result.append(item2) break return result
def corresponding_bracket(s, bracket): """ Given the index of a left or right bracket character, return the index of the correspoding bracket character in s. Assumes that all brackets are enclosed properly. Returns None if the index of a bracket is not given. Examples: >>> s = '(((a)))' ...
def forbidden_challenge_decider(environ, status, headers): # pylint: disable=W0613 """ Newer pyramid versions return 403 instead of 401 when a forbidden view is accessed. This prevents the standard `repoze.who.classifiers:default_request_classifier` from doing the right thing and a challenge is neve...
def sentence_tokenizer(raw_data): """Returns the list of the sentences. :param raw_data: gets codecs.open("..../filename", 'r', 'utf-8').read() :return: list of sentences """ ############# nltk line line ayirma islemi kodu ###################### # sent_detector = nltk.data.load('tokenizers/pun...
def removespecchar(test): """Function to Clean Up Strings. Specifically gets rid of quotes,tabs,new lines, and evens out the spaces.""" import re if type(test) == str: test=re.sub('\t',' ',test) test=re.sub('\"',' ',test) test=re.sub('\n',' ',test) test=re.sub('\r',' ',t...
def cleanup_io_name(name): """Cleanup op names.""" pos = name.find(":") if pos >= 0: return name[:pos] return name
def _superclasses(obj, cls): """return remaining classes in object's MRO after cls""" mro = type(obj).__mro__ return mro[mro.index(cls)+1:]
def override_key(key) -> str: """Handles the fn key for macs""" if str(key) == "<179>" or str(key) == "<63>": return "Key.fn" if str(key) == "'\\\\'": return "'\\'" return str(key)
def _get_jobs_names(jobs, deps): """Returns a list of dict {"job_id":"Si"}, where Si is the new id of job with id job_id.""" starting_jobs=[] all_dest=[] for some_dep in list(deps.values()): all_dest+=some_dep all_dest = sorted(list(set(all_dest))) for job in jobs: job_id=jo...
def apply_func_to_cutout(patch, mult_by, add_to): """function to be used in cutout test""" return mult_by * patch + add_to
def test_file_type(filename): """ Tests whether the given filename is a C++ header or implementation file (based on the filename extension.) """ pos = filename.rfind(".") if (pos >= 0): ext = filename[pos+1:] else: ext = "" return ext in ["c", "C", "cpp", "CPP", "c++", "C++", "h", "H", ...
def autoapi_skip_member(app, what, name, obj, skip, options): """Exclude all private attributes, methods, and dunder methods from Sphinx.""" import re exclude = re.findall("\._.*", str(obj)) or "stdout" in str(obj).lower() return skip or exclude
def seq_concat_seq(a, b): """Concatenate two sequences: ``a + b``. Returns: Sequence: The return value will depend on the largest sequence - if b is larger and is a tuple, the return value will be a tuple. - if a is larger and is a list, the return value will be a list, """ ...
def find_longest_element(element_list): """find longest element in the list Parameters ---------- element_list : list Returns ------- longest element in the list """ longest_element = '' for element in element_list: if len(element) > len(longest_element): ...
def process_opts(opts): """Process and enrich command line arguments Args: opts (dict): dictionary of parameters Returns: dict: dictionary of parameters from command line arguments """ # Remove options with None values opts = {k: v for k, v in opts.items() if v is not None} r...
def preconvert_bool(value, name): """ Converts the given `value` to an acceptable boolean by the wrapper. Parameters ---------- value : `int` The value to convert. name : `str` The name of the value. Returns ------- value : `str` Raises ------ ...
def feature_name(n): # pragma: no cover """normalize a feature name as encountered as column header in features.tsv converts camel case into space separated lowercase words. """ chars = [] for char in n: if char.isupper(): chars.append(' ' + char.lower()) else: ...
def bind(port: int) -> dict: """Request browser port binding. Parameters ---------- port: int Port number to bind. """ return {"method": "Tethering.bind", "params": {"port": port}}
def row_start_index(index): """ get index of the start of the 0x10 byte row containing the given index """ return index - (index % 0x10)
def to_base36(n): """ Return string representation of n in base 36 (use 0-9 and a-z) """ div, mod = divmod(n, 36) if mod <= 9: last_digit = str(mod) else: last_digit = chr(ord('a') + mod - 10) if n == mod: return last_digit else: return to_base36(div)+last...
def get_cuda_gpu_arch(cuda_cc): """Return CUDA gpu ARCH in LAMMPS required format. Example: 'sm_32' """ # Get largest cuda supported return 'sm_%s' % str(sorted(cuda_cc, reverse=True)[0]).replace(".", "")
def ljust_list(_list, length, fill_word=None): """ Similar to ljust but for list. Usage: $ ljust_list([1, 2, 3], 5) > [1, 2, 3, None, None] """ # make a copy to avoid mutation of passed list _list = list(_list) fill_length = length - len(_list) if fill_length > 0: _list.extend([fill_word] * fill_length) ...
def get_groups_of_a_user(username, all_groups): """ Get the groups of one user. Output contains strings like: [u'2A G42', u'2A IL 2'] Possible enhancement: the groups fetched need to not contain """ users_groups = list() for group in all_groups: members = all_groups[group] ...
def process_model(current_val): """ :param current_val: model generated by sat solver, atom is satisfied if in modal. :return tuple of sets comprising true and false atoms. """ true_atoms, false_atoms = set(), set() for atom in current_val: if current_val[atom]: true_atoms....
def square_dist(x, u): """Args: :int: x, num. :int: u, mean.""" return (x - u) ** 2
def tcp_opts_tuple_list_to_dict(opts_list: list) -> dict: """Convert tuple of TCP options to a dictionary :param opts_list: list of TCP options tuple :return: diction of TCP options """ opts = {} if None in opts_list: opts_list.remove(None) for opt, value in opts_list: # here...
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ total = 1 while k > 0: total *= n n-=1 k-=1 return tota...
def hash_values(input_list): """ maps/codes a list into integers :param input_list: enumerable of hashable elements """ hash_map = dict() for val in input_list: hash_map[val] = hash_map.get(val, len(hash_map)) return [hash_map[val] for val in input_list]
def convert_to_seconds(hms_time): """ convert '00:01:12' to 72 seconds. :hms_time (str): time in comma separated string, e.g. '00:01:12' :return (int): time in seconds, e.g. 72 """ times = [float(t) for t in hms_time.split(":")] return times[0] * 3600 + times[1] * 60 + times[2]
def makelist(seq): """Make list from string When comma or space is used, they are used as separators""" seq = seq.strip() if ',' in seq: seq = seq.replace(',', ' ') if ' ' in seq: seq = seq.split() seq = list(seq) return seq
def parseRating(line): """ Parses a rating record in MovieLens format userId::movieId::rating::count . """ fields = line.strip().split("::") return int(fields[3]), (int(fields[0]), int(fields[1]), float(fields[2]))
def maze_twisty_trampolines_v1(s): """A Maze of Twisty Trampolines, All Alike ---.""" steps = 0 cursor = 0 maze = s[:] l = len(maze) while True: if cursor < 0 or cursor >= l: break instruction = maze[cursor] maze[cursor] += 1 cursor += instruction ...
def maybe_quote_ws(value): """Surrounds a value with single quotes if it contains whitespace. """ if value is None: return value if any(x == ' ' or x == '\t' for x in value): return "'" + value + "'" return value
def base_circle_centre(m, y, c): """ This function returns the intersection of perpendicular bisector with the base line. Parameters ---------- m : slope y : y-cooordinate of the base line. c : y-intercept of the perpendicular bisector. """ return (y-c)/m
def _get_installers_from_configuration(configs): """Get installers from configurations. Example: { <installer_isntance>: { 'alias': <instance_name>, 'id': <instance_name>, 'name': <name>, 'settings': <dict pass to installer plugin> } } """...
def box(text, gen_text=None): """Create an HTML box of text""" if gen_text: raw_html = '<div style="padding:8px;font-size:28px;margin-top:28px;margin-bottom:14px;">' + str( text) + '<span style="color: red">' + str(gen_text) + '</div>' else: raw_html = '<div style="border-botto...
def json_as_python_set(dct): """Decode json {'_set_object': [1,2,3]} to set([1,2,3]) Example ------- decoded = json.loads(encoded, object_hook=json_as_python_set) Also see :class:`JSONSetEncoder` """ if '_set_object' in dct: return set(dct['_set_object']) return dc...
def _get_schema_table_name_map(table_name): """a method to split a qualified table into it's parts """ parts = table_name.split('.') schema_index = 1 table_index = 2 if len(parts) == 2: schema_index = 0 table_index = 1 return {'schema': parts[schema_index].lower(), 'table_...
def ms2knot(ws_ms): """ Convert unit of wind speed from meter per seconds to knots. Examples --------- >>> ws_knot = kkpy.util.ms2knot(ws_ms) Parameters ---------- ws_ms : array_like Array containing wind speed in **m/s**. Returns --------- ws_knot ...
def mode(numbers): """ Calculate mode of a list numbers. :param numbers: the numbers :return: mode number of the numbers. >>> mode([1, 2, 2, 3, 4, 7, 9]) 2 """ max_count = 1 mode_number = numbers[0] for number in numbers: count = 0 for temp in numbers: ...
def maybe_int(x): """Try to convert x' to int, or return x' if that fails.""" try: return int(x) except ValueError: return x
def process_special_annotation(v, lin): """ If the user wants a fancy annotation, like 'add middle column', this gets processed here. it's potentially the place where the user could add entropy score, or something like that. """ if v.lower() not in ['i', 'index', 'm', 'scheme', 't', 'q']: ...
def _getAction(sBase): """Get action from base url. Basically return the URL with no GET params""" n = sBase.find('?') if n != -1: return sBase[:n] else: return sBase
def get_range(size): """returns a range spanning from 1 to size size -- number of elements in the range """ return range(1, size+1)
def forge_block_header_data(protocol_data): """ Returns a binary encoding for a dict of the form `{'block_header_data: string}`, as expected by the protocol. This corresponds to the encoding given by `data_encoding.(obj1 (req "block_header_data" string))`. See `lib_data_encoding/data_encoding.m...
def check_float(potential_float): """Check if the passed argument is a valid float""" try: float(potential_float) return True except ValueError: return False
def escape_html(unsafe): """ Escape unsafe HTML entities @type unsafe: str @rtype: str """ return unsafe.replace('&', "&amp;")\ .replace('<', "&lt;")\ .replace('>', "&gt;")\ .replace('"', "&quot;")\ .replace("'", "&#039;")
def create_couples(persons): """ Create a list of couples without duplicate Args: persons (list[str]): Returns: list[set(str)] """ list_of_couples = [] for p1 in persons: for p2 in persons: couple = {p1, p2} if couple not in list_of_couples: ...
def distinct_words(X): """ Diagnostic function :param X: :return: >>> dl = distinct_words([['the', 'quick', 'brown'], ['here', 'lies', 'the', 'fox']]) >>> sorted(dl) ['brown', 'fox', 'here', 'lies', 'quick', 'the'] """ return set([word for sentence in X ...
def cents_to_decimal(cents): """ Used to turns clickbank amounts (in cents) to decimal number """ if cents: return float(cents) / 100
def reversed_hit(locus_list, decoy_string): """Checks if any proteins are reversed (decoy) entries. """ rev = False for loci in locus_list: if decoy_string in loci.ID: rev = True return rev
def timezone(zone): """Try to get timezone using pytz or python-dateutil :param zone: timezone str :return: timezone tzinfo or None """ try: import pytz return pytz.timezone(zone) except ImportError: pass try: from dateutil.tz import gettz return gett...
def disrete_logarithm(answer, base, mod): """ Compute x where answer == pow(base, x, mod). Some notes: * This is done by linearly searching, so don't actually use this for real cryptographic applications * This probably won't do what you think it does if base isn't a primitiv...
def num2tuple(num): """Convert an input number to a tuple of (num, num).""" return num if isinstance(num, tuple) else (num, num)
def or_sum (phrase): """Returns TRUE iff one element in <phrase> is TRUE""" for x in phrase: if x: return True return False
def norm_layer_name(name): """Some heuristics to normalize a layer name from multiple sources. For example, some depictions of VGG-16 use use upper case; others use lower case. Some use hyphens; others use underscores. These heuristics are by no means complete, but they increase the likelihood that...
def list_contains(list, filter): """Example: if list_contains(a_list, lambda x: x.n == 3) # True if any element has .n==3""" for x in list: if filter(x): return True return False
def read_filesys(etrans_save_fs, etrans_locs): """ get the lj params thar are saved currently in the filesystem """ _, _ = etrans_save_fs, etrans_locs sigmas, epsilons, geoms = [], [], [] return sigmas, epsilons, geoms
def tonative(n, encoding='ISO-8859-1'): """Return the given string as a native string in the given encoding.""" # In Python 3, the native string type is unicode if isinstance(n, bytes): return n.decode(encoding) return n
def CustomSearch(start_token, func, end_func=None, distance=None, reverse=False): """Returns the first token where func is True within distance of this token. Args: start_token: The token to start searching from func: The function to call to test a token for applicability end...
def ConvertBoolean(value): """ Attempt to convert value to a boolean. If the value is not a possible boolean string the result will return None instead of True or False. :param value: Value which should be checked as a boolean. :return: True or False if the value is recognized, or None if it is not...
def get_firmware(myjson): """ Get Firmware version from Json Payload """ firmware_text = "Unknown" if 'type' in myjson: if myjson['type'] == 'device_status' or myjson['type'] == 'hub_status': if 'firmware_revision' in myjson: firmware_text = "Firmware Ver " + str(myjson['...
def is_tls_record_magic(d): """ Returns: True, if the passed bytes start with the TLS record magic bytes. False, otherwise. """ d = d[:3] # TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2, and TLSv1.3 # http://www.moserware.com/2009/06/first-few-milliseconds-of...
def wget(url, dest=None): """ Downloads a web resource using wget. :type url: string :param url: Url to download. :type dest: string :param dest: Optional. Destination in our machine of the downloaded resource. """ return ["wget --no-check-certificate " + url + ("" if dest == None ...
def sentiment_lable(score): """ The function sentiment_lable() is to label the sentiment categories based on polarity score calculated by VADER model. :param score: float :return: string, sentiment label """ if score >= 0.05: return 'positive' elif score <= -0.05: return 'neg...
def build_lookup_dict_snmp_trap(list_content): """ Build key/value lookup dict specifically for SNMP Traps which use "server-ip" + "version" :param list_content: List of dicts to derive lookup structs from :return: lookup dict """ lookup_dict = {} for item in list_content: item_serv...