content
stringlengths
42
6.51k
def normalize_project_name(project): # pragma: no cover """Return the canonical name for a project specification.""" mapping = { 'nacl': 'nativeclient', 'cros': 'chromium-os', } return mapping.get(project, project)
def fullname(obj): """Returns full name of object""" if hasattr(obj, '__module__'): module = obj.__module__ else: module = obj.__class__.__module__ if hasattr(obj, '__name__'): name = obj.__name__ else: name = obj.__class__.__name__ if module is None or module == ...
def int_to_c(k, x_width): """ Takes an integer and a width and returns a complex number. """ ik = k >> x_width qk = k % pow(2, x_width) maxint = pow(2, x_width)-1 i = ik * 2.0 / maxint q = qk * 2.0 / maxint if i > 1: i -= 2 if q > 1: q -= 2 return i + (0+1j)*q
def fibonacci_series_from_to(m, n): """This function calculates the fibonacci series from the "m"th element until the "n"th element Args: m (int): The first element of the fibonacci series required n (int): The last element of the fibonacci series required Retu...
def searchCatchwords(string): """ Splits String (at '_', '-' and '.' and searches for non-digit strings that are longer than 2 characters. Arguments: string (string): The string to be searched. """ #Exceptions that should not be considered Catchwords exceptions = [...
def max_value(table): """ brief: give max number of a list Args: table: a list of numeric values Return: the max number the index max number Raises: ValueError if table is not a list ValueError if table is empty """ if not(isinstance(table, list)): ...
def extract_submittable_jobs( waiting ): """Return all jobs that aren't yet submitted, but have no dependencies that have not already been submitted.""" submittable = [] for job in waiting: unsatisfied = sum([(subjob.submitted==0) for subjob in job.dependencies]) if unsatisfied == 0: ...
def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 ...
def process_group(grp): """ Given a list of list of tokens, of the form "A B ... C (contains x, y, z)" where A, B, C are strings of ingredients, and x, y, z are allergens, determine the count of the ingredients that definitely do not contain any allergens. :param grp: A list of list of ...
def count(values): """ Returns a dict of counts for each value in the iterable. """ counts = dict() for v in values: if v not in counts: counts[v] = 0 counts[v] += 1 return counts
def linear_rampup(current, rampup_length): """Linear rampup""" assert current >= 0 and rampup_length >= 0 if current >= rampup_length: lr = 1.0 else: lr = current / rampup_length # print (lr) return lr
def fnv1a_32(string: str, seed=0): """ Returns: The FNV-1a (alternate) hash of a given string """ #Constants FNV_prime = 16777619 offset_basis = 2166136261 #FNV-1a Hash Function hash = offset_basis + seed for char in string: hash = hash ^ ord(char) hash = hash * FNV_...
def gettype(a): """ Distinguish between a number and a string: Returns integer 1 if the argument is a number, 2 if the argument is a string. """ import re type1 = re.compile("(^[+-]?[0-9]*[.]?[0-9]+$)|(^[+-]?[0-9]+[.]?[0-9]*$)|(^[+-]?[0-9]?[.]?[0-9]+[EeDd][+-][0-9]+$)") if type1.ma...
def slug_from_id(page_id: str) -> str: """Extract Notion page slug from the given id, e.g. lwuf-kj3r-fdw32-mnaks -> lwufkj3rfdw32mnaks.""" return page_id.replace("-", "")
def _method_with_pos_reference_2(fake_value, other_value, another_fake_value=2): """ :type other_value: [list, dict, str] """ return other_value.lower()
def IsInteger(Value): """Determine whether the specified value is an integer by converting it into an int. Arguments: Value (str, int or float): Text Returns: bool : True, Value is an integer; Otherwsie, False. """ Status = True if Value is None: return F...
def convert_request_to_hashtag_list(title): """ description Parameters ---------- title : str i.e. "#covid #vaccination" Returns ------- [str] i.e. [covid, vaccination] """ cleaned_hashtags = [] if ' ' in title: hashtags = ...
def fix_walletserver_url(url: str) -> str: """ Help guide users against including api version suffix in wallet server URL. """ for suffix in ["/api/v1/", "/api/v1", "/api/", "/api", "/"]: if not url.endswith(suffix): continue print( f'There\'s no need to add "{suf...
def pressure_to_elevation(pressure: float, p0: float) -> float: """ Calculate the elevation for a given pressure. Args: pressure: The pressure, in hPa (mbars) p0: P0, the pressure at sea level. Returns: Elevation in meters """ return (1 - ((pressure / p0) **...
def keyfunc(line): """Return the key from a TAB-delimited key-value pair.""" return line.partition("\t")[0]
def eval_expr(expr): """ Evaluate an expression without parantheses. """ current = "".join(expr) result = 1 for subexpr in current.split("*"): result *= eval(subexpr) return result
def has_numbers(inputString): """Check if there is a number in a string list and return True or False.""" return any(char.isdigit() for char in inputString)
def translate_to_hsv(in_color): """ Standard algorithm to switch from one color system (**RGB**) to another (**HSV**). :param tuple(float,float,float) in_color: The RGB tuple list that gets translated to HSV system. The values of each element of the tuple is between **0** and **1**. :return: The transl...
def _node_parent_listener(target, value, oldvalue, initiator): """Listen for Node.parent being modified and update path""" if value != oldvalue: if value is not None: if target._root != (value._root or value): target._update_root(value._root or value) target._upda...
def validate_config(config): """Validates config""" errors = [] required_config_keys = [ 'aws_access_key_id', 'aws_secret_access_key', 's3_bucket' ] # Check if mandatory keys exist for k in required_config_keys: if not config.get(k, None): errors.appe...
def calc_timeout(length, baud): """Calculate a timeout given the data and baudrate Positional arguments: length - size of data to be sent baud - baud rate to send data Calculate a reasonable timeout given the supplied parameters. This function adds slightly more time then is needed, to...
def flatten(groups): """Flatten a list of lists to a single list""" return [item for group in groups if group is not None for item in group if item is not None]
def null_bytes_to_na(string): """ (str -> str) replace strings of only null bytes (\x00) with "n/a". for M3L0 line prefix tables. """ if all([char == "\x00" for char in string]): return "n/a" return string
def make_hashable_list(lst: list) -> tuple: """ Recursively converts lists to tuples. >>> make_hashable_list([1, [2, [3, [4]]]]) (1, (2, (3, (4,)))) """ for n, index in enumerate(lst): if isinstance(index, list): lst[n] = make_hashable_list(index) return tuple(lst)
def distance_greater(vec1, vec2, length): """Return whether the distance between two vectors is greater than the given length.""" return ((vec1[0] - vec2[0])**2 + (vec1[1] - vec2[1])**2) > length**2
def job_id(username): """ The id of the RQ job that is processing this user. Redis key becomes `rq:job:{job_id(username)}`. """ return f'reddrec:recommend:{username.lower()}'
def get_deployment_endpoint(project, deployment): """Format endpoint service name using default logic. Args: project: str. Name of the deployed project. deployment: str. Name of deployment - e.g. app name. Returns: endpoint_name: str. Endpoint service name. """ return "{deployment}.endpoints.{pr...
def count_frequency(word_list): """ Count the frequency of each word in the list by scanning the list of already encountered words. """ D = dict() for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D
def find_artifact(artifacts, name): """Finds the artifact 'name' among the 'artifacts' Args: artifacts: The list of artifacts available to the function name: The artifact we wish to use Returns: The artifact dictionary found Raises: Exception: If no matching...
def market_on_close_order(liability): """ Create market order to be placed in the closing auction. :param float liability: amount to bet. :returns: Order information to place a market on close order. :rtype: dict """ return locals().copy()
def check_collision_h(x,y,vx,eyes): """ eyes = [lx,ly,rx,ry] """ if ( (eyes[1] < y) and (y < eyes[3]) and (abs(x - eyes[0]) < abs(vx)) ): return 2.0 * (y - eyes[1]) / (eyes[3] - eyes[1]) - 1 else: return None
def is_palindrome(s: str) -> bool: """ Determine whether the string is palindrome :param s: :return: Boolean >>> is_palindrome("a man a plan a canal panama".replace(" ", "")) True >>> is_palindrome("Hello") False >>> is_palindrome("Able was I ere I saw Elba") True ...
def case_lower(text): """ a function to convert English letters to lower case """ return text.lower()
def hilite(string, status, bold): """ Converts string color to be either red or green """ attr = [] if status: # green attr.append('32') else: # red attr.append('31') if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
def construct_hostname(region, account): """ Constructs hostname from region and account """ if region: if account.find(u'.') > 0: account = account[0:account.find(u'.')] host = u'{0}.{1}.snowflakecomputing.com'.format(account, region) else: host = u'{0}.snowflake...
def colorGlobalRule(scModel, edgeTuples): """ :param scModel: :param edgeTuples: :return: """ found = False for edgeTuple in edgeTuples: op = scModel.getGroupOperationLoader().getOperationWithGroups(edgeTuple.edge['op'], fake=True) if op.category == 'Color' or (op.groupedCat...
def get_output_ext(data): """ Detects output extension based on file signature """ ext = ".bin" if data[:3] == b'GIF': ext = ".gif" elif data[1:4] == b'PNG': ext = ".png" return ext
def is_list_of_type(check_list, check_type): """helper function for checking if it's a list and of a specific type""" assert isinstance(check_list, list) assert isinstance(check_list[0], check_type) return True
def _path_from_name(name, type): """Expand a 'design/foo' style name to its full path as a list of segments. """ if name.startswith('_'): return name.split('/') design, name = name.split('/', 1) return ['_design', design, type, name]
def rect_center(rect): """Return the centre of a rectangle as an (x, y) tuple.""" left = min(rect[0], rect[2]) top = min(rect[1], rect[3]) return (left + abs(((rect[2] - rect[0]) / 2)), top + abs(((rect[3] - rect[1]) / 2)))
def iseven(number): """ Convenience function to determine if a value is even. Returns boolean value or numpy array (depending on input) """ result = (number % 2) == 0 return result
def convertfrom_epoch_time(epoch_time: "int | float"): """Takes a given epoch timestamp int or float and converts it to a datetime object. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( now )\n >>> ...
def score(hand): """ Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. hand: full yahtzee hand Returns an integer score """ scoreboard = {} for dice in hand: if dice not in scoreboard.keys(): scoreboard[dice] = d...
def is_sorted(lyst): """ This function test if a list is sorted and returns true if it is """ result = True for num in range(1, len(lyst)): if lyst[num-1] > lyst[num]: result = False return result
def flatten(lst): """Flatten `lst` (return the depth first traversal of `lst`)""" out = [] for v in lst: if v is None: continue if isinstance(v, list): out.extend(flatten(v)) else: out.append(v) return out
def stringify_dict(_dict): """make all dict values to be string type""" new_dict = dict((key, str(value)) for key, value in _dict.items()) print(new_dict) return new_dict
def vowel_rule(word): """ If word starts with vowel, just add "way" to the end. Args: word (str): Word to translate. Returns: (str): Translated word. """ return word + "way"
def nicenum(num): """Return a nice string (eg "1.23M") for this integer.""" index = 0; n = num; while n >= 1024: n /= 1024 index += 1 u = " KMGTPE"[index] if index == 0: return "%u" % n; elif n >= 100 or num & ((1024*index)-1) == 0: # it's an exact multiple of its index, or it wouldn't # fit as float...
def compose_maxmin(R, S): """ X = {1: 0, 2: 0.2, 3: 0.4} Y = {1: 0, 2: 0.2} Relation (X*Y) = {(1, 1): 0, (1, 2): 0, (2, 1): 0, (2, 2): 0.04, (3, 1): 0, (3, 2): 0.08} :param R: a dictionary like above example that :param S: a dictionary like above example :return: RoS a composition of R to S ...
def odder(num: int) -> int: """Forces a number to be odd""" if num % 2 == 0: num += 1 return int(num)
def normalize_message(message): """Takes in a tuple message and converts it to a list, then lower cases it.""" message = list(message) for index, i in enumerate(message): i = i.lower() message[index] = i return message
def remove_empty_paragraphs(paragraphs): """ Removes empty paragraphs from a list of paragraphs """ return [para for para in paragraphs if para != ' ' and para != '']
def arr_to_string(arr: list, cutoff=float('inf')) -> str: """ Converts arr to string table, with cutoff length of characters arr is given as an array of arrays of strings, all of arbitrary length. expects every string in its list to have the same length e.g. arr [ ['line 1', 'line 2'], ...
def dict_merge(*dicts): """ Merge all provided dicts into 1 dict. *dicts : `dict` dictionaries to merge """ merged = {} for d in dicts: merged.update(d) return merged
def calc_relevance_scores( n, rel_measure ): """ Utility function to compute a sequence of relevance scores using the specified function. """ scores = [] for i in range(n): scores.append( rel_measure.relevance( i + 1 ) ) return scores
def floatToString(inp): """ Print a float nicely. """ return ("%.15f" % inp).rstrip("0").rstrip(".")
def color_reducer(c1, c2): """Helper function used to add two colors together when averaging.""" return tuple(v1 + v2 for v1, v2 in zip(c1, c2))
def is_sequence_of_type(sequence, t): """Determine if all items in a sequence are of a specific type. Parameters ---------- sequence : list or tuple The sequence of items. t : object The item type. Returns ------- bool True if all items in the sequence are of th...
def subsystem_item(subsystem, methods, services): """Function that sets the correct structure for subsystem item""" subsystem_status = 'ERROR' sorted_methods = [] if methods is not None: subsystem_status = 'OK' for method_key in sorted(methods.keys()): sorted_methods.append(m...
def L10_indicator(row): """ Determine the Indicator of L10 as one of five indicators """ if row < 40: return "Excellent" elif row < 50: return "Good" elif row < 61: return "Fair" elif row <= 85: return "Poor" else: return "Hazard"
def get_tail(text, tailpos, numchars): """Return text at end of entity.""" wheretoend = tailpos + numchars if wheretoend > len(text): wheretoend = len(text) thetail = text[tailpos: wheretoend] return thetail
def partition(arr, start, end, i_pivot): """ Partition the arr between [start, end) using the given index i_pivot :param arr: The list to partition. :param start: Start element. :param end: End element. :param i_pivot: The index of the pivot element. """ if not arr: return None ...
def get_black_and_white_rgb(distance: float) -> tuple: """ Kode warna hitam putih yang mengabaikan jarak relatif. Mandelbrot set berwarna hitam, yang lainnya putih. >>> get_black_and_white_rgb(0) (255, 255, 255) >>> get_black_and_white_rgb(0.5) (255, 255, 255) >>> get_black_and_white_rgb...
def get_project_id_from_service_account_email(service_account_email: str) -> str: """ Get GCP project id from service_account_email >>> get_project_id_from_service_account_email('cromwell-test@tob-wgs.iam.gserviceaccount.com') 'tob-wgs' """ # quick and dirty return service_account_email.spl...
def identhashtype(srcHash): """ Identifies the hash function type Now supports: MD5, SHA256, SHA512 :param srcHash: hasf as a string with hexadecimal digits :return: hash type -MD5, SHA256 or SHA512- as a string """ #calculation of bits length of the hexdigest try: lenBits = le...
def get_feature_filename( feature_extractor_name, h_stride, v_stride, feature_height, fov): """Returns a filename given feature map parameters.""" return "features_{}_h-{}_v-{}_height-{}_fov-{}.sstable@100".format( feature_extractor_name, h_stride, v_stride, feature_height, fov)
def get_wind(bearing): """get wind direction""" if (bearing <= 22.5) or (bearing > 337.5): bearing = u'\u2193 N' elif (bearing > 22.5) and (bearing <= 67.5): bearing = u'\u2199 NE' elif (bearing > 67.5) and (bearing <= 112.5): bearing = u'\u2190 E' elif (bearing > 112.5) and...
def get_size_bytes(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= fac...
def is_submodule(line): """Return True if the line is a valid submodule statement.""" if len(line) < 2: # XXX: This is just to prevent index error in the next test # Not entirely sure what this ought to be, come back to it... return False if (line[0], line[1]) != ('submodule', '('...
def _is_valid_kwarg(provided: dict, available: dict): """ Helper function to check if a user provided dictionary has the correct arguments, compared to a dictionary with the actual available arguments. Updates, if no difference found, the dictionary 'available'. Parameters ---------- provi...
def mirror(spine_pos, pos): """ This function . Parameters: spine_pos (int): the position of the spine. pos (int): the position of the middle of the image. Returns: spine_pos + (spine_pos - pos) or spine_pos - (pos - spine_pos) (int): mirror the sp...
def dupCounts(setList,pdup_cnt,opdup_cnt,opdupset_cnt,flagFA,dropOp): """This function calculates various counts and returns a list of counts.""" dupset_num = 0 for item in setList: if len(item) > 1: opdup_cnt += len(item) opdupset_cnt += 1 dupset_num += 1 ...
def hexstr_to_bytes(value): """Return bytes object and filter out formatting characters from a string of hexadecimal numbers.""" return bytes.fromhex(''.join(filter(str.isalnum, value)))
def cp_cmtsolution2structure(py, cmtsolution_directory, base_directory): """ cp cmtsolution files in cmtsolution_directory to the simulation structure. """ script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.cp_cmtsolution2structure --cmtsolution_directory {cmtsolution_directory} --base_dire...
def is_hidden_cell(cell: dict) -> bool: """ Checks if a cell is hidden. :param line: The cell to be checked. :returns: True if the cell contains is hidden. """ try: if cell["metadata"]["jupyter"]["source_hidden"] is True: return True else: return False ...
def maximum_grade(parsed_list, passing_grade, overall_max=True): """ This function calculates the maximum grade from the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_max: True, when calculating the maximum of all th...
def deep_tuple(l): """ Convert lists of lists of lists (...) into tuples of tuples of tuples, and so on. """ if type(l) != list: return l return tuple(deep_tuple(a) for a in l)
def web_tile_zoom_out(zxy): """ Compute tile at lower zoom level that contains this tile. """ z, x, y = zxy return (z-1, x//2, y//2)
def convert_service_to_p(tot_s_y, s_fueltype_tech): """Calculate fraction of service for every technology of total service Arguments ---------- tot_s_y : float Total yearly service s_fueltype_tech : dict Service per technology and fueltype Returns ------- s_tech_p :...
def end(n, d): """Print the final digits of N in reverse order until D is found. >>> end(34567, 5) 7 6 5 """ while n > 0: last, n = n % 10, n // 10 print(last) if d == last: return None
def generate_path(start, ref, nonref, stop): """ Given source, sink, and ref/non-ref nodes enumerate all possible paths """ ref_path = [x for x in [start, ref, stop] if x != "0"] nonref_path = [x for x in [start, nonref, stop] if x != "0"] return [ref_path, nonref_path]
def sort(seq): """ Tool function for normal order, should not be used separately Args: seq (list): array Returns: list: integer e.g. swapped array, number of swaps """ swap_counter = 0 changed = True while changed: changed = False for i in range(len(seq)...
def xorstrings(str1, str2): """Xor 'str1' [bytes] with 'str2' [bytes].""" res = [] for i in range(min(len(str1), len(str2))): res.append(str1[i] ^ str2[i]) return bytes(res)
def longestCommonPrefix(*sequences): """ Returns longest common prefix occuring in given sequences Reference: http://boredzo.org/blog/archives/2007-01-06/longest-common-prefix-in-python-2 >>> longestCommonPrefix('foobar', 'fobar') 'fo' """ if len(sequences) == 1: return sequences[0...
def convert_key(value): """convert a source file keyname value to a value usable for HotKeys """ w_shift = value.startswith('S-') w_ctrl = value.startswith('C-') if w_shift or w_ctrl: value = value[2:] test = {'Left': '', 'Up': '', 'Right': '', 'Down': '', 'Home': '', 'PageDo...
def normalize_token(token_name: str) -> str: """ As of click>=7, underscores in function names are replaced by dashes. To avoid the need to rename all cli functions, e.g. load_examples to load-examples, this function is used to convert dashes back to underscores. :param token_name: token name p...
def find_last_slash_pos_in_path(path): """ Find last slash position in a path exampe : files = find_last_slash_pos_in_path("./audioFiles/abc.wav") output : integer the value that is the position of the last slash """ import os LastSlashPos = path.rfind(os.path.split(path)[-1]) - 1 ...
def get_flag_param_decals_from_bool(option_name: str) -> str: """Return a '--do/not-do' style flag param""" name = option_name.replace("_", "-") return f'--{name}/--no-{name}'
def make_game(serverid, name, extras=None): """Create test game instance.""" result = { 'serverid': serverid, 'name': name, 'game_state': {'players': {}, 'min_players': 2, 'max_players': 4}, } if extras: result.update(extras) return result
def Boolean(value, message_error=None, message_valid=None): """ value : value element DOM. Example : document['id].value message_error : str message message_valid: str message function return tuple """ if isinstance(value, str): value = value.lower() if value in ('1', 'tr...
def _reg2int(reg): """Converts 32-bit register value to signed integer in Python. Parameters ---------- reg: int A 32-bit register value read from the mailbox. Returns ------- int A signed integer translated from the register value. """ result = -(reg >> 31 & 0x1) * (1 << 31) for i in range(31): resu...
def par_impar(num): """ num -> str Entra un numero y sale si es par o impar :param num: numero a ser revisado :return: mensaje dejando saber si es par o no >>> par_impar(6) 'Es par' >>> par_impar(7) 'Es impar' >>> par_impar('d') Traceback (most recent call last): .. ...
def parse_price(price: str) -> float: """Change price from str to float without dollar sign.""" return float(price.lstrip('$'))
def process_cpp_benchmark(entry): """Process the entry from JSON data""" name = entry["name"] iterations = entry["iterations"] speed = entry["cpu_time"] unit = entry["time_unit"] if unit == "ns": pass elif unit == "us": speed *= 1e3 elif unit == "ms": speed *= 1e...
def _cast_to_int(num, param_name): """Casts integer-like objects to int. Args: num: the number to be casted. param_name: the name of the parameter to be displayed in an error message. Returns: num as an int. Raises: TypeError: if num is not integer-like. """ try: # ...