_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q261300
_arg_parser
validation
def _arg_parser(): """Factory for creating the argument parser""" description = "Converts a completezip to a litezip" parser = argparse.ArgumentParser(description=description) verbose_group = parser.add_mutually_exclusive_group() verbose_group.add_argument( '-v', '--verbose', action='store_true', dest='verbose', default=None, help="increase verbosity") verbose_group.add_argument(
python
{ "resource": "" }
q261301
IF.to_bytes
validation
def to_bytes(self, previous: bytes): """ Complex code ahead. Comments have been added in as needed. """ # First, validate the lengths. if len(self.conditions) != len(self.body): raise exc.CompileError("Conditions and body length mismatch!") bc = b"" prev_len = len(previous) # Loop over the conditions and bodies for condition, body in zip(self.conditions, self.body): # Generate the conditional data. cond_bytecode = condition.to_bytecode(previous) bc += cond_bytecode # Complex calculation. First, generate the bytecode for all tokens in the body. Then # we calculate the len() of that. We create a POP_JUMP_IF_FALSE operation that jumps # to the instructions after the body code + 3 for the pop call. This is done for all # chained IF calls, as if it was an elif call. Else calls are not possible to be # auto-generated, but it is possible to emulate them using an elif call that checks # for the opposite of the above IF.
python
{ "resource": "" }
q261302
FOR_LOOP.to_bytes_35
validation
def to_bytes_35(self, previous: bytes): """ A to-bytes specific to Python 3.5 and below. """ # Calculations ahead. bc = b"" # Calculate the length of the iterator. it_bc = util.generate_bytecode_from_obb(self.iterator, previous) bc += it_bc # Push a get_iter on. bc += util.generate_bytecode_from_obb(tokens.GET_ITER, b"") prev_len = len(previous) + len(bc) # Calculate the bytecode for the body. body_bc = b"" for op in self._body: # Add padding bytes to the bytecode to allow if blocks to work. padded_bc = previous # Add padding for SETUP_LOOP padded_bc += b"\x00\x00\x00" padded_bc += bc # Add padding for FOR_ITER padded_bc += b"\x00\x00\x00" # Add previous body padded_bc += body_bc body_bc += util.generate_bytecode_from_obb(op, padded_bc)
python
{ "resource": "" }
q261303
FOR_LOOP.to_bytes_36
validation
def to_bytes_36(self, previous: bytes): """ A to-bytes specific to Python 3.6 and above. """ # Calculations ahead. bc = b"" # Calculate the length of the iterator. it_bc
python
{ "resource": "" }
q261304
validate_content
validation
def validate_content(*objs): """Runs the correct validator for given `obj`ects. Assumes all same type""" from .main import Collection, Module validator = { Collection:
python
{ "resource": "" }
q261305
validate_litezip
validation
def validate_litezip(struct): """Validate the given litezip as `struct`. Returns a list of validation messages. """ msgs = [] def _fmt_err(err): return (Path(err.filename), "{}:{} -- {}: {}".format(*(err[1:]))) obj_by_type = {} for obj in struct: if not is_valid_identifier(obj.id): msg = (obj.file.parent, "{} is not a valid identifier".format(obj.id),) logger.info("{}: {}".format(*msg)) msgs.append(msg) obj_by_type.setdefault(type(obj), []).append(obj) for obtype
python
{ "resource": "" }
q261306
ensure_instruction
validation
def ensure_instruction(instruction: int) -> bytes: """ Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below. This is most useful for operating on bare, single-width instructions such
python
{ "resource": "" }
q261307
pack_value
validation
def pack_value(index: int) -> bytes: """ Small helper value to pack an index value into bytecode. This is used for version compat between 3.5- and 3.6+ :param index: The item to pack. :return: The packed item. """ if PY36:
python
{ "resource": "" }
q261308
generate_simple_call
validation
def generate_simple_call(opcode: int, index: int): """ Generates a simple call, with an index for something. :param opcode: The opcode to generate. :param index: The index to use as an argument. :return: """ bs = b"" # add the opcode bs += opcode.to_bytes(1, byteorder="little") # Add the index
python
{ "resource": "" }
q261309
generate_bytecode_from_obb
validation
def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes: """ Generates a bytecode from an object. :param obb: The object to generate. :param previous: The previous bytecode to use when generating subobjects. :return: The generated bytecode. """ # Generates bytecode from a specified object, be it a validator or an int or bytes even. if isinstance(obb, pyte.superclasses._PyteOp): return obb.to_bytes(previous) elif isinstance(obb, (pyte.superclasses._PyteAugmentedComparator,
python
{ "resource": "" }
q261310
_get_const_info
validation
def _get_const_info(const_index, const_list): """ Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined. Otherwise returns the constant index and its repr(). """ argval = const_index if const_list is not None:
python
{ "resource": "" }
q261311
_get_name_info
validation
def _get_name_info(name_index, name_list): """Helper to get optional details about named references Returns the dereferenced name as both value and repr if the name list is defined. Otherwise returns the name index and its repr().
python
{ "resource": "" }
q261312
compile_bytecode
validation
def compile_bytecode(code: list) -> bytes: """ Compiles Pyte objects into a bytecode list. :param code: A list of objects to compile. :return: The computed bytecode. """ bc = b"" for i, op in enumerate(code): try: # Get the bytecode. if isinstance(op, _PyteOp) or isinstance(op, _PyteAugmentedComparator): bc_op = op.to_bytes(bc) elif isinstance(op, int): bc_op = op.to_bytes(1, byteorder="little") elif isinstance(op, bytes):
python
{ "resource": "" }
q261313
_simulate_stack
validation
def _simulate_stack(code: list) -> int: """ Simulates the actions of the stack, to check safety. This returns the maximum needed stack. """ max_stack = 0 curr_stack = 0 def _check_stack(ins): if curr_stack < 0: raise CompileError("Stack turned negative on instruction: {}".format(ins)) if curr_stack > max_stack: return curr_stack # Iterate over the bytecode. for instruction in code: assert isinstance(instruction, dis.Instruction) if instruction.arg is not None: try: effect = dis.stack_effect(instruction.opcode, instruction.arg) except ValueError as e: raise CompileError("Invalid opcode `{}` when compiling" .format(instruction.opcode)) from e else: try:
python
{ "resource": "" }
q261314
compile
validation
def compile(code: list, consts: list, names: list, varnames: list, func_name: str = "<unknown, compiled>", arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True): """ Compiles a set of bytecode instructions into a working function, using Python's bytecode compiler. :param code: A list of bytecode instructions. :param consts: A list of constants to compile into the function. :param names: A list of names to compile into the function. :param varnames: A list of ``varnames`` to compile into the function. :param func_name: The name of the function to use. :param arg_count: The number of arguments this function takes. Must be ``<= len(varnames)``. :param kwarg_defaults: A tuple of defaults for kwargs. :param use_safety_wrapper: Use the safety wrapper? This hijacks SystemError to print better \ stack traces. """ varnames = tuple(varnames) consts = tuple(consts) names = tuple(names) # Flatten the code list. code = util.flatten(code) if arg_count > len(varnames): raise CompileError("arg_count > len(varnames)") if len(kwarg_defaults) > len(varnames): raise CompileError("len(kwarg_defaults) > len(varnames)") # Compile it. bc = compile_bytecode(code) dis.dis(bc) # Check for a final RETURN_VALUE. if PY36: # TODO: Add Python 3.6 check pass else: if bc[-1] != tokens.RETURN_VALUE: raise CompileError( "No default RETURN_VALUE. Add a `pyte.tokens.RETURN_VALUE` to the end of your " "bytecode if you don't need one.") # Set default flags flags = 1 | 2 | 64 frame_data = inspect.stack()[1] if sys.version_info[0:2] > (3, 3): # Validate the stack. stack_size = _simulate_stack(dis._get_instructions_bytes( bc, constants=consts, names=names, varnames=varnames) ) else: warnings.warn("Cannot check stack for safety.") stack_size = 99 # Generate optimization warnings. _optimize_warn_pass(dis._get_instructions_bytes(bc, constants=consts, names=names, varnames=varnames)) obb = types.CodeType( arg_count, # Varnames - used for arguments. 0, # Kwargs are not supported yet len(varnames), # co_nlocals -> Non-argument local variables stack_size, # Auto-calculated flags, # 67 is default for a normal function. bc, # co_code - use the bytecode we generated. consts, # co_consts names, # co_names, used for global calls. varnames, # arguments frame_data[1], # use <unknown, compiled>
python
{ "resource": "" }
q261315
_parse_document_id
validation
def _parse_document_id(elm_tree): """Given the parsed xml to an `ElementTree`, parse the id from the content. """ xpath = '//md:content-id/text()'
python
{ "resource": "" }
q261316
parse_module
validation
def parse_module(path, excludes=None): """Parse the file structure to a data structure given the path to a module directory. """ file = path / MODULE_FILENAME if not file.exists(): raise MissingFile(file) id = _parse_document_id(etree.parse(file.open())) excludes = excludes or [] excludes.extend([ lambda filepath: filepath.name == MODULE_FILENAME,
python
{ "resource": "" }
q261317
parse_collection
validation
def parse_collection(path, excludes=None): """Parse a file structure to a data structure given the path to a collection directory. """ file = path / COLLECTION_FILENAME if not file.exists(): raise MissingFile(file) id = _parse_document_id(etree.parse(file.open())) excludes = excludes or [] excludes.extend([ lambda filepath: filepath.name == COLLECTION_FILENAME,
python
{ "resource": "" }
q261318
parse_litezip
validation
def parse_litezip(path): """Parse a litezip file structure to a data structure given the path to the litezip directory.
python
{ "resource": "" }
q261319
convert_completezip
validation
def convert_completezip(path): """Converts a completezip file structure to a litezip file structure. Returns a litezip data structure. """ for filepath in path.glob('**/index_auto_generated.cnxml'): filepath.rename(filepath.parent / 'index.cnxml')
python
{ "resource": "" }
q261320
_get_instructions_bytes
validation
def _get_instructions_bytes(code, varnames=None, names=None, constants=None, cells=None, linestarts=None, line_offset=0): """Iterate over the instructions in a bytecode string. Generates a sequence of Instruction namedtuples giving the details of each opcode. Additional information about the code's runtime environment (e.g. variable names, constants) can be specified using optional arguments. """ labels = dis.findlabels(code) extended_arg = 0 starts_line = None free = None # enumerate() is not an option, since we sometimes process # multiple elements on a single pass through the loop n = len(code) i = 0 while i < n: op = code[i] offset = i if linestarts is not None: starts_line = linestarts.get(i, None) if starts_line is not None: starts_line += line_offset is_jump_target = i in labels i = i + 1 arg = None argval = None argrepr = '' if op >= dis.HAVE_ARGUMENT: arg = code[i] + code[i + 1] * 256 + extended_arg extended_arg = 0 i = i + 2 if op == dis.EXTENDED_ARG: extended_arg = arg * 65536 # Set argval to the dereferenced value of the argument when # availabe, and argrepr to the string representation of argval. # _disassemble_bytes needs the string repr of the # raw name index for LOAD_GLOBAL, LOAD_CONST, etc. argval = arg if op in dis.hasconst: argval, argrepr = dis._get_const_info(arg, constants) elif op in dis.hasname:
python
{ "resource": "" }
q261321
Instruction._disassemble
validation
def _disassemble(self, lineno_width=3, mark_as_current=False): """Format instruction details for inclusion in disassembly output *lineno_width* sets the width of the line number field (0 omits it) *mark_as_current* inserts a '-->' marker arrow as part of the line """ fields = [] # Column: Source code line number if lineno_width: if self.starts_line is not None: lineno_fmt = "%%%dd" % lineno_width fields.append(lineno_fmt % self.starts_line) else: fields.append(' ' * lineno_width) # Column: Current instruction indicator if mark_as_current: fields.append('-->') else: fields.append(' ') # Column: Jump target marker if self.is_jump_target: fields.append('>>') else: fields.append(' ')
python
{ "resource": "" }
q261322
intersection
validation
def intersection(l1, l2): '''Returns intersection of two lists. Assumes the lists are sorted by start positions''' if len(l1) == 0 or len(l2) == 0: return [] out = [] l2_pos = 0 for l in l1:
python
{ "resource": "" }
q261323
remove_contained_in_list
validation
def remove_contained_in_list(l): '''Sorts list in place, then removes any intervals that are completely contained inside another interval''' i = 0 l.sort() while i < len(l) - 1: if l[i+1].contains(l[i]):
python
{ "resource": "" }
q261324
Interval.distance_to_point
validation
def distance_to_point(self, p): '''Returns the distance from the point to the interval. Zero if the point lies inside the interval.''' if self.start <= p <= self.end:
python
{ "resource": "" }
q261325
Interval.intersects
validation
def intersects(self, i): '''Returns true iff this interval intersects the interval i'''
python
{ "resource": "" }
q261326
Interval.contains
validation
def contains(self, i): '''Returns true iff this interval contains the interval i'''
python
{ "resource": "" }
q261327
Interval.union
validation
def union(self, i): '''If intervals intersect, returns their union, otherwise returns None''' if self.intersects(i) or self.end + 1 == i.start or i.end + 1 == self.start:
python
{ "resource": "" }
q261328
Interval.union_fill_gap
validation
def union_fill_gap(self, i): '''Like union, but ignores whether the two intervals intersect or not'''
python
{ "resource": "" }
q261329
Interval.intersection
validation
def intersection(self, i): '''If intervals intersect, returns their intersection, otherwise returns None''' if self.intersects(i):
python
{ "resource": "" }
q261330
Fasta.subseq
validation
def subseq(self, start, end): '''Returns Fasta object with the same name, of the bases from start to end, but
python
{ "resource": "" }
q261331
Fasta.replace_bases
validation
def replace_bases(self, old, new): '''Replaces all occurrences of 'old' with 'new' '''
python
{ "resource": "" }
q261332
Fasta.gaps
validation
def gaps(self, min_length = 1): '''Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based''' gaps = [] regex = re.compile('N+', re.IGNORECASE) for m in regex.finditer(self.seq):
python
{ "resource": "" }
q261333
Fasta.orfs
validation
def orfs(self, frame=0, revcomp=False): '''Returns a list of ORFs that the sequence has, starting on the given frame. Each returned ORF is an interval.Interval object. If revomp=True, then finds the ORFs of the reverse complement of the sequence.''' assert frame in [0,1,2] if revcomp: self.revcomp() aa_seq = self.translate(frame=frame).seq.rstrip('X') if revcomp: self.revcomp() orfs = _orfs_from_aa_seq(aa_seq) for i in range(len(orfs)): if revcomp:
python
{ "resource": "" }
q261334
Fasta.is_complete_orf
validation
def is_complete_orf(self): '''Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end''' if len(self) %3 != 0 or len(self) < 6: return False orfs = self.orfs()
python
{ "resource": "" }
q261335
Fasta.to_Fastq
validation
def to_Fastq(self, qual_scores): '''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file'''
python
{ "resource": "" }
q261336
Fastq.subseq
validation
def subseq(self, start, end): '''Returns Fastq object with the same name, of the bases from start to end, but not including end'''
python
{ "resource": "" }
q261337
Fastq.trim_Ns
validation
def trim_Ns(self): '''Removes any leading or trailing N or n characters from the sequence''' # get index of first base that is not an N i = 0 while i < len(self) and self.seq[i] in 'nN': i += 1 # strip off start of sequence and quality
python
{ "resource": "" }
q261338
count_sequences
validation
def count_sequences(infile): '''Returns the number of sequences in a file''' seq_reader = sequences.file_reader(infile)
python
{ "resource": "" }
q261339
interleave
validation
def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None): '''Makes interleaved file from two sequence files. If used, will append suffix1 onto end of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.''' seq_reader_1 = sequences.file_reader(infile_1) seq_reader_2 = sequences.file_reader(infile_2) f_out = utils.open_file_write(outfile) for seq_1 in seq_reader_1: try: seq_2 = next(seq_reader_2) except: utils.close(f_out) raise Error('Error getting mate for sequence', seq_1.id, ' ... cannot continue') if suffix1 is not None
python
{ "resource": "" }
q261340
make_random_contigs
validation
def make_random_contigs(contigs, length, outfile, name_by_letters=False, prefix='', seed=None, first_number=1): '''Makes a multi fasta file of random sequences, all the same length''' random.seed(a=seed) fout = utils.open_file_write(outfile) letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') letters_index = 0 for i in range(contigs): if name_by_letters: name = letters[letters_index] letters_index += 1 if letters_index == len(letters):
python
{ "resource": "" }
q261341
mean_length
validation
def mean_length(infile, limit=None): '''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N''' total = 0 count = 0 seq_reader = sequences.file_reader(infile) for seq in seq_reader:
python
{ "resource": "" }
q261342
merge_to_one_seq
validation
def merge_to_one_seq(infile, outfile, seqname='union'): '''Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order''' seq_reader = sequences.file_reader(infile) seqs = [] for seq in seq_reader: seqs.append(copy.copy(seq)) new_seq = ''.join([seq.seq for seq in seqs]) if type(seqs[0]) == sequences.Fastq:
python
{ "resource": "" }
q261343
scaffolds_to_contigs
validation
def scaffolds_to_contigs(infile, outfile, number_contigs=False): '''Makes a file of contigs from scaffolds by splitting at every N. Use number_contigs=True to add .1, .2, etc onto end of each contig, instead of default to append coordinates.''' seq_reader = sequences.file_reader(infile) fout = utils.open_file_write(outfile) for seq in seq_reader: contigs = seq.contig_coords() counter = 1 for contig in contigs: if number_contigs:
python
{ "resource": "" }
q261344
sort_by_size
validation
def sort_by_size(infile, outfile, smallest_first=False): '''Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first''' seqs = {} file_to_dict(infile, seqs)
python
{ "resource": "" }
q261345
sort_by_name
validation
def sort_by_name(infile, outfile): '''Sorts input sequence file by sort -d -k1,1, writes sorted output file.''' seqs = {} file_to_dict(infile, seqs) #seqs = list(seqs.values()) #seqs.sort() fout
python
{ "resource": "" }
q261346
to_fastg
validation
def to_fastg(infile, outfile, circular=None): '''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs''' if circular is None: to_circularise = set() elif type(circular) is not set: f = utils.open_file_read(circular) to_circularise = set([x.rstrip() for x in f.readlines()]) utils.close(f) else: to_circularise = circular seq_reader = sequences.file_reader(infile) fout = utils.open_file_write(outfile) nodes = 1 for seq in seq_reader: new_id = '_'.join([ 'NODE', str(nodes), 'length', str(len(seq)), 'cov', '1', 'ID', seq.id ]) if seq.id in to_circularise:
python
{ "resource": "" }
q261347
to_boulderio
validation
def to_boulderio(infile, outfile): '''Converts input sequence file into a "Boulder-IO format", as used by primer3''' seq_reader = sequences.file_reader(infile) f_out = utils.open_file_write(outfile) for sequence in seq_reader:
python
{ "resource": "" }
q261348
pbkdf2
validation
def pbkdf2(password, salt, iterations, dklen=0, digest=None): """ Implements PBKDF2 with the same API as Django's existing implementation, using cryptography. :type password: any :type salt: any :type iterations: int :type dklen: int :type digest: cryptography.hazmat.primitives.hashes.HashAlgorithm """ if digest is None: digest = settings.CRYPTOGRAPHY_DIGEST if not dklen:
python
{ "resource": "" }
q261349
get_encrypted_field
validation
def get_encrypted_field(base_class): """ A get or create method for encrypted fields, we cache the field in the module to avoid recreation. This also allows us to always return the same class reference for a field. :type base_class: models.Field[T] :rtype: models.Field[EncryptedMixin, T] """ assert not isinstance(base_class, models.Field) field_name = 'Encrypted' + base_class.__name__ if base_class not in FIELD_CACHE:
python
{ "resource": "" }
q261350
encrypt
validation
def encrypt(base_field, key=None, ttl=None): """ A decorator for creating encrypted model fields. :type base_field: models.Field[T] :param bytes key: This is an optional argument. Allows for specifying an instance specific encryption key. :param int ttl: This is an optional argument. The amount of time in seconds that a value can be stored for.
python
{ "resource": "" }
q261351
PickledField.value_to_string
validation
def value_to_string(self, obj): """Pickled data is serialized as base64"""
python
{ "resource": "" }
q261352
dumps
validation
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False): """ Returns URL-safe, sha1 signed base64 compressed JSON string. If key is None, settings.SECRET_KEY is used instead. If compress is True (not the default) checks if compressing using zlib can save some space. Prepends a '.' to signify compression. This is included in the signature, to protect against zip bombs. Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application without good cause is a security risk. The serializer is expected to return a bytestring. """ data =
python
{ "resource": "" }
q261353
FernetSigner.unsign
validation
def unsign(self, signed_value, ttl=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. :type signed_value: bytes :type ttl: int | datetime.timedelta """ h_size, d_size = struct.calcsize('>cQ'), self.digest.digest_size fmt = '>cQ%ds%ds' % (len(signed_value) - h_size - d_size, d_size) try: version, timestamp, value, sig = struct.unpack(fmt, signed_value) except struct.error: raise BadSignature('Signature is not valid')
python
{ "resource": "" }
q261354
get_version
validation
def get_version(version=None): """ Returns a PEP 386-compliant version number from VERSION. """ version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases main = get_main_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0:
python
{ "resource": "" }
q261355
get_complete_version
validation
def get_complete_version(version=None): """ Returns a tuple of the django_cryptography version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django_cryptography import VERSION as version
python
{ "resource": "" }
q261356
enumeration
validation
def enumeration(*args): """ Return a value check function which raises a value error if the value is not in a pre-defined enumeration of values. If you pass in a list, tuple or set as the single argument, it is assumed that the list/tuple/set defines the membership of the enumeration. If you pass in more than on argument, it is assumed the arguments themselves define the enumeration. """ assert len(args) > 0, 'at least
python
{ "resource": "" }
q261357
match_pattern
validation
def match_pattern(regex): """ Return a value check function which raises a ValueError if the value does not match the supplied regular expression, see also `re.match`. """ prog =
python
{ "resource": "" }
q261358
search_pattern
validation
def search_pattern(regex): """ Return a value check function which raises a ValueError if the supplied regular expression does not match anywhere in
python
{ "resource": "" }
q261359
number_range_inclusive
validation
def number_range_inclusive(min, max, type=float): """ Return a value check function which raises a ValueError if the supplied value when cast as `type` is less than `min` or greater than `max`.
python
{ "resource": "" }
q261360
number_range_exclusive
validation
def number_range_exclusive(min, max, type=float): """ Return a value check function which raises a ValueError if the supplied value when cast
python
{ "resource": "" }
q261361
datetime_range_inclusive
validation
def datetime_range_inclusive(min, max, format): """ Return a value check function which raises a ValueError if the supplied value when converted to a datetime using the supplied `format` string is less than `min` or greater than `max`. """ dmin = datetime.strptime(min, format) dmax = datetime.strptime(max, format)
python
{ "resource": "" }
q261362
CSVValidator.add_header_check
validation
def add_header_check(self, code=HEADER_CHECK_FAILED, message=MESSAGES[HEADER_CHECK_FAILED]): """ Add a header check, i.e., check whether the header record is consistent
python
{ "resource": "" }
q261363
CSVValidator.add_record_length_check
validation
def add_record_length_check(self, code=RECORD_LENGTH_CHECK_FAILED, message=MESSAGES[RECORD_LENGTH_CHECK_FAILED], modulus=1): """ Add a record length check, i.e., check whether the length of a record is consistent with the number of
python
{ "resource": "" }
q261364
CSVValidator.add_value_check
validation
def add_value_check(self, field_name, value_check, code=VALUE_CHECK_FAILED, message=MESSAGES[VALUE_CHECK_FAILED], modulus=1): """ Add a value check function for the specified field. Arguments --------- `field_name` - the name of the field to attach the value check function to `value_check` - a function that accepts a single argument (a value) and raises a `ValueError` if the value is not valid `code` - problem code to report if a value is not valid, defaults to `VALUE_CHECK_FAILED` `message` - problem message to report if a value is
python
{ "resource": "" }
q261365
CSVValidator.add_value_predicate
validation
def add_value_predicate(self, field_name, value_predicate, code=VALUE_PREDICATE_FALSE, message=MESSAGES[VALUE_PREDICATE_FALSE], modulus=1): """ Add a value predicate function for the specified field. N.B., everything you can do with value predicates can also be done with value check functions, whether you use one or the other is a matter of style. Arguments --------- `field_name` - the name of the field to attach the value predicate function to `value_predicate` - a function that accepts a single argument (a value) and returns False if the value is not valid `code` - problem code to report if
python
{ "resource": "" }
q261366
CSVValidator.add_record_check
validation
def add_record_check(self, record_check, modulus=1): """ Add a record check function. Arguments --------- `record_check` - a function that accepts a single argument (a record as a dictionary of values indexed by field name) and raises a `RecordError` if the record is not valid `modulus` - apply the
python
{ "resource": "" }
q261367
CSVValidator.add_record_predicate
validation
def add_record_predicate(self, record_predicate, code=RECORD_PREDICATE_FALSE, message=MESSAGES[RECORD_PREDICATE_FALSE], modulus=1): """ Add a record predicate function. N.B., everything you can do with record predicates can also be done with record check functions, whether you use one or the other is a matter of style. Arguments --------- `record_predicate` - a function that accepts a single argument (a record as a dictionary of values indexed by field name) and returns False if the value is not valid `code` - problem code to report if
python
{ "resource": "" }
q261368
CSVValidator.add_unique_check
validation
def add_unique_check(self, key, code=UNIQUE_CHECK_FAILED, message=MESSAGES[UNIQUE_CHECK_FAILED]): """ Add a unique check on a single column or combination of columns. Arguments --------- `key` - a single field name (string) specifying a field in which all values are expected to be unique, or a sequence of field names (tuple or list of strings) specifying a compound key `code` - problem code to report if a record is not valid, defaults to `UNIQUE_CHECK_FAILED` `message` - problem message to report if a record is not
python
{ "resource": "" }
q261369
CSVValidator.validate
validation
def validate(self, data, expect_header_row=True, ignore_lines=0, summarize=False, limit=0, context=None, report_unexpected_exceptions=True): """ Validate `data` and return a list of validation problems found. Arguments --------- `data` - any source of row-oriented data, e.g., as provided by a `csv.reader`, or a list of lists of strings, or ... `expect_header_row` - does the data contain a header row (i.e., the first record is a list of field names)? Defaults to True. `ignore_lines` - ignore n lines (rows) at the beginning of the data `summarize` -
python
{ "resource": "" }
q261370
CSVValidator.ivalidate
validation
def ivalidate(self, data, expect_header_row=True, ignore_lines=0, summarize=False, context=None, report_unexpected_exceptions=True): """ Validate `data` and return a iterator over problems found. Use this function rather than validate() if you expect a large number of problems. Arguments --------- `data` - any source of row-oriented data, e.g., as provided by a `csv.reader`, or a list of lists of strings, or ... `expect_header_row` - does the data contain a header row (i.e., the first record is a list of field names)? Defaults to True. `ignore_lines` - ignore n lines (rows) at the beginning of the data `summarize` - only report problem codes, no other details `context` - a dictionary of any additional information to be added to any problems found - useful if problems are being aggregated from multiple validators `report_unexpected_exceptions` - value check function, value predicates, record check functions, record predicates, and other user-supplied validation functions may raise unexpected exceptions. If this argument is true, any unexpected exceptions will be reported as validation problems; if False, unexpected exceptions will be handled silently. """ unique_sets = self._init_unique_sets() # used for unique checks for i, r in enumerate(data): if expect_header_row and i == ignore_lines: # r is the header row for p in self._apply_header_checks(i, r, summarize, context): yield p elif i >= ignore_lines: # r is a data row skip = False for p in self._apply_skips(i, r, summarize, report_unexpected_exceptions, context): if p is True: skip = True else: yield p if not skip: for p in self._apply_each_methods(i, r, summarize, report_unexpected_exceptions, context): yield p # may yield a problem if an exception is raised for p in self._apply_value_checks(i, r, summarize, report_unexpected_exceptions, context): yield p
python
{ "resource": "" }
q261371
CSVValidator._init_unique_sets
validation
def _init_unique_sets(self): """Initialise sets used for uniqueness checking."""
python
{ "resource": "" }
q261372
CSVValidator._apply_value_checks
validation
def _apply_value_checks(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply value check functions on the given record `r`.""" for field_name, check, code, message, modulus in self._value_checks: if i % modulus == 0: # support sampling fi = self._field_names.index(field_name) if fi < len(r): # only apply checks if there is a value value = r[fi] try: check(value) except ValueError: p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['column'] = fi + 1 p['field'] = field_name p['value'] = value p['record'] = r if context is not None: p['context'] = context yield p except Exception as e: if report_unexpected_exceptions: p = {'code': UNEXPECTED_EXCEPTION}
python
{ "resource": "" }
q261373
CSVValidator._apply_header_checks
validation
def _apply_header_checks(self, i, r, summarize=False, context=None): """Apply header checks on the given record `r`.""" for code, message in self._header_checks: if tuple(r) != self._field_names: p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1
python
{ "resource": "" }
q261374
CSVValidator._apply_record_length_checks
validation
def _apply_record_length_checks(self, i, r, summarize=False, context=None): """Apply record length checks on the given record `r`.""" for code, message, modulus in self._record_length_checks: if i % modulus == 0: # support sampling if len(r) != len(self._field_names): p = {'code': code} if not summarize:
python
{ "resource": "" }
q261375
CSVValidator._apply_value_predicates
validation
def _apply_value_predicates(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply value predicates on the given record `r`.""" for field_name, predicate, code, message, modulus in self._value_predicates: if i % modulus == 0: # support sampling fi = self._field_names.index(field_name) if fi < len(r): # only apply predicate if there is a value value = r[fi] try: valid = predicate(value) if not valid: p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['column'] = fi + 1 p['field'] = field_name p['value'] = value p['record'] = r if context is not None: p['context'] = context yield p except Exception as e: if report_unexpected_exceptions:
python
{ "resource": "" }
q261376
CSVValidator._apply_record_checks
validation
def _apply_record_checks(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply record checks on `r`.""" for check, modulus in self._record_checks: if i % modulus == 0: # support sampling rdict = self._as_dict(r) try: check(rdict) except RecordError as e: code = e.code if e.code is not None else RECORD_CHECK_FAILED p = {'code': code} if not summarize: message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]
python
{ "resource": "" }
q261377
CSVValidator._apply_record_predicates
validation
def _apply_record_predicates(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply record predicates on `r`.""" for predicate, code, message, modulus in self._record_predicates: if i % modulus == 0: # support sampling rdict = self._as_dict(r) try: valid = predicate(rdict) if not valid: p = {'code': code} if not summarize:
python
{ "resource": "" }
q261378
CSVValidator._apply_unique_checks
validation
def _apply_unique_checks(self, i, r, unique_sets, summarize=False, context=None): """Apply unique checks on `r`.""" for key, code, message in self._unique_checks: value = None values = unique_sets[key] if isinstance(key, basestring): # assume key is a field name fi = self._field_names.index(key) if fi >= len(r): continue value = r[fi] else: # assume key is a list or tuple, i.e., compound key value = [] for f in key: fi = self._field_names.index(f) if fi >= len(r): break
python
{ "resource": "" }
q261379
CSVValidator._apply_each_methods
validation
def _apply_each_methods(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Invoke 'each' methods on `r`.""" for a in dir(self): if a.startswith('each'): rdict = self._as_dict(r) f = getattr(self, a) try: f(rdict) except Exception as e: if report_unexpected_exceptions: p = {'code': UNEXPECTED_EXCEPTION} if not summarize: p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e) p['row']
python
{ "resource": "" }
q261380
CSVValidator._apply_assert_methods
validation
def _apply_assert_methods(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply 'assert' methods on `r`.""" for a in dir(self): if a.startswith('assert'): rdict = self._as_dict(r) f = getattr(self, a) try: f(rdict) except AssertionError as e: code = ASSERT_CHECK_FAILED message = MESSAGES[ASSERT_CHECK_FAILED] if len(e.args) > 0: custom = e.args[0] if isinstance(custom, (list, tuple)): if len(custom) > 0: code = custom[0] if len(custom) > 1: message = custom[1] else: code = custom p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['record'] = r
python
{ "resource": "" }
q261381
CSVValidator._apply_check_methods
validation
def _apply_check_methods(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply 'check' methods on `r`.""" for a in dir(self): if a.startswith('check'): rdict = self._as_dict(r) f = getattr(self, a) try: f(rdict) except RecordError as e: code = e.code if e.code is not None else RECORD_CHECK_FAILED p = {'code': code} if not summarize: message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED] p['message'] = message p['row'] = i + 1 p['record'] = r if context is not None: p['context'] = context if e.details
python
{ "resource": "" }
q261382
CSVValidator._apply_skips
validation
def _apply_skips(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply skip functions on `r`.""" for skip in self._skips: try: result = skip(r) if result is True: yield True except Exception as e:
python
{ "resource": "" }
q261383
CSVValidator._as_dict
validation
def _as_dict(self, r): """Convert the record to a dictionary using field names as keys.""" d = dict()
python
{ "resource": "" }
q261384
create_validator
validation
def create_validator(): """Create an example CSV validator for patient demographic data.""" field_names = ( 'study_id', 'patient_id', 'gender', 'age_years', 'age_months', 'date_inclusion' ) validator = CSVValidator(field_names) # basic header and record length checks validator.add_header_check('EX1', 'bad header') validator.add_record_length_check('EX2', 'unexpected record length') # some simple value checks validator.add_value_check('study_id', int, 'EX3', 'study id must be an integer') validator.add_value_check('patient_id', int, 'EX4', 'patient id must be an integer') validator.add_value_check('gender', enumeration('M', 'F'), 'EX5', 'invalid gender') validator.add_value_check('age_years', number_range_inclusive(0, 120, int), 'EX6', 'invalid
python
{ "resource": "" }
q261385
main
validation
def main(): """Main function.""" # define a command-line argument parser description = 'Validate a CSV data file.' parser = argparse.ArgumentParser(description=description) parser.add_argument('file', metavar='FILE', help='a file to be validated') parser.add_argument('-l', '--limit', dest='limit', type=int, action='store', default=0, help='limit the number of problems reported' ) parser.add_argument('-s', '--summarize', dest='summarize', action='store_true', default=False, help='output only a summary of the different types of problem found' ) parser.add_argument('-e', '--report-unexpected-exceptions', dest='report_unexpected_exceptions', action='store_true', default=False, help='report any unexpected exceptions as problems' ) # parse arguments args = parser.parse_args() # sanity check arguments if not os.path.isfile(args.file): print '%s is not a file' % args.file sys.exit(1) with open(args.file, 'r') as f: # set up a csv reader for the data data = csv.reader(f, delimiter='\t') # create a validator validator = create_validator() # validate the data from the csv reader # N.B., validate() returns a list of problems; # if you expect a large number of
python
{ "resource": "" }
q261386
pack_into
validation
def pack_into(fmt, buf, offset, *args, **kwargs): """Pack given values v1, v2, ... into given bytearray `buf`, starting at given bit offset `offset`. Pack according to given format string `fmt`. Give `fill_padding` as ``False`` to leave padding bits in `buf` unmodified.
python
{ "resource": "" }
q261387
byteswap
validation
def byteswap(fmt, data, offset=0): """Swap bytes in `data` according to `fmt`, starting at byte `offset` and return the result. `fmt` must be an iterable, iterating over number of bytes to swap. For example, the format string ``'24'`` applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``. """ data = BytesIO(data)
python
{ "resource": "" }
q261388
TelegramEngine.get_chat_id
validation
def get_chat_id(self, message): ''' Telegram chat type can be either "private", "group", "supergroup" or "channel". Return user ID if it is of type "private", chat ID otherwise. '''
python
{ "resource": "" }
q261389
MessengerEngine.build_message
validation
def build_message(self, data): ''' Return a Message instance according to the data received from Facebook Messenger API. ''' if not data: return None return Message( id=data['message']['mid'], platform=self.platform,
python
{ "resource": "" }
q261390
BaseEngine._get_response
validation
async def _get_response(self, message): """ Get response running the view with await syntax if it is a coroutine function, otherwise just run it the normal way. """ view = self.discovery_view(message) if not view:
python
{ "resource": "" }
q261391
BaseEngine.discovery_view
validation
def discovery_view(self, message): """ Use the new message to search for a registered view according to its pattern. """ for handler in self.registered_handlers:
python
{ "resource": "" }
q261392
BaseEngine.message_handler
validation
async def message_handler(self, data): """ For each new message, build its platform specific message object and get a response. """ message = self.build_message(data) if not message: logger.error( '[%s] Unable to build Message with data, data=%s, error', self.engine_name, data )
python
{ "resource": "" }
q261393
unpack
validation
def unpack(endian, fmt, data): """Unpack a byte string to the given format. If the byte string contains more bytes than required for the given format, the function returns a tuple of values. """ if fmt == 's': # read data as an array
python
{ "resource": "" }
q261394
read_file_header
validation
def read_file_header(fd, endian): """Read mat 5 file header of the file fd. Returns a dict with header values. """ fields = [ ('description', 's', 116), ('subsystem_offset', 's', 8), ('version', 'H', 2), ('endian_test', 's', 2) ] hdict = {} for name, fmt, num_bytes in fields:
python
{ "resource": "" }
q261395
read_elements
validation
def read_elements(fd, endian, mtps, is_name=False): """Read elements from the file. If list of possible matrix data types mtps is provided, the data type of the elements are verified. """ mtpn, num_bytes, data = read_element_tag(fd, endian) if mtps and mtpn not in [etypes[mtp]['n'] for mtp in mtps]: raise ParseError('Got type {}, expected {}'.format( mtpn, ' / '.join('{} ({})'.format( etypes[mtp]['n'], mtp) for mtp in mtps)))
python
{ "resource": "" }
q261396
read_header
validation
def read_header(fd, endian): """Read and return the matrix header.""" flag_class, nzmax = read_elements(fd, endian, ['miUINT32']) header = { 'mclass': flag_class & 0x0FF, 'is_logical': (flag_class >> 9 & 1) == 1, 'is_global': (flag_class >> 10 & 1) == 1, 'is_complex': (flag_class >> 11 & 1) == 1, 'nzmax': nzmax
python
{ "resource": "" }
q261397
read_var_header
validation
def read_var_header(fd, endian): """Read full header tag. Return a dict with the parsed header, the file position of next tag, a file like object for reading the uncompressed element data. """ mtpn, num_bytes = unpack(endian, 'II', fd.read(8)) next_pos = fd.tell() + num_bytes if mtpn == etypes['miCOMPRESSED']['n']: # read compressed data data = fd.read(num_bytes) dcor = zlib.decompressobj() # from here, read of the decompressed data fd_var = BytesIO(dcor.decompress(data)) del data fd = fd_var # Check the stream is not so broken as to leave cruft behind
python
{ "resource": "" }
q261398
read_numeric_array
validation
def read_numeric_array(fd, endian, header, data_etypes): """Read a numeric matrix. Returns an array with rows of the numeric matrix. """ if header['is_complex']: raise ParseError('Complex arrays are not supported') # read array data (stored as column-major) data = read_elements(fd, endian, data_etypes) if not isinstance(data, Sequence): # not an array, just a value return data
python
{ "resource": "" }
q261399
read_cell_array
validation
def read_cell_array(fd, endian, header): """Read a cell array. Returns an array with rows of the cell array. """ array = [list() for i in range(header['dims'][0])] for row in range(header['dims'][0]): for col in range(header['dims'][1]):
python
{ "resource": "" }