content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def configure_approle(client, name, cidr, policies): """Create/update a role within vault associating the supplied policies :param client: Vault client :ptype client: hvac.Client :param name: Name of role :ptype name: str :param cidr: Network address of remote unit :ptype cidr: str :par...
c65befd6afa3cb865b9ecffdf35a2c04e534d59a
642,548
def _get_update_fields(queryset, to_update, exclude=None): """ Get the fields to be updated in an upsert. Always exclude auto_now_add, auto_created fields, and unique fields in an update """ exclude = exclude or [] model = queryset.model fields = { **{field.attname: field for fi...
40f0dc4efaf640b7cd5759a6310c83bf7e0f0460
642,552
def Metadata2dict(md): """ Converts a Metadata object to a Python dict. This is the inverse of dict2Metadata. It converts a Metadata object to a Python dict. Note that Metadata behavies like dict, so this conversion is usually not necessay. :param md: Metadata object to convert. :type md:...
e59fc5bbcbb765c13e6d577dd0f750ca798aa59f
642,553
def split_text(lines): """Split a text devided by newline into chunks of about 4000 characters.""" chunks = [] current_chunk = [] chars = 0 for line in lines: # Append the length of the line + a newline chars += len(line) + 1 if chars < 4000: current_chunk.append...
864ebc8d66fcd9370ada68e9cb9db8fbfd86208d
642,554
def sellmeier(lmbda, B1, B2, B3, C1, C2, C3): """ Estimate refractive index of glass with wavelength. Using the Sellmeier equation. Input: lmbda: the Wavelength B(1-3) : B coefficients of glass C(1-3) : C coefficients of glass Returns: n : Fitted refractive index """ n_squ...
3c31a1087893e2abddd47d5e3164a326a7a8744d
642,555
def discrete_binary_search(func, lo, hi): """ Locate the first value x s.t. func(x) = True within [lo, hi] """ while lo < hi: mi = lo + (hi - lo) // 2 if func(mi): hi = mi else: lo = mi + 1 return lo
f8233515a822178898b93a333356c51069493440
642,558
def dummy_import(monkeypatch): # (MonkeyPatch) -> Callable """ This fixture monkeypatches the import mechanism to fail. After raising an `ImportError`, the monkeypatch is immediately removed. """ def dummy_import(*args, **kwargs): try: raise ImportError("this is a monkeypatch"...
341bd038135e1d689af50677d1fc1fbdc96c730a
642,559
def clean_sample_data(samples): """Clean unnecessary information from sample data, reducing size for message passing. """ out = [] for data in (x[0] for x in samples): data["dirs"] = {"work": data["dirs"]["work"], "galaxy": data["dirs"]["galaxy"], "fastq": data["dirs"].ge...
75b8df2c42926cdcca111d4f4f68ea02a76e17f9
642,563
def noop(*args, **kwargs): """No-Op function for when callable is required""" return None
f031dcfe98e5fe17faaed3d8e1a7820a84b8dfa7
642,564
def is_source(f): """Returns true iff the input file name is considered a source file.""" return not f.endswith('_test.go') and ( f.endswith('.go') or f.endswith('.s'))
8beea19b8f2918088d02970f571fb87a47bbf9a7
642,567
def primo(n): """Verifica se número é primo. Considera que n sempre é maior que 1. Retorna True se n for primo ou False caso contrário. """ if n % 2 == 0 and n != 2: resultado = False elif n % 3 == 0 and n != 3: resultado = False else: resultado = True return...
a10cedf721af61420d82ad532135533b0e2b389e
642,570
def eiler_func(p, q): """ Computes Euler's totient function for the modulus 'n' computed as `p`*`q`. Args: p (long): First modulus factor. q (long): Second modulus factor. Returns: long: Euler's totient function value for the modulus n=`p`*`q`. """ phi = (p...
75f8c75f5b2d58e5981e451b7f05497117ecffc2
642,573
def _CountPositives(solution): """Counts number of test images with non-empty ground-truth in `solution`. Args: solution: Dict mapping test image ID to list of ground-truth IDs. Returns: count: Number of test images with non-empty ground-truth. """ count = 0 for v in solution.values(): if v: ...
fe6efdc83b85eb3667067f22ffc8cba5bbb33d03
642,574
def get_bounds(points): """ Given a list of n-dimensional points, returns a list of length n where each element is a tuple holding (min, max) for that dimension. points -- list of n-dimensional points """ bounds = [[None, None] for dimension_num in range(len(points[0]))] for point in poin...
6edeeab0e5c0ea84276d4c4ecc83e0f603a62c9f
642,582
from typing import Iterable from typing import List def flatten_nested(input_iter: Iterable) -> List: """Flatten a nested Iterable with arbitrary levels of nesting. If the input is an iterator then this function will exhaust it. Args: input_iter: The input Iterable which may or may not be nested...
2f452c8d0d5b0b79a7c757af9d3fa7d901beb701
642,583
def mass_spring(x, u, dt=0.05, m=1, c=2, k=1): """Mass-spring-damper system x :: state variables (x1, x2) where x1 = position (m) x2 = velocity (m/s) u :: input force (N) dt :: timestep (s) m :: mass (kg) c :: damping coefficient (Ns/m) k :: spring constant (N/m) ...
97a303b80f0bc3eef9d27d474a7756ab539d089d
642,585
def transform_init_state_cause(cause, message): """ Transforms the init failure cause to a user-friendly message. :param cause: cause of failure :param message: failure message :return: transformed message """ return { 'credentials': 'No or invalid credentials provided', 'to...
53d443bc3952511328c4b2713d2fb7f885331aa1
642,587
import torch def get_optimizer(opt_config, model): """Creates an optimizer based on the opt_config and model parameters. Args: - opt_config: (dict) optimizer config. It should have the following fields: * name: (str) name of the optimizer. It should be one of SGD, Adam, or LBFGS * params: (dict) o...
22f75b12dee5c79a5d278611141c23e273a8d252
642,591
def height(grid): """Gets the height of a rectangular grid (stored row-major).""" return len(grid)
6dc5778cc695d71155dcca28aa29741c0ececee7
642,595
def extras_msg(extras): """ Create an error message for extra items or properties. """ if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in sorted(extras)), verb
4c62adf3c7bd1dbe622e462e868d5f06f7e2d576
642,597
import decimal def ceiling(x): """Return the smallest integral value >= x.""" return x.to_integral(rounding=decimal.ROUND_CEILING)
cf22c44d4d6616236fb9bd99284627da9dfb13d7
642,602
def generalized_fibonacci_sequence(n, p): """Compute the generalized Fibonacci sequence. Args: n: An `int`. The number of terms to compute. Must be >= 2. p: An `int`. The number of the generalized sequence. Must be >= 1. If `p` is 1, the sequence is the standard Fibonacci sequence. Returns: A ...
2b7b2c5e2f7102166deb4f81b37e950fa900a17e
642,605
def apply_selection_cuts(input_catalog, snap_tolerance=1e-3): """ Select only galaxies with petrotheta > 3 and not within 1e-3 of bad measurement snap value Args: catalog (astropy.Table): Galaxy catalog including NSA information snap_tolerance (float): Minimum deviation from bad measurement...
7f3c0b6a6a6afa60508e4db7115eca227cead90d
642,608
def list_to_dict(list_): """Transform a list to a dictionary with its indices as keys.""" dict_ = { str(i): element for i, element in enumerate(list_) } return dict_
8953ede9156ab93cca6ad5686be8b5b80bf0726f
642,609
def sanitise_text(text: str): """Sanitise input text. Args: text: input text. Returns: Sanitised text """ return ''.join(e for e in text if e.isalnum() or e.isspace())
5b1c398893214d0680cc2da708b330183cccaf27
642,610
def getAllSubclasses(cls): """ Searches all subclasses of given class. :param cls: The base class. :type cls: class """ stack = [cls] sub=[] while len(stack): base = stack.pop() for child in base.__subclasses__(): if child not in sub: ...
0fecd0f5ffedf4a113b6ba921606b78fce6e8bb4
642,615
def kid_kernel(x, y): """KID kernel introduced in https://arxiv.org/pdf/1801.01401.pdf. k(x, y) = (1/ndim * x @ y + 1)^3 Args: x: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim]. y: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim]. Returns: `nu...
7579e99f81d31f51e9c974534d915068a31c7116
642,618
def str2bool(val): """ convert string to bool (used to pass arguments with argparse) """ dict = {'True': True, 'False': False, 'true': True, 'false': False, '1': True, '0': False} return dict[val]
eaeb7d553fc264cdc495298f97cb75554f1a3055
642,620
import datetime import datetime def get_dates(start_date,end_date): """ Creates a list of dates in string format 'Y-M-D' Yields ------ list Note ------ To change collection time frame, mend start_date and end_date """ # the command argument is a string # convert the strin...
03f7fab9c603abe90946de927a69a39b291adfff
642,625
def format_platform(platform): """Return formatted uppercase or capitalized platform value""" if platform == "linux" or platform == "windows": return platform.capitalize() else: return platform.upper()
be775ae1ec4a7647c72cc53f10dab2c317a47e97
642,626
def is_route_login_required(fn): """ Determine if a function is decorated to require a logged-in session. :param fn: The function to check. :return: True if this function requires a logged-in session, False otherwise. """ return hasattr(fn, "route_login_required") and fn.route_login_required
e64e145ff5299063d32d9adaa9eaea6c5232163d
642,629
import json def get_changes(changes_file): """Obtain changes from a changes file.""" with open(changes_file, "r") as ch_file: return json.load(ch_file)
f0ff398ff4ca671764fa5bc5fd615fc718e8784c
642,632
def clean_tokens(tokens, callback=lambda token: token): """ >>> clean_tokens(['Hello', '3', 'P.M.']) ['hello', '3', 'p.m.'] >>> clean_tokens(['Hello', '3', 'P.M.'], lambda token: token.replace('.', '')) ['hello', '3', 'pm'] """ return [callback(token.lower()) if isinstance(token, str) ...
bde861dafe5b365c77301139a02840124e183568
642,635
import torch def get_error_instance_ids_by_class(model, batch_ids, batched_evaluation_data, batched_evaluation_target, device="cpu"): """ Return the instance ids corresponding to errors of the model by class. Args: model: The model being evaluated. batc...
6e5665c1b70c4a8a86e6dd46101f30bed6cc7ec5
642,636
import csv def get_reactions(input_file): """ Get all the reactions from the input file Reads the input file and gets the reactions that the user might want to add to the universal model. Input file must be in the same folder as the script. The file name must be a string including .csv ext...
521850554b1eeef007e7b508a6dfb9c6261423a7
642,637
def have_shared_allelic_variation( ref_string, qry_string ): """ Because the VCF files have ellele columns with comma-separated values, this function takes two of them and looks for any single shared allele among them, returning True if one is found. """ refs = ref_string.split(",") qrys = q...
e75d0be9ba1c2feb32159ce503bcee6fabbc8ba6
642,638
def construct_filter_url(zipcode, page_num=1): """ Return a landing url that filters by zipcode. page_num is used to determine the page of the search results. Redfin search results are up to 18 pages long. In the current version, the filter is set to 'sold-3yr' and could be expanded to include 'sol...
acb9679da686d49c26ae183945b5f538b3ddcf28
642,643
from typing import List from typing import Dict def make_task_name_to_index_map( lifelong_learning_task_names: List[str]) -> Dict[str, int]: """Creates a map going from the task name to the task index. The tasks might be repeated, so task indexes aren't just a range. """ task_name_to_task_ind...
bea6e4208ea541880cf61616ecf88fe3c7fffdbd
642,648
async def get_health(): """ Check health of service. """ return {"status": "OK"}
17a8c5f7f96bff26a7044fcd0c785c438272e2b4
642,649
def titleType(dataFrame): """ Count how many series and movies exists in the dataFrame. Used for mostWatchedType visualization Parameters: dataFrame: string The name of the dataFrame the user wants to work with. Returns: a dataFrame """ dataFrameTypeCount = da...
865c4d1654592bad9f01ce67f3e9d23559d322f7
642,650
def to_bytes(string): """Converts a string with a human-readable byte size to a number of bytes. Takes strings like '7536 kB', in the format of proc.""" num, units = string.split() num = int(num) powers = {'kb': 10, 'mb': 20, 'gb': 30} if units and units.lower() in powers: num <<= power...
adfdb4dbdb175f012714390a48b04aec9bfcc705
642,651
def format_as(format_string): """format_as(form)(obj) = form % obj Useful to format many objects with the same format string. >>> list(map(format_as("0x%x"), [0, 1, 10, 11, 15])) ['0x0', '0x1', '0xa', '0xb', '0xf'] """ return lambda obj : format_string % obj
ad2e02106b32b2157c6c026f8031120f3d16fe1e
642,652
from typing import List from typing import Any import random def generate_random_batches(values: List[Any], min_batch_size: int, max_batch_size: int) -> List[List[Any]]: """ Generate random batches of elements in values without replacement and return the list of all batches. Batch sizes can be anything be...
ab122041de32fb731251dacc5cfac77888e8ae03
642,653
def pig_actions_d(state): """The legal actions from a state. Usually, ["roll", "hold"]. Exceptions: If double is "double", can only "accept" or "decline". Can't "hold" if pending is 0. If double is 1, can "double" (in addition to other moves). (If double > 1, cannot "double"). """ # state is...
59088cc91d8033a88e997627f6b50a37b8b68b3b
642,660
def tail_stream(stream, nlines=10): """Returns last N lines from the io object (file or io.string).""" # Seek to eof, backtrack 1024 or to the beginning, return last # N lines. stream.seek(0, 2) fsize = stream.tell() stream.seek(max(fsize - 1024, 0), 0) lines = stream.readlines() return ...
44c4a0291cba6590981308216f0aecc64d8f5001
642,663
def timedelta2seconds(delta): """ Convert a datetime.timedelta() objet to a number of second (floatting point number). >>> timedelta2seconds(timedelta(seconds=2, microseconds=40000)) 2.04 >>> timedelta2seconds(timedelta(minutes=1, milliseconds=250)) 60.25 """ return delta.microsecon...
9133e812a73366e961e68c4868ed589e959f93af
642,664
def get_assumed_creds(sts, arn): """Retrieves the AWS assume role credentials. Args: sts: boto3 sts object arn: Arn of the role we want to assume Returns: AWS credentials """ if arn: credentials = sts.assume_role( RoleArn=arn, RoleSessionName...
d293a553ca1087318108a571e9fe4920e78abcd9
642,667
def get_full_verbs(tokens): """Identify, color and count full verbs """ full_verbs = [k for k in tokens if k.full_pos.startswith('VV')] for t in full_verbs: t.pos_color.append('Full verbs') return len(full_verbs)
f68b22058c50e44ba25aef498225082504358dfe
642,669
import math def length_of_degree(lat): """Calcualte the length of a degree in meters.""" m1 = 111132.92 m2 = -559.82 m3 = 1.175 m4 = -0.0023 p1 = 111412.84 p2 = -93.5 p3 = 0.118 lat_rad = lat * math.pi / 180 latlen = ( m1 + m2 * math.cos(2 * lat_rad) + m3 * math.cos(4 *...
c9e46bc04b8476ba6f14993fa21c651bf1da3a8f
642,671
def hexstr(s): """Compact inline hexdump""" return ' '.join(['%02x' % ord(b) for b in s])
4539c9866752206e4f4fe1c2b8026f7abdf540ed
642,674
def _prefixed_flag_vals(prefixes, flag_vals): """Returns a dict of prefixed flag values. Prefixes are stripped from matching flag names. The value for the first matching prefix from prefixes is used. """ prefixed = {} for prefix in prefixes: for full_name in flag_vals: if f...
ab6f865dce34f21966466f72db424cced3bfe998
642,675
def navigation_key_expected_key_pair(request): """ Fixture to generate pairs of navigation keys with their respective expected key. The expected key is the one which is passed to the super `keypress` calls. """ return request.param
5292a535714fdf46f0e0555be627b89e0a01c63f
642,678
def parabola_through_three_points(p1, p2, p3): """ Calculates the parabola a*(x-b)+c through three points. The points should be given as (y, x) tuples. Returns a tuple (a, b, c) """ # formula taken from http://stackoverflow.com/questions/4039039/fastest-way-to-fit-a-parabola-to-set-of-points # A...
477c3a4190dc04c26edd4eedf7232e1f64003834
642,682
import requests def get_access_token(username, password, client_id, client_secret): """ Get the Netatmo access token :param username: Netamo username :param password: Netamo password :param client_id: Netamo Client ID :param client_secret: Netamo Client Secret :return: access token """...
5f4513bf65df8ba255c3479c48ac9ad73d9a7f4e
642,687
from typing import List from typing import Any def read_keyword_list(keywords: List[Any], list_length: int) -> List[Any]: """Reads a number of tokens from a keyword list and returns as separate list""" newlist = [] #Uses a loop like this to ensure the original list is modified when removing keywords, rath...
d9250fc3960cce0491a7b3d1861d0d116ec31ceb
642,690
def split_tag(chunk_tag): """ split chunk tag into IOBES prefix and chunk_type e.g. B-PER -> (B, PER) O -> (O, None) """ if chunk_tag == 'O': return ('O', None) return chunk_tag.split('-', maxsplit=1)
edf51eb54d68be4b606be99c3166776ceb157345
642,692
def apply_image_filter(image, image_filter=None): """ unpacking / pseudo-dispatch function `image_filter` is a dict() that contains 'params' and 'function' keys. The optional 'params' value is a parameters dict() and the 'function' value is the corresponding function to run on `image`. """ ...
360c428fede9d5280aaa4c271facd705c8a120b8
642,693
import math def angleBetweenPoints( firstPoint, secondPoint ): """ Returns the angle (in degrees) of the straight line between firstPoint and secondPoint, 0 degrees being the second point to the right of first point. firstPoint, secondPoint: must be NSPoint or GSNode """ xDiff = secondPoint.x - firstPoint.x yD...
d3b633b105ae90382e0ae900cb26d97986f0bee5
642,694
def find_example3(sequence): """ Returns the FIRST STRING in the given sequence, or None if the sequence contains no strings. """ # Returns the item ( sequence[k] ) or None for k in range(len(sequence)): if type(sequence[k]) == str: return sequence[k] return None
8e9edd18b62e6ef121025f400cd386799404f679
642,700
def get_num_rows(puzzle: str) -> int: """Return the number of rows in puzzle. puzzle is a game board. >>> get_num_rows('abcd\nefgh\nijkl\n') 3 """ return puzzle.count('\n')
30985b6477a5ce8db82e289f157313f79fe1a39d
642,702
import torch def generate_anchors(anchor_shapes, grid_centers): """ Generate all anchors. @Params: ------- anchor_shapes (tensor): Tensor of shape [A, 2] giving the shapes of anchor boxes to consider at each point in the grid. anchor_shapes[a] = (w, h) indicate width and height ...
5248e7a6854e8e8bd6366c4352a6ee1fca8e8602
642,704
def parse_string(parser, header, arg_name, arg_value): """ Parse an argument from the given parser. If the argument is not specified, return the default value :param parser: the parser to be used for parsing :param header: name of the header in the configuration file :param arg_name: name in the con...
cd987bfac49a4f14c411250df8362bb0cb95b547
642,707
def msg2typestr(msg): """ Introspects the message type from the passed in `msg` and encodes it as a string in the format required by rosbag2. Parameters ---------- msg : Message A ROS 2 message (deserialized) whose type we need to introspect Returns ------- A string encoding ...
2ad3ed44d6bb110290ad8a92fa95c11a639a7cc9
642,712
def timedelta2duration(delta): """ Convert a datetime.timedelta to ISO 8601 duration format Parameters ---------- delta : datetime.timedelta Returns ------- str """ s = "P" if delta.days: s += f"{delta.days}D" if delta.seconds or delta.microseconds: sec ...
ffd550ce8852046d08c39388362e677741ad117c
642,721
def mean(mylist): """ Returns the mean value of a list """ total = 1.0 * sum(mylist) length = len(mylist) if length == 0.0: raise ArithmeticError( "Attempting to compute the mean of a zero-length list") return (total / length)
bbecfc1929d20c71a81c867dfc672f5dc4296ca0
642,723
def format_font_name(value): """Formats a font name into the display version""" return value \ .replace('_', ' ') \ .title()
1707b1f86c37bd1aa68934b9ae857e6e89e90be8
642,726
from pathlib import Path def get_resource_type(pth: Path) -> str: """Get the resource type from the path - useful for finding the right resources.""" typ = Path(pth).parts[1].replace('_backfill', '') return typ
6aa5bb922fd60c5b32ac5081c4dcd12e7f9375ae
642,727
import requests import zipfile import io def get_files(code): """ A wrapper function to obtain .csv files from the world bank. Parameters: ----------- code: str The code of the indicator. Returns: -------- str downloaded .csv filename """ r = requests....
1a23e9760bde8f5f29701fbe0afcc0af4a2ee693
642,738
def parse_col_name(col_name): """ Standardize column name `col_name` """ return col_name.upper().strip()
9c96348651ec441a1957571d55c3b8afd8fee7e8
642,739
def _update_globals(task_file_to_run, globals_dict): """Updates globals dictionary with default data path for provided task if Inputs/Outputs directories are equal to None. Args: task_file_to_run (str): path to the task that will be run. globals_dict (dict): contains global variables for f...
4ee348eec90f5886056994dd61d00d32dc244237
642,744
import json def create_error_response(error): """ Create error response from an error exception Parameters ---------- error : Exception An error exception Returns ------- string A JSON string of the error response """ error_response = json.dumps({ 'sta...
f1d8cee0db2ed83c9e7bb1ee7b058da2905bc5de
642,747
def _is_json(q): """Check if q is JSON. Parameters ---------- q : str Query string. Returns ------- bool True if q starts with "{" and ends with "}". """ return q.strip().startswith("{") and q.strip().endswith("}")
0146cc62d550bbcdbd4fc8ef5e9a81325c044cb6
642,751
def ComputeR(edge_weights): """ Computes the value of R (sum of edge weights) given the edge weights of a graph. """ sume = 0 for (i, j) in edge_weights.keys(): sume += edge_weights[(i, j)] return sume
cd4607305d8422c15978641162b3e51331046496
642,753
def str_list(input_list): """ Convert all the elements in a list to str Args: input_list: list of any elements Returns: list of string elements """ return ['{}'.format(e) for e in input_list]
5e0897a4c2de8516a1154a35e860f93133d9b17b
642,758
import torch from typing import Dict def standardize( x: torch.Tensor, stats: Dict[str, torch.Tensor]) -> torch.Tensor: """Standardize a tensor using precalculated global mean and std. Parameters ---------- x A tensor to be standardized. stats A dict with keys ``me...
76f63ba87380c8a0bf1dc9bcff2558bccb1275e2
642,759
import re def filter_re_replace(val, pattern, repl): """Perform a regexp replacement on the given string.""" return re.sub(pattern, repl, str(val))
3ed0121260fbc90a600f66b3df9c1db6465c1ee9
642,762
def unpack_transform_msg(msg, stamped=False): """ Get translation and rotation from a Transform(Stamped) message. """ if stamped: t = msg.transform.translation r = msg.transform.rotation else: t = msg.translation r = msg.rotation return (t.x, t.y, t.z), (r.w, r.x, r.y, r...
de952759dbe61a100e9db5b01de20eb5cf9a1849
642,763
def make_poem_html(poem, pid): """This function makes a section of HTML code for a poem. Args: poem: A poem defined as a list (rows) of lists (words in rows). pid: HTML <p> tag ID attribute for CSS identification. Returns: A string containing HTML code for displaying a poem, for ex...
f4e139403bd1e8039aee1a3ad459eddf1dff2b93
642,767
def _img_crop(im, x_pos, y_pos, radius, im_shape): """ Perform crop of the image. Crop the region of the image containing the cell of interest. Parameters ---------- im : numpy.array Fluorescence microscopy image. x_pos : int :math:`x`-coordinate of the center of the cell o...
c49d18d0891d77fabc52ecda77cb69355f475abb
642,768
def scrub_response(secret): """Helper function that provides a filter function for stripping secrets from HTTP responses before they are stored by vcrpy Based on the example implementation found her: https://vcrpy.readthedocs.io/en/latest/advanced.html#custom-response-filtering Example: >...
01701e31e4eac98f234e8dbcb5bc49d4bcd5f999
642,769
def to_int(n): """Converts a string to an integer value. Returns None, if the string cannot be converted.""" try: return int(n) except ValueError: return None
109da76f1368df598016a7bb34af2b11f5d97920
642,772
import re def validate_period_format(period_str): """validates a period in string format Args: period_str (string): period in string format starting with a number and ending with the letters m, h or d, for minutes, hour and day, respectively. Returns: bool: True if the period is valid, else F...
86909345fd09a09d55971bb4567ac268ff48606e
642,774
def get_upper_long_from_trace_id(trace_id): """Returns the upper 8 bytes of the trace ID as a long value, assuming little endian order. :rtype: long :returns: Upper 8 bytes of trace ID """ upper_bytes = trace_id[:16] upper_long = int(upper_bytes, 16) return upper_long
6e9ea39521a21c5e03c6b6a9f63b4b3268977f1d
642,781
from functools import reduce import operator def birthday_problem(g, n): """returns the probability that n independent choices from a set of g objects are all unique""" return reduce(operator.mul, [float(g-i)/g for i in range(0, n)])
a9d9d0d27307d05cbad0cb711cf237e8e846a4a1
642,785
def remove_private_prefix(attr_name: str, prefix: str) -> str: """Return the specified attribute name without the specified prefix.""" return attr_name[len(prefix):]
5a41d4c48d0998b7c1cfdc3371da3977a943a29f
642,790
def default_archiver(random, population, archive, args): """Do nothing. This function just returns the existing archive (which is probably empty) with no changes. .. Arguments: random -- the random number generator object population -- the population of individuals archive...
41c42404480dbe30c9884887cd064f1a124fd3b9
642,791
from datetime import datetime def to_ISO8601(dt: datetime) -> str: """Convert datetime object to ISO 8601 standard UTC string""" return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
a3a0550871fa904d3fd61d2591034cdbf103b66c
642,793
def cmd_subject_hash(cert): """Returns hash of certificate subject. """ return cert.get_subject().hash()
d8c37c7ee5150af69226c321ec606f3605857392
642,794
def findResource(resource, request): """Traverse resource tree to find who will handle the request.""" while request.postpath and not resource.isLeaf: #print 'findResource:', resource, request.postpath pathElement = request.postpath.pop(0) request.prepath.append(pathElement) next...
3a1139feb78060c4b55dd0552bd41bbfe7636260
642,795
def neq(a, b): """Checks if antecedent ⇎ consequent (a ⇎ b). `📘`_ - a: antecedent - b: consequent Example: >>> neq(True, False) == True >>> neq(False, True) == True >>> neq(True, True) == False >>> neq(False, False) == False .. _📘: https://github.com/python3f/extra-boolean/wiki/neq ...
944a157ed824307c3174bbcb32207558ecd51f23
642,801
def sort_annotations_by_offset(annotations): """ This function expects as input a list of dictionaries with this structure: {'ann_id': u'T34', 'continuation': False, 'entity_type': u'Registry', 'positions': [{'end': 2465, 'start': 2448}], 'surface': u'reg 38 Padavinus,'}, And sorts...
3c2cee926243ae487161afb78baa0394cddcb1f3
642,805
from operator import add def do_query(issues, config_file=None, logger=None, context=None): """ Iterate through issues and count total number of issues and total number of words. Returns result of form: { "num_issues": num_issues, "num_words": num_words } :pa...
79231f5e0076ee4bbf0b6d9a96649d034ceb6651
642,807
import time def wait_for( func, max_seconds=10, pause=1 ): """ def wait_for Wait for up to max_seconds for func to return True If func returns True within time alloted, return True Otherwise, return False func must return a boolean value (others might work, but behavior is undefine...
ad4079bb961a4f7be335f5c8616aa7689f367013
642,808
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...
751689e93e66f54251944343f0cac626bf5103c2
642,815
import copy def dict_np_to_dict_list(input_dict): """ Convert a dict of numpy array to a dict of list """ input_dict = copy.copy(input_dict) if type(input_dict) is dict: for name in list(input_dict.keys()): input_dict.update({name: input_dict[name].tolist()}) return inp...
6ced5c818820d2f2d1d4407ee8422370eaf0b140
642,826
from typing import List def dict_value_from_path(src_dict: dict, path: List[str], case_sensitive: bool = False): """ returns the value of dict field specified via "path" in form of a list of keys. By default the keys are matching case insensitive way. Example: src_dict = {"level1:{"level2":{"lev...
a76a15c7b0f35ff20fbc0320cac71297b4a7ddcf
642,829
from math import floor def calcL1Ainterval(rate): """ Returns the L1Ainterval in BX associated with a given rate in Hz """ return floor((1.0 / rate) * (1e9 / 25))
57233912db7fb9f0bf6aa189b1f419a9daa759f4
642,836
def expectation_description(expect = None, expect_failure = None): """Turn expectation of result or error into a string.""" if expect_failure: return "failure " + str(expect_failure) else: return "result " + repr(expect)
0a6944cbe83fbc14723526fd145ab816b86d2f0a
642,839
def get_simulation_priority_value(simulation_result, data_item, target_priority): """ Collect a priority metric from the simulation. :param simulation_result: Metrics on simulation :param data_item: Metric name :param target_priority: Priority :return: List of values from simulation. """ ...
259ecb92c5c0902d60d6fcfb35a4b08ed373fcbb
642,840
def get_keytable_path(opendkim_conf): """Returns the path to the KeyTable file from the OpenDKIM config. """ param = 'KeyTable' with open(opendkim_conf, 'r') as f: for line in f: if line.startswith(param): return line.replace(param, '').strip() msg = "Could not ...
cc40686d6dd9440747dff76ea0ceaafc0c3357ad
642,842