content
stringlengths
42
6.51k
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 valide_Lambda(Lambda) : """ Valide si Lambda est entre .5 et 1""" return (Lambda >= .5) and (Lambda < 1)
def factorial(n): """ This function calculates n! by the simplest method imaginable n: input integer f: return value """ f = 1 #the smallest factorial is 1 for i in range(2,n+1): #starting from 2 and stopping at n f *= i return f
def create_make_command(keyboard, keymap, target=None): """Create a make compile command Args: keyboard The path of the keyboard, for example 'plank' keymap The name of the keymap, for example 'algernon' target Usually a bootloader. Returns: ...
def next_char(char): """Return next character. >>> next_char('a') 'b' """ return chr(ord(char) + 1)
def ERR_ALREADYREGISTRED(sender, receipient, message): """ Error Code 462 """ return "ERROR from <" + sender + ">: " + message
def get_entity_name(s): """ Detect entity name from the raw entity string. :param s: Entity string :return: entity name """ tokens = s.split("/") name = tokens[3] return name
def to(value,dtype): """Force conversion to int data type. If failed return 0: dtype: int8, int32, int64""" isfloat = "float" in str(dtype) try: return dtype(value) except: return 0 if not isfloat else 0.0
def my_extract(value, delim=',', index=0): """Split a given string and return value at given index position.""" return value.split(delim)[index]
def is_geq_than(x,y): """ x is not None and greater than or equal to y """ if x != None: if x>=y: return True return False
def splitDataset(data, column, valuetoDivide): """ This function takes in the data and the value to divide on and splits the dataset into two divisions (postiive and negative), which will be assigned to the left/right childs of the dataset equivalently """ positiveSet = [row for row in data ...
def assocs(labels): """ Converts a list of labels to a dictionary. """ d = {} for label in labels: d[label["name"]] = label["value"] return d
def _extract_extldflags(gc_linkopts, extldflags): """Extracts -extldflags from gc_linkopts and combines them into a single list. Args: gc_linkopts: a list of flags passed in through the gc_linkopts attributes. ctx.expand_make_variables should have already been applied. -extldflags may app...
def build_regexp(searchline, strictsearch): """ construct regexp for search """ # building regexp for search if strictsearch: # ver 0.0 # searchline= "^%(lookupstr)s\s|\s%(lookupstr)s\s|\s%(lookupstr)s$" % { "lookupstr": searchline } # ver 0.1 searchline= "^%(lookupstr)s([^a-...
def scale_01(x, vmin=-1, vmax=1): """scale to 0 - 1""" return (x - vmin) / (vmax - vmin)
def _flatten_and_tokenize_metadata(encoder, item): """ Turn the article into tokens :param item: Contains things that need to be tokenized fields are ['domain', 'date', 'authors', 'title', 'article', 'summary'] :return: dict """ metadata = [] for key in ['domain', 'date', 'authors', 'ti...
def hammingdistance(string, reference): """ Given two sequences, find the hamming distance. """ answer = 0 if (len(string) == len(reference)): for i in range(len(string)): if string[i] != reference[i]: answer += 1 else: answer = -1 return answer
def index_of(val, listOfVals): """ Useful method for lists (returns -1 instead of ValueError when value not in list) """ try: index = listOfVals.index(val) except ValueError: index = -1 return index
def box(text: str, lang: str = "") -> str: """Get the given text in a code block. Parameters ---------- text : str The text to be marked up. lang : `str`, optional The syntax highlighting language for the codeblock. Returns ------- str The marked up text. "...
def create_matrix(nr_rows, nr_cols): """ Create a 2d list of size """ matrix = [[0 for i in range(nr_cols)] for j in range(nr_rows)] return matrix
def _VerifyDirectoryIterables(existing, expected): """Compare two iterables representing contents of a directory. Paths in |existing| and |expected| will be compared for exact match. Args: existing: An iterable containing paths that exist. expected: An iterable of paths that are expected. Raises: ...
def bend_stress(mom, y, i): """ bend_stress(mom, y, i) Returns the bending stress given the applied moment, distance to the centroid, and moment of inertia. """ return mom * y / i
def create_get_global_settings_payload(plugin_context: str): """Create and return "getGlobalSettings" dictionary to send to the Plugin Manager. Args: plugin_context (str): An opaque value identifying the plugin/Property Inspector. Received during the plugin registration procedure. Retu...
def pipe1(value0, *bodys): """Perform a sequence of operations on an initial value. Bodys are applied left to right. Each body must be a 1-argument function. It takes the current value, and it must return the next value (the last body, the final value). Examples. Given:: double = lambda ...
def create_login_url(path): """Returns the URL of a login page that redirects to 'path' on success.""" return "/auth/hello?redirect=%s" % path
def hammingSimilarity(l1=[], l2=[]): """ computes hamming similarity """ hammingD = 0 nsensors = len(l1) # using the total number of non-zero sensors per odor nNonZero = len(l1) # nsensors = len(l1) for i in range(0, nsensors): if l1[i] != l2[i]: hammingD += 1 if l1[...
def date_to_json(pydate, manager): """Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor. """ if pydate is None: return None else: return dict( year=pydate.year, month=pydate.month - 1, # Mon...
def knight_amount(board, player): """ Returns the amount knights a player has :param board_state: multidimensional list defining the game state :param player: **numeric** integer defining player :return: **numeric** how many knights the player owns on that game state """ knight_amt = 0 ...
def make_form_error(message): """Turn a string into an error that looks like a WTForm validation error. This can be used to generate one-off errors, like auth errors, that need to be displayed in the same space as WTForm validation errors. """ # WTForm errors are stored in a dict. Keys are the fiel...
def clean_end_spaces(text): """ Remove spaces at the end of lines >>> clean_end_spaces("a \\n \\n b \\n") 'a\\n\\n b\\n' """ while " \n" in text: text = text.replace(" \n", "\n") while text and text[-1] == " ": text = text[:-1] return text
def get_workflow_name(workflowType): """ Given a workflowType, return the name of a corresponding workflow class to load """ return "workflow_" + workflowType
def get_user(user_id, users): """ Returns given user id from all id """ for user in users: _id = user.get("_id") if _id == user_id: return user return {}
def offsetRect(rect, dx, dy): """Offset a bounding box rectangle. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to offset the rectangle along the X axis. dY: Amount to offset the rectangle along the Y axis. Returns: ...
def lon360_2lon180(lon): """ convert from 0-360 to -180 - 180 :param lon: :return: """ return (lon+180)%360-180
def merge(source: dict, destination: dict) -> dict: """ Perform a "deep" merge of the two dictionaries """ for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) merge(value, node) ...
def split_coords_(str): """\ Split the str in position 1 for each element in the argument """ return str.split(' ')
def param_name(p): """Extract parameter name from attributes. Examples: - ``fix_x`` -> ``x`` - ``error_x`` -> ``x`` - ``limit_x`` -> ``x`` """ prefix = ['limit_', 'error_', 'fix_'] for prf in prefix: if p.startswith(prf): return p[len(prf):] return p
def getattr_or_subscribe(instance, name): """Get an attribute from a class instance or a value from a dictionary. :param dict|object instance: :param str name: name of attribute or dictionary key :return any: """ try: return getattr(instance, name) except AttributeError: try...
def get_threshold(obj_name, mode): """ The default values correspond to ~66th percentile of obj_name ("qed", "plogp") on ChEMBL dataset, hence, "low" mode chooses value below that percentile, and "high" mode above that percentile. """ if obj_name == "qed": if mode == "low": r...
def com_arrays(x,y): """This Function return x intersection y""" return [var for var in x if var in y]
def tong_pso(n): """Tinh tong 1/1+1/2+1/3+...+1/n""" sum = 0 for i in range(1,n+1): sum+=1/i return sum
def __find_service_account_in_message(message): """ The command "gcloud logging sinks create", communicates a service account Id as part of its message. Knowing the message format, this function extracts the service account Id and returns it to the caller, which will grant it with BQ per...
def pre_shape_params(n_samples): """Generate pre shape benchmarking parameters. Parameters ---------- n_samples : int Number of samples to be used. Returns ------- _ : list. List of params. """ manifold = "PreShapeSpace" manifold_args = [(3, 3), (5, 5)] modu...
def input_upload_image(field, mime_types="image/jpg,image/jpeg,image/png"): """Return HTML markup for a image upload input.""" return {"field": field, "mime_types": mime_types}
def strip_locals(data): """Returns a dictionary with all keys that begin with local_ removed. If data is a dictionary, recurses through cleaning the keys of that as well. If data is a list, any dictionaries it contains are cleaned. Any lists it contains are recursively handled in the same way. """...
def deduplicate_listoflists(listoflists): """ Remove double ups in lists. Parameters ---------- arg1: list of lists Exceptions ---------- None Usage ----- deduplicate_listoflists([['test'], ['test']]) Returns ------- [['test']] ...
def cast_elements_to_numeric( splitted_lines: list, float_sep=(",", "."), minus_sign=("-") ) -> dict: """helper function for casting str to numeric in a list of lists""" result = {} for n, elem in enumerate(splitted_lines): if isinstance(elem, list) and len(elem) == 2: key, value = ...
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" return (perimeter * apothem) / 2
def find_threshold_value(energy_element="Au", above_or_below="above", modality="esrf"): """We return the energy corresponding attenuation value used for bone segmentation Args: energy_element (str): what k-edge element are we trying to quantify (Au, I, Gd..) above_or_below (str): aobe or below ...
def read(table, **kwargs): """ Generates SQL for a SELECT statement matching the kwargs passed. """ sql = list() sql.append("SELECT * FROM %s " % table) if kwargs: sql.append("WHERE " + " AND ".join("%s = %s" % (k, repr(v)) for k, v in kwargs.items())) sql.append(";") return "".join(sql)
def remove_number(words): """remove numbers""" new_words = [] for word in words: if not word.isdigit(): new_words.append(word) return new_words
def check(inp, sol): """Check an input string against a solution string, returning a human-readable message as output, detailing either the results or an error message.""" if len(inp) != len(sol): return "!Invalid length (Required: %s)" % len(sol) black,white = 0,0 fuzzy = set(inp) for i in range(0,l...
def parse_file(txt): """extract todo lines from a file >>> parse_file("# todo: foo\\n foo") [' foo'] """ res = [] for line in txt.split('\n'): if line.strip().startswith('#'): #valid possible for token in ['todo:']: stpoint = line.lower().fin...
def to_dict(object, attrs): """Generate dictionary with specified attributes.""" output = {} for attr in attrs: if hasattr(object, attr): if ":" in attr: # to remove the part before the colon: e.g. OS-FLV-EXT-DATA:ephemeral # to match the output of comman...
def is_alphabet(ch): """ """ code = ord(ch) return 0x3041 <= code <= 0x3093 or \ 0x30a1 <= code <= 0x30f3 or \ 0xac00 <= code <= 0xd7af or \ 0x1100 <= code <= 0x11ff or \ 0x3130 <= code <= 0x318f or \ 0xa960 <= code <= 0xa97f or \ 0xd7b0 <= code <= 0xd7ff ...
def user_model(username, oidc_config, audience='generic_horse'): """Return a user model""" return { 'iss': oidc_config['issuer'], 'aud': audience, 'sub': username, 'username': username, 'scope': 'basic', 'resource_access': { 'generic_horse': { ...
def tupledate_to_isodate(tupledate): """ Turns a gregorian (year, month, day, hour, minute, nearest_second) into a standard YYYY-MM-DDTHH:MM:SS ISO date. If the date part is all zeros, it's assumed to be a time; if the time part is all zeros it's assumed to be a date; if all of it is zeros it's tak...
def _unpack_one_element_list(scalar_or_list): """If the value is a list and it only has one value, we unpack it; otherwise, we keep the list. This is used for size parameter inside tf.io.SparseFeature. """ if isinstance(scalar_or_list, list) and len(scalar_or_list) == 1: return scalar_or_lis...
def combined_dict(*dicts): """Combine one or more dicts into a new, unified dict (dicts to the right take precedence).""" return {k: v for d in dicts for k, v in d.items()}
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def generate_file_path(taxi: str, year: str, month: str) -> str: """Generate target file path""" return f"{taxi}_tripdata_{year}-{month}.parquet"
def poly2d(co, x, y): """ co contains the 10 coefficents of the cubic bivariate polynomial """ return co[0] + co[1]*x + co[2]*y + co[3]*x**2 + co[4]*x*y + co[5]*y**2 +co[6]*x**3 + co[7]*x**2*y + co[8]*x*y**2 + co[9]*y**3
def add_odd_par(b): """ The chess link protocol is 7-Bit ASCII. This adds an odd-parity-bit to an ASCII char :param b: an ASCII character (0..127) :returns: a byte (0..255) with odd parity in most significant bit. """ byte = ord(b) & 127 par = 1 for _ in range(7): bit = byte & 1...
def _hex_to_bin(hex_message: str) -> str: """ Converts message from hex to bin Args: hex_message (str) Returns bin_message (str) """ bits = len(hex_message[2:]) * 4 bin_message = bin(int(hex_message, 16))[2:] return "0b" + bin_message.zfill(bits)
def platform_matches(requested_platform: str, specific_platform) -> bool: """ Compare two platforms. Common platforms: - Windows - macos / darwin / osx - linux - unix (macos, sunos, bsd unix's) - *nix / posix (not windows) :return: True if current platform matches requested platform...
def get_number_of_nucleotides( string ): """ returns the number of nucleotides ([ATCGN-]) within the string. """ string = string.upper() return string.count( 'A' ) + string.count( 'T' ) + string.count( 'C' ) + string.count( 'G' ) + string.count( 'N' ) + string.count( '-' )
def vector_mul(k, a): """Multiplication of a vector by a scalar. >>> vector_mul((1, 2), 2) (2, 4) """ return tuple(map(lambda x: k * x, a))
def _max_item(d: dict) -> int: """ find largest len item of a dict :param d: dict[key: list] :return: int """ largest = 0 for i in d.values(): temp = len(i) if temp > largest: largest = temp return largest
def less_than_version(value): """ Converts the current version to the next one for inserting into requirements in the ' < version' format """ items = list(map(int, str(value).split('.'))) if len(items) == 1: items.append(0) items[1] += 1 return '.'.join(map(str, items))
def get_UA(maxValence_list, valence_list): """ """ UA = [] DU = [] for i, (maxValence, valence) in enumerate(zip(maxValence_list, valence_list)): if not maxValence - valence > 0: continue UA.append(i) DU.append(maxValence - valence) return UA, DU
def _get_payout(player: int, dealer: int) -> float: """Calculates the payout for the given hand totals. Args: player: The hand total of the player. dealer: The hand total of the dealer. Returns: The payout of the payout. """ if player > 21: return -1. if dealer ...
def all_equal(s): """Return whether all elements in a list are equal.""" return len(set(s)) <= 1
def get_name_parts(au): """ Fares Z. Najar => last, first, initials >>> get_name_parts("Fares Z. Najar") ('Najar', 'Fares', 'F.Z.') """ parts = au.split() first = parts[0] middle = [x for x in parts if x[-1] == '.'] middle = "".join(middle) last = [x for x in parts[1:] if x[-1]...
def getWordsUntilLength(t, maxLength): """take words until maxLength is reached >>> getWordsUntilLength('this is a test', 60) u'this is a test' >>> getWordsUntilLength('this is a test', 7) u'this is' >>> getWordsUntilLength('this is a test', 2) u'this' """ t = t.replace(',', '') t ...
def checkP(board, intX, intY, newX, newY): """Check if the pawn move is legal, returns true if legal""" tmp=False if abs(intX-newX)<=1: if board[intY-1][intX-1][0]=='W':#Checks for white pawns if intY==7 and intY-newY==2 and intX==newX and board[newY][newX-1]=='OO': ...
def parser_system_clock_Descriptor(data,i,length,end): """\ parser_system_clock_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "system_clock", "contents" : unparsed_descriptor_contents } (De...
def _calc_padding_for_alignment(align, base): """ Returns byte padding required to move the base pointer into proper alignment """ rmdr = int(base) % align if rmdr == 0: return 0 else: return align - rmdr
def _uint_size_in_bytes(x): """ Compute the number of bytes needed to hold an unsigned integer of arbitrary length. Needed for DER re-encoding """ assert type(x) is int, "`x` should be of type `int`" assert 0 <= x, "`x` should be >= 0" size = 0 while True: x >>= 8 size +...
def return_intersect(cameraList): """ Calculates the intersection of the Camera objects in the *cameraList*. Function returns an empty Camera if there exists no intersection. Parameters: cameraList : *list* of *camera.Camera* objects A list of cameras from the camera.Camera class, e...
def is_scalar_integer(value): """ e.g. 10, -2 """ return type(value) == int
def is_sublist_of(sublist, given): """ Returns whether the sublist is part of the given combination. The order of the sublist must also correspond to the order of the corresponding part in the given combination.""" lenght = len(sublist) startposition = 0 while startposition <= len(give...
def select_favorite_sdist_release(sdist_releases): """ Selects one sdist from a list while prioritizing the file suffixes (tar.gz, tgz, zip, tar.bz2) (left == better). If multiple filenames with same suffix exist, the shortest filename is picked """ sdist_releases = list(sdist_releases) f_ty...
def extract_domains(email_addresses): """ Returns a list of email domains extracted from list of email addresses Parameters ---------- email_addresses: list, required Email addresses are dict of type { "address" : "recipient1@domain.test" } Returns ------- list list of em...
def swap32(x): """Swap bytes in 32 bit integer.""" return (((x << 24) & 0xFF000000) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | ((x >> 24) & 0x000000FF))
def unique4(s): """Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?""" # Time complexity is O(n^2), no space n = len(s) for i in range(0, n): for j in range(i + 1, n): if s[i] == s[j]: r...
def _check_role(brain, match_kind, match, target_dict, cred_dict): """Check that there is a matching role in the cred dict.""" return match.lower() in [x.lower() for x in cred_dict['roles']]
def find_exact_match_for_login_id(search_results, target_login_id): """The Canvas user search API results do not return only exact matches, so this function filters search results for an exact match only. search_results -- List of user objects returned by Canvas user search API. target_login_id -- Canv...
def u_b97(x, gamma, polarized=False): """Evaluates auxiliary quantity u for B97-based functionals. 10.1063/1.475007. Args: x: Float numpy array with shape (num_grids,), the reduced density gradient. gamma: Float, parameter. polarized: Boolean, whether the system is spin polarized. Returns: Flo...
def query_drop_index(index): """Generate drop query for index with name 'index'""" return 'DROP INDEX IF EXISTS ' + index
def hyphenate(path): """Replaces underscores with hyphens""" return path.replace('_', '-')
def get_ascii_sum(text): """Returns the sum of the ascii values of a string Args: **text (str)**: string of which to get the ascii value Returns: The sum of the ascii values of the string provided """ sum = 0 for c in text: sum += int(ord(c)) return sum
def find_index_list(inputlist, key): """get a list of index for key in inputlist""" start = 0 indexlist = [] while 1: try: index = inputlist.index(key, start) except: break indexlist.append(index) start = index + 1 return indexlist
def unique_pairs(l1, l2): """ Given two lists, identify unique pairings for elements where the same element may not be repeated. Args ---- l1: list l2: list """ return list({ tuple(sorted([x,y])) for x in l1 for y in l2 if x!=y })
def parseNum(num): """0x is hex, 0b is binary, 0 is octal. Otherwise assume decimal.""" num = str(num).strip() base = 10 if (num[0] == '0') & (len(num) > 1): if num[1] == 'x': base = 16 elif num[1] == 'b': base = 2 else: base = 8 return int(num, base)
def dict_pick(content, key, value, needle=True): """Find match in a list of dicts based on key/value.""" item = next((item for item in content if item[key] == value), None) if item and needle: return item['value']
def _avoid_me(my_body,our_moves): """ my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake. e.g. [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0}] possible_moves: List of strings. Moves to pick from. e.g. ["up", "down", "left", "right"] return...
def is_data(value): """Return whether the value is a wrapped data descriptor.""" return value is not None and value.is_data
def dec_to_set(row): """Convert the dec columns into a set, and fix the sign. """ if '-' in row['sign']: return (-1*row['dec_deg'],row['dec_minutes'],row['dec_seconds']) else: return (row['dec_deg'],row['dec_minutes'],row['dec_seconds'])
def get_remaining(headers): """ Get the ratelimit header. """ remain = headers.get("X-Rate-Limit-Remaining", None) if remain is None: remain = headers.get("X-RateLimit-Remaining", None) if remain is None: return 0 try: remain = int(remain) except ValueError: ...
def route_for_task(name, args, kwargs, options, task=None, **kw): """ Custom task router for queues """ if ":" in name: queue, _ = name.split(":") return {"queue": queue}