signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def _until_eof(stream): | while True:<EOL><INDENT>line = stream.readline()<EOL>if line == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>yield line<EOL><DEDENT> | Yield lines from an open file.
Iterating over `sys.stdin` continues after EOF marker. This is annoying,
since it means having to type ``^D`` twice to stop. Wrap this function
around the stream to stop at the first EOF marker. | f2258:m0 |
def _fasta_iter(fasta): | <EOL>groups = (group for _, group in<EOL>itertools.groupby(fasta, lambda line: line.startswith('<STR_LIT:>>')))<EOL>for group in groups:<EOL><INDENT>header = next(group)[<NUM_LIT:1>:].strip()<EOL>sequence = '<STR_LIT>'.join(line.strip() for line in next(groups))<EOL>yield header, sequence<EOL><DEDENT> | Given an open FASTA file, yield tuples of (`header`, `sequence`). | f2258:m1 |
def _bed_iter(bed): | records = (line.split()[:<NUM_LIT:3>] for line in bed if<EOL>not (line.startswith('<STR_LIT>') or line.startswith('<STR_LIT>')))<EOL>for chrom, chrom_iter in itertools.groupby(records, lambda x: x[<NUM_LIT:0>]):<EOL><INDENT>yield chrom, ((int(start), int(stop))<EOL>for _, start, stop in chrom_iter)<EOL><DEDENT> | Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where
`chrom_iter` yields tuples of (`start`, `stop`). | f2258:m2 |
def _pprint_fasta(fasta, annotations=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = annotations or []<EOL>as_by_chrom = collections.defaultdict(lambda: [a for a in annotations] or [])<EOL>if annotation_file:<EOL><INDENT>for chrom, chrom_iter in _bed_iter(annotation_file):<EOL><INDENT>as_by_chrom[chrom].append(list(chrom_iter))<EOL><DEDENT><DEDENT>for header, sequence in _fasta_iter(fasta):<EOL><INDENT>print(header)<EOL>print(pprint_sequence(sequence,<EOL>annotations=as_by_chrom[header.split()[<NUM_LIT:0>]],<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line,<EOL>format=AnsiFormat))<EOL><DEDENT> | Pretty-print each record in the FASTA file. | f2258:m3 |
def _pprint_line(line, annotations=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = annotations or []<EOL>if annotation_file:<EOL><INDENT>_, chrom_iter = next(_bed_iter(annotation_file))<EOL>annotations.append(list(chrom_iter))<EOL><DEDENT>print(pprint_sequence(line, annotations=annotations,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line, format=AnsiFormat))<EOL> | Pretty-print one line. | f2258:m4 |
def pprint(sequence_file, annotation=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = []<EOL>if annotation:<EOL><INDENT>annotations.append([(first - <NUM_LIT:1>, last) for first, last in annotation])<EOL><DEDENT>try:<EOL><INDENT>line = next(sequence_file)<EOL>if line.startswith('<STR_LIT:>>'):<EOL><INDENT>_pprint_fasta(itertools.chain([line], sequence_file),<EOL>annotations=annotations,<EOL>annotation_file=annotation_file,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line)<EOL><DEDENT>else:<EOL><INDENT>_pprint_line(line.strip(), annotations=annotations,<EOL>annotation_file=annotation_file,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT> | Pretty-print sequence(s) from a file. | f2258:m5 |
def main(): | parser = argparse.ArgumentParser(<EOL>description='<STR_LIT>',<EOL>epilog='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', metavar='<STR_LIT>', nargs='<STR_LIT:?>', default=sys.stdin,<EOL>type=argparse.FileType('<STR_LIT:r>'), help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', dest='<STR_LIT>',<EOL>type=int, default=<NUM_LIT:10>, help='<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', dest='<STR_LIT>',<EOL>type=int, default=<NUM_LIT:6>, help='<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', dest='<STR_LIT>', nargs=<NUM_LIT:2>,<EOL>action='<STR_LIT>', type=int, help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', dest='<STR_LIT>',<EOL>type=argparse.FileType('<STR_LIT:r>'), help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>args = parser.parse_args()<EOL>pprint(_until_eof(args.sequence_file), annotation=args.annotation,<EOL>annotation_file=args.annotation_file,<EOL>block_length=args.block_length,<EOL>blocks_per_line=args.blocks_per_line)<EOL> | Command line interface. | f2258:m6 |
def partition_range(stop, annotations=None): | annotations = annotations or []<EOL>partitioning = []<EOL>part_start, part_levels = <NUM_LIT:0>, None<EOL>for p in sorted(set(itertools.chain([<NUM_LIT:0>, stop],<EOL>*itertools.chain(*annotations)))):<EOL><INDENT>if p == stop:<EOL><INDENT>partitioning.append( (part_start, p, part_levels) )<EOL>break<EOL><DEDENT>levels = {level for level, regions in enumerate(annotations)<EOL>if any(x <= p < y for x, y in regions)}<EOL>if p == <NUM_LIT:0>:<EOL><INDENT>part_levels = levels<EOL>continue<EOL><DEDENT>if levels != part_levels:<EOL><INDENT>partitioning.append( (part_start, p, part_levels) )<EOL>part_start, part_levels = p, levels<EOL><DEDENT><DEDENT>return partitioning<EOL> | Partition the range from 0 to `stop` based on annotations.
>>> partition_range(50, annotations=[[(0, 21), (30, 35)],
... [(15, 32), (40, 46)]])
[(0, 15, {0}),
(15, 21, {0, 1}),
(21, 30, {1}),
(30, 32, {0, 1}),
(32, 35, {0}),
(35, 40, set()),
(40, 46, {1}),
(46, 50, set())]
:arg stop: End point (not included) of the range (similar to the `stop`
argument of the built-in :func:`range` function).
:type stop: int
:arg annotations: For each annotation level, a list of (`start`, `stop`)
pairs defining an annotated region.
:type annotations: list
:return: Partitioning of the range as (`start`, `stop`, `levels`) tuples
defining a region with a set of annotation levels.
:rtype: list
All regions (`start`, `stop`) are defined as in slicing notation, so
zero-based and `stop` is not included.
The `annotations` argument is a list of annotations. An annotation is a
list of regions as (`start`, `stop`) tuples. The level of each annotation
is its index in `annotations`.
Annotation regions can overlap (overlap within one level is ignored) and
do not need to be sorted. | f2259:m0 |
def pprint_sequence(sequence, annotations=None, block_length=<NUM_LIT:10>,<EOL>blocks_per_line=<NUM_LIT:6>, format=PlaintextFormat): | annotations = annotations or []<EOL>partitioning = partition_range(len(sequence), annotations)<EOL>margin = int(math.floor(math.log(max(len(sequence), <NUM_LIT:1>), <NUM_LIT:10>))<EOL>+ <NUM_LIT:1>) + len(format.margin[<NUM_LIT:0>])<EOL>result = (format.margin[<NUM_LIT:0>] + '<STR_LIT:1>').rjust(margin) + format.margin[<NUM_LIT:1>] + '<STR_LIT:U+0020>'<EOL>for p in range(<NUM_LIT:0>, len(sequence), block_length):<EOL><INDENT>block = [(max(start, p), min(stop, p + block_length), levels)<EOL>for start, stop, levels in partitioning<EOL>if start < p + block_length and stop > p]<EOL>result += '<STR_LIT:U+0020>'<EOL>for start, stop, levels in block:<EOL><INDENT>delimiters = [(left, right) for level, (left, right)<EOL>in enumerate(format.annotations) if level in levels]<EOL>result += ('<STR_LIT>'.join(left for left, right in reversed(delimiters)) +<EOL>str(sequence[start:stop]) +<EOL>'<STR_LIT>'.join(right for left, right in delimiters))<EOL><DEDENT>if (not (p + block_length) % (block_length * blocks_per_line) and<EOL>p + block_length < len(sequence)):<EOL><INDENT>result += ('<STR_LIT:\n>' + (format.margin[<NUM_LIT:0>] +<EOL>str(p + block_length + <NUM_LIT:1>)).rjust(margin) +<EOL>format.margin[<NUM_LIT:1>] + '<STR_LIT:U+0020>')<EOL><DEDENT><DEDENT>return result<EOL> | Pretty-print sequence for use with a monospace font.
>>> sequence = 'MIMANQPLWLDSEVEMNHYQQSHIKSKSPYFPEDKHICWIKIFKAFGT' * 4
>>> print pprint_sequence(sequence, format=PlaintextFormat)
1 MIMANQPLWL DSEVEMNHYQ QSHIKSKSPY FPEDKHICWI KIFKAFGTMI MANQPLWLDS
61 EVEMNHYQQS HIKSKSPYFP EDKHICWIKI FKAFGTMIMA NQPLWLDSEV EMNHYQQSHI
121 KSKSPYFPED KHICWIKIFK AFGTMIMANQ PLWLDSEVEM NHYQQSHIKS KSPYFPEDKH
181 ICWIKIFKAF GT
:arg sequence: Sequence to pretty-print.
:type sequence: str or any sliceable yielding slices representable as
strings.
:arg annotations: For each annotation level, a list of (`start`, `stop`)
pairs defining an annotated region.
:type annotations: list
:arg block_length: Length of space-separated blocks.
:type block_length: int
:arg blocks_per_line: Number of blocks per line.
:type blocks_per_line: int
:arg format: Output format to use for pretty-printing. Some formats are
pre-defined as :data:`HtmlFormat`, :data:`AnsiFormat`, and
:data:`PlaintextFormat`.
:type format: :class:`Format`
:return: Pretty-printed version of `sequence`.
:rtype: str
All regions (`start`, `stop`) are defined as in slicing notation, so
zero-based and `stop` is not included.
The `annotations` argument is a list of annotations. An annotation is a
list of regions as (`start`, `stop`) tuples. The level of each annotation
is its index in `annotations`.
Annotation regions can overlap (overlap within one level is ignored) and
do not need to be sorted.
The number of annotation levels supported depends on `format`.
:data:`HtmlFormat` supports 10 levels, :data:`AnsiFormat` supports 3
levels and annotations are ignored completely with
:data:`PlaintextFormat`. | f2259:m1 |
def Seq(sequence, annotations=None, block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>,<EOL>style=DEFAULT_STYLE): | seq_id = '<STR_LIT>' + binascii.hexlify(os.urandom(<NUM_LIT:4>))<EOL>pprinted = pprint_sequence(sequence,<EOL>annotations=annotations,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line,<EOL>format=HtmlFormat)<EOL>return HTML('<STR_LIT>'<EOL>.format(style=style.format(selector='<STR_LIT:#>' + seq_id),<EOL>seq_id=seq_id,<EOL>pprinted=pprinted))<EOL> | Pretty-printed sequence object that's displayed nicely in the IPython
Notebook.
:arg style: Custom CSS as a `format string`, where a selector for the
top-level ``<pre>`` element is substituted for `{selector}`. See
:data:`DEFAULT_STYLE` for an example.
:type style: str
For a description of the other arguments, see
:func:`monoseq.pprint_sequence`. | f2261:m0 |
def run(self, toolbox): | self.results.put(toolbox.count)<EOL>toolbox.count += <NUM_LIT:1><EOL> | Append the current count to results and increment. | f2265:c1:m1 |
def put(self, job, result): | self.job.put(job)<EOL>r = result.get()<EOL>return r<EOL> | Perform a job by a member in the pool and return the result. | f2270:c0:m0 |
def contract(self, jobs, result): | for j in jobs:<EOL><INDENT>WorkerPool.put(self, j)<EOL><DEDENT>r = []<EOL>for i in xrange(len(jobs)):<EOL><INDENT>r.append(result.get())<EOL><DEDENT>return r<EOL> | Perform a contract on a number of jobs and block until a result is
retrieved for each job. | f2270:c0:m1 |
def run(self): | while <NUM_LIT:1>:<EOL><INDENT>job = self.jobs.get()<EOL>try:<EOL><INDENT>job.run()<EOL>self.jobs.task_done()<EOL><DEDENT>except TerminationNotice:<EOL><INDENT>self.jobs.task_done()<EOL>break<EOL><DEDENT><DEDENT> | Get jobs from the queue and perform them as they arrive. | f2271:c0:m1 |
def run(self): | while <NUM_LIT:1>:<EOL><INDENT>job = self.jobs.get()<EOL>try:<EOL><INDENT>job.run(toolbox=self.toolbox)<EOL>self.jobs.task_done()<EOL><DEDENT>except TerminationNotice:<EOL><INDENT>self.jobs.task_done()<EOL>break<EOL><DEDENT><DEDENT> | Get jobs from the queue and perform them as they arrive. | f2271:c1:m1 |
def run(self): | pass<EOL> | The actual task for the job should be implemented here. | f2272:c0:m1 |
def _return(self, r): | self.result.put(r)<EOL> | Handle return value by appending to the ``self.result`` queue. | f2272:c2:m2 |
def task_done(self): | pass<EOL> | Does nothing in Python 2.4 | f2274:c0:m0 |
def join(self): | pass<EOL> | Does nothing in Python 2.4 | f2274:c0:m1 |
def grow(self): | t = self.worker_factory(self)<EOL>t.start()<EOL>self._size += <NUM_LIT:1><EOL> | Add another worker to the pool. | f2275:c0:m1 |
def shrink(self): | if self._size <= <NUM_LIT:0>:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>self._size -= <NUM_LIT:1><EOL>self.put(SuicideJob())<EOL> | Get rid of one worker from the pool. Raises IndexError if empty. | f2275:c0:m2 |
def shutdown(self): | for i in range(self.size()):<EOL><INDENT>self.put(SuicideJob())<EOL><DEDENT> | Retire the workers. | f2275:c0:m3 |
def size(self): | "<STR_LIT>"<EOL>return self._size<EOL> | Approximate number of active workers | f2275:c0:m4 |
def map(self, fn, *seq): | "<STR_LIT>"<EOL>results = Queue()<EOL>args = zip(*seq)<EOL>for seq in args:<EOL><INDENT>j = SimpleJob(results, fn, seq)<EOL>self.put(j)<EOL><DEDENT>r = []<EOL>for i in range(len(list(args))):<EOL><INDENT>r.append(results.get())<EOL><DEDENT>return r<EOL> | Perform a map operation distributed among the workers. Will | f2275:c0:m5 |
def wait(self): | self.join()<EOL> | DEPRECATED: Use join() instead. | f2275:c0:m6 |
def async_run(self, keyword, *args, **kwargs): | handle = self._last_thread_handle<EOL>thread = self._threaded(keyword, *args, **kwargs)<EOL>thread.start()<EOL>self._thread_pool[handle] = thread<EOL>self._last_thread_handle += <NUM_LIT:1><EOL>return handle<EOL> | Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get | f2278:c0:m1 |
def async_get(self, handle): | assert handle in self._thread_pool, '<STR_LIT>'<EOL>result = self._thread_pool[handle].result_queue.get()<EOL>del self._thread_pool[handle]<EOL>return result<EOL> | Blocks until the thread created by async_run returns | f2278:c0:m2 |
def _get_handler_from_keyword(self, keyword): | if EXECUTION_CONTEXTS.current is None:<EOL><INDENT>raise RobotNotRunningError('<STR_LIT>')<EOL><DEDENT>return EXECUTION_CONTEXTS.current.get_handler(keyword)<EOL> | Gets the Robot Framework handler associated with the given keyword | f2278:c0:m3 |
def Lower(v): | return _fix_str(v).lower()<EOL> | Transform a string to lower case.
>>> s = Schema(Lower)
>>> s('HI')
'hi' | f2281:m1 |
def Upper(v): | return _fix_str(v).upper()<EOL> | Transform a string to upper case.
>>> s = Schema(Upper)
>>> s('hi')
'HI' | f2281:m2 |
def Capitalize(v): | return _fix_str(v).capitalize()<EOL> | Capitalise a string.
>>> s = Schema(Capitalize)
>>> s('hello world')
'Hello world' | f2281:m3 |
def Title(v): | return _fix_str(v).title()<EOL> | Title case a string.
>>> s = Schema(Title)
>>> s('hello world')
'Hello World' | f2281:m4 |
def Strip(v): | return _fix_str(v).strip()<EOL> | Strip whitespace from a string.
>>> s = Schema(Strip)
>>> s(' hello world ')
'hello world' | f2281:m5 |
def truth(f): | @wraps(f)<EOL>def check(v):<EOL><INDENT>t = f(v)<EOL>if not t:<EOL><INDENT>raise ValueError<EOL><DEDENT>return v<EOL><DEDENT>return check<EOL> | Convenience decorator to convert truth functions into validators.
>>> @truth
... def isdir(v):
... return os.path.isdir(v)
>>> validate = Schema(isdir)
>>> validate('/')
'/'
>>> with raises(MultipleInvalid, 'not a valid value'):
... validate('/notavaliddir') | f2284:m0 |
@message('<STR_LIT>', cls=TrueInvalid)<EOL>@truth<EOL>def IsTrue(v): | return v<EOL> | Assert that a value is true, in the Python sense.
>>> validate = Schema(IsTrue())
"In the Python sense" means that implicitly false values, such as empty
lists, dictionaries, etc. are treated as "false":
>>> with raises(MultipleInvalid, "value was not true"):
... validate([])
>>> validate([1])
[1]
>>> with raises(MultipleInvalid, "value was not true"):
... validate(False)
...and so on.
>>> try:
... validate([])
... except MultipleInvalid as e:
... assert isinstance(e.errors[0], TrueInvalid) | f2284:m1 |
@message('<STR_LIT>', cls=FalseInvalid)<EOL>def IsFalse(v): | if v:<EOL><INDENT>raise ValueError<EOL><DEDENT>return v<EOL> | Assert that a value is false, in the Python sense.
(see :func:`IsTrue` for more detail)
>>> validate = Schema(IsFalse())
>>> validate([])
[]
>>> with raises(MultipleInvalid, "value was not false"):
... validate(True)
>>> try:
... validate(True)
... except MultipleInvalid as e:
... assert isinstance(e.errors[0], FalseInvalid) | f2284:m2 |
@message('<STR_LIT>', cls=BooleanInvalid)<EOL>def Boolean(v): | if isinstance(v, basestring):<EOL><INDENT>v = v.lower()<EOL>if v in ('<STR_LIT:1>', '<STR_LIT:true>', '<STR_LIT:yes>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>if v in ('<STR_LIT:0>', '<STR_LIT:false>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>raise ValueError<EOL><DEDENT>return bool(v)<EOL> | Convert human-readable boolean values to a bool.
Accepted values are 1, true, yes, on, enable, and their negatives.
Non-string values are cast to bool.
>>> validate = Schema(Boolean())
>>> validate(True)
True
>>> validate("1")
True
>>> validate("0")
False
>>> with raises(MultipleInvalid, "expected boolean"):
... validate('moo')
>>> try:
... validate('moo')
... except MultipleInvalid as e:
... assert isinstance(e.errors[0], BooleanInvalid) | f2284:m3 |
@message('<STR_LIT>', cls=EmailInvalid)<EOL>def Email(v): | try:<EOL><INDENT>if not v or "<STR_LIT:@>" not in v:<EOL><INDENT>raise EmailInvalid("<STR_LIT>")<EOL><DEDENT>user_part, domain_part = v.rsplit('<STR_LIT:@>', <NUM_LIT:1>)<EOL>if not (USER_REGEX.match(user_part) and DOMAIN_REGEX.match(domain_part)):<EOL><INDENT>raise EmailInvalid("<STR_LIT>")<EOL><DEDENT>return v<EOL><DEDENT>except:<EOL><INDENT>raise ValueError<EOL><DEDENT> | Verify that the value is an Email or not.
>>> s = Schema(Email())
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("[email protected]")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("[email protected]")
>>> s('[email protected]')
'[email protected]' | f2284:m5 |
@message('<STR_LIT>', cls=UrlInvalid)<EOL>def FqdnUrl(v): | try:<EOL><INDENT>parsed_url = _url_validation(v)<EOL>if "<STR_LIT:.>" not in parsed_url.netloc:<EOL><INDENT>raise UrlInvalid("<STR_LIT>")<EOL><DEDENT>return v<EOL><DEDENT>except:<EOL><INDENT>raise ValueError<EOL><DEDENT> | Verify that the value is a Fully qualified domain name URL.
>>> s = Schema(FqdnUrl())
>>> with raises(MultipleInvalid, 'expected a Fully qualified domain name URL'):
... s("http://localhost/")
>>> s('http://w3.org')
'http://w3.org' | f2284:m6 |
@message('<STR_LIT>', cls=UrlInvalid)<EOL>def Url(v): | try:<EOL><INDENT>_url_validation(v)<EOL>return v<EOL><DEDENT>except:<EOL><INDENT>raise ValueError<EOL><DEDENT> | Verify that the value is a URL.
>>> s = Schema(Url())
>>> with raises(MultipleInvalid, 'expected a URL'):
... s(1)
>>> s('http://w3.org')
'http://w3.org' | f2284:m7 |
@message('<STR_LIT>', cls=FileInvalid)<EOL>@truth<EOL>def IsFile(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.isfile(v)<EOL><DEDENT>else:<EOL><INDENT>raise FileInvalid('<STR_LIT>')<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise FileInvalid('<STR_LIT>')<EOL><DEDENT> | Verify the file exists.
>>> os.path.basename(IsFile()(__file__)).startswith('validators.py')
True
>>> with raises(FileInvalid, 'not a file'):
... IsFile()("random_filename_goes_here.py")
>>> with raises(FileInvalid, 'Not a file'):
... IsFile()(None) | f2284:m8 |
@message('<STR_LIT>', cls=DirInvalid)<EOL>@truth<EOL>def IsDir(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.isdir(v)<EOL><DEDENT>else:<EOL><INDENT>raise DirInvalid("<STR_LIT>")<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise DirInvalid("<STR_LIT>")<EOL><DEDENT> | Verify the directory exists.
>>> IsDir()('/')
'/'
>>> with raises(DirInvalid, 'Not a directory'):
... IsDir()(None) | f2284:m9 |
@message('<STR_LIT>', cls=PathInvalid)<EOL>@truth<EOL>def PathExists(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.exists(v)<EOL><DEDENT>else:<EOL><INDENT>raise PathInvalid("<STR_LIT>")<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise PathInvalid("<STR_LIT>")<EOL><DEDENT> | Verify the path exists, regardless of its type.
>>> os.path.basename(PathExists()(__file__)).startswith('validators.py')
True
>>> with raises(Invalid, 'path does not exist'):
... PathExists()("random_filename_goes_here.py")
>>> with raises(PathInvalid, 'Not a Path'):
... PathExists()(None) | f2284:m10 |
def Maybe(validator, msg=None): | return Any(None, validator, msg=msg)<EOL> | Validate that the object matches given validator or is None.
:raises Invalid: if the value does not match the given validator and is not
None
>>> s = Schema(Maybe(int))
>>> s(10)
10
>>> with raises(Invalid):
... s("string") | f2284:m11 |
def __call__(self, v): | precision, scale, decimal_num = self._get_precision_scale(v)<EOL>if self.precision is not None and self.scale is not None and precision != self.precisionand scale != self.scale:<EOL><INDENT>raise Invalid(self.msg or "<STR_LIT>" % (self.precision,<EOL>self.scale))<EOL><DEDENT>else:<EOL><INDENT>if self.precision is not None and precision != self.precision:<EOL><INDENT>raise Invalid(self.msg or "<STR_LIT>" % self.precision)<EOL><DEDENT>if self.scale is not None and scale != self.scale:<EOL><INDENT>raise Invalid(self.msg or "<STR_LIT>" % self.scale)<EOL><DEDENT><DEDENT>if self.yield_decimal:<EOL><INDENT>return decimal_num<EOL><DEDENT>else:<EOL><INDENT>return v<EOL><DEDENT> | :param v: is a number enclosed with string
:return: Decimal number | f2284:c18:m1 |
def _get_precision_scale(self, number): | try:<EOL><INDENT>decimal_num = Decimal(number)<EOL><DEDENT>except InvalidOperation:<EOL><INDENT>raise Invalid(self.msg or '<STR_LIT>')<EOL><DEDENT>return (len(decimal_num.as_tuple().digits), -(decimal_num.as_tuple().exponent), decimal_num)<EOL> | :param number:
:return: tuple(precision, scale, decimal_number) | f2284:c18:m3 |
def humanize_error(data, validation_error, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH): | if isinstance(validation_error, MultipleInvalid):<EOL><INDENT>return '<STR_LIT:\n>'.join(sorted(<EOL>humanize_error(data, sub_error, max_sub_error_length)<EOL>for sub_error in validation_error.errors<EOL>))<EOL><DEDENT>else:<EOL><INDENT>offending_item_summary = repr(_nested_getitem(data, validation_error.path))<EOL>if len(offending_item_summary) > max_sub_error_length:<EOL><INDENT>offending_item_summary = offending_item_summary[:max_sub_error_length - <NUM_LIT:3>] + '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>' % (validation_error, offending_item_summary)<EOL><DEDENT> | Provide a more helpful + complete validation error message than that provided automatically
Invalid and MultipleInvalid do not include the offending value in error messages,
and MultipleInvalid.__str__ only provides the first error. | f2285:m1 |
def Extra(_): | raise er.SchemaError('<STR_LIT>')<EOL> | Allow keys in the data that are not present in the schema. | f2288:m4 |
def _compile_scalar(schema): | if inspect.isclass(schema):<EOL><INDENT>def validate_instance(path, data):<EOL><INDENT>if isinstance(data, schema):<EOL><INDENT>return data<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % schema.__name__<EOL>raise er.TypeInvalid(msg, path)<EOL><DEDENT><DEDENT>return validate_instance<EOL><DEDENT>if callable(schema):<EOL><INDENT>def validate_callable(path, data):<EOL><INDENT>try:<EOL><INDENT>return schema(data)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise er.ValueInvalid('<STR_LIT>', path)<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>e.prepend(path)<EOL>raise<EOL><DEDENT><DEDENT>return validate_callable<EOL><DEDENT>def validate_value(path, data):<EOL><INDENT>if data != schema:<EOL><INDENT>raise er.ScalarInvalid('<STR_LIT>', path)<EOL><DEDENT>return data<EOL><DEDENT>return validate_value<EOL> | A scalar value.
The schema can either be a value or a type.
>>> _compile_scalar(int)([], 1)
1
>>> with raises(er.Invalid, 'expected float'):
... _compile_scalar(float)([], '1')
Callables have
>>> _compile_scalar(lambda v: float(v))([], '1')
1.0
As a convenience, ValueError's are trapped:
>>> with raises(er.Invalid, 'not a valid value'):
... _compile_scalar(lambda v: float(v))([], 'a') | f2288:m5 |
def _compile_itemsort(): | def is_extra(key_):<EOL><INDENT>return key_ is Extra<EOL><DEDENT>def is_remove(key_):<EOL><INDENT>return isinstance(key_, Remove)<EOL><DEDENT>def is_marker(key_):<EOL><INDENT>return isinstance(key_, Marker)<EOL><DEDENT>def is_type(key_):<EOL><INDENT>return inspect.isclass(key_)<EOL><DEDENT>def is_callable(key_):<EOL><INDENT>return callable(key_)<EOL><DEDENT>priority = [(<NUM_LIT:1>, is_remove), <EOL>(<NUM_LIT:2>, is_marker), <EOL>(<NUM_LIT:4>, is_type), <EOL>(<NUM_LIT:3>, is_callable), <EOL>(<NUM_LIT:5>, is_extra)] <EOL>def item_priority(item_):<EOL><INDENT>key_ = item_[<NUM_LIT:0>]<EOL>for i, check_ in priority:<EOL><INDENT>if check_(key_):<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL><DEDENT>return item_priority<EOL> | return sort function of mappings | f2288:m6 |
def _iterate_mapping_candidates(schema): | <EOL>return sorted(iteritems(schema), key=_sort_item)<EOL> | Iterate over schema in a meaningful order. | f2288:m7 |
def _iterate_object(obj): | d = {}<EOL>try:<EOL><INDENT>d = vars(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>d = obj._asdict()<EOL><DEDENT><DEDENT>for item in iteritems(d):<EOL><INDENT>yield item<EOL><DEDENT>try:<EOL><INDENT>slots = obj.__slots__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>for key in slots:<EOL><INDENT>if key != '<STR_LIT>':<EOL><INDENT>yield (key, getattr(obj, key))<EOL><DEDENT><DEDENT><DEDENT> | Return iterator over object attributes. Respect objects with
defined __slots__. | f2288:m8 |
def message(default=None, cls=None): | if cls and not issubclass(cls, er.Invalid):<EOL><INDENT>raise er.SchemaError("<STR_LIT>")<EOL><DEDENT>def decorator(f):<EOL><INDENT>@wraps(f)<EOL>def check(msg=None, clsoverride=None):<EOL><INDENT>@wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise (clsoverride or cls or er.ValueInvalid)(msg or default or '<STR_LIT>')<EOL><DEDENT><DEDENT>return wrapper<EOL><DEDENT>return check<EOL><DEDENT>return decorator<EOL> | Convenience decorator to allow functions to provide a message.
Set a default message:
>>> @message('not an integer')
... def isint(v):
... return int(v)
>>> validate = Schema(isint())
>>> with raises(er.MultipleInvalid, 'not an integer'):
... validate('a')
The message can be overridden on a per validator basis:
>>> validate = Schema(isint('bad'))
>>> with raises(er.MultipleInvalid, 'bad'):
... validate('a')
The class thrown too:
>>> class IntegerInvalid(er.Invalid): pass
>>> validate = Schema(isint('bad', clsoverride=IntegerInvalid))
>>> try:
... validate('a')
... except er.MultipleInvalid as e:
... assert isinstance(e.errors[0], IntegerInvalid) | f2288:m9 |
def _args_to_dict(func, args): | if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>arg_count = func.__code__.co_argcount<EOL>arg_names = func.__code__.co_varnames[:arg_count]<EOL><DEDENT>else:<EOL><INDENT>arg_count = func.func_code.co_argcount<EOL>arg_names = func.func_code.co_varnames[:arg_count]<EOL><DEDENT>arg_value_list = list(args)<EOL>arguments = dict((arg_name, arg_value_list[i])<EOL>for i, arg_name in enumerate(arg_names)<EOL>if i < len(arg_value_list))<EOL>return arguments<EOL> | Returns argument names as values as key-value pairs. | f2288:m10 |
def _merge_args_with_kwargs(args_dict, kwargs_dict): | ret = args_dict.copy()<EOL>ret.update(kwargs_dict)<EOL>return ret<EOL> | Merge args with kwargs. | f2288:m11 |
def validate(*a, **kw): | RETURNS_KEY = '<STR_LIT>'<EOL>def validate_schema_decorator(func):<EOL><INDENT>returns_defined = False<EOL>returns = None<EOL>schema_args_dict = _args_to_dict(func, a)<EOL>schema_arguments = _merge_args_with_kwargs(schema_args_dict, kw)<EOL>if RETURNS_KEY in schema_arguments:<EOL><INDENT>returns_defined = True<EOL>returns = schema_arguments[RETURNS_KEY]<EOL>del schema_arguments[RETURNS_KEY]<EOL><DEDENT>input_schema = (Schema(schema_arguments, extra=ALLOW_EXTRA)<EOL>if len(schema_arguments) != <NUM_LIT:0> else lambda x: x)<EOL>output_schema = Schema(returns) if returns_defined else lambda x: x<EOL>@wraps(func)<EOL>def func_wrapper(*args, **kwargs):<EOL><INDENT>args_dict = _args_to_dict(func, args)<EOL>arguments = _merge_args_with_kwargs(args_dict, kwargs)<EOL>validated_arguments = input_schema(arguments)<EOL>output = func(**validated_arguments)<EOL>return output_schema(output)<EOL><DEDENT>return func_wrapper<EOL><DEDENT>return validate_schema_decorator<EOL> | Decorator for validating arguments of a function against a given schema.
Set restrictions for arguments:
>>> @validate(arg1=int, arg2=int)
... def foo(arg1, arg2):
... return arg1 * arg2
Set restriction for returned value:
>>> @validate(arg=int, __return__=int)
... def bar(arg1):
... return arg1 * 2 | f2288:m12 |
def __init__(self, schema, required=False, extra=PREVENT_EXTRA): | self.schema = schema<EOL>self.required = required<EOL>self.extra = int(extra) <EOL>self._compiled = self._compile(schema)<EOL> | Create a new Schema.
:param schema: Validation schema. See :module:`voluptuous` for details.
:param required: Keys defined in the schema must be in the data.
:param extra: Specify how extra keys in the data are treated:
- :const:`~voluptuous.PREVENT_EXTRA`: to disallow any undefined
extra keys (raise ``Invalid``).
- :const:`~voluptuous.ALLOW_EXTRA`: to include undefined extra
keys in the output.
- :const:`~voluptuous.REMOVE_EXTRA`: to exclude undefined extra keys
from the output.
- Any value other than the above defaults to
:const:`~voluptuous.PREVENT_EXTRA` | f2288:c1:m0 |
@classmethod<EOL><INDENT>def infer(cls, data, **kwargs):<DEDENT> | def value_to_schema_type(value):<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>if len(value) == <NUM_LIT:0>:<EOL><INDENT>return dict<EOL><DEDENT>return {k: value_to_schema_type(v)<EOL>for k, v in iteritems(value)}<EOL><DEDENT>if isinstance(value, list):<EOL><INDENT>if len(value) == <NUM_LIT:0>:<EOL><INDENT>return list<EOL><DEDENT>else:<EOL><INDENT>return [value_to_schema_type(v)<EOL>for v in value]<EOL><DEDENT><DEDENT>return type(value)<EOL><DEDENT>return cls(value_to_schema_type(data), **kwargs)<EOL> | Create a Schema from concrete data (e.g. an API response).
For example, this will take a dict like:
{
'foo': 1,
'bar': {
'a': True,
'b': False
},
'baz': ['purple', 'monkey', 'dishwasher']
}
And return a Schema:
{
'foo': int,
'bar': {
'a': bool,
'b': bool
},
'baz': [str]
}
Note: only very basic inference is supported. | f2288:c1:m1 |
def __call__(self, data): | try:<EOL><INDENT>return self._compiled([], data)<EOL><DEDENT>except er.MultipleInvalid:<EOL><INDENT>raise<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>raise er.MultipleInvalid([e])<EOL><DEDENT> | Validate data against this schema. | f2288:c1:m6 |
def _compile_mapping(self, schema, invalid_msg=None): | invalid_msg = invalid_msg or '<STR_LIT>'<EOL>all_required_keys = set(key for key in schema<EOL>if key is not Extra and<EOL>((self.required and not isinstance(key, (Optional, Remove))) or<EOL>isinstance(key, Required)))<EOL>all_default_keys = set(key for key in schema<EOL>if isinstance(key, Required) or<EOL>isinstance(key, Optional))<EOL>_compiled_schema = {}<EOL>for skey, svalue in iteritems(schema):<EOL><INDENT>new_key = self._compile(skey)<EOL>new_value = self._compile(svalue)<EOL>_compiled_schema[skey] = (new_key, new_value)<EOL><DEDENT>candidates = list(_iterate_mapping_candidates(_compiled_schema))<EOL>additional_candidates = []<EOL>candidates_by_key = {}<EOL>for skey, (ckey, cvalue) in candidates:<EOL><INDENT>if type(skey) in primitive_types:<EOL><INDENT>candidates_by_key.setdefault(skey, []).append((skey, (ckey, cvalue)))<EOL><DEDENT>elif isinstance(skey, Marker) and type(skey.schema) in primitive_types:<EOL><INDENT>candidates_by_key.setdefault(skey.schema, []).append((skey, (ckey, cvalue)))<EOL><DEDENT>else:<EOL><INDENT>additional_candidates.append((skey, (ckey, cvalue)))<EOL><DEDENT><DEDENT>def validate_mapping(path, iterable, out):<EOL><INDENT>required_keys = all_required_keys.copy()<EOL>key_value_map = type(out)()<EOL>for key, value in iterable:<EOL><INDENT>key_value_map[key] = value<EOL><DEDENT>for key in all_default_keys:<EOL><INDENT>if not isinstance(key.default, Undefined) andkey.schema not in key_value_map:<EOL><INDENT>key_value_map[key.schema] = key.default()<EOL><DEDENT><DEDENT>error = None<EOL>errors = []<EOL>for key, value in key_value_map.items():<EOL><INDENT>key_path = path + [key]<EOL>remove_key = False<EOL>relevant_candidates = itertools.chain(candidates_by_key.get(key, []), additional_candidates)<EOL>for skey, (ckey, cvalue) in relevant_candidates:<EOL><INDENT>try:<EOL><INDENT>new_key = ckey(key_path, key)<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>if len(e.path) > len(key_path):<EOL><INDENT>raise<EOL><DEDENT>if not error or len(e.path) > len(error.path):<EOL><INDENT>error = e<EOL><DEDENT>continue<EOL><DEDENT>exception_errors = []<EOL>is_remove = new_key is Remove<EOL>try:<EOL><INDENT>cval = cvalue(key_path, value)<EOL>if not is_remove:<EOL><INDENT>out[new_key] = cval<EOL><DEDENT>else:<EOL><INDENT>remove_key = True<EOL>continue<EOL><DEDENT><DEDENT>except er.MultipleInvalid as e:<EOL><INDENT>exception_errors.extend(e.errors)<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>exception_errors.append(e)<EOL><DEDENT>if exception_errors:<EOL><INDENT>if is_remove or remove_key:<EOL><INDENT>continue<EOL><DEDENT>for err in exception_errors:<EOL><INDENT>if len(err.path) <= len(key_path):<EOL><INDENT>err.error_type = invalid_msg<EOL><DEDENT>errors.append(err)<EOL><DEDENT>required_keys.discard(skey)<EOL>break<EOL><DEDENT>required_keys.discard(skey)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>if remove_key:<EOL><INDENT>continue<EOL><DEDENT>elif self.extra == ALLOW_EXTRA:<EOL><INDENT>out[key] = value<EOL><DEDENT>elif self.extra != REMOVE_EXTRA:<EOL><INDENT>errors.append(er.Invalid('<STR_LIT>', key_path))<EOL><DEDENT><DEDENT><DEDENT>for key in required_keys:<EOL><INDENT>msg = key.msg if hasattr(key, '<STR_LIT>') and key.msg else '<STR_LIT>'<EOL>errors.append(er.RequiredFieldInvalid(msg, path + [key]))<EOL><DEDENT>if errors:<EOL><INDENT>raise er.MultipleInvalid(errors)<EOL><DEDENT>return out<EOL><DEDENT>return validate_mapping<EOL> | Create validator for given mapping. | f2288:c1:m8 |
def _compile_object(self, schema): | base_validate = self._compile_mapping(<EOL>schema, invalid_msg='<STR_LIT>')<EOL>def validate_object(path, data):<EOL><INDENT>if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):<EOL><INDENT>raise er.ObjectInvalid('<STR_LIT>'.format(schema.cls), path)<EOL><DEDENT>iterable = _iterate_object(data)<EOL>iterable = ifilter(lambda item: item[<NUM_LIT:1>] is not None, iterable)<EOL>out = base_validate(path, iterable, {})<EOL>return type(data)(**out)<EOL><DEDENT>return validate_object<EOL> | Validate an object.
Has the same behavior as dictionary validator but work with object
attributes.
For example:
>>> class Structure(object):
... def __init__(self, one=None, three=None):
... self.one = one
... self.three = three
...
>>> validate = Schema(Object({'one': 'two', 'three': 'four'}, cls=Structure))
>>> with raises(er.MultipleInvalid, "not a valid value for object value @ data['one']"):
... validate(Structure(one='three')) | f2288:c1:m9 |
def _compile_dict(self, schema): | base_validate = self._compile_mapping(<EOL>schema, invalid_msg='<STR_LIT>')<EOL>groups_of_exclusion = {}<EOL>groups_of_inclusion = {}<EOL>for node in schema:<EOL><INDENT>if isinstance(node, Exclusive):<EOL><INDENT>g = groups_of_exclusion.setdefault(node.group_of_exclusion, [])<EOL>g.append(node)<EOL><DEDENT>elif isinstance(node, Inclusive):<EOL><INDENT>g = groups_of_inclusion.setdefault(node.group_of_inclusion, [])<EOL>g.append(node)<EOL><DEDENT><DEDENT>def validate_dict(path, data):<EOL><INDENT>if not isinstance(data, dict):<EOL><INDENT>raise er.DictInvalid('<STR_LIT>', path)<EOL><DEDENT>errors = []<EOL>for label, group in groups_of_exclusion.items():<EOL><INDENT>exists = False<EOL>for exclusive in group:<EOL><INDENT>if exclusive.schema in data:<EOL><INDENT>if exists:<EOL><INDENT>msg = exclusive.msg if hasattr(exclusive, '<STR_LIT>') and exclusive.msg else"<STR_LIT>" % label<EOL>next_path = path + [VirtualPathComponent(label)]<EOL>errors.append(er.ExclusiveInvalid(msg, next_path))<EOL>break<EOL><DEDENT>exists = True<EOL><DEDENT><DEDENT><DEDENT>if errors:<EOL><INDENT>raise er.MultipleInvalid(errors)<EOL><DEDENT>for label, group in groups_of_inclusion.items():<EOL><INDENT>included = [node.schema in data for node in group]<EOL>if any(included) and not all(included):<EOL><INDENT>msg = "<STR_LIT>" % label<EOL>for g in group:<EOL><INDENT>if hasattr(g, '<STR_LIT>') and g.msg:<EOL><INDENT>msg = g.msg<EOL>break<EOL><DEDENT><DEDENT>next_path = path + [VirtualPathComponent(label)]<EOL>errors.append(er.InclusiveInvalid(msg, next_path))<EOL>break<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise er.MultipleInvalid(errors)<EOL><DEDENT>out = data.__class__()<EOL>return base_validate(path, iteritems(data), out)<EOL><DEDENT>return validate_dict<EOL> | Validate a dictionary.
A dictionary schema can contain a set of values, or at most one
validator function/type.
A dictionary schema will only validate a dictionary:
>>> validate = Schema({})
>>> with raises(er.MultipleInvalid, 'expected a dictionary'):
... validate([])
An invalid dictionary value:
>>> validate = Schema({'one': 'two', 'three': 'four'})
>>> with raises(er.MultipleInvalid, "not a valid value for dictionary value @ data['one']"):
... validate({'one': 'three'})
An invalid key:
>>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['two']"):
... validate({'two': 'three'})
Validation function, in this case the "int" type:
>>> validate = Schema({'one': 'two', 'three': 'four', int: str})
Valid integer input:
>>> validate({10: 'twenty'})
{10: 'twenty'}
By default, a "type" in the schema (in this case "int") will be used
purely to validate that the corresponding value is of that type. It
will not Coerce the value:
>>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['10']"):
... validate({'10': 'twenty'})
Wrap them in the Coerce() function to achieve this:
>>> from voluptuous import Coerce
>>> validate = Schema({'one': 'two', 'three': 'four',
... Coerce(int): str})
>>> validate({'10': 'twenty'})
{10: 'twenty'}
Custom message for required key
>>> validate = Schema({Required('one', 'required'): 'two'})
>>> with raises(er.MultipleInvalid, "required @ data['one']"):
... validate({})
(This is to avoid unexpected surprises.)
Multiple errors for nested field in a dict:
>>> validate = Schema({
... 'adict': {
... 'strfield': str,
... 'intfield': int
... }
... })
>>> try:
... validate({
... 'adict': {
... 'strfield': 123,
... 'intfield': 'one'
... }
... })
... except er.MultipleInvalid as e:
... print(sorted(str(i) for i in e.errors)) # doctest: +NORMALIZE_WHITESPACE
["expected int for dictionary value @ data['adict']['intfield']",
"expected str for dictionary value @ data['adict']['strfield']"] | f2288:c1:m10 |
def _compile_sequence(self, schema, seq_type): | _compiled = [self._compile(s) for s in schema]<EOL>seq_type_name = seq_type.__name__<EOL>def validate_sequence(path, data):<EOL><INDENT>if not isinstance(data, seq_type):<EOL><INDENT>raise er.SequenceTypeInvalid('<STR_LIT>' % seq_type_name, path)<EOL><DEDENT>if not schema:<EOL><INDENT>if data:<EOL><INDENT>raise er.MultipleInvalid([<EOL>er.ValueInvalid('<STR_LIT>', [value]) for value in data<EOL>])<EOL><DEDENT>return data<EOL><DEDENT>out = []<EOL>invalid = None<EOL>errors = []<EOL>index_path = UNDEFINED<EOL>for i, value in enumerate(data):<EOL><INDENT>index_path = path + [i]<EOL>invalid = None<EOL>for validate in _compiled:<EOL><INDENT>try:<EOL><INDENT>cval = validate(index_path, value)<EOL>if cval is not Remove: <EOL><INDENT>out.append(cval)<EOL><DEDENT>break<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>if len(e.path) > len(index_path):<EOL><INDENT>raise<EOL><DEDENT>invalid = e<EOL><DEDENT><DEDENT>else:<EOL><INDENT>errors.append(invalid)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise er.MultipleInvalid(errors)<EOL><DEDENT>if _isnamedtuple(data):<EOL><INDENT>return type(data)(*out)<EOL><DEDENT>else:<EOL><INDENT>return type(data)(out)<EOL><DEDENT><DEDENT>return validate_sequence<EOL> | Validate a sequence type.
This is a sequence of valid values or validators tried in order.
>>> validator = Schema(['one', 'two', int])
>>> validator(['one'])
['one']
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator([3.5])
>>> validator([1])
[1] | f2288:c1:m11 |
def _compile_tuple(self, schema): | return self._compile_sequence(schema, tuple)<EOL> | Validate a tuple.
A tuple is a sequence of valid values or validators tried in order.
>>> validator = Schema(('one', 'two', int))
>>> validator(('one',))
('one',)
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator((3.5,))
>>> validator((1,))
(1,) | f2288:c1:m12 |
def _compile_list(self, schema): | return self._compile_sequence(schema, list)<EOL> | Validate a list.
A list is a sequence of valid values or validators tried in order.
>>> validator = Schema(['one', 'two', int])
>>> validator(['one'])
['one']
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator([3.5])
>>> validator([1])
[1] | f2288:c1:m13 |
def _compile_set(self, schema): | type_ = type(schema)<EOL>type_name = type_.__name__<EOL>def validate_set(path, data):<EOL><INDENT>if not isinstance(data, type_):<EOL><INDENT>raise er.Invalid('<STR_LIT>' % type_name, path)<EOL><DEDENT>_compiled = [self._compile(s) for s in schema]<EOL>errors = []<EOL>for value in data:<EOL><INDENT>for validate in _compiled:<EOL><INDENT>try:<EOL><INDENT>validate(path, value)<EOL>break<EOL><DEDENT>except er.Invalid:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>invalid = er.Invalid('<STR_LIT>' % type_name, path)<EOL>errors.append(invalid)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise er.MultipleInvalid(errors)<EOL><DEDENT>return data<EOL><DEDENT>return validate_set<EOL> | Validate a set.
A set is an unordered collection of unique elements.
>>> validator = Schema({int})
>>> validator(set([42])) == set([42])
True
>>> with raises(er.Invalid, 'expected a set'):
... validator(42)
>>> with raises(er.MultipleInvalid, 'invalid value in set'):
... validator(set(['a'])) | f2288:c1:m14 |
def extend(self, schema, required=None, extra=None): | assert type(self.schema) == dict and type(schema) == dict, '<STR_LIT>'<EOL>result = self.schema.copy()<EOL>def key_literal(key):<EOL><INDENT>return (key.schema if isinstance(key, Marker) else key)<EOL><DEDENT>result_key_map = dict((key_literal(key), key) for key in result)<EOL>for key, value in iteritems(schema):<EOL><INDENT>if key_literal(key) in result_key_map:<EOL><INDENT>result_key = result_key_map[key_literal(key)]<EOL>result_value = result[result_key]<EOL>if type(result_value) == dict and type(value) == dict:<EOL><INDENT>new_value = Schema(result_value).extend(value).schema<EOL>del result[result_key]<EOL>result[key] = new_value<EOL><DEDENT>else:<EOL><INDENT>del result[result_key]<EOL>result[key] = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result[key] = value<EOL><DEDENT><DEDENT>result_cls = type(self)<EOL>result_required = (required if required is not None else self.required)<EOL>result_extra = (extra if extra is not None else self.extra)<EOL>return result_cls(result, required=result_required, extra=result_extra)<EOL> | Create a new `Schema` by merging this and the provided `schema`.
Neither this `Schema` nor the provided `schema` are modified. The
resulting `Schema` inherits the `required` and `extra` parameters of
this, unless overridden.
Both schemas must be dictionary-based.
:param schema: dictionary to extend this `Schema` with
:param required: if set, overrides `required` of this `Schema`
:param extra: if set, overrides `extra` of this `Schema` | f2288:c1:m15 |
def chunk(seq, n):<EOL> | for i in range(<NUM_LIT:0>, len(seq), n):<EOL><INDENT>yield seq[i:i + n]<EOL><DEDENT> | Yield successive n-sized chunks from seq. | f2290:m1 |
def r_num(obj): | if isinstance(obj, (list, tuple)):<EOL><INDENT>it = iter<EOL><DEDENT>else:<EOL><INDENT>it = LinesIterator<EOL><DEDENT>dataset = Dataset([Dataset.FLOAT])<EOL>return dataset.load(it(obj))<EOL> | Read list of numbers. | f2292:m2 |
def r_date_num(obj, multiple=False): | if isinstance(obj, (list, tuple)):<EOL><INDENT>it = iter<EOL><DEDENT>else:<EOL><INDENT>it = LinesIterator<EOL><DEDENT>if multiple:<EOL><INDENT>datasets = {}<EOL>for line in it(obj):<EOL><INDENT>label = line[<NUM_LIT:2>]<EOL>if label not in datasets:<EOL><INDENT>datasets[label] = Dataset([Dataset.DATE, Dataset.FLOAT])<EOL>datasets[label].name = label<EOL><DEDENT>datasets[label].parse_elements(line[<NUM_LIT:0>:<NUM_LIT:2>])<EOL><DEDENT>return datasets.values()<EOL><DEDENT>dataset = Dataset([Dataset.DATE, Dataset.FLOAT])<EOL>return dataset.load(it(obj))<EOL> | Read date-value table. | f2292:m3 |
def plot_date(datasets, **kwargs): | defaults = {<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:title>': '<STR_LIT>',<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': (<NUM_LIT:8>, <NUM_LIT:6>),<EOL>}<EOL>plot_params = {<EOL>'<STR_LIT>': '<STR_LIT:b>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>}<EOL>_update_params(defaults, plot_params, kwargs)<EOL>if isinstance(datasets, Dataset):<EOL><INDENT>datasets = [datasets]<EOL><DEDENT>colors = ['<STR_LIT:b>', '<STR_LIT:g>', '<STR_LIT:r>', '<STR_LIT:c>', '<STR_LIT:m>', '<STR_LIT:y>', '<STR_LIT:k>']<EOL>color = plot_params.pop('<STR_LIT>')<EOL>try:<EOL><INDENT>del colors[colors.index(color)]<EOL>colors.insert(<NUM_LIT:0>, color)<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>colors = cycle(colors)<EOL>fig, ax = plt.subplots()<EOL>fig.set_size_inches(*defaults['<STR_LIT>'])<EOL>fig.autofmt_xdate()<EOL>ax.autoscale_view()<EOL>for dataset in datasets:<EOL><INDENT>if isinstance(dataset, Dataset):<EOL><INDENT>dates = list(dataset.get_column_by_type(dataset.DATE))<EOL>values = list(dataset.get_column_by_type(dataset.NUM))<EOL>label = dataset.name<EOL><DEDENT>else:<EOL><INDENT>dates, values = dataset<EOL>label = '<STR_LIT>'<EOL><DEDENT>dates = date2num(dates)<EOL>color = next(colors)<EOL>plt.plot_date(dates, values, color=color, label=label, **plot_params)<EOL><DEDENT>plt.xlabel(defaults['<STR_LIT>'])<EOL>plt.ylabel(defaults['<STR_LIT>'])<EOL>plt.title(defaults['<STR_LIT:title>'])<EOL>plt.grid(defaults['<STR_LIT>'])<EOL>plt.legend(loc='<STR_LIT>', prop={'<STR_LIT:size>': <NUM_LIT:10>})<EOL>filename = defaults['<STR_LIT>'] or get_tmp_file_name('<STR_LIT>')<EOL>plt.savefig(filename)<EOL>return filename<EOL> | Plot points with dates.
datasets can be Dataset object or list of Dataset. | f2294:m1 |
def similar_objects(self, num=None, **filters): | tags = self.tags<EOL>if not tags:<EOL><INDENT>return []<EOL><DEDENT>content_type = ContentType.objects.get_for_model(self.__class__)<EOL>filters['<STR_LIT>'] = content_type<EOL>lookup_kwargs = tags._lookup_kwargs()<EOL>lookup_keys = sorted(lookup_kwargs)<EOL>subq = tags.all()<EOL>qs = (tags.through.objects<EOL>.values(*lookup_kwargs.keys())<EOL>.annotate(n=models.Count('<STR_LIT>'))<EOL>.exclude(**lookup_kwargs)<EOL>.filter(tag__in=list(subq))<EOL>.order_by('<STR_LIT>'))<EOL>if filters is not None:<EOL><INDENT>qs = qs.filter(**filters)<EOL><DEDENT>if num is not None:<EOL><INDENT>qs = qs[:num]<EOL><DEDENT>items = {}<EOL>if len(lookup_keys) == <NUM_LIT:1>:<EOL><INDENT>f = tags.through._meta.get_field_by_name(lookup_keys[<NUM_LIT:0>])[<NUM_LIT:0>]<EOL>objs = f.rel.to._default_manager.filter(**{<EOL>"<STR_LIT>" % f.rel.field_name: [r["<STR_LIT>"] for r in qs]<EOL>})<EOL>for obj in objs:<EOL><INDENT>items[(getattr(obj, f.rel.field_name),)] = obj<EOL><DEDENT><DEDENT>else:<EOL><INDENT>preload = {}<EOL>for result in qs:<EOL><INDENT>preload.setdefault(result['<STR_LIT>'], set())<EOL>preload[result["<STR_LIT>"]].add(result["<STR_LIT>"])<EOL><DEDENT>for ct, obj_ids in preload.items():<EOL><INDENT>ct = ContentType.objects.get_for_id(ct)<EOL>for obj in ct.model_class()._default_manager.filter(pk__in=obj_ids):<EOL><INDENT>items[(ct.pk, obj.pk)] = obj<EOL><DEDENT><DEDENT><DEDENT>results = []<EOL>for result in qs:<EOL><INDENT>obj = items[<EOL>tuple(result[k] for k in lookup_keys)<EOL>]<EOL>obj.similar_tags = result["<STR_LIT:n>"]<EOL>results.append(obj)<EOL><DEDENT>return results<EOL> | Find similar objects using related tags. | f2299:c0:m0 |
def get_public_comments_for_model(model): | if not IS_INSTALLED:<EOL><INDENT>return CommentModelStub.objects.none()<EOL><DEDENT>else:<EOL><INDENT>return CommentModel.objects.for_model(model).filter(is_public=True, is_removed=False)<EOL><DEDENT> | Get visible comments for the model. | f2301:m0 |
def get_comments_are_open(instance): | if not IS_INSTALLED:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>mod = moderator._registry[instance.__class__]<EOL><DEDENT>except KeyError:<EOL><INDENT>return True<EOL><DEDENT>return CommentModerator.allow(mod, None, instance, None)<EOL> | Check if comments are open for the instance | f2301:m1 |
def get_comments_are_moderated(instance): | if not IS_INSTALLED:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>mod = moderator._registry[instance.__class__]<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>return CommentModerator.moderate(mod, None, instance, None)<EOL> | Check if comments are moderated for the instance | f2301:m2 |
@property<EOL><INDENT>def comments_are_open(self):<DEDENT> | if not self.enable_comments:<EOL><INDENT>return False<EOL><DEDENT>return get_comments_are_open(self)<EOL> | Check if comments are open | f2301:c2:m0 |
def import_settings_class(setting_name): | config_value = getattr(settings, setting_name)<EOL>if config_value is None:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(setting_name))<EOL><DEDENT>return import_class(config_value, setting_name)<EOL> | Return the class pointed to be an app setting variable. | f2315:m0 |
def import_class(import_path, setting_name=None): | mod_name, class_name = import_path.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>mod = import_module_or_none(mod_name)<EOL>if mod is not None:<EOL><INDENT>try:<EOL><INDENT>return getattr(mod, class_name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if setting_name:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(setting_name, import_path))<EOL><DEDENT>else:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(import_path))<EOL><DEDENT> | Import a class by name. | f2315:m1 |
def import_apps_submodule(submodule): | found_apps = []<EOL>for appconfig in apps.get_app_configs():<EOL><INDENT>app = appconfig.name<EOL>if import_module_or_none('<STR_LIT>'.format(app, submodule)) is not None:<EOL><INDENT>found_apps.append(app)<EOL><DEDENT><DEDENT>return found_apps<EOL> | Look for a submodule is a series of packages, e.g. ".pagetype_plugins" in all INSTALLED_APPS. | f2315:m2 |
def import_module_or_none(module_label): | try:<EOL><INDENT>return importlib.import_module(module_label)<EOL><DEDENT>except ImportError:<EOL><INDENT>__, __, exc_traceback = sys.exc_info()<EOL>frames = traceback.extract_tb(exc_traceback)<EOL>frames = [f for f in frames<EOL>if f[<NUM_LIT:0>] != "<STR_LIT>" and <EOL>f[<NUM_LIT:0>] != IMPORT_PATH_IMPORTLIB and<EOL>not f[<NUM_LIT:0>].endswith(IMPORT_PATH_GEVENT) and<EOL>not IMPORT_PATH_PYDEV in f[<NUM_LIT:0>]]<EOL>if len(frames) > <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>return None<EOL> | Imports the module with the given name.
Returns None if the module doesn't exist,
but it does propagates import errors in deeper modules. | f2315:m3 |
def request(self, **request): | environ = {<EOL>'<STR_LIT>': self.cookies,<EOL>'<STR_LIT>': '<STR_LIT:/>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:GET>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>environ.update(self.defaults)<EOL>environ.update(request)<EOL>request = WSGIRequest(environ)<EOL>handler = BaseHandler()<EOL>handler.load_middleware()<EOL>for middleware_method in handler._request_middleware:<EOL><INDENT>if middleware_method(request):<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>return request<EOL> | Similar to parent class, but returns the request object as soon as it
has created it. | f2322:c0:m0 |
def get_version(svn=False, limit=<NUM_LIT:3>): | v = '<STR_LIT:.>'.join([str(i) for i in VERSION[:limit]])<EOL>if svn and limit >= <NUM_LIT:3>:<EOL><INDENT>from django.utils.version import get_svn_revision<EOL>import os<EOL>svn_rev = get_svn_revision(os.path.dirname(__file__))<EOL>if svn_rev:<EOL><INDENT>v = '<STR_LIT>' % (v, svn_rev)<EOL><DEDENT><DEDENT>return v<EOL> | Returns the version as a human-format string. | f2325:m0 |
def __getattribute__(self, name): | get = lambda p:super(MothertongueModelTranslate, self).__getattribute__(p)<EOL>translated_fields = get('<STR_LIT>')<EOL>if name in translated_fields:<EOL><INDENT>try:<EOL><INDENT>translation_set = get('<STR_LIT>')<EOL>code = translation.get_language()<EOL>translated_manager = get(translation_set)<EOL>try:<EOL><INDENT>translated_object = None<EOL>translated_object = self._translation_cache[code]<EOL><DEDENT>except KeyError:<EOL><INDENT>translated_object = translated_manager.get(language=code)<EOL><DEDENT>finally:<EOL><INDENT>self._translation_cache[code] = translated_object<EOL><DEDENT>if translated_object:<EOL><INDENT>return getattr(translated_object, name)<EOL><DEDENT><DEDENT>except (ObjectDoesNotExist, AttributeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return get(name)<EOL> | Specialise to look for translated content, note we use super's
__getattribute__ within this function to avoid a recursion error. | f2327:c0:m1 |
def t_newline(self, t): | t.lexer.lineno += t.value.count("<STR_LIT:\n>")<EOL> | r'\n+ | f2331:c0:m1 |
def p_statement_expr(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>self.accu.add(Term('<STR_LIT:input>', [t[<NUM_LIT:1>]]))<EOL><DEDENT>else :<EOL><INDENT>self.accu.add(Term('<STR_LIT>', [t[<NUM_LIT:1>],t[<NUM_LIT:3>]]))<EOL>if t[<NUM_LIT:4>]!="<STR_LIT:?>" : self.accu.add(Term('<STR_LIT>', [t[<NUM_LIT:1>],t[<NUM_LIT:3>],t[<NUM_LIT:4>]]))<EOL><DEDENT> | statement : node_expression ARROW node_expression value
| node_expression | f2331:c1:m1 |
def p_node_expression(self, t): | t[<NUM_LIT:0>] = "<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"<EOL>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"]))<EOL> | node_expression : IDENT | f2331:c1:m2 |
def p_value(self, t): | if t[<NUM_LIT:1>] == '<STR_LIT:->' : t[<NUM_LIT:0>] = "<STR_LIT>"<EOL>elif t[<NUM_LIT:1>] == '<STR_LIT:+>' : t[<NUM_LIT:0>] = "<STR_LIT:1>"<EOL>elif t[<NUM_LIT:1>] == '<STR_LIT:?>' : t[<NUM_LIT:0>] = "<STR_LIT:?>"<EOL> | value : PLUS
| MINUS
| UNK | f2331:c1:m3 |
def is_consistent(instance): | return get_consistent_labelings(instance,<NUM_LIT:1>) != []<EOL> | [is_consistent(instance)] returns [True] if there exists a consistent extension
to the system described by the TermSet object [instance]. | f2332:m0 |
def get_consistent_labelings(instance,nmodels=<NUM_LIT:0>,exclude=[]): | <EOL>inst = instance.to_file()<EOL>prg = [ consistency_prg, inst, exclude_sol(exclude) ]<EOL>co = str(nmodels)<EOL>solver = GringoClasp(clasp_options=co)<EOL>models = solver.run(prg)<EOL>os.unlink(inst)<EOL>os.unlink(prg[<NUM_LIT:2>])<EOL>return models<EOL> | [consistent_labelings(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing consistent extensions of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [nmodels] equals [0]
then the list contain all feasible models. | f2332:m1 |
def get_minimal_inconsistent_cores(instance,nmodels=<NUM_LIT:0>,exclude=[]): | inputs = get_reductions(instance)<EOL>prg = [ dyn_mic_prg, inputs.to_file(), instance.to_file(), exclude_sol(exclude) ]<EOL>options ='<STR_LIT>'+str(nmodels)<EOL>solver = GringoClasp(clasp_options=options)<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(prg[<NUM_LIT:1>])<EOL>os.unlink(prg[<NUM_LIT:2>])<EOL>os.unlink(prg[<NUM_LIT:3>])<EOL>return models<EOL> | [compute_mic(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing subset minimal inconsistent cores of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [nmodels] equals [0]
then the list contain all feasible models. | f2332:m2 |
def get_predictions_under_minimal_repair(instance, repair_options, optimum): | inst = instance.to_file()<EOL>repops = repair_options.to_file()<EOL>prg = [ inst, repops, prediction_core_prg, repair_cardinality_prg ]<EOL>options = '<STR_LIT>'+str(optimum)<EOL>solver = GringoClasp(clasp_options=options)<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(inst)<EOL>os.unlink(repops)<EOL>return whatsnew(instance,models[<NUM_LIT:0>])<EOL> | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | f2332:m12 |
def whatsnew(instance,pred): | accu = TermSet(pred)<EOL>for t in instance:<EOL><INDENT>if t.pred() == '<STR_LIT>':<EOL><INDENT>[_,e,v,s] = t.explode()<EOL>accu.discard(Term('<STR_LIT>',[e,v,s]))<EOL><DEDENT>elif t.p('<STR_LIT>'):<EOL><INDENT>[_,j,i,s] = t.explode()<EOL>accu.discard(Term('<STR_LIT>',[j,i,s]))<EOL><DEDENT><DEDENT>return accu<EOL> | [whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of the observations. | f2332:m14 |
def get_predictions_under_consistency(instance): | inst = instance.to_file()<EOL>prg = [ prediction_prg, inst, exclude_sol([]) ]<EOL>solver = GringoClasp(clasp_options='<STR_LIT>')<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(inst)<EOL>os.unlink(prg[<NUM_LIT:2>])<EOL>return whatsnew(instance,models[<NUM_LIT:0>])<EOL> | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | f2332:m15 |
def t_newline(self, t): | t.lexer.lineno += t.value.count("<STR_LIT:\n>")<EOL> | r'\n+ | f2334:c0:m1 |
def p_statement_expr(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>self.accu.add(Term('<STR_LIT:input>', [t[<NUM_LIT:1>]]))<EOL>print('<STR_LIT:input>', t[<NUM_LIT:1>])<EOL><DEDENT>else :<EOL><INDENT>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>","<STR_LIT>"+t[<NUM_LIT:3>]+"<STR_LIT>"]))<EOL>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>","<STR_LIT>"+t[<NUM_LIT:3>]+"<STR_LIT>",t[<NUM_LIT:2>]]))<EOL><DEDENT> | statement : node_expression PLUS node_expression
| node_expression MINUS node_expression | f2334:c1:m1 |
def p_node_expression(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>t[<NUM_LIT:0>]=t[<NUM_LIT:1>]<EOL>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"]))<EOL><DEDENT>else : t[<NUM_LIT:0>] = "<STR_LIT>"<EOL> | node_expression : IDENT | f2334:c1:m2 |
def _inputLoop(self): | try:<EOL><INDENT>while self.alive:<EOL><INDENT>try:<EOL><INDENT>c = console.getkey() <EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print('<STR_LIT>')<EOL>c = serial.to_bytes([<NUM_LIT:3>])<EOL><DEDENT>if c == self.EXIT_CHARACTER: <EOL><INDENT>self.stop()<EOL><DEDENT>elif c == '<STR_LIT:\n>':<EOL><INDENT>self.serial.write(self.WRITE_TERM)<EOL>if self.echo:<EOL><INDENT>sys.stdout.write(c)<EOL>sys.stdout.flush()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.serial.write(c)<EOL>if self.echo:<EOL><INDENT>sys.stdout.write(c)<EOL>sys.stdout.flush()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>self.alive = False<EOL>raise<EOL><DEDENT> | Loop and copy console->serial until EXIT_CHARCTER character is found. | f2337:c0:m5 |
def _color(self, color, msg): | if self.useColor:<EOL><INDENT>return '<STR_LIT>'.format(color, msg, self.RESET_SEQ)<EOL><DEDENT>else:<EOL><INDENT>return msg<EOL><DEDENT> | Converts a message to be printed to the user's terminal in red | f2337:c1:m2 |
def _boldFace(self, msg): | return self._color(self.BOLD_SEQ, msg)<EOL> | Converts a message to be printed to the user's terminal in bold | f2337:c1:m3 |
def _inputLoop(self): | <EOL>actionChars = {self.EXIT_CHARACTER: self._exit,<EOL>self.EXIT_CHARACTER_2: self._exit,<EOL>console.CURSOR_LEFT: self._cursorLeft,<EOL>console.CURSOR_RIGHT: self._cursorRight,<EOL>console.CURSOR_UP: self._cursorUp,<EOL>console.CURSOR_DOWN: self._cursorDown,<EOL>'<STR_LIT:\n>': self._doConfirmInput,<EOL>'<STR_LIT:\t>': self._doCommandCompletion,<EOL>self.CTRL_Z_CHARACTER: self._handleCtrlZ,<EOL>self.ESC_CHARACTER: self._handleEsc,<EOL>self.BACKSPACE_CHARACTER: self._handleBackspace,<EOL>console.DELETE: self._handleDelete,<EOL>console.HOME: self._handleHome,<EOL>console.END: self._handleEnd}<EOL>try:<EOL><INDENT>while self.alive:<EOL><INDENT>try:<EOL><INDENT>c = console.getkey()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>c = serial.to_bytes([<NUM_LIT:3>])<EOL><DEDENT>if c in actionChars:<EOL><INDENT>actionChars[c]()<EOL><DEDENT>elif len(c) == <NUM_LIT:1> and self._isPrintable(c):<EOL><INDENT>self.inputBuffer.insert(self.cursorPos, c)<EOL>self.cursorPos += <NUM_LIT:1><EOL>self._refreshInputPrompt()<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>self.alive = False<EOL>raise<EOL><DEDENT> | Loop and copy console->serial until EXIT_CHARCTER character is found. | f2337:c1:m6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.