Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|> def testRightClippingPaddedTwo(self):
"""
Test that right soft clipping of two bases works when the reference
is padded on the right.
"""
self.assertEqual('2M2S', makeCigar(' ACGT ',
' ATAA'))
def testLeftInsert(self):
"""
Test that an insert on the left works.
"""
self.assertEqual(
'2I2M',
makeCigar('--ACGT ', 'ATAC', noEdgeInsertions=False))
# When edge insertions are not allowed, the first two bases are
# soft-clipped (as in tests above).
self.assertEqual('2S2M', makeCigar('--ACGT ',
'ATAC'))
class TestCigarTuplesToOperations(TestCase):
"""
Test the cigarTuplesToOperations function.
"""
def testEmpty(self):
"""
If there are no tuples, the empty list must be returned.
"""
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (classes, functions, or code) from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | self.assertEqual([], list(cigarTuplesToOperations([]))) |
Based on the snippet: <|code_start|> """
self.assertEqual(
[CHARD_CLIP, CHARD_CLIP, CINS, CINS, CMATCH, CMATCH, CMATCH],
list(cigarTuplesToOperations(
[(CHARD_CLIP, 2), (CINS, 2), (CMATCH, 3)])))
def testSkipHardClipping(self):
"""
It must be possible to have hard clipping operations skipped.
"""
self.assertEqual(
[CINS, CINS, CMATCH, CMATCH, CMATCH],
list(cigarTuplesToOperations(
[(CHARD_CLIP, 2), (CINS, 2), (CMATCH, 3)],
includeHardClip=False)))
class TestSoftClippedOffset(TestCase):
"""
Test the softClippedOffset function.
"""
def testNoNonClippedBases(self):
"""
If there are no preceding or following non-clipped bases, a ValueError
must be raised.
"""
error = (r'^Soft-clipped base with no following or preceding '
r'non-hard-clipped bases\.$')
self.assertRaisesRegex(
ValueError, error,
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (classes, functions, sometimes code) from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | softClippedOffset, 0, ((0, None),), (CSOFT_CLIP,)) |
Given the code snippet: <|code_start|> softClippedOffset(2,
((0, 10), (1, None), (2, None)),
(CMATCH, CSOFT_CLIP, CSOFT_CLIP)))
def testMatchTwoAfterThenHardClips(self):
"""
Test that a soft-clipped base two sites after a non-soft-clipped site
returns the correct offset, including when there are also hard clips.
"""
self.assertEqual(
12,
softClippedOffset(
2,
((0, 10), (1, None), (2, None), (3, None), (4, None)),
(CMATCH, CSOFT_CLIP, CSOFT_CLIP, CHARD_CLIP, CHARD_CLIP)))
class TestInsertionOffset(TestCase):
"""
Test the insertionOffset function.
"""
def testNoNonInsertionBases(self):
"""
If there are no preceding or following non-inserted bases, a ValueError
must be raised.
"""
error = (r'^Inserted base with no following or preceding reference '
r'bases\.$')
self.assertRaisesRegex(
ValueError, error,
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (functions, classes, or occasionally code) from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | insertionOffset, 0, ((0, None),), (CINS,)) |
Predict the next line for this snippet: <|code_start|> 'non-hard-clipped bases.')
def insertionOffset(offset, pairs, cigarOperations):
"""
Get the insertion offset in the reference for a base that is part of an
insertion.
@param offset: The offset (in C{pairs}) of the soft-clipped base (which
has a to-be-determined offset in the reference).
@param pairs: A C{list} of C{int} (queryOffset, referenceOffset) pairs
for a pysam C{pysam.AlignedSegment}, as returned by
C{read.get_aligned_pairs} where the read is returned by the pysam
C{fetch} method.
@param cigarOperations: A C{list} of pysam CIGAR operations.
@return: A 2-tuple containing a C{bool} and the C{int} reference offset of
the base after the insertion. The C{bool} indicates whether we needed
to look back in the sequence to find a reference base.
"""
assert cigarOperations[offset] == CINS
assert pairs[offset][1] is None
# Look back.
for pair, cigarOperation in zip(pairs[offset::-1],
cigarOperations[offset::-1]):
if cigarOperation != CINS:
_, referenceOffset = pair
# If we have a reference offset, then we've found our
# answer. Otherwise, check as above.
if referenceOffset is None:
<|code_end|>
with the help of current file imports:
from pysam import CINS, CSOFT_CLIP, CHARD_CLIP
from dark.sam import CONSUMES_REFERENCE
and context from other files:
# Path: dark/sam.py
# CONSUMES_REFERENCE = {CMATCH, CDEL, CREF_SKIP, CEQUAL, CDIFF}
, which may contain function names, class names, or code. Output only the next line. | assert cigarOperation not in CONSUMES_REFERENCE |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write information about the '
'number of various characters to stdout.'))
parser.add_argument(
'--ignoreCase', '-i', action='store_true',
help='Map all characters to uppercase.')
parser.add_argument(
'--sep', default='\t',
help='The output field separator character.')
parser.add_argument(
'--omitIds', action='store_true',
help='Do not print sequence ids as the first field')
parser.add_argument(
'--chars', '-c', required=True,
help='The characters to count.')
<|code_end|>
, predict the next line using imports from the current file:
import sys
import csv
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context including class names, function names, and sometimes code from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write information about the '
'number of various characters to stdout.'))
parser.add_argument(
'--ignoreCase', '-i', action='store_true',
help='Map all characters to uppercase.')
parser.add_argument(
'--sep', default='\t',
help='The output field separator character.')
parser.add_argument(
'--omitIds', action='store_true',
help='Do not print sequence ids as the first field')
parser.add_argument(
'--chars', '-c', required=True,
help='The characters to count.')
addFASTACommandLineOptions(parser)
args = parser.parse_args()
chars = args.chars.upper() if args.ignoreCase else args.chars
<|code_end|>
. Use current file imports:
import sys
import csv
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context (classes, functions, or code) from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write the sequence ids and '
'lengths to stdout.'))
<|code_end|>
using the current file's imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and any relevant context from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write the sequence ids and '
'lengths to stdout.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
, predict the next line using imports from the current file:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context including class names, function names, and sometimes code from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA sequences (of equal length) on stdin '
'write Phylip to stdout.'))
parser.add_argument(
'--addIdSpace', action='store_true', default=False,
help=('If True, print an extra space after each sequence id (the '
'space is expected by some programs that process Phylip files, '
'e.g., baseml).'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import tempfile
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
which might include code, classes, or functions. Output only the next line. | addFASTACommandLineOptions(parser) |
Next line prediction: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA sequences (of equal length) on stdin '
'write Phylip to stdout.'))
parser.add_argument(
'--addIdSpace', action='store_true', default=False,
help=('If True, print an extra space after each sequence id (the '
'space is expected by some programs that process Phylip files, '
'e.g., baseml).'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
idSpace = ' ' if args.addIdSpace else ''
<|code_end|>
. Use current file imports:
(import sys
import tempfile
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions)
and context including class names, function names, or small code snippets from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write the sequence ids and '
'lengths to stdout.'))
<|code_end|>
, generate the next line using the imports in this file:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context (functions, classes, or occasionally code) from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write the sequence ids and '
'lengths to stdout.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
. Use current file imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context (classes, functions, or code) from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given snippet: <|code_start|>
@param dnaMatch: A C{dict} returned by C{compareDNAReads}.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param matchAmbiguous: If C{True}, ambiguous nucleotides that are
possibly correct were counted as actually being correct. Otherwise,
the match was done strictly, insisting that only non-ambiguous
nucleotides could contribute to the matching nucleotide count.
@param indent: A C{str} to indent all returned lines with.
@param offsets: If not C{None}, a C{set} of offsets of interest that were
only considered when making C{match}.
@param includeGapLocations: If C{True} indicate the (1-based) locations of
gaps.
@return: A C{str} describing the match.
"""
match = dnaMatch['match']
identicalMatchCount = match['identicalMatchCount']
ambiguousMatchCount = match['ambiguousMatchCount']
gapMismatchCount = match['gapMismatchCount']
gapGapMismatchCount = match['gapGapMismatchCount']
nonGapMismatchCount = match['nonGapMismatchCount']
if offsets:
len1 = len2 = len(offsets)
else:
len1, len2 = map(len, (read1, read2))
result = []
append = result.append
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import defaultdict
from operator import itemgetter
from dark.utils import countPrint
from itertools import zip_longest
from itertools import izip_longest as zip_longest
from dark.reads import DNAKozakRead
and context:
# Path: dark/utils.py
# def countPrint(mesg, count, len1, len2=None):
# """
# Format a message followed by an integer count and a percentage (or
# two, if the sequence lengths are unequal).
#
# @param mesg: a C{str} message.
# @param count: a numeric value.
# @param len1: the C{int} length of sequence 1.
# @param len2: the C{int} length of sequence 2. If C{None}, will
# default to C{len1}.
# @return: A C{str} for printing.
# """
# def percentage(a, b):
# """
# What percent of a is b?
#
# @param a: a numeric value.
# @param b: a numeric value.
# @return: the C{float} percentage.
# """
# return 100.0 * a / b if b else 0.0
#
# if count == 0:
# return '%s: %d' % (mesg, count)
# else:
# len2 = len2 or len1
# if len1 == len2:
# return '%s: %d/%d (%.2f%%)' % (
# mesg, count, len1, percentage(count, len1))
# else:
# return ('%s: %d/%d (%.2f%%) of sequence 1, '
# '%d/%d (%.2f%%) of sequence 2' % (
# mesg,
# count, len1, percentage(count, len1),
# count, len2, percentage(count, len2)))
which might include code, classes, or functions. Output only the next line. | append(countPrint('%sExact matches' % indent, identicalMatchCount, |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""
Read DNA FASTA from stdin and print FASTA to stdout, with the sequences
randomized. The read ids and lengths are preserved.
Note: This produces DNA sequences. If you have AA reads and you need this
functionality, we can add it.
"""
from __future__ import print_function
if __name__ == '__main__':
for read in FastaReads(sys.stdin):
seq = ''.join(choice(['A', 'C', 'G', 'T'], len(read), replace=True))
<|code_end|>
. Write the next line using the current file imports:
import sys
from numpy.random import choice
from dark.fasta import FastaReads
from dark.reads import DNARead
and context from other files:
# Path: dark/reads.py
# class DNARead(_NucleotideRead):
# """
# Hold information and methods to work with DNA reads.
# """
# ALPHABET = set('ATCG')
#
# COMPLEMENT_TABLE = _makeComplementTable(ambiguous_dna_complement)
, which may include functions, classes, or code. Output only the next line. | print(DNARead(read.id, seq).toString('fasta')) |
Next line prediction: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Given FASTA on stdin, write the sequences to stdout.'))
<|code_end|>
. Use current file imports:
(from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse)
and context including class names, function names, or small code snippets from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Given snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Given FASTA on stdin, write the sequences to stdout.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
which might include code, classes, or functions. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=(
'Given FASTA on stdin, print the number of sequences to stdout.'))
<|code_end|>
with the help of current file imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
, which may contain function names, class names, or code. Output only the next line. | addFASTACommandLineOptions(parser) |
Next line prediction: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=(
'Given FASTA on stdin, print the number of sequences to stdout.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
. Use current file imports:
(from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse)
and context including class names, function names, or small code snippets from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given snippet: <|code_start|> an amino acid match is due to an exact nucleotide matches or not.
Also, the numbers in the BTOP string will be multiplied by 3 since
they refer to a number of amino acids matching.
@raise ValueError: If L{parseBtop} finds an error in C{btopString} or
if C{aa} and C{concise} are both C{True}.
@return: A generator that yields C{str} pieces of a CIGAR string. Use
''.join(btopString(...)) to get a complete CIGAR string.
"""
if aa and concise:
raise ValueError('aa and concise cannot both be True')
thisLength = thisOperation = currentLength = currentOperation = None
for item in parseBtop(btopString):
if isinstance(item, int):
thisLength = item
thisOperation = CEQUAL_STR if concise else CMATCH_STR
else:
thisLength = 1
query, reference = item
if query == '-':
# The query has a gap. That means that in matching the
# query to the reference a deletion is needed in the
# reference.
assert reference != '-'
thisOperation = CDEL_STR
elif reference == '-':
# The reference has a gap. That means that in matching the
# query to the reference an insertion is needed in the
# reference.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dark.cigar import CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR
and context:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
which might include code, classes, or functions. Output only the next line. | thisOperation = CINS_STR |
Given snippet: <|code_start|> of the more specific 'X' and '='.
@param aa: If C{True}, C{btopString} will be interpreted as though it
refers to amino acids (as in the BTOP string produced by DIAMOND).
In that case, it is not possible to use the 'precise' CIGAR characters
because amino acids have multiple codons so we cannot know whether
an amino acid match is due to an exact nucleotide matches or not.
Also, the numbers in the BTOP string will be multiplied by 3 since
they refer to a number of amino acids matching.
@raise ValueError: If L{parseBtop} finds an error in C{btopString} or
if C{aa} and C{concise} are both C{True}.
@return: A generator that yields C{str} pieces of a CIGAR string. Use
''.join(btopString(...)) to get a complete CIGAR string.
"""
if aa and concise:
raise ValueError('aa and concise cannot both be True')
thisLength = thisOperation = currentLength = currentOperation = None
for item in parseBtop(btopString):
if isinstance(item, int):
thisLength = item
thisOperation = CEQUAL_STR if concise else CMATCH_STR
else:
thisLength = 1
query, reference = item
if query == '-':
# The query has a gap. That means that in matching the
# query to the reference a deletion is needed in the
# reference.
assert reference != '-'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dark.cigar import CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR
and context:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
which might include code, classes, or functions. Output only the next line. | thisOperation = CDEL_STR |
Given the following code snippet before the placeholder: <|code_start|> return (queryGaps, subjectGaps)
def btop2cigar(btopString, concise=False, aa=False):
"""
Convert a BTOP string to a CIGAR string.
@param btopString: A C{str} BTOP sequence.
@param concise: If C{True}, use 'M' for matches and mismatches instead
of the more specific 'X' and '='.
@param aa: If C{True}, C{btopString} will be interpreted as though it
refers to amino acids (as in the BTOP string produced by DIAMOND).
In that case, it is not possible to use the 'precise' CIGAR characters
because amino acids have multiple codons so we cannot know whether
an amino acid match is due to an exact nucleotide matches or not.
Also, the numbers in the BTOP string will be multiplied by 3 since
they refer to a number of amino acids matching.
@raise ValueError: If L{parseBtop} finds an error in C{btopString} or
if C{aa} and C{concise} are both C{True}.
@return: A generator that yields C{str} pieces of a CIGAR string. Use
''.join(btopString(...)) to get a complete CIGAR string.
"""
if aa and concise:
raise ValueError('aa and concise cannot both be True')
thisLength = thisOperation = currentLength = currentOperation = None
for item in parseBtop(btopString):
if isinstance(item, int):
thisLength = item
<|code_end|>
, predict the next line using imports from the current file:
from dark.cigar import CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR
and context including class names, function names, and sometimes code from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | thisOperation = CEQUAL_STR if concise else CMATCH_STR |
Using the snippet: <|code_start|> return (queryGaps, subjectGaps)
def btop2cigar(btopString, concise=False, aa=False):
"""
Convert a BTOP string to a CIGAR string.
@param btopString: A C{str} BTOP sequence.
@param concise: If C{True}, use 'M' for matches and mismatches instead
of the more specific 'X' and '='.
@param aa: If C{True}, C{btopString} will be interpreted as though it
refers to amino acids (as in the BTOP string produced by DIAMOND).
In that case, it is not possible to use the 'precise' CIGAR characters
because amino acids have multiple codons so we cannot know whether
an amino acid match is due to an exact nucleotide matches or not.
Also, the numbers in the BTOP string will be multiplied by 3 since
they refer to a number of amino acids matching.
@raise ValueError: If L{parseBtop} finds an error in C{btopString} or
if C{aa} and C{concise} are both C{True}.
@return: A generator that yields C{str} pieces of a CIGAR string. Use
''.join(btopString(...)) to get a complete CIGAR string.
"""
if aa and concise:
raise ValueError('aa and concise cannot both be True')
thisLength = thisOperation = currentLength = currentOperation = None
for item in parseBtop(btopString):
if isinstance(item, int):
thisLength = item
<|code_end|>
, determine the next line of code. You have imports:
from dark.cigar import CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR
and context (class names, function names, or code) available:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | thisOperation = CEQUAL_STR if concise else CMATCH_STR |
Using the snippet: <|code_start|> if C{aa} and C{concise} are both C{True}.
@return: A generator that yields C{str} pieces of a CIGAR string. Use
''.join(btopString(...)) to get a complete CIGAR string.
"""
if aa and concise:
raise ValueError('aa and concise cannot both be True')
thisLength = thisOperation = currentLength = currentOperation = None
for item in parseBtop(btopString):
if isinstance(item, int):
thisLength = item
thisOperation = CEQUAL_STR if concise else CMATCH_STR
else:
thisLength = 1
query, reference = item
if query == '-':
# The query has a gap. That means that in matching the
# query to the reference a deletion is needed in the
# reference.
assert reference != '-'
thisOperation = CDEL_STR
elif reference == '-':
# The reference has a gap. That means that in matching the
# query to the reference an insertion is needed in the
# reference.
thisOperation = CINS_STR
else:
# A substitution was needed.
assert query != reference
<|code_end|>
, determine the next line of code. You have imports:
from dark.cigar import CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR
and context (class names, function names, or code) available:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | thisOperation = CDIFF_STR if concise else CMATCH_STR |
Given the code snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Print SAM/BAM file reference names and lengths.')
parser.add_argument(
'samfile', metavar='FILENAME',
help='The name of a SAM/BAM alignment file.')
<|code_end|>
, generate the next line using the imports in this file:
import argparse
from dark.sam import samReferencesToStr
and context (functions, classes, or occasionally code) from other files:
# Path: dark/sam.py
# def samReferencesToStr(filenameOrSamfile, indent=0):
# """
# List SAM/BAM file reference names and lengths.
#
# @param filenameOrSamfile: Either a C{str} SAM/BAM file name or an
# instance of C{pysam.AlignmentFile}.
# @param indent: An C{int} number of spaces to indent each line.
# @return: A C{str} describing known reference names and their lengths.
# """
# indent = ' ' * indent
#
# def _references(sam):
# result = []
# for i in range(sam.nreferences):
# result.append('%s%s (length %d)' % (
# indent, sam.get_reference_name(i), sam.lengths[i]))
# return '\n'.join(result)
#
# if isinstance(filenameOrSamfile, six.string_types):
# with samfile(filenameOrSamfile) as sam:
# return _references(sam)
# else:
# return _references(sam)
. Output only the next line. | print(samReferencesToStr(parser.parse_args().samfile)) |
Given snippet: <|code_start|> help=('The name of the FASTA files containing the sequences to be '
'combined.'))
parser.add_argument(
'--threads', type=int, default=multiprocessing.cpu_count(),
help=('The number of threads to use when running the aligner (if '
'--align is used and the alignment algorithm can make use of '
'multiple threads).'))
parser.add_argument(
'--alignerOptions', default=MAFFT_DEFAULT_ARGS,
help=('Optional arguments to pass to the alignment algorithm. The '
'default options are %r. See %s for some possible option '
'combinations.' % (MAFFT_DEFAULT_ARGS, MAFFT_ALGORITHMS_URL)))
args = parser.parse_args()
reads = []
for fastaFile in args.fastaFiles:
reads.extend(FastaReads(fastaFile))
if len(reads) == 1:
print('Cannot combine just one read. Exiting.', file=sys.stderr)
sys.exit(1)
alignedReads = mafft(reads, options=args.alignerOptions,
threads=args.threads)
combinedSequence = alignedReads.combineReads()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import argparse
import multiprocessing
from dark.aligners import mafft
from dark.reads import DNARead
from dark.fasta import FastaReads
and context:
# Path: dark/reads.py
# class DNARead(_NucleotideRead):
# """
# Hold information and methods to work with DNA reads.
# """
# ALPHABET = set('ATCG')
#
# COMPLEMENT_TABLE = _makeComplementTable(ambiguous_dna_complement)
which might include code, classes, or functions. Output only the next line. | print(DNARead('Combined', combinedSequence).toString(format_='fasta')) |
Next line prediction: <|code_start|>
log = logging.getLogger(__package__)
def init(app):
app.hooks.connect("pre-arg-parse", add_argparse)
app.hooks.connect("post-arg-parse", post_argparse)
def add_argparse(app, parser, subparsers):
s = subparsers.add_parser("openscap", help="Security management")
s.add_argument("--all", action="store_true",
help="List all available profiles")
s.add_argument("--list", action="store_true",
help="List registered profile")
s.add_argument("--configure", action="store_true",
help="Auto configure SCAP profile and datastream")
s.add_argument("--register", nargs=2, metavar=("DATASTREAM", "PROFILE"),
help="Register data for scanning")
s.add_argument("--unregister", metavar="PROFILE",
help="Register data for scanning")
s.add_argument("--scan", metavar="PATH",
help="Use registered profile to perform a scan")
s.add_argument("--remediate", metavar="PATH",
help="Use registered profile to remediate system")
def post_argparse(app, args):
if args.command == "openscap":
<|code_end|>
. Use current file imports:
(import logging
from ..openscap import OSCAPScanner)
and context including class names, function names, or small code snippets from other files:
# Path: src/imgbased/openscap.py
# class OSCAPScanner(object):
# def __init__(self):
# if not os.path.exists(SCAP_REPORTSDIR):
# os.makedirs(SCAP_REPORTSDIR, mode=0o550)
# self._config = OSCAPConfig()
#
# def process(self, path):
# if self._config.registered:
# self.scan(remediate=True, path=path)
# else:
# self.configure()
#
# def register(self, datastream, profile):
# log.info("Registering profile %s from %s", profile, datastream)
# if profile not in self.profiles(datastream):
# log.error("Profile %s not found", profile)
# return
# self._config.datastream = os.path.realpath(datastream)
# self._config.profile = profile
#
# def unregister(self, profile):
# if profile == self._config.profile:
# log.info("Unregistering profile %s", profile)
# self._config.profile = ""
# else:
# log.warn("Profile [%s] is not registered, skipping", profile)
#
# def scan(self, remediate=False, path="/"):
# log.debug("Running OSCAP scan on %s, (remediate=%s)", path, remediate)
# if not self._config.registered:
# log.warn("Security profile not registered, skipping")
# return
# report = SCAP_REPORT_FMT % time.strftime("%Y%m%d%H%M%S")
# args = ["chroot", path, "oscap", "xccdf", "eval",
# "--profile", self.profile, "--report", report]
# if remediate:
# args.append("--remediate")
# args.append(self._config.datastream)
# with bindmounted("/proc", path + "/proc"):
# with bindmounted("/var", path + "/var", rbind=True):
# nsenter(args)
# log.info("Report available at %s", report)
#
# def profiles(self, datastream=None):
# if not datastream:
# datastream = self._config.datastream
# if not datastream or not File(datastream).exists():
# raise ScapDatastreamError("Datastream not found: %s" % datastream)
# cmd = ["oscap", "info", "--profiles", datastream]
# stdout = nsenter(cmd).decode(errors="replace")
# profiles = dict([x.split(":") for x in stdout.splitlines()])
# log.debug("Collected OSCAP profiles: %s", profiles)
# return profiles
#
# @property
# def profile(self):
# if not self._config.registered:
# raise ScapProfileError("SCAP profile not registered")
# return self._config.profile
#
# def configure(self):
# if self._config.configured:
# log.debug("SCAP was already auto-configured, skipping")
# return
# self._config.configured = "1"
# j = journal.Reader()
# j.this_boot()
# j.add_match(SYSLOG_IDENTIFIER="oscap")
# msgs = [x for x in j if x["MESSAGE"].startswith("Evaluation started")]
# if not msgs:
# log.info("No SCAP evaluation found, skipping")
# return
# ds, profile = [x[:-1] for x in msgs[0]["MESSAGE"].split()[3::2]]
# self.register(ds, profile)
. Output only the next line. | os = OSCAPScanner() |
Given the code snippet: <|code_start|> if name == '.' or name == '..':
return False
# Check that all characters are in the allowed set and that the name
# does not start with a -
if not re.match('^[a-zA-Z0-9+_.][a-zA-Z0-9+_.-]*$', name):
return False
# According to the LVM developers, vgname + lvname is limited to
# 126 characters
# minus the number of hyphens, and possibly minus up to another
# 8 characters
# in some unspecified set of situations. Instead of figuring all
# of that out,
# no one gets a vg or lv name longer than, let's say, 55.
if len(name) > 55:
return False
return True
@staticmethod
def register_volume(vol):
assert isinstance(vol, LVM.LV)
LVM._volume_registry.append(vol)
return vol
@staticmethod
def reset_registered_volumes():
if os.getenv("IMGBASED_KEEP_VOLUMES"):
return
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import re
import shlex
from operator import itemgetter
from .utils import ExternalBinary, LvmCLI, find_mount_source
and context (functions, classes, or occasionally code) from other files:
# Path: src/imgbased/utils.py
# class ExternalBinary(object):
# dry = False
# squash_output = False
#
# def call(self, *args, **kwargs):
# stdout = bytes()
# if not self.dry:
# stdout = command.call(*args, **kwargs)
# if stdout and not self.squash_output:
# log.debug("Returned: %s" % stdout[0:1024])
# return stdout.decode(errors="replace").strip()
#
# def lvs(self, args, **kwargs):
# return self.call(["lvs"] + args, **kwargs)
#
# def vgs(self, args, **kwargs):
# return self.call(["vgs"] + args, **kwargs)
#
# def lvcreate(self, args, **kwargs):
# return self.call(["lvcreate"] + args, **kwargs)
#
# def lvremove(self, args, **kwargs):
# return self.call(["lvremove"] + args, **kwargs)
#
# def lvrename(self, args, **kwargs):
# return self.call(["lvrename"] + args, **kwargs)
#
# def lvextend(self, args, **kwargs):
# return self.call(["lvextend"] + args, **kwargs)
#
# def vgcreate(self, args, **kwargs):
# return self.call(["vgcreate"] + args, **kwargs)
#
# def lvchange(self, args, **kwargs):
# return self.call(["lvchange"] + args, **kwargs)
#
# def vgchange(self, args, **kwargs):
# return self.call(["vgchange"] + args, **kwargs)
#
# def find(self, args, **kwargs):
# return self.call(["find"] + args, **kwargs)
#
# def findmnt(self, args, **kwargs):
# return self.call(["findmnt"] + args, **kwargs)
#
# def du(self, args, **kwargs):
# return self.call(["du"] + args, **kwargs)
#
# def rm(self, args, **kwargs):
# return self.call(["rm"] + args, **kwargs)
#
# def cp(self, args, **kwargs):
# return self.call(["cp"] + args, **kwargs)
#
# def rpm(self, args, **kwargs):
# self.squash_output = True
# return self.call(["rpm"] + args, **kwargs)
#
# def grubby(self, args, **kwargs):
# return self.call(["grubby"] + args, **kwargs)
#
# def grub2_mkconfig(self, args, **kwargs):
# return self.call(["grub2-mkconfig"] + args, **kwargs)
#
# def grub2_editenv(self, args, **kwargs):
# return self.call(["grub2-editenv"] + args, **kwargs)
#
# def systemctl(self, args, **kwargs):
# return self.call(["systemctl"] + args, **kwargs)
#
# def pkill(self, args, **kwargs):
# return self.call(["pkill"] + args, **kwargs)
#
# def umount(self, args, **kwargs):
# return self.call(["umount", "-l"] + args, **kwargs)
#
# def semanage(self, args, **kwargs):
# return self.call(["semanage"] + args, **kwargs)
#
# def runcon(self, args, **kwargs):
# return self.call(["runcon"] + args, **kwargs)
#
# def lvmconfig(self, args, **kwargs):
# return self.call(["lvmconfig"] + args, **kwargs)
#
# def mount(self, args, **kwargs):
# return self.call(["mount"] + args, **kwargs)
#
# def getenforce(self):
# return self.call(["getenforce"])
#
# def mknod(self, args, **kwargs):
# return self.call(["mknod"] + args, **kwargs)
#
# def ldconfig(self, args, **kwargs):
# return self.call(["ldconfig"] + args, **kwargs)
#
# def sync(self, args, **kwargs):
# return self.call(["sync"] + args, **kwargs)
#
# class LvmCLI():
# lvs = LvmBinary().lvs
# vgs = LvmBinary().vgs
# lvcreate = ExternalBinary().lvcreate
# lvchange = LvmBinary().lvchange
# lvremove = LvmBinary().lvremove
# lvrename = LvmBinary().lvrename
# lvextend = LvmBinary().lvextend
# vgcreate = LvmBinary().vgcreate
# vgchange = LvmBinary().vgchange
# lvmconfig = LvmBinary().lvmconfig
#
# def find_mount_source(path, raise_on_error=False):
# mnt_source = findmnt(["SOURCE"], path=path, raise_on_error=raise_on_error)
# if mnt_source is not None:
# return mnt_source.strip()
# return None
. Output only the next line. | run = ExternalBinary() |
Given the code snippet: <|code_start|>#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): Fabian Deutsch <fabiand@redhat.com>
#
log = logging.getLogger(__package__)
class MissingLvmThinPool(Exception):
pass
class ThinPoolMetadataError(Exception):
pass
class LVM(object):
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import re
import shlex
from operator import itemgetter
from .utils import ExternalBinary, LvmCLI, find_mount_source
and context (functions, classes, or occasionally code) from other files:
# Path: src/imgbased/utils.py
# class ExternalBinary(object):
# dry = False
# squash_output = False
#
# def call(self, *args, **kwargs):
# stdout = bytes()
# if not self.dry:
# stdout = command.call(*args, **kwargs)
# if stdout and not self.squash_output:
# log.debug("Returned: %s" % stdout[0:1024])
# return stdout.decode(errors="replace").strip()
#
# def lvs(self, args, **kwargs):
# return self.call(["lvs"] + args, **kwargs)
#
# def vgs(self, args, **kwargs):
# return self.call(["vgs"] + args, **kwargs)
#
# def lvcreate(self, args, **kwargs):
# return self.call(["lvcreate"] + args, **kwargs)
#
# def lvremove(self, args, **kwargs):
# return self.call(["lvremove"] + args, **kwargs)
#
# def lvrename(self, args, **kwargs):
# return self.call(["lvrename"] + args, **kwargs)
#
# def lvextend(self, args, **kwargs):
# return self.call(["lvextend"] + args, **kwargs)
#
# def vgcreate(self, args, **kwargs):
# return self.call(["vgcreate"] + args, **kwargs)
#
# def lvchange(self, args, **kwargs):
# return self.call(["lvchange"] + args, **kwargs)
#
# def vgchange(self, args, **kwargs):
# return self.call(["vgchange"] + args, **kwargs)
#
# def find(self, args, **kwargs):
# return self.call(["find"] + args, **kwargs)
#
# def findmnt(self, args, **kwargs):
# return self.call(["findmnt"] + args, **kwargs)
#
# def du(self, args, **kwargs):
# return self.call(["du"] + args, **kwargs)
#
# def rm(self, args, **kwargs):
# return self.call(["rm"] + args, **kwargs)
#
# def cp(self, args, **kwargs):
# return self.call(["cp"] + args, **kwargs)
#
# def rpm(self, args, **kwargs):
# self.squash_output = True
# return self.call(["rpm"] + args, **kwargs)
#
# def grubby(self, args, **kwargs):
# return self.call(["grubby"] + args, **kwargs)
#
# def grub2_mkconfig(self, args, **kwargs):
# return self.call(["grub2-mkconfig"] + args, **kwargs)
#
# def grub2_editenv(self, args, **kwargs):
# return self.call(["grub2-editenv"] + args, **kwargs)
#
# def systemctl(self, args, **kwargs):
# return self.call(["systemctl"] + args, **kwargs)
#
# def pkill(self, args, **kwargs):
# return self.call(["pkill"] + args, **kwargs)
#
# def umount(self, args, **kwargs):
# return self.call(["umount", "-l"] + args, **kwargs)
#
# def semanage(self, args, **kwargs):
# return self.call(["semanage"] + args, **kwargs)
#
# def runcon(self, args, **kwargs):
# return self.call(["runcon"] + args, **kwargs)
#
# def lvmconfig(self, args, **kwargs):
# return self.call(["lvmconfig"] + args, **kwargs)
#
# def mount(self, args, **kwargs):
# return self.call(["mount"] + args, **kwargs)
#
# def getenforce(self):
# return self.call(["getenforce"])
#
# def mknod(self, args, **kwargs):
# return self.call(["mknod"] + args, **kwargs)
#
# def ldconfig(self, args, **kwargs):
# return self.call(["ldconfig"] + args, **kwargs)
#
# def sync(self, args, **kwargs):
# return self.call(["sync"] + args, **kwargs)
#
# class LvmCLI():
# lvs = LvmBinary().lvs
# vgs = LvmBinary().vgs
# lvcreate = ExternalBinary().lvcreate
# lvchange = LvmBinary().lvchange
# lvremove = LvmBinary().lvremove
# lvrename = LvmBinary().lvrename
# lvextend = LvmBinary().lvextend
# vgcreate = LvmBinary().vgcreate
# vgchange = LvmBinary().vgchange
# lvmconfig = LvmBinary().lvmconfig
#
# def find_mount_source(path, raise_on_error=False):
# mnt_source = findmnt(["SOURCE"], path=path, raise_on_error=raise_on_error)
# if mnt_source is not None:
# return mnt_source.strip()
# return None
. Output only the next line. | _lvs = LvmCLI.lvs |
Given the code snippet: <|code_start|> return LVM._lvs(["--noheadings", "--ignoreskippedcluster",
"-olv_path", self.lvm_name])
@property
def dm_path(self):
return LVM._lvs(["--noheadings", "--ignoreskippedcluster",
"-olv_dm_path", self.lvm_name])
@property
def size_bytes(self):
return LVM._lvs(["--noheadings", "--ignoreskippedcluster",
"-osize", "--units", "B", self.lvm_name])
@classmethod
def from_lv_name(cls, vg_name, lv_name):
lv = cls()
lv.vg_name = vg_name
lv.lv_name = lv_name
return lv
def __repr__(self):
return "<LV '%s' />" % self.lvm_name
@classmethod
def try_find(cls, mixed):
log.debug("Trying to find LV for: %s" % mixed)
assert mixed
if mixed.startswith("/dev"):
return cls.from_path(mixed)
elif os.path.ismount(mixed):
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import re
import shlex
from operator import itemgetter
from .utils import ExternalBinary, LvmCLI, find_mount_source
and context (functions, classes, or occasionally code) from other files:
# Path: src/imgbased/utils.py
# class ExternalBinary(object):
# dry = False
# squash_output = False
#
# def call(self, *args, **kwargs):
# stdout = bytes()
# if not self.dry:
# stdout = command.call(*args, **kwargs)
# if stdout and not self.squash_output:
# log.debug("Returned: %s" % stdout[0:1024])
# return stdout.decode(errors="replace").strip()
#
# def lvs(self, args, **kwargs):
# return self.call(["lvs"] + args, **kwargs)
#
# def vgs(self, args, **kwargs):
# return self.call(["vgs"] + args, **kwargs)
#
# def lvcreate(self, args, **kwargs):
# return self.call(["lvcreate"] + args, **kwargs)
#
# def lvremove(self, args, **kwargs):
# return self.call(["lvremove"] + args, **kwargs)
#
# def lvrename(self, args, **kwargs):
# return self.call(["lvrename"] + args, **kwargs)
#
# def lvextend(self, args, **kwargs):
# return self.call(["lvextend"] + args, **kwargs)
#
# def vgcreate(self, args, **kwargs):
# return self.call(["vgcreate"] + args, **kwargs)
#
# def lvchange(self, args, **kwargs):
# return self.call(["lvchange"] + args, **kwargs)
#
# def vgchange(self, args, **kwargs):
# return self.call(["vgchange"] + args, **kwargs)
#
# def find(self, args, **kwargs):
# return self.call(["find"] + args, **kwargs)
#
# def findmnt(self, args, **kwargs):
# return self.call(["findmnt"] + args, **kwargs)
#
# def du(self, args, **kwargs):
# return self.call(["du"] + args, **kwargs)
#
# def rm(self, args, **kwargs):
# return self.call(["rm"] + args, **kwargs)
#
# def cp(self, args, **kwargs):
# return self.call(["cp"] + args, **kwargs)
#
# def rpm(self, args, **kwargs):
# self.squash_output = True
# return self.call(["rpm"] + args, **kwargs)
#
# def grubby(self, args, **kwargs):
# return self.call(["grubby"] + args, **kwargs)
#
# def grub2_mkconfig(self, args, **kwargs):
# return self.call(["grub2-mkconfig"] + args, **kwargs)
#
# def grub2_editenv(self, args, **kwargs):
# return self.call(["grub2-editenv"] + args, **kwargs)
#
# def systemctl(self, args, **kwargs):
# return self.call(["systemctl"] + args, **kwargs)
#
# def pkill(self, args, **kwargs):
# return self.call(["pkill"] + args, **kwargs)
#
# def umount(self, args, **kwargs):
# return self.call(["umount", "-l"] + args, **kwargs)
#
# def semanage(self, args, **kwargs):
# return self.call(["semanage"] + args, **kwargs)
#
# def runcon(self, args, **kwargs):
# return self.call(["runcon"] + args, **kwargs)
#
# def lvmconfig(self, args, **kwargs):
# return self.call(["lvmconfig"] + args, **kwargs)
#
# def mount(self, args, **kwargs):
# return self.call(["mount"] + args, **kwargs)
#
# def getenforce(self):
# return self.call(["getenforce"])
#
# def mknod(self, args, **kwargs):
# return self.call(["mknod"] + args, **kwargs)
#
# def ldconfig(self, args, **kwargs):
# return self.call(["ldconfig"] + args, **kwargs)
#
# def sync(self, args, **kwargs):
# return self.call(["sync"] + args, **kwargs)
#
# class LvmCLI():
# lvs = LvmBinary().lvs
# vgs = LvmBinary().vgs
# lvcreate = ExternalBinary().lvcreate
# lvchange = LvmBinary().lvchange
# lvremove = LvmBinary().lvremove
# lvrename = LvmBinary().lvrename
# lvextend = LvmBinary().lvextend
# vgcreate = LvmBinary().vgcreate
# vgchange = LvmBinary().vgchange
# lvmconfig = LvmBinary().lvmconfig
#
# def find_mount_source(path, raise_on_error=False):
# mnt_source = findmnt(["SOURCE"], path=path, raise_on_error=raise_on_error)
# if mnt_source is not None:
# return mnt_source.strip()
# return None
. Output only the next line. | return cls.from_path(find_mount_source(mixed)) |
Based on the snippet: <|code_start|> self.configure()
def register(self, datastream, profile):
log.info("Registering profile %s from %s", profile, datastream)
if profile not in self.profiles(datastream):
log.error("Profile %s not found", profile)
return
self._config.datastream = os.path.realpath(datastream)
self._config.profile = profile
def unregister(self, profile):
if profile == self._config.profile:
log.info("Unregistering profile %s", profile)
self._config.profile = ""
else:
log.warn("Profile [%s] is not registered, skipping", profile)
def scan(self, remediate=False, path="/"):
log.debug("Running OSCAP scan on %s, (remediate=%s)", path, remediate)
if not self._config.registered:
log.warn("Security profile not registered, skipping")
return
report = SCAP_REPORT_FMT % time.strftime("%Y%m%d%H%M%S")
args = ["chroot", path, "oscap", "xccdf", "eval",
"--profile", self.profile, "--report", report]
if remediate:
args.append("--remediate")
args.append(self._config.datastream)
with bindmounted("/proc", path + "/proc"):
with bindmounted("/var", path + "/var", rbind=True):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import time
from six.moves.configparser import ConfigParser
from systemd import journal
from .command import nsenter
from .constants import IMGBASED_STATE_DIR
from .utils import File, bindmounted
and context (classes, functions, sometimes code) from other files:
# Path: src/imgbased/command.py
# def nsenter(arg, new_root=None, shell=False, environ=None):
# DEVNULL = open(os.devnull, "w")
# if new_root:
# if shell:
# arg = "nsenter --root={0} --wd={0} {1}".format(new_root, arg)
# else:
# arg = [
# "nsenter",
# "--root={}".format(new_root),
# "--wd={}".format(new_root),
# ] + arg
# environ = environ or os.environ
# log.debug("Executing: %s", arg)
# proc = subprocess.Popen(arg, stdout=subprocess.PIPE, env=environ,
# stderr=DEVNULL, shell=shell).communicate()
# ret = proc[0]
# log.debug("Result: %s", repr(ret))
# return ret
#
# Path: src/imgbased/utils.py
# class File(object):
# filename = None
#
# @property
# def contents(self):
# return self.read()
#
# @property
# def stat(self):
# return os.stat(self.filename)
#
# def __init__(self, fn):
# self.filename = fn
#
# def __str__(self):
# return "<%s %s>" % (self.__class__.__name__, self.filename)
#
# def read(self):
# with open(self.filename) as src:
# return src.read()
#
# def exists(self):
# return os.path.exists(self.filename)
#
# def replace(self, pat, repl):
# self.write(self.contents.replace(pat, repl))
#
# def sub(self, pat, repl):
# self.write(re.sub(pat, repl, self.contents))
#
# def write(self, data, mode="w", mkdir=False):
# if mkdir:
# os.makedirs(os.path.dirname(self.filename))
# with open(self.filename, mode) as dst:
# dst.write(data)
#
# def writen(self, data, mode="w"):
# self.write(data + "\n", mode)
#
# def remove(self):
# os.unlink(self.filename)
#
# def lines(self, keepends=False):
# for line in self.contents.splitlines(keepends):
# yield line
#
# def findall(self, pat):
# r = []
# for line in self.lines():
# r += re.findall(pat, line)
# return r
#
# def chmod(self, mode):
# return os.chmod(self.filename, mode)
#
# def basename(self):
# return os.path.basename(self.filename)
#
# def truncate(self, size=0):
# """Truncate the file to size
# """
# with open(self.filename, "w") as fd:
# fd.truncate(size)
#
# @contextmanager
# def bindmounted(source, target, rbind=False, readonly=False):
# options = "rbind" if rbind else "bind,private"
# options = options + ",ro" if readonly else options
# with mounted(source, target=target, options=options) as mnt:
# yield mnt
# log.debug("Done!")
. Output only the next line. | nsenter(args) |
Using the snippet: <|code_start|> return
self._config.datastream = os.path.realpath(datastream)
self._config.profile = profile
def unregister(self, profile):
if profile == self._config.profile:
log.info("Unregistering profile %s", profile)
self._config.profile = ""
else:
log.warn("Profile [%s] is not registered, skipping", profile)
def scan(self, remediate=False, path="/"):
log.debug("Running OSCAP scan on %s, (remediate=%s)", path, remediate)
if not self._config.registered:
log.warn("Security profile not registered, skipping")
return
report = SCAP_REPORT_FMT % time.strftime("%Y%m%d%H%M%S")
args = ["chroot", path, "oscap", "xccdf", "eval",
"--profile", self.profile, "--report", report]
if remediate:
args.append("--remediate")
args.append(self._config.datastream)
with bindmounted("/proc", path + "/proc"):
with bindmounted("/var", path + "/var", rbind=True):
nsenter(args)
log.info("Report available at %s", report)
def profiles(self, datastream=None):
if not datastream:
datastream = self._config.datastream
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import time
from six.moves.configparser import ConfigParser
from systemd import journal
from .command import nsenter
from .constants import IMGBASED_STATE_DIR
from .utils import File, bindmounted
and context (class names, function names, or code) available:
# Path: src/imgbased/command.py
# def nsenter(arg, new_root=None, shell=False, environ=None):
# DEVNULL = open(os.devnull, "w")
# if new_root:
# if shell:
# arg = "nsenter --root={0} --wd={0} {1}".format(new_root, arg)
# else:
# arg = [
# "nsenter",
# "--root={}".format(new_root),
# "--wd={}".format(new_root),
# ] + arg
# environ = environ or os.environ
# log.debug("Executing: %s", arg)
# proc = subprocess.Popen(arg, stdout=subprocess.PIPE, env=environ,
# stderr=DEVNULL, shell=shell).communicate()
# ret = proc[0]
# log.debug("Result: %s", repr(ret))
# return ret
#
# Path: src/imgbased/utils.py
# class File(object):
# filename = None
#
# @property
# def contents(self):
# return self.read()
#
# @property
# def stat(self):
# return os.stat(self.filename)
#
# def __init__(self, fn):
# self.filename = fn
#
# def __str__(self):
# return "<%s %s>" % (self.__class__.__name__, self.filename)
#
# def read(self):
# with open(self.filename) as src:
# return src.read()
#
# def exists(self):
# return os.path.exists(self.filename)
#
# def replace(self, pat, repl):
# self.write(self.contents.replace(pat, repl))
#
# def sub(self, pat, repl):
# self.write(re.sub(pat, repl, self.contents))
#
# def write(self, data, mode="w", mkdir=False):
# if mkdir:
# os.makedirs(os.path.dirname(self.filename))
# with open(self.filename, mode) as dst:
# dst.write(data)
#
# def writen(self, data, mode="w"):
# self.write(data + "\n", mode)
#
# def remove(self):
# os.unlink(self.filename)
#
# def lines(self, keepends=False):
# for line in self.contents.splitlines(keepends):
# yield line
#
# def findall(self, pat):
# r = []
# for line in self.lines():
# r += re.findall(pat, line)
# return r
#
# def chmod(self, mode):
# return os.chmod(self.filename, mode)
#
# def basename(self):
# return os.path.basename(self.filename)
#
# def truncate(self, size=0):
# """Truncate the file to size
# """
# with open(self.filename, "w") as fd:
# fd.truncate(size)
#
# @contextmanager
# def bindmounted(source, target, rbind=False, readonly=False):
# options = "rbind" if rbind else "bind,private"
# options = options + ",ro" if readonly else options
# with mounted(source, target=target, options=options) as mnt:
# yield mnt
# log.debug("Done!")
. Output only the next line. | if not datastream or not File(datastream).exists(): |
Here is a snippet: <|code_start|> self.scan(remediate=True, path=path)
else:
self.configure()
def register(self, datastream, profile):
log.info("Registering profile %s from %s", profile, datastream)
if profile not in self.profiles(datastream):
log.error("Profile %s not found", profile)
return
self._config.datastream = os.path.realpath(datastream)
self._config.profile = profile
def unregister(self, profile):
if profile == self._config.profile:
log.info("Unregistering profile %s", profile)
self._config.profile = ""
else:
log.warn("Profile [%s] is not registered, skipping", profile)
def scan(self, remediate=False, path="/"):
log.debug("Running OSCAP scan on %s, (remediate=%s)", path, remediate)
if not self._config.registered:
log.warn("Security profile not registered, skipping")
return
report = SCAP_REPORT_FMT % time.strftime("%Y%m%d%H%M%S")
args = ["chroot", path, "oscap", "xccdf", "eval",
"--profile", self.profile, "--report", report]
if remediate:
args.append("--remediate")
args.append(self._config.datastream)
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import time
from six.moves.configparser import ConfigParser
from systemd import journal
from .command import nsenter
from .constants import IMGBASED_STATE_DIR
from .utils import File, bindmounted
and context from other files:
# Path: src/imgbased/command.py
# def nsenter(arg, new_root=None, shell=False, environ=None):
# DEVNULL = open(os.devnull, "w")
# if new_root:
# if shell:
# arg = "nsenter --root={0} --wd={0} {1}".format(new_root, arg)
# else:
# arg = [
# "nsenter",
# "--root={}".format(new_root),
# "--wd={}".format(new_root),
# ] + arg
# environ = environ or os.environ
# log.debug("Executing: %s", arg)
# proc = subprocess.Popen(arg, stdout=subprocess.PIPE, env=environ,
# stderr=DEVNULL, shell=shell).communicate()
# ret = proc[0]
# log.debug("Result: %s", repr(ret))
# return ret
#
# Path: src/imgbased/utils.py
# class File(object):
# filename = None
#
# @property
# def contents(self):
# return self.read()
#
# @property
# def stat(self):
# return os.stat(self.filename)
#
# def __init__(self, fn):
# self.filename = fn
#
# def __str__(self):
# return "<%s %s>" % (self.__class__.__name__, self.filename)
#
# def read(self):
# with open(self.filename) as src:
# return src.read()
#
# def exists(self):
# return os.path.exists(self.filename)
#
# def replace(self, pat, repl):
# self.write(self.contents.replace(pat, repl))
#
# def sub(self, pat, repl):
# self.write(re.sub(pat, repl, self.contents))
#
# def write(self, data, mode="w", mkdir=False):
# if mkdir:
# os.makedirs(os.path.dirname(self.filename))
# with open(self.filename, mode) as dst:
# dst.write(data)
#
# def writen(self, data, mode="w"):
# self.write(data + "\n", mode)
#
# def remove(self):
# os.unlink(self.filename)
#
# def lines(self, keepends=False):
# for line in self.contents.splitlines(keepends):
# yield line
#
# def findall(self, pat):
# r = []
# for line in self.lines():
# r += re.findall(pat, line)
# return r
#
# def chmod(self, mode):
# return os.chmod(self.filename, mode)
#
# def basename(self):
# return os.path.basename(self.filename)
#
# def truncate(self, size=0):
# """Truncate the file to size
# """
# with open(self.filename, "w") as fd:
# fd.truncate(size)
#
# @contextmanager
# def bindmounted(source, target, rbind=False, readonly=False):
# options = "rbind" if rbind else "bind,private"
# options = options + ",ro" if readonly else options
# with mounted(source, target=target, options=options) as mnt:
# yield mnt
# log.debug("Done!")
, which may include functions, classes, or code. Output only the next line. | with bindmounted("/proc", path + "/proc"): |
Given the code snippet: <|code_start|>
log = logging.getLogger(__package__)
def init(app):
app.hooks.connect("pre-arg-parse", add_argparse)
app.hooks.connect("post-arg-parse", post_argparse)
def add_argparse(app, parser, subparsers):
if not app.experimental:
return
s = subparsers.add_parser("volume",
help="Volume management")
s.add_argument("--list", action="store_true",
help="List all known volumnes")
s.add_argument("--attach", metavar="PATH",
help="Attach a volume to the current layer")
s.add_argument("--detach", metavar="PATH",
help="Detach a volume from the current layer")
s.add_argument("--create", nargs=2, metavar=("PATH", "SIZE"),
help="Create a volume of SIZE for PATH")
s.add_argument("--remove", metavar="PATH",
help="Remove the volume for PATH")
def post_argparse(app, args):
if args.command == "volume":
<|code_end|>
, generate the next line using the imports in this file:
import logging
from ..volume import Volumes
and context (functions, classes, or occasionally code) from other files:
# Path: src/imgbased/volume.py
# class Volumes(object):
# tag_volume = "imgbased:volume"
#
# imgbase = None
#
# mountfile_tmpl = """# Created by imgbased
# [Mount]
# What={what}
# Where={where}
# Options={options}
# SloppyOptions=yes
#
# [Install]
# WantedBy=local-fs.target
# """
#
# def __init__(self, imgbase):
# self.imgbase = imgbase
# self.fs = Filesystem.from_mountpoint("/")
#
# def _volname(self, where):
# return where.strip("/").replace("-", "--").replace("/", "_")
#
# def _mountfile(self, where, unittype="mount"):
# safewhere = self._volname(where).replace("_", "-")
# return File("/etc/systemd/system/%s.%s" % (safewhere, unittype))
#
# def _rename_volume(self, thinpool, volname):
# new_name = "%s.%s" % (volname, time.strftime("%Y%m%d%H%M%S"))
# lv = LVM.LV.from_lv_name(thinpool.vg_name, volname)
# lv.rename(new_name)
# lv.deltag(self.tag_volume)
#
# def volumes(self):
# lvs = LVM.LV.find_by_tag(self.tag_volume)
# return ["/" + lv.lv_name.replace("_", "/").replace("--", "-")
# for lv in lvs]
#
# def is_volume(self, where):
# return where.rstrip("/") in self.volumes()
#
# def create(self, where, size, attach_now=True):
# assert where.startswith("/"), "An absolute path is required"
# assert os.path.isdir(where), "Is no dir: %s" % where
#
# thinpool = self.imgbase._thinpool()
# volname = self._volname(where)
#
# if self.is_volume(where):
# self._rename_volume(thinpool, volname)
#
# # Create the vol
# vol = thinpool.create_thinvol(volname, size)
# vol.addtag(self.tag_volume)
#
# self.fs.mkfs(vol.path)
#
# # Populate
# with mounted(vol.path) as mount:
# Rsync().sync(where + "/", mount.target.rstrip("/"))
# pass
#
# log.info("Volume for '%s' was created successful" % where)
# self.attach(where, attach_now)
#
# def remove(self, where, force=False):
# assert self.is_volume(where), "Path is no volume: %s" % where
#
# log.warn("Removing the volume will also remove the data "
# "on that volume.")
#
# volname = self._volname(where)
# self.detach(where)
# self.imgbase.lv(volname).remove(force)
#
# log.info("Volume for '%s' was removed successful" % where)
#
# def attach(self, where, attach_now):
# assert self.is_volume(where), "Path is no volume: %s" % where
#
# volname = self._volname(where)
# what = self.imgbase.lv(volname).path
#
# unitfile = self._mountfile(where)
# unitfile.write(self.mountfile_tmpl.format(what=what,
# where=where,
# options="discard"))
#
# systemctl.daemon_reload()
#
# systemctl.enable(unitfile.basename())
# if attach_now:
# systemctl.start(unitfile.basename())
#
# # Access it to start it
# os.listdir(where)
#
# log.info("Volume for '%s' was attached successful" % where)
# else:
# log.info("Volume for '%s' was created but not attached" % where)
#
# def detach(self, where):
# assert self.is_volume(where), "Path is no volume: %s" % where
#
# unitfile = self._mountfile(where)
#
# systemctl.disable(unitfile.basename())
# systemctl.stop(unitfile.basename())
# unitfile.remove()
#
# systemctl.daemon_reload()
#
# log.info("Volume for '%s' was detached successful" % where)
. Output only the next line. | vols = Volumes(app.imgbase) |
Using the snippet: <|code_start|># Copyright (C) 2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): Ryan Barry <rbarry@redhat.com>
#
log = logging.getLogger(__package__)
class TimeserverError(Exception):
pass
class NoKeyFoundError(TimeserverError):
pass
<|code_end|>
, determine the next line of code. You have imports:
import logging
import re
from .utils import File
and context (class names, function names, or code) available:
# Path: src/imgbased/utils.py
# class File(object):
# filename = None
#
# @property
# def contents(self):
# return self.read()
#
# @property
# def stat(self):
# return os.stat(self.filename)
#
# def __init__(self, fn):
# self.filename = fn
#
# def __str__(self):
# return "<%s %s>" % (self.__class__.__name__, self.filename)
#
# def read(self):
# with open(self.filename) as src:
# return src.read()
#
# def exists(self):
# return os.path.exists(self.filename)
#
# def replace(self, pat, repl):
# self.write(self.contents.replace(pat, repl))
#
# def sub(self, pat, repl):
# self.write(re.sub(pat, repl, self.contents))
#
# def write(self, data, mode="w", mkdir=False):
# if mkdir:
# os.makedirs(os.path.dirname(self.filename))
# with open(self.filename, mode) as dst:
# dst.write(data)
#
# def writen(self, data, mode="w"):
# self.write(data + "\n", mode)
#
# def remove(self):
# os.unlink(self.filename)
#
# def lines(self, keepends=False):
# for line in self.contents.splitlines(keepends):
# yield line
#
# def findall(self, pat):
# r = []
# for line in self.lines():
# r += re.findall(pat, line)
# return r
#
# def chmod(self, mode):
# return os.chmod(self.filename, mode)
#
# def basename(self):
# return os.path.basename(self.filename)
#
# def truncate(self, size=0):
# """Truncate the file to size
# """
# with open(self.filename, "w") as fd:
# fd.truncate(size)
. Output only the next line. | class TimeserverConfiguration(File): |
Predict the next line for this snippet: <|code_start|>#! /usr/bin/env python
from __future__ import unicode_literals, print_function
# TODO(cnicolaou): get the multi section tests working
class MyMultiSectionFactory(MultiSectionFactory):
def __init__(self, dir):
self.main_file_name = os.path.join(dir, "foomodule4.cc")
<|code_end|>
with the help of current file imports:
import sys
import os.path
import pybindgen
import foomodulegen_split
import foomodulegen_module1, foomodulegen_module2
import foomodulegen_common
import cProfile as profile
from pybindgen.module import MultiSectionFactory
from pybindgen import (FileCodeSink)
and context from other files:
# Path: pybindgen/module.py
# class MultiSectionFactory(object):
# """
# Abstract base class for objects providing support for
# multi-section code generation, i.e., splitting the generated C/C++
# code into multiple files. The generated code will generally have
# the following structure:
#
# 1. For each section there is one source file specific to that section;
#
# 2. There is a I{main} source file, e.g. C{foomodule.cc}. Code
# that does not belong to any section will be included in this
# main file;
#
# 3. Finally, there is a common header file, (e.g. foomodule.h),
# which is included by the main file and section files alike.
# Typically this header file contains function prototypes and
# type definitions.
#
# @see: L{Module.generate}
#
# """
# def get_section_code_sink(self, section_name):
# """
# Create and/or return a code sink for a given section.
#
# :param section_name: name of the section
# :return: a L{CodeSink} object that will receive generated code belonging to the section C{section_name}
# """
# raise NotImplementedError
# def get_main_code_sink(self):
# """
# Create and/or return a code sink for the main file.
# """
# raise NotImplementedError
# def get_common_header_code_sink(self):
# """
# Create and/or return a code sink for the common header.
# """
# raise NotImplementedError
# def get_common_header_include(self):
# """
# Return the argument for an #include directive to include the common header.
#
# :returns: a string with the header name, including surrounding
# "" or <>. For example, '"foomodule.h"'.
# """
# raise NotImplementedError
#
# Path: pybindgen/typehandlers/codesink.py
# class FileCodeSink(CodeSink):
# """A code sink that writes to a file-like object"""
# def __init__(self, file_):
# """
# :param file_: a file like object
# """
# CodeSink.__init__(self)
# self.file = file_
#
# def __repr__(self):
# return "<pybindgen.typehandlers.codesink.FileCodeSink %r>" % (self.file.name,)
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# self.file.write('\n'.join(self._format_code(line)))
# self.file.write('\n')
#
# def __lt__(self, other):
# if isinstance(other, FileCodeSink):
# return self.file.name < other.file.name
, which may contain function names, class names, or code. Output only the next line. | self.main_sink = FileCodeSink(open(self.main_file_name, "wt")) |
Next line prediction: <|code_start|>
if PY3:
string_types = str,
else:
string_types = basestring,
try:
any = any
except NameError:
def any(iterable):
for element in iterable:
if element:
return True
return False
try:
except ImportError:
__version__ = [0, 0, 0, 0]
def write_preamble(code_sink, min_python_version=None):
"""
Write a preamble, containing includes, #define's and typedef's
necessary to correctly compile the code with the given minimum python
version.
"""
if min_python_version is None:
min_python_version = settings.min_python_version
<|code_end|>
. Use current file imports:
(import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings)
and context including class names, function names, or small code snippets from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | assert isinstance(code_sink, CodeSink) |
Continue the code snippet: <|code_start|> else:
raise TypeError("Could not parse `%r' as a Parameter" % param_spec)
return args, kwargs
def parse_retval_spec(retval_spec):
if isinstance(retval_spec, tuple):
assert len(retval_spec) >= 1
if isinstance(retval_spec[-1], dict):
kwargs = retval_spec[-1]
args = retval_spec[:-1]
else:
kwargs = dict()
args = retval_spec
elif isinstance(retval_spec, string_types):
kwargs = dict()
args = (retval_spec,)
else:
raise TypeError("Could not parse `%r' as a ReturnValue" % retval_spec)
return args, kwargs
def eval_param(param_value, wrapper=None):
if isinstance(param_value, Parameter):
return param_value
else:
args, kwargs = parse_param_spec(param_value)
return call_with_error_handling(Parameter.new, args, kwargs, wrapper,
exceptions_to_handle=(TypeConfigurationError,
NotSupportedError,
<|code_end|>
. Use current file imports:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and context (classes, functions, or code) from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | TypeLookupError)) |
Given the code snippet: <|code_start|>
def mangle_name(name):
"""make a name Like<This,and,That> look Like__lt__This_and_That__gt__"""
s = name.replace('<', '__lt__').replace('>', '__gt__').replace(',', '_')
s = s.replace(' ', '_').replace('&', '__amp__').replace('*', '__star__')
s = s.replace(':', '_')
s = s.replace('(', '_lp_').replace(')', '_rp_')
return s
def get_mangled_name(base_name, template_args):
"""for internal pybindgen use"""
assert isinstance(base_name, string_types)
assert isinstance(template_args, (tuple, list))
if template_args:
return '%s__lt__%s__gt__' % (mangle_name(base_name), '_'.join(
[mangle_name(arg) for arg in template_args]))
else:
return mangle_name(base_name)
class SkipWrapper(Exception):
"""Exception that is raised to signal a wrapper failed to generate but
must simply be skipped.
for internal pybindgen use"""
def call_with_error_handling(callback, args, kwargs, wrapper,
<|code_end|>
, generate the next line using the imports in this file:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and context (functions, classes, or occasionally code) from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | exceptions_to_handle=(TypeConfigurationError, |
Predict the next line after this snippet: <|code_start|>
def mangle_name(name):
"""make a name Like<This,and,That> look Like__lt__This_and_That__gt__"""
s = name.replace('<', '__lt__').replace('>', '__gt__').replace(',', '_')
s = s.replace(' ', '_').replace('&', '__amp__').replace('*', '__star__')
s = s.replace(':', '_')
s = s.replace('(', '_lp_').replace(')', '_rp_')
return s
def get_mangled_name(base_name, template_args):
"""for internal pybindgen use"""
assert isinstance(base_name, string_types)
assert isinstance(template_args, (tuple, list))
if template_args:
return '%s__lt__%s__gt__' % (mangle_name(base_name), '_'.join(
[mangle_name(arg) for arg in template_args]))
else:
return mangle_name(base_name)
class SkipWrapper(Exception):
"""Exception that is raised to signal a wrapper failed to generate but
must simply be skipped.
for internal pybindgen use"""
def call_with_error_handling(callback, args, kwargs, wrapper,
exceptions_to_handle=(TypeConfigurationError,
<|code_end|>
using the current file's imports:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and any relevant context from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | CodeGenerationError, |
Predict the next line after this snippet: <|code_start|>
def mangle_name(name):
"""make a name Like<This,and,That> look Like__lt__This_and_That__gt__"""
s = name.replace('<', '__lt__').replace('>', '__gt__').replace(',', '_')
s = s.replace(' ', '_').replace('&', '__amp__').replace('*', '__star__')
s = s.replace(':', '_')
s = s.replace('(', '_lp_').replace(')', '_rp_')
return s
def get_mangled_name(base_name, template_args):
"""for internal pybindgen use"""
assert isinstance(base_name, string_types)
assert isinstance(template_args, (tuple, list))
if template_args:
return '%s__lt__%s__gt__' % (mangle_name(base_name), '_'.join(
[mangle_name(arg) for arg in template_args]))
else:
return mangle_name(base_name)
class SkipWrapper(Exception):
"""Exception that is raised to signal a wrapper failed to generate but
must simply be skipped.
for internal pybindgen use"""
def call_with_error_handling(callback, args, kwargs, wrapper,
exceptions_to_handle=(TypeConfigurationError,
CodeGenerationError,
<|code_end|>
using the current file's imports:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and any relevant context from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | NotSupportedError)): |
Predict the next line for this snippet: <|code_start|> assert len(param_spec) >= 2
if isinstance(param_spec[-1], dict):
kwargs = param_spec[-1]
args = param_spec[:-1]
else:
kwargs = dict()
args = param_spec
else:
raise TypeError("Could not parse `%r' as a Parameter" % param_spec)
return args, kwargs
def parse_retval_spec(retval_spec):
if isinstance(retval_spec, tuple):
assert len(retval_spec) >= 1
if isinstance(retval_spec[-1], dict):
kwargs = retval_spec[-1]
args = retval_spec[:-1]
else:
kwargs = dict()
args = retval_spec
elif isinstance(retval_spec, string_types):
kwargs = dict()
args = (retval_spec,)
else:
raise TypeError("Could not parse `%r' as a ReturnValue" % retval_spec)
return args, kwargs
def eval_param(param_value, wrapper=None):
<|code_end|>
with the help of current file imports:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and context from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
, which may contain function names, class names, or code. Output only the next line. | if isinstance(param_value, Parameter): |
Here is a snippet: <|code_start|>
def parse_retval_spec(retval_spec):
if isinstance(retval_spec, tuple):
assert len(retval_spec) >= 1
if isinstance(retval_spec[-1], dict):
kwargs = retval_spec[-1]
args = retval_spec[:-1]
else:
kwargs = dict()
args = retval_spec
elif isinstance(retval_spec, string_types):
kwargs = dict()
args = (retval_spec,)
else:
raise TypeError("Could not parse `%r' as a ReturnValue" % retval_spec)
return args, kwargs
def eval_param(param_value, wrapper=None):
if isinstance(param_value, Parameter):
return param_value
else:
args, kwargs = parse_param_spec(param_value)
return call_with_error_handling(Parameter.new, args, kwargs, wrapper,
exceptions_to_handle=(TypeConfigurationError,
NotSupportedError,
TypeLookupError))
def eval_retval(retval_value, wrapper=None):
<|code_end|>
. Write the next line using the current file imports:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and context from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
, which may include functions, classes, or code. Output only the next line. | if isinstance(retval_value, ReturnValue): |
Given the code snippet: <|code_start|>PY3 = (sys.version_info[0] >= 3)
if PY3:
string_types = str,
else:
string_types = basestring,
try:
any = any
except NameError:
def any(iterable):
for element in iterable:
if element:
return True
return False
try:
except ImportError:
__version__ = [0, 0, 0, 0]
def write_preamble(code_sink, min_python_version=None):
"""
Write a preamble, containing includes, #define's and typedef's
necessary to correctly compile the code with the given minimum python
version.
"""
if min_python_version is None:
<|code_end|>
, generate the next line using the imports in this file:
import sys
import warnings
from pybindgen.typehandlers.codesink import CodeSink
from pybindgen.typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
Parameter, ReturnValue
from pybindgen.version import __version__
from pybindgen import settings
and context (functions, classes, or occasionally code) from other files:
# Path: pybindgen/typehandlers/codesink.py
# class CodeSink(object):
# """Abstract base class for code sinks"""
# def __init__(self):
# r'''Constructor
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln("if (true) {")
# >>> sink.indent()
# >>> sink.writeln("bar();")
# >>> sink.unindent()
# >>> sink.writeln("zbr();")
# >>> print sink.flush().rstrip()
# foo();
# if (true) {
# bar();
# zbr();
#
# >>> sink = MemoryCodeSink()
# >>> sink.writeln("foo();")
# >>> sink.writeln()
# >>> sink.writeln("bar();")
# >>> print len(sink.flush().split("\n"))
# 4
# '''
# self.indent_level = 0 # current indent level
# self.indent_stack = [] # previous indent levels
# if DEBUG:
# self._last_unindent_stack = None # for debugging
#
# def _format_code(self, code):
# """Utility method for subclasses to use for formatting code
# (splits lines and indents them)"""
# assert isinstance(code, string_types)
# l = []
# for line in code.split('\n'):
# l.append(' '*self.indent_level + line)
# return l
#
# def writeln(self, line=''):
# """Write one or more lines of code"""
# raise NotImplementedError
#
# def indent(self, level=4):
# '''Add a certain ammount of indentation to all lines written
# from now on and until unindent() is called'''
# self.indent_stack.append(self.indent_level)
# self.indent_level += level
#
# def unindent(self):
# '''Revert indentation level to the value before last indent() call'''
# if DEBUG:
# try:
# self.indent_level = self.indent_stack.pop()
# except IndexError:
# if self._last_unindent_stack is not None:
# for line in traceback.format_list(self._last_unindent_stack):
# sys.stderr.write(line)
# raise
# self._last_unindent_stack = traceback.extract_stack()
# else:
# self.indent_level = self.indent_stack.pop()
#
# Path: pybindgen/typehandlers/base.py
# class TypeLookupError(CodegenErrorBase):
# """Exception that is raised when lookup of a type handler fails"""
#
# class TypeConfigurationError(CodegenErrorBase):
# """Exception that is raised when a type handler does not find some
# information it needs, such as owernship transfer semantics."""
#
# class CodeGenerationError(CodegenErrorBase):
# """Exception that is raised when wrapper generation fails for some reason."""
#
# class NotSupportedError(CodegenErrorBase):
# """Exception that is raised when declaring an interface configuration
# that is not supported or not implemented."""
#
# class Parameter(_Parameter):
# __metaclass__ = ParameterMeta
#
# class ReturnValue(_ReturnValue):
# __metaclass__ = ReturnValueMeta
#
# Path: pybindgen/settings.py
# def _get_deprecated_virtuals():
# def handle_error(self, wrapper, exception, traceback_):
# class ErrorHandler(object):
. Output only the next line. | min_python_version = settings.min_python_version |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
"""
<|code_end|>
, determine the next line of code. You have imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
from ma.xml_loader.builtins_loader import BuiltinLoader
and context (class names, function names, or code) available:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/builtins_loader.py
# class BuiltinLoader(object):
# """ Class to load builtins from xml file """
#
# def __init__(self):
# self.builtins = []
# self.__load_builtins(BUILTINS_FILE)
# self._builtins_names = []
# self.__load_builtins_names()
# self._builtins_headers = []
# self.__load_builtins_headers()
#
# @property
# def builtins_names(self):
# """ Builtins names (functions and data types) """
# return self._builtins_names
#
# @property
# def builtins_headers(self):
# """ Builtins headers """
# return self._builtins_headers
#
# def is_builtin(self, name):
# """ Check if the given name is a builtin """
# if name in self.builtins:
# return True
#
# def __load_builtins_names(self):
# """ Load builtins name (do not include headers) """
# for builtin in self.builtins:
# if isinstance(builtin, Type) or isinstance(builtin, Function):
# self._builtins_names.append(builtin.name)
#
# def __load_builtins_headers(self):
# """ Load builtins headers """
# for builtin in self.builtins:
# if isinstance(builtin, Include):
# self._builtins_headers.append(builtin.name)
#
# def __load_builtins(self, file_name):
# """ Load all builtins elements """
# tree = elemTree.parse(file_name)
# root = tree.getroot()
# self.__load_includes(root)
# self.__load_types(root)
# self.__load_functions(root)
#
# def __load_includes(self, root):
# """ Load includes elements """
# for incl in root.iter('include'):
# name = incl.attrib['name']
# replacer = incl.text
# include = Include(name, replacer)
# self.builtins.append(include)
#
# def __load_types(self, root):
# """ Load types elements """
# for dtype in root.iter('type'):
# name = dtype.attrib['name']
# replacer = dtype.text
# data_type = Type(name, replacer)
# self.builtins.append(data_type)
#
# def __load_functions(self, root):
# """ Load functions elements """
# for func in root.iter('function'):
# name = func.attrib['name']
# try:
# finput = func.find(".//in").text
# except AttributeError:
# finput = ""
# try:
# foutput = func.find(".//out").text
# except AttributeError:
# foutput = ""
#
# code_list = []
# for cfunc in func.iter('code'):
# endian = cfunc.attrib['endian']
# nlines = cfunc.attrib['nlines']
# replacer = cfunc.text
# code = Function.Code(endian, nlines, replacer)
# code_list.append(code)
# function = Function(name, finput, foutput, code_list)
# self.builtins.append(function)
. Output only the next line. | class BuiltinChecker(Checker): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
"""
class BuiltinChecker(Checker):
""" Checker for x86-specific built-ins """
def __init__(self):
self.problem_type = "x86-specific compiler built-in"
self.problem_msg = "x86 built-ins not supported in Power"
<|code_end|>
. Write the next line using the current file imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
from ma.xml_loader.builtins_loader import BuiltinLoader
and context from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/builtins_loader.py
# class BuiltinLoader(object):
# """ Class to load builtins from xml file """
#
# def __init__(self):
# self.builtins = []
# self.__load_builtins(BUILTINS_FILE)
# self._builtins_names = []
# self.__load_builtins_names()
# self._builtins_headers = []
# self.__load_builtins_headers()
#
# @property
# def builtins_names(self):
# """ Builtins names (functions and data types) """
# return self._builtins_names
#
# @property
# def builtins_headers(self):
# """ Builtins headers """
# return self._builtins_headers
#
# def is_builtin(self, name):
# """ Check if the given name is a builtin """
# if name in self.builtins:
# return True
#
# def __load_builtins_names(self):
# """ Load builtins name (do not include headers) """
# for builtin in self.builtins:
# if isinstance(builtin, Type) or isinstance(builtin, Function):
# self._builtins_names.append(builtin.name)
#
# def __load_builtins_headers(self):
# """ Load builtins headers """
# for builtin in self.builtins:
# if isinstance(builtin, Include):
# self._builtins_headers.append(builtin.name)
#
# def __load_builtins(self, file_name):
# """ Load all builtins elements """
# tree = elemTree.parse(file_name)
# root = tree.getroot()
# self.__load_includes(root)
# self.__load_types(root)
# self.__load_functions(root)
#
# def __load_includes(self, root):
# """ Load includes elements """
# for incl in root.iter('include'):
# name = incl.attrib['name']
# replacer = incl.text
# include = Include(name, replacer)
# self.builtins.append(include)
#
# def __load_types(self, root):
# """ Load types elements """
# for dtype in root.iter('type'):
# name = dtype.attrib['name']
# replacer = dtype.text
# data_type = Type(name, replacer)
# self.builtins.append(data_type)
#
# def __load_functions(self, root):
# """ Load functions elements """
# for func in root.iter('function'):
# name = func.attrib['name']
# try:
# finput = func.find(".//in").text
# except AttributeError:
# finput = ""
# try:
# foutput = func.find(".//out").text
# except AttributeError:
# foutput = ""
#
# code_list = []
# for cfunc in func.iter('code'):
# endian = cfunc.attrib['endian']
# nlines = cfunc.attrib['nlines']
# replacer = cfunc.text
# code = Function.Code(endian, nlines, replacer)
# code_list.append(code)
# function = Function(name, finput, foutput, code_list)
# self.builtins.append(function)
, which may include functions, classes, or code. Output only the next line. | self.loader = BuiltinLoader() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
class CheckersBase(object):
""" Base class to use checkers test """
def __init__(self):
<|code_end|>
, determine the next line of code. You have imports:
from ma.problem_reporter import ProblemReporter
from ma import controller
and context (class names, function names, or code) available:
# Path: ma/problem_reporter.py
# class ProblemReporter(object):
# """ Class to handle with reported problems """
# problems = {}
#
# @classmethod
# def report_include(cls, name, file_name, line, problem_type, problem_msg,
# solution):
# """ Report a problem in an include directive """
# if not cls.__should_report(file_name, line, file_name):
# return
# name = "include " + name
# problem = Problem(name, file_name, line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_node(cls, node, current_file, problem_type, problem_msg,
# solution):
# """ Report a problem in a node """
# node_loc = node.location
# node_file = node_loc.file
# node_line = node_loc.line
# if not cls.__should_report(node_file, node_line, current_file):
# return
#
# name = core.get_raw_node(node)
# problem = Problem(name, node_file, node_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_file(cls, file_name, num_line, name, problem_type, problem_msg,
# solution):
# """ Report a problem in a file """
# if not cls.__should_report(file_name, num_line, file_name):
# return
# problem = Problem(name, file_name, num_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def __report_problem(cls, problem, problem_type):
# """ Add the reported problem in a dictionary """
# if cls.problems.get(problem_type, None) is not None:
# cls.problems.get(problem_type).append(problem)
# else:
# problem_list = []
# problem_list.append(problem)
# cls.problems[problem_type] = problem_list
#
# @classmethod
# def print_problems(cls):
# """ Print all reported problems """
# if not cls.problems:
# print("\nNo migration reports found.")
# return
#
# tab = " "
# cls.__print_logo()
# for problem_type, problems in cls.problems.items():
# problems_dict = {}
# # Group problems by file
# for problem in problems:
# name = problem.file_name
# problems_dict[name] = problems_dict.get(name, []) + [problem]
#
# print("Problem type: " + problem_type)
# print("Problem description: " + problems[0].problem_msg)
# for file_name, problems in problems_dict.items():
# print(tab + "File: " + file_name)
# for problem in problems:
# print((tab * 2) + "Line: " + str(problem.line))
# print((tab * 2) + "Problem: " + str(problem.name))
# if problem.solution:
# print((tab * 2) + "Solution: " + problem.solution)
# print("")
# print("")
#
# @classmethod
# def get_problems(cls):
# """ Get all reported problems """
# return cls.problems
#
# @classmethod
# def clear_problems(cls):
# """ Clear reported problems """
# cls.problems.clear()
#
# @classmethod
# def __should_report(cls, node_file, node_line, current_file):
# """ Check if should report the node """
# # Location is not known
# if not node_file:
# return False
# # Node is not in the current file
# if str(node_file) != current_file:
# return False
# # Node is inside a blocked line
# if node_line in ReportBlocker.blocked_lines:
# return False
# return True
#
# @classmethod
# def __print_logo(cls):
# """ Print the report logo """
# title = "Migration Report"
# border = "=" * len(title)
# print("")
# print(border)
# print(title)
# print(border)
#
# Path: ma/controller.py
# def run(argv):
# def _include_paths():
# def _run_checker(checker, argv):
# def _load_checkers(checkers):
# def __current_wip(checker, files):
. Output only the next line. | self.reporter = ProblemReporter() |
Given the code snippet: <|code_start|>
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
class CheckersBase(object):
""" Base class to use checkers test """
def __init__(self):
self.reporter = ProblemReporter()
def run(self, checker, path):
""" Run MA checker. The checker is the one that will be activated
and the path is the folder with the files used in the test """
self.reporter.clear_problems()
<|code_end|>
, generate the next line using the imports in this file:
from ma.problem_reporter import ProblemReporter
from ma import controller
and context (functions, classes, or occasionally code) from other files:
# Path: ma/problem_reporter.py
# class ProblemReporter(object):
# """ Class to handle with reported problems """
# problems = {}
#
# @classmethod
# def report_include(cls, name, file_name, line, problem_type, problem_msg,
# solution):
# """ Report a problem in an include directive """
# if not cls.__should_report(file_name, line, file_name):
# return
# name = "include " + name
# problem = Problem(name, file_name, line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_node(cls, node, current_file, problem_type, problem_msg,
# solution):
# """ Report a problem in a node """
# node_loc = node.location
# node_file = node_loc.file
# node_line = node_loc.line
# if not cls.__should_report(node_file, node_line, current_file):
# return
#
# name = core.get_raw_node(node)
# problem = Problem(name, node_file, node_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_file(cls, file_name, num_line, name, problem_type, problem_msg,
# solution):
# """ Report a problem in a file """
# if not cls.__should_report(file_name, num_line, file_name):
# return
# problem = Problem(name, file_name, num_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def __report_problem(cls, problem, problem_type):
# """ Add the reported problem in a dictionary """
# if cls.problems.get(problem_type, None) is not None:
# cls.problems.get(problem_type).append(problem)
# else:
# problem_list = []
# problem_list.append(problem)
# cls.problems[problem_type] = problem_list
#
# @classmethod
# def print_problems(cls):
# """ Print all reported problems """
# if not cls.problems:
# print("\nNo migration reports found.")
# return
#
# tab = " "
# cls.__print_logo()
# for problem_type, problems in cls.problems.items():
# problems_dict = {}
# # Group problems by file
# for problem in problems:
# name = problem.file_name
# problems_dict[name] = problems_dict.get(name, []) + [problem]
#
# print("Problem type: " + problem_type)
# print("Problem description: " + problems[0].problem_msg)
# for file_name, problems in problems_dict.items():
# print(tab + "File: " + file_name)
# for problem in problems:
# print((tab * 2) + "Line: " + str(problem.line))
# print((tab * 2) + "Problem: " + str(problem.name))
# if problem.solution:
# print((tab * 2) + "Solution: " + problem.solution)
# print("")
# print("")
#
# @classmethod
# def get_problems(cls):
# """ Get all reported problems """
# return cls.problems
#
# @classmethod
# def clear_problems(cls):
# """ Clear reported problems """
# cls.problems.clear()
#
# @classmethod
# def __should_report(cls, node_file, node_line, current_file):
# """ Check if should report the node """
# # Location is not known
# if not node_file:
# return False
# # Node is not in the current file
# if str(node_file) != current_file:
# return False
# # Node is inside a blocked line
# if node_line in ReportBlocker.blocked_lines:
# return False
# return True
#
# @classmethod
# def __print_logo(cls):
# """ Print the report logo """
# title = "Migration Report"
# border = "=" * len(title)
# print("")
# print(border)
# print(title)
# print(border)
#
# Path: ma/controller.py
# def run(argv):
# def _include_paths():
# def _run_checker(checker, argv):
# def _load_checkers(checkers):
# def __current_wip(checker, files):
. Output only the next line. | controller._run_checker(checker, False, path) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
, determine the next line of code. You have imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
and context (class names, function names, or code) available:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class ApiMpiChecker(Checker): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
and context (classes, functions, sometimes code) from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class ApiDfpChecker(Checker): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
. Write the next line using the current file imports:
import re
from ma.checkers.checker import Checker
from ma import core
and context from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/core.py
# X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486",
# "[iI]686"]
# PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"]
# def get_supported_checkers():
# def get_supported_extensions():
# def execute(command):
# def execute_stdout(command):
# def cmdexists(command):
# def get_timestamp():
# def get_files(location, hint=''):
# def get_file_content(file_name, offset, length):
# def get_raw_node(node):
# def get_includes(file_path):
# def get_ifdefs(file_path):
# def get_ifdef_regex(arch, separator):
, which may include functions, classes, or code. Output only the next line. | class PerformanceDegradationChecker(Checker): |
Predict the next line after this snippet: <|code_start|>
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
class PerformanceDegradationChecker(Checker):
""" This checker finds preprocessor ifs with architecture
optimizations and without an optimization for Linux on Power"""
def __init__(self):
super(PerformanceDegradationChecker, self).__init__()
self.problem_type = "Performance degradation"
self.problem_msg = "This preprocessor can contain code without Power optimization"
<|code_end|>
using the current file's imports:
import re
from ma.checkers.checker import Checker
from ma import core
and any relevant context from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/core.py
# X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486",
# "[iI]686"]
# PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"]
# def get_supported_checkers():
# def get_supported_extensions():
# def execute(command):
# def execute_stdout(command):
# def cmdexists(command):
# def get_timestamp():
# def get_files(location, hint=''):
# def get_file_content(file_name, offset, length):
# def get_raw_node(node):
# def get_includes(file_path):
# def get_ifdefs(file_path):
# def get_ifdef_regex(arch, separator):
. Output only the next line. | self.hint = core.get_ifdef_regex("x86", "\\|") |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
"""
<|code_end|>
, determine the next line of code. You have imports:
from clang.cindex import CursorKind
from ma.checkers.checker import Checker
from ma.xml_loader.htm_loader import HtmLoader
and context (class names, function names, or code) available:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/htm_loader.py
# class HtmLoader(object):
# """ Load htm.xml information into a Python element"""
#
# def __init__(self):
# self.htms = []
# self.htms_include = []
# self.__load_xml(HTM_FILE)
#
# def __load_xml(self, file_name):
# """Load the contents of htm.xml into a Python element"""
# tree = elemTree.parse(file_name)
# self.root = tree.getroot()
# for htm in self.root.iter('function'):
# self.htms.append(htm.attrib)
# for htm_header in self.root.iter('header'):
# self.htms_include.append(htm_header.attrib)
#
# def get_functions(self):
# """Populate a list of HTM names"""
# for htm in self.root.findall('htmapi'):
# if htm.get("type") == "function":
# self.htms.append(htm.get('target'))
# return self.htms
#
# def get_includes(self):
# """Populate a list of HTM includes in the header"""
# for htm in self.root.findall('htmapi'):
# if htm.get('type') == 'header':
# self.htms_include.append(htm.get('target'))
# return self.htms_include
#
# def get_fixes(self):
# '''Method to populate a list of htm fixes'''
# suggestion_dict = {}
# for sysc in self.root.findall('htmapi'):
# if sysc.get("replacer"):
# suggestion_dict[sysc.get("target")] = (sysc.get("replacer"))
# return suggestion_dict
. Output only the next line. | class HtmChecker(Checker): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
"""
class HtmChecker(Checker):
""" Checker for HTM calls. """
def __init__(self):
self.problem_type = "Hardware Transactional Memory (HTM)"
self.problem_msg = "x86 specific HTM calls are not supported in Power Systems"
<|code_end|>
. Use current file imports:
from clang.cindex import CursorKind
from ma.checkers.checker import Checker
from ma.xml_loader.htm_loader import HtmLoader
and context (classes, functions, or code) from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/htm_loader.py
# class HtmLoader(object):
# """ Load htm.xml information into a Python element"""
#
# def __init__(self):
# self.htms = []
# self.htms_include = []
# self.__load_xml(HTM_FILE)
#
# def __load_xml(self, file_name):
# """Load the contents of htm.xml into a Python element"""
# tree = elemTree.parse(file_name)
# self.root = tree.getroot()
# for htm in self.root.iter('function'):
# self.htms.append(htm.attrib)
# for htm_header in self.root.iter('header'):
# self.htms_include.append(htm_header.attrib)
#
# def get_functions(self):
# """Populate a list of HTM names"""
# for htm in self.root.findall('htmapi'):
# if htm.get("type") == "function":
# self.htms.append(htm.get('target'))
# return self.htms
#
# def get_includes(self):
# """Populate a list of HTM includes in the header"""
# for htm in self.root.findall('htmapi'):
# if htm.get('type') == 'header':
# self.htms_include.append(htm.get('target'))
# return self.htms_include
#
# def get_fixes(self):
# '''Method to populate a list of htm fixes'''
# suggestion_dict = {}
# for sysc in self.root.findall('htmapi'):
# if sysc.get("replacer"):
# suggestion_dict[sysc.get("target")] = (sysc.get("replacer"))
# return suggestion_dict
. Output only the next line. | self.htm_functions = HtmLoader().get_functions() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
, predict the next line using imports from the current file:
from clang.cindex import CursorKind
from ma.checkers.checker import Checker
and context including class names, function names, and sometimes code from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class AsmChecker(Checker): |
Given the following code snippet before the placeholder: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
class QuickfixLoaderTest(unittest.TestCase):
""" Test cases for the quickfix loader"""
@unittest.skip
def get_include_test(self):
"""This test aim to check correct include value return from
get_include() method in QuickfixLoader class"""
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from ma.xml_loader.quickfix_loader import QuickfixLoader
and context including class names, function names, and sometimes code from other files:
# Path: ma/xml_loader/quickfix_loader.py
# class QuickfixLoader(object):
# """Class to load Quickfix Loader for MA.
# This class get information stored in XML file
# into a python module"""
# def __init__(self):
# self.items = {}
# self.load_xml(QUICKFIX_XML)
#
# def load_xml(self, file_name):
# '''Method to load Quickfixes strings.
# This method open XML file and load info inside a
# dictionary data structure'''
#
# tree = elemTree.parse(file_name)
# root = tree.getroot()
# orig_item = None
#
# for item in root.iter():
# if item.tag == 'item':
# orig_item = item.attrib
#
# if item.tag == 'replacer':
# replacer = item.attrib
# self.items[orig_item['target']] = [orig_item, replacer]
#
# def get_include(self, target):
# '''Method to get include value for selected target'''
# replacer = self.items[target][1]
# return replacer['include']
#
# def get_type(self, target):
# '''Method to get type value for selected target'''
# replacer = self.items[target][1]
# return replacer['type']
#
# def get_value(self, target):
# '''Method to get type value for selected target'''
# replacer = self.items[target][1]
# return replacer['value']
#
# def get_define(self, target):
# '''Method to get define value for selected target'''
# replacer = self.items[target][1]
# return replacer['define']
. Output only the next line. | quickfix_loader = QuickfixLoader() |
Predict the next line after this snippet: <|code_start|>
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
LINE_DELIMITER = "$"
def _get_lines(names, file_name):
""" Get all lines that contain names and return it as a list """
grep_delimiter = "\\|"
command = "grep -n '"
for name in names:
command += name + grep_delimiter
command = command[:-len(grep_delimiter)]
command += "' " + file_name + " | cut -f1 -d:"
<|code_end|>
using the current file's imports:
import re
from ma import core
and any relevant context from other files:
# Path: ma/core.py
# X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486",
# "[iI]686"]
# PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"]
# def get_supported_checkers():
# def get_supported_extensions():
# def execute(command):
# def execute_stdout(command):
# def cmdexists(command):
# def get_timestamp():
# def get_files(location, hint=''):
# def get_file_content(file_name, offset, length):
# def get_raw_node(node):
# def get_includes(file_path):
# def get_ifdefs(file_path):
# def get_ifdef_regex(arch, separator):
. Output only the next line. | lines = core.execute_stdout(command)[1] |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
, determine the next line of code. You have imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
and context (class names, function names, or code) available:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class ApiMklChecker(Checker): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
* Roberto Oliveira <rdutra@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
, predict the next line using imports from the current file:
from clang.cindex import CursorKind
from clang.cindex import TypeKind
from ma.checkers.checker import Checker
and context including class names, function names, and sometimes code from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class LongDoubleChecker(Checker): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
"""
<|code_end|>
. Use current file imports:
import ma.checkers.checker_file_utils as utils
from ma.checkers.checker import Checker
and context (classes, functions, or code) from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class ApiIppChecker(Checker): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
class Statistics(object):
""" Class to deal with statistics """
def __init__(self, kind):
self.kind = kind
<|code_end|>
. Use current file imports:
(from terminaltables import AsciiTable
from .problem_reporter import ProblemReporter)
and context including class names, function names, or small code snippets from other files:
# Path: ma/problem_reporter.py
# class ProblemReporter(object):
# """ Class to handle with reported problems """
# problems = {}
#
# @classmethod
# def report_include(cls, name, file_name, line, problem_type, problem_msg,
# solution):
# """ Report a problem in an include directive """
# if not cls.__should_report(file_name, line, file_name):
# return
# name = "include " + name
# problem = Problem(name, file_name, line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_node(cls, node, current_file, problem_type, problem_msg,
# solution):
# """ Report a problem in a node """
# node_loc = node.location
# node_file = node_loc.file
# node_line = node_loc.line
# if not cls.__should_report(node_file, node_line, current_file):
# return
#
# name = core.get_raw_node(node)
# problem = Problem(name, node_file, node_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def report_file(cls, file_name, num_line, name, problem_type, problem_msg,
# solution):
# """ Report a problem in a file """
# if not cls.__should_report(file_name, num_line, file_name):
# return
# problem = Problem(name, file_name, num_line, problem_msg, solution)
# cls.__report_problem(problem, problem_type)
#
# @classmethod
# def __report_problem(cls, problem, problem_type):
# """ Add the reported problem in a dictionary """
# if cls.problems.get(problem_type, None) is not None:
# cls.problems.get(problem_type).append(problem)
# else:
# problem_list = []
# problem_list.append(problem)
# cls.problems[problem_type] = problem_list
#
# @classmethod
# def print_problems(cls):
# """ Print all reported problems """
# if not cls.problems:
# print("\nNo migration reports found.")
# return
#
# tab = " "
# cls.__print_logo()
# for problem_type, problems in cls.problems.items():
# problems_dict = {}
# # Group problems by file
# for problem in problems:
# name = problem.file_name
# problems_dict[name] = problems_dict.get(name, []) + [problem]
#
# print("Problem type: " + problem_type)
# print("Problem description: " + problems[0].problem_msg)
# for file_name, problems in problems_dict.items():
# print(tab + "File: " + file_name)
# for problem in problems:
# print((tab * 2) + "Line: " + str(problem.line))
# print((tab * 2) + "Problem: " + str(problem.name))
# if problem.solution:
# print((tab * 2) + "Solution: " + problem.solution)
# print("")
# print("")
#
# @classmethod
# def get_problems(cls):
# """ Get all reported problems """
# return cls.problems
#
# @classmethod
# def clear_problems(cls):
# """ Clear reported problems """
# cls.problems.clear()
#
# @classmethod
# def __should_report(cls, node_file, node_line, current_file):
# """ Check if should report the node """
# # Location is not known
# if not node_file:
# return False
# # Node is not in the current file
# if str(node_file) != current_file:
# return False
# # Node is inside a blocked line
# if node_line in ReportBlocker.blocked_lines:
# return False
# return True
#
# @classmethod
# def __print_logo(cls):
# """ Print the report logo """
# title = "Migration Report"
# border = "=" * len(title)
# print("")
# print(border)
# print(title)
# print(border)
. Output only the next line. | self.problems = ProblemReporter.get_problems() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
* Roberto Oliveira <rdutra@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
<|code_end|>
, generate the next line using the imports in this file:
from clang.cindex import CursorKind
from ma.checkers.checker import Checker
from ma.xml_loader.syscalls_loader import SyscallsLoader
and context (functions, classes, or occasionally code) from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/syscalls_loader.py
# class SyscallsLoader(object):
# ''' Load syscalls into a Python element '''
#
# def __init__(self):
# self.syscalls = []
# self.__load_xml(SYSCALLS_FILE)
#
# def __load_xml(self, file_name):
# '''Function to load the contents of syscalls.xml'''
# tree = elemTree.parse(file_name)
# self.root = tree.getroot()
# for sysc in self.root.iter('syscall'):
# self.syscalls.append(sysc.attrib)
#
# def get_names(self):
# '''Method to populate a list of syscall names '''
# for sysc in self.root.findall('syscall'):
# self.syscalls.append(sysc.get("target"))
# return self.syscalls
#
# def get_fixes(self):
# '''Method to populate a list of syscall fixes'''
# suggestion_dict = {}
# for sysc in self.root.findall('syscall'):
# if sysc.get("replacer"):
# suggestion_dict[sysc.get("target")] = (sysc.get("replacer"),
# sysc.get("includes"))
# return suggestion_dict
. Output only the next line. | class SyscallChecker(Checker): |
Based on the snippet: <|code_start|>Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Daniel Kreling <dbkreling@br.ibm.com>
* Roberto Oliveira <rdutra@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
class SyscallChecker(Checker):
""" Checker for syscall declarations """
def __init__(self):
self.problem_type = "Syscall usage"
self.problem_msg = "Syscall not available in Power architecture."
self.hint = 'ch[s/g/l/f/v/o/m/]\|SYS_\|' + 'statat'
<|code_end|>
, predict the immediate next line with the help of imports:
from clang.cindex import CursorKind
from ma.checkers.checker import Checker
from ma.xml_loader.syscalls_loader import SyscallsLoader
and context (classes, functions, sometimes code) from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/xml_loader/syscalls_loader.py
# class SyscallsLoader(object):
# ''' Load syscalls into a Python element '''
#
# def __init__(self):
# self.syscalls = []
# self.__load_xml(SYSCALLS_FILE)
#
# def __load_xml(self, file_name):
# '''Function to load the contents of syscalls.xml'''
# tree = elemTree.parse(file_name)
# self.root = tree.getroot()
# for sysc in self.root.iter('syscall'):
# self.syscalls.append(sysc.attrib)
#
# def get_names(self):
# '''Method to populate a list of syscall names '''
# for sysc in self.root.findall('syscall'):
# self.syscalls.append(sysc.get("target"))
# return self.syscalls
#
# def get_fixes(self):
# '''Method to populate a list of syscall fixes'''
# suggestion_dict = {}
# for sysc in self.root.findall('syscall'):
# if sysc.get("replacer"):
# suggestion_dict[sysc.get("target")] = (sysc.get("replacer"),
# sysc.get("includes"))
# return suggestion_dict
. Output only the next line. | self.syscalls_names = SyscallsLoader().get_names() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Roberto Oliveira <rdutra@br.ibm.com>
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
<|code_end|>
. Write the next line using the current file imports:
import re
import os
from clang.cindex import CursorKind
from clang.cindex import TypeKind
from ma.checkers.checker import Checker
from ma import core
and context from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/core.py
# X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486",
# "[iI]686"]
# PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"]
# def get_supported_checkers():
# def get_supported_extensions():
# def execute(command):
# def execute_stdout(command):
# def cmdexists(command):
# def get_timestamp():
# def get_files(location, hint=''):
# def get_file_content(file_name, offset, length):
# def get_raw_node(node):
# def get_includes(file_path):
# def get_ifdefs(file_path):
# def get_ifdef_regex(arch, separator):
, which may include functions, classes, or code. Output only the next line. | class CharChecker(Checker): |
Here is a snippet: <|code_start|>
def get_pattern_hint(self):
return self.hint
def get_problem_msg(self):
return self.problem_msg
def get_problem_type(self):
return self.problem_type
def check_node(self, node):
kind = node.kind
if kind != CursorKind.BINARY_OPERATOR and kind != CursorKind.VAR_DECL:
return False
if self._is_dangerous_type(node) and self._has_children(node):
last_children_node = list(node.get_children())[-1]
return self._is_dangerous_assignment(last_children_node)
def get_solution(self, node):
kind = node.kind
type_kind = node.type.kind
info = ""
if kind == CursorKind.BINARY_OPERATOR or type_kind == TypeKind.TYPEDEF:
node = self._get_var_declaration(node, node)
location = node.location
line = location.line
file_name = os.path.basename(str(location.file))
info = " (file: {0} | line: {1})".format(file_name, line)
<|code_end|>
. Write the next line using the current file imports:
import re
import os
from clang.cindex import CursorKind
from clang.cindex import TypeKind
from ma.checkers.checker import Checker
from ma import core
and context from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
#
# Path: ma/core.py
# X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486",
# "[iI]686"]
# PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"]
# def get_supported_checkers():
# def get_supported_extensions():
# def execute(command):
# def execute_stdout(command):
# def cmdexists(command):
# def get_timestamp():
# def get_files(location, hint=''):
# def get_file_content(file_name, offset, length):
# def get_raw_node(node):
# def get_includes(file_path):
# def get_ifdefs(file_path):
# def get_ifdef_regex(arch, separator):
, which may include functions, classes, or code. Output only the next line. | raw_node = core.get_raw_node(node) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Rafael Peria de Sene <rpsene@br.ibm.com>
"""
<|code_end|>
, predict the next line using imports from the current file:
from ma.checkers.checker import Checker
import ma.checkers.checker_file_utils as utils
and context including class names, function names, and sometimes code from other files:
# Path: ma/checkers/checker.py
# class Checker(object):
# """ Abstract class Checker """
# __metaclass__ = abc.ABCMeta
#
# def check_node(self, node):
# """ Check node from AST and return if it is a migration issue """
# return False
#
# def check_include(self, include_name):
# """ Check include from AST and return if it is a migration issue """
# return False
#
# def check_file(self, file_name):
# """ Check issues into file and return a list of lists, containing the
# problem name and line number """
# return []
#
# def get_solution(self, problem):
# """ Get solution for the problem using the node from AST or the raw
# node from file """
# return ""
#
# @abc.abstractmethod
# def get_pattern_hint(self):
# """Return the pattern that should be used to get the
# problematics files"""
# raise NotImplementedError('users must define __get_pattern_hint__ to\
# use this base class')
#
# @abc.abstractmethod
# def get_problem_msg(self):
# """Return the problem message of the checker"""
# raise NotImplementedError('users must define __get_problem_msg__ to \
# use this base class')
#
# @abc.abstractmethod
# def get_problem_type(self):
# """Return the problem type of the checker"""
# raise NotImplementedError('users must define __get_problem_type__ to \
# use this base class')
. Output only the next line. | class PthreadChecker(Checker): |
Predict the next line for this snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
class AssemblyReplacerTest(unittest.TestCase):
""" Test cases for the Assembly replacer """
def get_replace_test(self):
'''This test aim to check correct replace value return from
get_replace() method in AssemblyReplacer class'''
<|code_end|>
with the help of current file imports:
import unittest
from ma.xml_loader.asm_to_ppc import AssemblyReplacer
and context from other files:
# Path: ma/xml_loader/asm_to_ppc.py
# class AssemblyReplacer(object):
# """Class to assembly replacer for MA.
# This class get information stored in XML file
# into a python module"""
# def __init__(self):
# self.replacer = {}
# self.load_xml(LOCAL_XML_ASM)
#
# def load_xml(self, file_name):
# '''Method to load ASM replace strings.
# This method open XML file and load info inside a
# dictionary data structure'''
# tree = elemTree.parse(file_name)
# root = tree.getroot()
# for asm in root.iter('asm'):
# self.replacer[asm.attrib['target']] = [asm.attrib['type'],
# asm.attrib['replacer']]
#
# def get_replace(self, target):
# '''Method to get the replace for selected target'''
# return self.replacer[target][1]
#
# def get_type(self, target):
# '''Method to get the type for selected target'''
# return self.replacer[target][0]
, which may contain function names, class names, or code. Output only the next line. | asm_replacer = AssemblyReplacer() |
Here is a snippet: <|code_start|>
class ISupport(object):
def __init__(self):
self.serverName = None
self.serverVersion = None
self.network = None
self.rawTokens = {}
self.userModes = "iosw"
self.chanModes = {
<|code_end|>
. Write the next line using the current file imports:
from desertbot.ircbase import ModeType
and context from other files:
# Path: desertbot/ircbase.py
# class ModeType(Enum):
# LIST = 0,
# PARAM_SET = 1,
# PARAM_SET_UNSET = 2,
# NO_PARAM = 3
, which may include functions, classes, or code. Output only the next line. | "b": ModeType.LIST, |
Given the following code snippet before the placeholder: <|code_start|> supportedStatuses = self.bot.supportHelper.statusModes
modesAdded = []
paramsAdded = []
modesRemoved = []
paramsRemoved = []
for mode in modes:
if mode == "+":
adding = True
elif mode == "-":
adding = False
elif mode not in supportedChanModes and mode not in supportedStatuses:
self.logger.warning('Received unknown MODE char {} in MODE string {}'.format(mode, modes))
# We received a mode char that's unknown to use, so we abort parsing to prevent desync.
return None
elif mode in supportedStatuses:
if len(params) < 1:
self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
return {}
user = params.pop(0)
if user not in self.users:
self.logger.warning("Received status MODE for unknown user {} in channel {}.".format(user, self.name))
else:
if adding:
self.ranks[user] += mode
modesAdded.append(mode)
paramsAdded.append(user)
elif not adding and mode in self.ranks[user]:
self.ranks[user] = self.ranks[user].replace(mode, "")
modesRemoved.append(mode)
paramsRemoved.append(user)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from typing import Dict, List, Optional, TYPE_CHECKING
from desertbot.ircbase import ModeType
from desertbot.desertbot import DesertBot
from desertbot.user import IRCUser
and context including class names, function names, and sometimes code from other files:
# Path: desertbot/ircbase.py
# class ModeType(Enum):
# LIST = 0,
# PARAM_SET = 1,
# PARAM_SET_UNSET = 2,
# NO_PARAM = 3
. Output only the next line. | elif supportedChanModes[mode] == ModeType.LIST: |
Next line prediction: <|code_start|>
if TYPE_CHECKING:
class TargetTypes(Enum):
CHANNEL = 1
USER = 2
class IRCMessage(object):
<|code_end|>
. Use current file imports:
(import re
from enum import Enum
from typing import Dict, Optional, TYPE_CHECKING
from desertbot.channel import IRCChannel
from desertbot.user import IRCUser
from desertbot.desertbot import DesertBot)
and context including class names, function names, or small code snippets from other files:
# Path: desertbot/channel.py
# class IRCChannel(object):
# def __init__(self, name: str, bot: 'DesertBot'):
# self.logger = logging.getLogger('desertbot.core.{}'.format(name))
# self.name = name
# self.bot = bot
# self.modes = {}
# self.users = {}
# self.ranks = {}
# self.topic = None
# self.topicSetter = None
# self.topicTimestamp = 0
# self.creationTime = 0
# self.userlistComplete = True
#
# def setModes(self, modes: str, params: List) -> Optional[Dict]:
# adding = True
# supportedChanModes = self.bot.supportHelper.chanModes
# supportedStatuses = self.bot.supportHelper.statusModes
# modesAdded = []
# paramsAdded = []
# modesRemoved = []
# paramsRemoved = []
# for mode in modes:
# if mode == "+":
# adding = True
# elif mode == "-":
# adding = False
# elif mode not in supportedChanModes and mode not in supportedStatuses:
# self.logger.warning('Received unknown MODE char {} in MODE string {}'.format(mode, modes))
# # We received a mode char that's unknown to use, so we abort parsing to prevent desync.
# return None
# elif mode in supportedStatuses:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# user = params.pop(0)
# if user not in self.users:
# self.logger.warning("Received status MODE for unknown user {} in channel {}.".format(user, self.name))
# else:
# if adding:
# self.ranks[user] += mode
# modesAdded.append(mode)
# paramsAdded.append(user)
# elif not adding and mode in self.ranks[user]:
# self.ranks[user] = self.ranks[user].replace(mode, "")
# modesRemoved.append(mode)
# paramsRemoved.append(user)
# elif supportedChanModes[mode] == ModeType.LIST:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# if mode not in self.modes:
# self.modes[mode] = set()
# if adding:
# self.modes[mode].add(param)
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and param in self.modes[mode]:
# self.modes[mode].remove(param)
# modesRemoved.append(mode)
# paramsRemoved.append(param)
# elif supportedChanModes[mode] == ModeType.PARAM_SET:
# if adding:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# self.modes[mode] = param
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(None)
# elif supportedChanModes[mode] == ModeType.PARAM_SET_UNSET:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# if adding:
# self.modes[mode] = param
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(param)
# elif supportedChanModes[mode] == ModeType.NO_PARAM:
# if adding:
# self.modes[mode] = None
# modesAdded.append(mode)
# paramsAdded.append(None)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(None)
# return {
# "added": modesAdded,
# "removed": modesRemoved,
# "addedParams": paramsAdded,
# "removedParams": paramsRemoved
# }
#
# def getHighestStatusOfUser(self, user: 'IRCUser') -> str:
# if user.nick not in self.ranks:
# return ""
#
# for status in self.bot.supportHelper.statusOrder:
# if status in self.ranks[user.nick]:
# return self.bot.supportHelper.statusModes[status]
# return ""
#
# def userIsChanOp(self, user: 'IRCUser') -> bool:
# if user.nick not in self.ranks:
# return False
#
# for status in self.bot.supportHelper.statusModes:
# if status in self.ranks[user.nick]:
# return True
# if status == "o": # We consider anyone with +o or higher to be an op
# break
#
# return False
#
# def __str__(self):
# return self.name
#
# Path: desertbot/user.py
# class IRCUser(object):
# def __init__(self, nick: str, ident: Optional[str] = None, host: Optional[str] = None):
# self.nick = nick
# self.ident = ident
# self.host = host
# self.gecos = None
# self.server = None
# self.hops = 0
# self.isOper = False
# self.isAway = False
# self.awayMessage = None
# self.account = None
#
# def fullUserPrefix(self) -> str:
# return "{}!{}@{}".format(self.nick, self.ident, self.host)
. Output only the next line. | def __init__(self, msgType: str, user: IRCUser, channel: Optional[IRCChannel], message: str, bot: 'DesertBot', |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
class TargetTypes(Enum):
CHANNEL = 1
USER = 2
class IRCMessage(object):
<|code_end|>
with the help of current file imports:
import re
from enum import Enum
from typing import Dict, Optional, TYPE_CHECKING
from desertbot.channel import IRCChannel
from desertbot.user import IRCUser
from desertbot.desertbot import DesertBot
and context from other files:
# Path: desertbot/channel.py
# class IRCChannel(object):
# def __init__(self, name: str, bot: 'DesertBot'):
# self.logger = logging.getLogger('desertbot.core.{}'.format(name))
# self.name = name
# self.bot = bot
# self.modes = {}
# self.users = {}
# self.ranks = {}
# self.topic = None
# self.topicSetter = None
# self.topicTimestamp = 0
# self.creationTime = 0
# self.userlistComplete = True
#
# def setModes(self, modes: str, params: List) -> Optional[Dict]:
# adding = True
# supportedChanModes = self.bot.supportHelper.chanModes
# supportedStatuses = self.bot.supportHelper.statusModes
# modesAdded = []
# paramsAdded = []
# modesRemoved = []
# paramsRemoved = []
# for mode in modes:
# if mode == "+":
# adding = True
# elif mode == "-":
# adding = False
# elif mode not in supportedChanModes and mode not in supportedStatuses:
# self.logger.warning('Received unknown MODE char {} in MODE string {}'.format(mode, modes))
# # We received a mode char that's unknown to use, so we abort parsing to prevent desync.
# return None
# elif mode in supportedStatuses:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# user = params.pop(0)
# if user not in self.users:
# self.logger.warning("Received status MODE for unknown user {} in channel {}.".format(user, self.name))
# else:
# if adding:
# self.ranks[user] += mode
# modesAdded.append(mode)
# paramsAdded.append(user)
# elif not adding and mode in self.ranks[user]:
# self.ranks[user] = self.ranks[user].replace(mode, "")
# modesRemoved.append(mode)
# paramsRemoved.append(user)
# elif supportedChanModes[mode] == ModeType.LIST:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# if mode not in self.modes:
# self.modes[mode] = set()
# if adding:
# self.modes[mode].add(param)
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and param in self.modes[mode]:
# self.modes[mode].remove(param)
# modesRemoved.append(mode)
# paramsRemoved.append(param)
# elif supportedChanModes[mode] == ModeType.PARAM_SET:
# if adding:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# self.modes[mode] = param
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(None)
# elif supportedChanModes[mode] == ModeType.PARAM_SET_UNSET:
# if len(params) < 1:
# self.logger.warning('Received a broken MODE string for channel {}!'.format(self.name))
# return {}
# param = params.pop(0)
# if adding:
# self.modes[mode] = param
# modesAdded.append(mode)
# paramsAdded.append(param)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(param)
# elif supportedChanModes[mode] == ModeType.NO_PARAM:
# if adding:
# self.modes[mode] = None
# modesAdded.append(mode)
# paramsAdded.append(None)
# elif not adding and mode in self.modes:
# del self.modes[mode]
# modesRemoved.append(mode)
# paramsRemoved.append(None)
# return {
# "added": modesAdded,
# "removed": modesRemoved,
# "addedParams": paramsAdded,
# "removedParams": paramsRemoved
# }
#
# def getHighestStatusOfUser(self, user: 'IRCUser') -> str:
# if user.nick not in self.ranks:
# return ""
#
# for status in self.bot.supportHelper.statusOrder:
# if status in self.ranks[user.nick]:
# return self.bot.supportHelper.statusModes[status]
# return ""
#
# def userIsChanOp(self, user: 'IRCUser') -> bool:
# if user.nick not in self.ranks:
# return False
#
# for status in self.bot.supportHelper.statusModes:
# if status in self.ranks[user.nick]:
# return True
# if status == "o": # We consider anyone with +o or higher to be an op
# break
#
# return False
#
# def __str__(self):
# return self.name
#
# Path: desertbot/user.py
# class IRCUser(object):
# def __init__(self, nick: str, ident: Optional[str] = None, host: Optional[str] = None):
# self.nick = nick
# self.ident = ident
# self.host = host
# self.gecos = None
# self.server = None
# self.hops = 0
# self.isOper = False
# self.isAway = False
# self.awayMessage = None
# self.account = None
#
# def fullUserPrefix(self) -> str:
# return "{}!{}@{}".format(self.nick, self.ident, self.host)
, which may contain function names, class names, or code. Output only the next line. | def __init__(self, msgType: str, user: IRCUser, channel: Optional[IRCChannel], message: str, bot: 'DesertBot', |
Based on the snippet: <|code_start|>
def hookBot(self, bot: 'DesertBot') -> None:
self.bot = bot
def loadDataStore(self):
dataRootPath = os.path.join(self.bot.rootDir, 'data', 'servers', self.bot.server)
defaultRootPath = os.path.join(self.bot.rootDir, 'data', 'defaults')
self.storage = DataStore(storagePath=os.path.join(dataRootPath, f'{self.__class__.__name__}.json'),
defaultsPath=os.path.join(defaultRootPath, f'{self.__class__.__name__}.json'))
# ensure storage is periodically synced to disk - DataStore.__set__() does call DataStore.save(), but you never know
self.storageSync = LoopingCall(self.storage.save)
# since each module has its own LoopingCall,
# space them out over a second using random.random() to add 0-1 seconds to each module's storage save interval
self.storageSync.start(self.bot.config.getWithDefault('storage_save_interval', 60) + random.random(), now=False)
def saveDataStore(self):
self.storage.save()
def displayHelp(self, query: Union[List[str], None]) -> str:
if query is not None and query[0].lower() == self.__class__.__name__.lower():
return self.help(query)
def help(self, query: Union[List[str], None]) -> str:
return 'This module has no help text'
def onUnload(self) -> None:
self.storage.save()
<|code_end|>
, predict the immediate next line with the help of imports:
from twisted.internet.task import LoopingCall
from zope.interface import Interface
from functools import wraps
from fnmatch import fnmatch
from typing import Any, Callable, List, Tuple, Union, TYPE_CHECKING
from desertbot.message import IRCMessage
from desertbot.datastore import DataStore
from desertbot.desertbot import DesertBot
import os
import random
import logging
and context (classes, functions, sometimes code) from other files:
# Path: desertbot/message.py
# class IRCMessage(object):
# def __init__(self, msgType: str, user: IRCUser, channel: Optional[IRCChannel], message: str, bot: 'DesertBot',
# metadata: Dict=None, tags: Dict=None):
# if metadata is None:
# metadata = {}
# self.metadata = metadata
# if tags is None:
# tags = {}
# self.tags = tags
#
# if isinstance(message, bytes):
# unicodeMessage = message.decode('utf-8', 'ignore')
# else: # Already utf-8?
# unicodeMessage = message
# self.type = msgType
# self.messageList = unicodeMessage.strip().split(' ')
# self.messageString = unicodeMessage
# self.user = user
#
# self.channel = None
# if channel is None:
# self.replyTo = self.user.nick
# self.targetType = TargetTypes.USER
# else:
# self.channel = channel
# # I would like to set this to the channel object but I would probably break functionality if I did :I
# self.replyTo = channel.name
# self.targetType = TargetTypes.CHANNEL
#
# self.command = ''
# self.parameters = ''
# self.parameterList = []
#
# if len(self.messageList) == 1 and self.messageList[0] == bot.commandChar:
# self.command = ''
# elif self.messageList[0].startswith(bot.commandChar) and self.messageList[0][:3].count(bot.commandChar) == 1:
# self.command = self.messageList[0][len(bot.commandChar):]
# if self.command == '':
# self.command = self.messageList[1]
# self.parameters = u' '.join(self.messageList[2:])
# else:
# self.parameters = u' '.join(self.messageList[1:])
# elif re.match('{}[:,]?'.format(re.escape(bot.nick)), self.messageList[0], re.IGNORECASE):
# if len(self.messageList) > 1:
# self.command = self.messageList[1]
# self.parameters = u' '.join(self.messageList[2:])
# self.command = self.command.lower()
# if self.parameters.strip():
# self.parameterList = self.parameters.split(' ')
#
# self.parameterList = [param for param in self.parameterList if param != '']
#
# if len(self.parameterList) == 1 and not self.parameterList[0]:
# self.parameterList = []
#
# Path: desertbot/datastore.py
# class DataStore(object):
# def __init__(self, storagePath, defaultsPath):
# self.storagePath = storagePath
# self.defaultsPath = defaultsPath
# self.data = {}
# self.load()
#
# def load(self):
# # if a file data/defaults/<module>.json exists, it has priority on load
# if os.path.exists(self.defaultsPath):
# with open(self.defaultsPath) as storageFile:
# self.data = json.load(storageFile)
# # if not, use data/<network>/<module>.json instead
# elif os.path.exists(self.storagePath):
# with open(self.storagePath) as storageFile:
# self.data = json.load(storageFile)
# # if there's nothing, make sure the folder at least exists for the server-specific data files
# else:
# os.makedirs(os.path.dirname(self.storagePath), exist_ok=True)
#
# def save(self):
# # don't save empty files, to keep the data directories from filling up with pointless files
# if len(self.data) != 0:
# tmpFile = f"{self.storagePath}.tmp"
# with open(tmpFile, "w") as storageFile:
# storageFile.write(json.dumps(self.data, indent=4))
# os.rename(tmpFile, self.storagePath)
#
# def __len__(self):
# return len(self.data)
#
# def __iter__(self):
# return iter(self.data)
#
# def __getitem__(self, item):
# return self.data[item]
#
# def __setitem__(self, key, value):
# self.data[key] = value
# self.save()
#
# def __contains__(self, key):
# return key in self.data
#
# def __delitem__(self, key):
# del self.data[key]
#
# def items(self):
# return self.data.items()
#
# def values(self):
# return self.data.values()
#
# def keys(self):
# return self.data.keys()
#
# def get(self, key, defaultValue=None):
# return self.data.get(key, defaultValue)
#
# def pop(self, key):
# data = self.data.pop(key)
# self.save()
# return data
. Output only the next line. | def checkIgnoreList(self, message: IRCMessage) -> bool: |
Using the snippet: <|code_start|> return func(inst, message)
return wrapped
class BotModule(object):
def __init__(self):
self.logger = logging.getLogger('desertbot.{}'.format(self.__class__.__name__))
self.bot = None
self.storage = None
self.storageSync = None
self.loadingPriority = 1
"""
Increase this number in the module's class if the module should be loaded before other modules.
"""
def actions(self) -> List[Tuple[str, int, Callable]]:
return [('help', 1, self.displayHelp)]
def onLoad(self) -> None:
pass
def hookBot(self, bot: 'DesertBot') -> None:
self.bot = bot
def loadDataStore(self):
dataRootPath = os.path.join(self.bot.rootDir, 'data', 'servers', self.bot.server)
defaultRootPath = os.path.join(self.bot.rootDir, 'data', 'defaults')
<|code_end|>
, determine the next line of code. You have imports:
from twisted.internet.task import LoopingCall
from zope.interface import Interface
from functools import wraps
from fnmatch import fnmatch
from typing import Any, Callable, List, Tuple, Union, TYPE_CHECKING
from desertbot.message import IRCMessage
from desertbot.datastore import DataStore
from desertbot.desertbot import DesertBot
import os
import random
import logging
and context (class names, function names, or code) available:
# Path: desertbot/message.py
# class IRCMessage(object):
# def __init__(self, msgType: str, user: IRCUser, channel: Optional[IRCChannel], message: str, bot: 'DesertBot',
# metadata: Dict=None, tags: Dict=None):
# if metadata is None:
# metadata = {}
# self.metadata = metadata
# if tags is None:
# tags = {}
# self.tags = tags
#
# if isinstance(message, bytes):
# unicodeMessage = message.decode('utf-8', 'ignore')
# else: # Already utf-8?
# unicodeMessage = message
# self.type = msgType
# self.messageList = unicodeMessage.strip().split(' ')
# self.messageString = unicodeMessage
# self.user = user
#
# self.channel = None
# if channel is None:
# self.replyTo = self.user.nick
# self.targetType = TargetTypes.USER
# else:
# self.channel = channel
# # I would like to set this to the channel object but I would probably break functionality if I did :I
# self.replyTo = channel.name
# self.targetType = TargetTypes.CHANNEL
#
# self.command = ''
# self.parameters = ''
# self.parameterList = []
#
# if len(self.messageList) == 1 and self.messageList[0] == bot.commandChar:
# self.command = ''
# elif self.messageList[0].startswith(bot.commandChar) and self.messageList[0][:3].count(bot.commandChar) == 1:
# self.command = self.messageList[0][len(bot.commandChar):]
# if self.command == '':
# self.command = self.messageList[1]
# self.parameters = u' '.join(self.messageList[2:])
# else:
# self.parameters = u' '.join(self.messageList[1:])
# elif re.match('{}[:,]?'.format(re.escape(bot.nick)), self.messageList[0], re.IGNORECASE):
# if len(self.messageList) > 1:
# self.command = self.messageList[1]
# self.parameters = u' '.join(self.messageList[2:])
# self.command = self.command.lower()
# if self.parameters.strip():
# self.parameterList = self.parameters.split(' ')
#
# self.parameterList = [param for param in self.parameterList if param != '']
#
# if len(self.parameterList) == 1 and not self.parameterList[0]:
# self.parameterList = []
#
# Path: desertbot/datastore.py
# class DataStore(object):
# def __init__(self, storagePath, defaultsPath):
# self.storagePath = storagePath
# self.defaultsPath = defaultsPath
# self.data = {}
# self.load()
#
# def load(self):
# # if a file data/defaults/<module>.json exists, it has priority on load
# if os.path.exists(self.defaultsPath):
# with open(self.defaultsPath) as storageFile:
# self.data = json.load(storageFile)
# # if not, use data/<network>/<module>.json instead
# elif os.path.exists(self.storagePath):
# with open(self.storagePath) as storageFile:
# self.data = json.load(storageFile)
# # if there's nothing, make sure the folder at least exists for the server-specific data files
# else:
# os.makedirs(os.path.dirname(self.storagePath), exist_ok=True)
#
# def save(self):
# # don't save empty files, to keep the data directories from filling up with pointless files
# if len(self.data) != 0:
# tmpFile = f"{self.storagePath}.tmp"
# with open(tmpFile, "w") as storageFile:
# storageFile.write(json.dumps(self.data, indent=4))
# os.rename(tmpFile, self.storagePath)
#
# def __len__(self):
# return len(self.data)
#
# def __iter__(self):
# return iter(self.data)
#
# def __getitem__(self, item):
# return self.data[item]
#
# def __setitem__(self, key, value):
# self.data[key] = value
# self.save()
#
# def __contains__(self, key):
# return key in self.data
#
# def __delitem__(self, key):
# del self.data[key]
#
# def items(self):
# return self.data.items()
#
# def values(self):
# return self.data.values()
#
# def keys(self):
# return self.data.keys()
#
# def get(self, key, defaultValue=None):
# return self.data.get(key, defaultValue)
#
# def pop(self, key):
# data = self.data.pop(key)
# self.save()
# return data
. Output only the next line. | self.storage = DataStore(storagePath=os.path.join(dataRootPath, f'{self.__class__.__name__}.json'), |
Given snippet: <|code_start|> phase.
"""
def __init__(self,
direction=None,
observable=None,
interface=None,
symmetry='default',
mode='default',
MCnorm=True,
**kargs):
_dir = {'x': 0, 'y': 1, 'z': 2}
if direction is None:
try:
self._dir = interface.normal
except:
self._dir = 2
else:
self._dir = _dir[direction]
self.mode = mode
self.interface = interface
self._MCnorm = MCnorm
self.kargs = kargs
if symmetry == 'default' and interface is not None:
self.symmetry = self.interface.symmetry
else:
self.symmetry = symmetry
if observable is None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .basic_observables import Number
from .intrinsic_distance import IntrinsicDistance
from scipy import stats
from MDAnalysis.core.groups import Atom, AtomGroup, Residue, ResidueGroup
import numpy as np
and context:
# Path: pytim/observables/basic_observables.py
# class Number(Observable):
# """The number of atoms.
# """
#
# def __init__(self, *arg, **kwarg):
# Observable.__init__(self, None)
#
# def compute(self, inp, kargs=None):
# """Compute the observable.
#
# :param AtomGroup inp: the input atom group
# :returns: one, for each atom in the group
#
# """
# return np.ones(len(inp))
#
# Path: pytim/observables/intrinsic_distance.py
# class IntrinsicDistance(Observable):
# """Initialize the intrinsic distance calculation.
#
# :param PYTIM interface: compute the intrinsic distance with respect
# to this interface
# :param str symmetry: force calculation using this symmetry, if
# availabe (e.g. 'generic', 'planar', 'spherical')
# If 'default', uses the symmetry selected in
# the PYTIM interface instance.
#
# Example:
#
# >>> import MDAnalysis as mda
# >>> import pytim
# >>> import numpy as np
# >>> from pytim import observables
# >>> from pytim.datafiles import MICELLE_PDB
# >>> u = mda.Universe(MICELLE_PDB)
# >>> micelle = u.select_atoms('resname DPC')
# >>> waterox = u.select_atoms('type O and resname SOL')
# >>> inter = pytim.GITIM(u,group=micelle, molecular=False, alpha=2.0)
# >>> dist = observables.IntrinsicDistance(interface=inter)
# >>> d = dist.compute(waterox)
# >>> np.set_printoptions(precision=3,threshold=10)
# >>> print(d)
# [25.733 8.579 8.852 ... 18.566 13.709 9.876]
#
# >>> np.set_printoptions(precision=None,threshold=None)
# """
#
# def __init__(self, interface, symmetry='default', mode='default'):
# Observable.__init__(self, interface.universe)
# self.interface = interface
# self.mode = mode
# if symmetry == 'default':
# self.symmetry = self.interface.symmetry
# else:
# self.symmetry = symmetry
#
# def compute(self, inp, kargs=None):
# """Compute the intrinsic distance of a set of points from the first
# layers.
#
# :param ndarray positions: compute the intrinsic distance for this set
# of points
# """
# # see pytim/surface.py
# return self.interface._surfaces[0].distance(inp, self.symmetry, mode=self.mode)
which might include code, classes, or functions. Output only the next line. | self.observable = Number() |
Given the following code snippet before the placeholder: <|code_start|> if self._dir is not None:
r = np.array([0., box[self._dir]])
if self.interface is not None:
r -= r[1] / 2.
self._range = r
def _determine_bins(self):
nbins = int((self._range[1] - self._range[0]) / self.binsize)
# we need to make sure that the number of bins is odd, so that the
# central one encompasses zero (to make the delta-function
# contribution appear always in this bin)
if (nbins % 2 > 0):
nbins += 1
self._nbins = nbins
def _sample_random_distribution(self, group):
box = group.universe.dimensions[:3]
rnd_accum = np.array(0)
try:
size = self.kargs['MCpoints']
except:
# assume atomic volumes of ~ 30 A^3 and sample
# 10 points per atomic volue as a rule of thumb
size1 = int(np.prod(box) / 3.)
# just in case 'unphysical' densities are used:
size2 = 10 * len(group.universe.atoms)
size = np.max([size1, size2])
rnd = np.random.random((size, 3))
rnd *= self.interface.universe.dimensions[:3]
<|code_end|>
, predict the next line using imports from the current file:
from .basic_observables import Number
from .intrinsic_distance import IntrinsicDistance
from scipy import stats
from MDAnalysis.core.groups import Atom, AtomGroup, Residue, ResidueGroup
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: pytim/observables/basic_observables.py
# class Number(Observable):
# """The number of atoms.
# """
#
# def __init__(self, *arg, **kwarg):
# Observable.__init__(self, None)
#
# def compute(self, inp, kargs=None):
# """Compute the observable.
#
# :param AtomGroup inp: the input atom group
# :returns: one, for each atom in the group
#
# """
# return np.ones(len(inp))
#
# Path: pytim/observables/intrinsic_distance.py
# class IntrinsicDistance(Observable):
# """Initialize the intrinsic distance calculation.
#
# :param PYTIM interface: compute the intrinsic distance with respect
# to this interface
# :param str symmetry: force calculation using this symmetry, if
# availabe (e.g. 'generic', 'planar', 'spherical')
# If 'default', uses the symmetry selected in
# the PYTIM interface instance.
#
# Example:
#
# >>> import MDAnalysis as mda
# >>> import pytim
# >>> import numpy as np
# >>> from pytim import observables
# >>> from pytim.datafiles import MICELLE_PDB
# >>> u = mda.Universe(MICELLE_PDB)
# >>> micelle = u.select_atoms('resname DPC')
# >>> waterox = u.select_atoms('type O and resname SOL')
# >>> inter = pytim.GITIM(u,group=micelle, molecular=False, alpha=2.0)
# >>> dist = observables.IntrinsicDistance(interface=inter)
# >>> d = dist.compute(waterox)
# >>> np.set_printoptions(precision=3,threshold=10)
# >>> print(d)
# [25.733 8.579 8.852 ... 18.566 13.709 9.876]
#
# >>> np.set_printoptions(precision=None,threshold=None)
# """
#
# def __init__(self, interface, symmetry='default', mode='default'):
# Observable.__init__(self, interface.universe)
# self.interface = interface
# self.mode = mode
# if symmetry == 'default':
# self.symmetry = self.interface.symmetry
# else:
# self.symmetry = symmetry
#
# def compute(self, inp, kargs=None):
# """Compute the intrinsic distance of a set of points from the first
# layers.
#
# :param ndarray positions: compute the intrinsic distance for this set
# of points
# """
# # see pytim/surface.py
# return self.interface._surfaces[0].distance(inp, self.symmetry, mode=self.mode)
. Output only the next line. | rnd_pos = IntrinsicDistance( |
Based on the snippet: <|code_start|> self.count = count * 0.0
self.edges = edges
self.g1 = self.universe.atoms
self.g2 = None
self._rdf = self.count
def _set_default_values(self, generalized_coordinate, max_distance, nbins):
self.dimensions = np.asarray(self.coords_in).shape[0]
self.dimensions_out = np.asarray(self.coords_out).shape[0]
self.generalized_coordinate = generalized_coordinate
self.cartesian = np.any(
[coord in self.cartesian_coords for coord in self.coords_out])
self.spherical = np.any(
[coord in self.spherical_coords for coord in self.coords_out])
if (self.cartesian and self.spherical) or (not self.cartesian and not self.spherical):
raise ValueError("Can pass either any of Cartesian ['x','y','z'] \
or of spherical ['r','phi','theta'] coordinates ")
if self.spherical:
all_coords = self.spherical_coords
if self.cartesian:
all_coords = self.cartesian_coords
self.dirmask_out = np.array(
[np.where(np.asarray(all_coords) == c)[0][0] for c in self.coords_out])
if self.generalized_coordinate is None:
if self.order == 1:
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from . import Position, RelativePosition
and context (classes, functions, sometimes code) from other files:
# Path: pytim/observables/basic_observables.py
# class Position(Vector):
# """ Atomic positions
#
# Example: compute the projection on the xz plane of the first water molecule
#
# >>> import MDAnalysis as mda
# >>> import pytim
# >>> u = mda.Universe(pytim.datafiles.WATER_GRO)
# >>> proj = pytim.observables.Position('xz')
# >>> with np.printoptions(precision=3):
# ... print(proj.compute(u.residues[0].atoms) )
# [[28.62 11.37]
# [28.42 10.51]
# [29.61 11.51]]
#
# """
# # TODO: add a flag to prevent recomputing the reference frame, in case
# # it's constant
#
# def __init__(self, arg='xyz', **kwarg):
# Vector.__init__(self, arg, kwarg)
# try:
# self.folded = kwarg['folded']
# except KeyError:
# self.folded = True
# try:
# self.cartesian = kwarg['cartesian']
# except KeyError:
# self.cartesian = True
# try:
# self.spherical = kwarg['spherical']
# except KeyError:
# self.spherical = False
#
# if self.spherical is True:
# self.cartesian = False
#
# def _cartesian_to_spherical(self, cartesian):
# spherical = np.empty(cartesian.shape)
# spherical[:, 0] = np.linalg.norm(cartesian, axis=1)
# if len(self.dirmask) > 1: # 2d or 3d
# spherical[:, 1] = np.arctan2(cartesian[:, 1], cartesian[:, 0])
# if len(self.dirmask) == 3: # 3d
# xy = np.sum(cartesian[:, [0, 1]]**2, axis=1)
# spherical[:, 2] = np.arctan2(np.sqrt(xy), cartesian[:, 2])
#
# return spherical
#
# def compute(self, inp, **kwarg):
# """Compute the observable.
#
# :param AtomGroup inp: the input atom group
# :returns: atomic positions
#
# """
# inp = self._to_atomgroup(inp)
# box = inp.universe.dimensions[:3]
# if self.folded:
# cartesian = inp.atoms.pack_into_box()
# # return cartesian[:,self.dirmask]
# else:
# cartesian = inp.positions
#
# if self.cartesian:
# return cartesian[:, self.dirmask]
# if self.spherical:
# return self._cartesian_to_spherical(cartesian)[:, self.dirmask]
#
# class RelativePosition(Position):
#
# def __init__(self, arg='xyz', **kwarg):
# return Position.__init__(self, arg, **kwarg)
#
# def compute(self, inp1, inp2, reference_frame=None):
# # by adding a new axis we allow take the difference of positions
# # of the N inp atoms to the M reference_group ones.
# # pos here has dimension (N,M,3)
#
# inp1 = self._to_atomgroup(inp1)
# inp2 = self._to_atomgroup(inp2)
# pos = inp1.positions[:, np.newaxis] - inp2.positions
# if reference_frame is True:
# ref = ReferenceFrame().compute(inp2)
# pos = 0
# elif reference_frame is not None:
# try:
# ref = ReferenceFrame().compute(reference_frame)
# pos = 0
# except:
# raise ValueError(
# 'reference_frame can be None,True, or an atom group ')
#
# # let's get back to dimension (NxM,dimension)
# pos = pos[:, :, self.dirmask]
# dimension = len(self.dirmask)
# pos = pos.reshape((np.prod(pos.shape[:-1]), dimension))
# box = inp1.universe.dimensions[self.dirmask]
# if self.folded:
# cond = np.where(pos > box / 2.)
# pos[cond] -= box[cond[1]]
# cond = np.where(pos < -box / 2.)
# pos[cond] += box[cond[1]]
#
# if self.cartesian:
# return pos
# if self.spherical:
# return self._cartesian_to_spherical(pos)
. Output only the next line. | self.generalized_coordinate = Position(self.coords_in, cartesian=self.cartesian, |
Here is a snippet: <|code_start|> self.g2 = None
self._rdf = self.count
def _set_default_values(self, generalized_coordinate, max_distance, nbins):
self.dimensions = np.asarray(self.coords_in).shape[0]
self.dimensions_out = np.asarray(self.coords_out).shape[0]
self.generalized_coordinate = generalized_coordinate
self.cartesian = np.any(
[coord in self.cartesian_coords for coord in self.coords_out])
self.spherical = np.any(
[coord in self.spherical_coords for coord in self.coords_out])
if (self.cartesian and self.spherical) or (not self.cartesian and not self.spherical):
raise ValueError("Can pass either any of Cartesian ['x','y','z'] \
or of spherical ['r','phi','theta'] coordinates ")
if self.spherical:
all_coords = self.spherical_coords
if self.cartesian:
all_coords = self.cartesian_coords
self.dirmask_out = np.array(
[np.where(np.asarray(all_coords) == c)[0][0] for c in self.coords_out])
if self.generalized_coordinate is None:
if self.order == 1:
self.generalized_coordinate = Position(self.coords_in, cartesian=self.cartesian,
spherical=self.spherical)
if self.order == 2:
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from . import Position, RelativePosition
and context from other files:
# Path: pytim/observables/basic_observables.py
# class Position(Vector):
# """ Atomic positions
#
# Example: compute the projection on the xz plane of the first water molecule
#
# >>> import MDAnalysis as mda
# >>> import pytim
# >>> u = mda.Universe(pytim.datafiles.WATER_GRO)
# >>> proj = pytim.observables.Position('xz')
# >>> with np.printoptions(precision=3):
# ... print(proj.compute(u.residues[0].atoms) )
# [[28.62 11.37]
# [28.42 10.51]
# [29.61 11.51]]
#
# """
# # TODO: add a flag to prevent recomputing the reference frame, in case
# # it's constant
#
# def __init__(self, arg='xyz', **kwarg):
# Vector.__init__(self, arg, kwarg)
# try:
# self.folded = kwarg['folded']
# except KeyError:
# self.folded = True
# try:
# self.cartesian = kwarg['cartesian']
# except KeyError:
# self.cartesian = True
# try:
# self.spherical = kwarg['spherical']
# except KeyError:
# self.spherical = False
#
# if self.spherical is True:
# self.cartesian = False
#
# def _cartesian_to_spherical(self, cartesian):
# spherical = np.empty(cartesian.shape)
# spherical[:, 0] = np.linalg.norm(cartesian, axis=1)
# if len(self.dirmask) > 1: # 2d or 3d
# spherical[:, 1] = np.arctan2(cartesian[:, 1], cartesian[:, 0])
# if len(self.dirmask) == 3: # 3d
# xy = np.sum(cartesian[:, [0, 1]]**2, axis=1)
# spherical[:, 2] = np.arctan2(np.sqrt(xy), cartesian[:, 2])
#
# return spherical
#
# def compute(self, inp, **kwarg):
# """Compute the observable.
#
# :param AtomGroup inp: the input atom group
# :returns: atomic positions
#
# """
# inp = self._to_atomgroup(inp)
# box = inp.universe.dimensions[:3]
# if self.folded:
# cartesian = inp.atoms.pack_into_box()
# # return cartesian[:,self.dirmask]
# else:
# cartesian = inp.positions
#
# if self.cartesian:
# return cartesian[:, self.dirmask]
# if self.spherical:
# return self._cartesian_to_spherical(cartesian)[:, self.dirmask]
#
# class RelativePosition(Position):
#
# def __init__(self, arg='xyz', **kwarg):
# return Position.__init__(self, arg, **kwarg)
#
# def compute(self, inp1, inp2, reference_frame=None):
# # by adding a new axis we allow take the difference of positions
# # of the N inp atoms to the M reference_group ones.
# # pos here has dimension (N,M,3)
#
# inp1 = self._to_atomgroup(inp1)
# inp2 = self._to_atomgroup(inp2)
# pos = inp1.positions[:, np.newaxis] - inp2.positions
# if reference_frame is True:
# ref = ReferenceFrame().compute(inp2)
# pos = 0
# elif reference_frame is not None:
# try:
# ref = ReferenceFrame().compute(reference_frame)
# pos = 0
# except:
# raise ValueError(
# 'reference_frame can be None,True, or an atom group ')
#
# # let's get back to dimension (NxM,dimension)
# pos = pos[:, :, self.dirmask]
# dimension = len(self.dirmask)
# pos = pos.reshape((np.prod(pos.shape[:-1]), dimension))
# box = inp1.universe.dimensions[self.dirmask]
# if self.folded:
# cond = np.where(pos > box / 2.)
# pos[cond] -= box[cond[1]]
# cond = np.where(pos < -box / 2.)
# pos[cond] += box[cond[1]]
#
# if self.cartesian:
# return pos
# if self.spherical:
# return self._cartesian_to_spherical(pos)
, which may include functions, classes, or code. Output only the next line. | self.generalized_coordinate = RelativePosition(self.coords_in, cartesian=self.cartesian, |
Given snippet: <|code_start|> universe.add_TopologyAttr(missing_class(values))
if name == 'elements':
types = MDAnalysis.topology.guessers.guess_types(group.names)
# is there an inconsistency in the way 'element' is defined
# in different modules in MDA?
# Note: the second arg in .get() is the default.
group.elements = np.array([t.ljust(2) for t in types])
if name == 'radii':
guess_radii(interface)
def weighted_close_match(string, dictionary):
# increase weight of the first letter
# this fixes problems with atom names like CH12
_wdict = {}
_dict = dictionary
_str = string[0] + string[0] + string
for key in _dict.keys():
_wdict[key[0] + key[0] + key] = _dict[key]
m = get_close_matches(_str, _wdict.keys(), n=1, cutoff=0.1)[0]
return m[2:]
def _guess_radii_from_masses(interface, group, guessed):
radii = np.copy(group.radii)
masses = group.masses
types = group.types
unique_masses = np.unique(masses)
# Let's not consider atoms with zero mass.
unique_masses = unique_masses[unique_masses > 0]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import abstractproperty
from .atoms_maps import atoms_maps
from difflib import get_close_matches
import MDAnalysis
import importlib
import numpy as np
and context:
# Path: pytim/atoms_maps.py
which might include code, classes, or functions. Output only the next line. | d = atoms_maps |
Predict the next line for this snippet: <|code_start|> correlation at time lag :math:`t` by its value at time lag 0
computed over all trajectories that extend up to time
lag :math:`t` and do not start with :math:`h=0`.
>>> # not normalizd, intermittent
>>> corr = vv.correlation(normalized=False,continuous=False)
>>> c0 = (1+1+1+0.25+1+1+0.25)/7
>>> c1 = (1+1+0.5+1)/5 ; c2 = (1+0.5+0.5)/4 ; c3 = (0.5+0.5)/2
>>> print (np.allclose(corr, [ c0, c1, c2, c3]))
True
>>> # check normalization
>>> np.all(vv.correlation(continuous=False) == corr/corr[0])
True
>>> # not normalizd, continuous
>>> corr = vv.correlation(normalized=False,continuous=True)
>>> c0 = (1+1+1+0.25+1+1+0.25)/7
>>> c1 = (1+1+0.5+1)/5 ; c2 = (1+0.5)/4 ; c3 = (0.5+0.)/2
>>> print (np.allclose(corr, [ c0, c1, c2, c3]))
True
>>> # check normalization
>>> np.all(vv.correlation(continuous=True) == corr/corr[0])
True
"""
intermittent = not continuous
self.dim = self._determine_dimension()
# the standard correlation
if self.reference is None:
ts = np.asarray(self.timeseries)
<|code_end|>
with the help of current file imports:
import numpy as np
from pytim import utilities
from MDAnalysis.core.groups import Atom, AtomGroup, Residue, ResidueGroup
and context from other files:
# Path: pytim/utilities.py
# def lap(show=False):
# def correlate(a1, a2=None, _normalize=True):
# def extract_positions(inp):
# def get_box(universe, normal=2):
# def get_pos(group, normal=2):
# def get_coord(coord, group, normal=2):
# def get_x(group, normal=2):
# def get_y(group, normal=2):
# def get_z(group, normal=2):
# def centerbox(universe,
# x=None,
# y=None,
# z=None,
# vector=None,
# center_direction=2,
# halfbox_shift=True):
# def guess_normal(universe, group):
# def density_map(pos, grid, sigma, box):
# def _NN_query(kdtree, position, qrange):
# def consecutive_filename(universe, basename, extension):
# def generate_cube_vertices(box, delta=0.0, jitter=False, dim=3):
, which may contain function names, class names, or code. Output only the next line. | corr = utilities.correlate(ts) |
Using the snippet: <|code_start|>
def generatecodewithinit(self, _cfilepath_from_pipsdb, _cfileanalyzed, _dicvarinitandloc):
"""
write new code where for each function identified in (2) we should add
the new vars to VAR#init
:param _cfilepath_from_pipsdb:
:param _dicvarinitandloc:
:return: pathcodewithinit
"""
# generating path to save this new code generated
# new_namefile = os.path.basename(_cfilepath).replace(".i", "_depthk_t.c")
#pathnewfile = os.path.dirname(_cfilepath) + "/" + new_namefile
#pathcodewithinit = "/tmp/" + str(os.path.basename(_cfilepath_from_pipsdb).replace(".c", "_init.c"))
pathcodewithinit = _cfileanalyzed
filewithinit = open(pathcodewithinit, "w")
flag_initpips = True
if not _dicvarinitandloc:
flag_initpips = False
# Get lines from C file
filec = open(_cfilepath_from_pipsdb, "r")
linescfile = filec.readlines()
filec.close()
# Get all variable declaration data
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and context (class names, function names, or code) available:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
. Output only the next line. | r = ast.RunAstDecl(_cfilepath_from_pipsdb) |
Here is a snippet: <|code_start|> for var in _dicvarinitandloc[nextline]:
# print("INIT: ", var)
# Creating INIT vars
#print(">>>>>> ", dict_varsdata[var][0])
#print(var)
#print("INIT: ", dict_varsdata[var][0], var+"_init")
nametype = ' '.join(dict_varsdata[var][0])
#print(nametype+str(" " + var + "_init = " + var + ";"))
filewithinit.write(nametype + str(" " + var + "_init = " + var + "; \n"))
#sys.exit()
count += 1
filewithinit.close()
return pathcodewithinit
def translatepipsannot(self, _cpathpipscode):
# Get the number line where each function begin
listnumbeginfunc = self.getnumbeginfuncts(_cpathpipscode)
if not self.listnumbeginfunc:
print("ERROR. Identifying functions")
sys.exit()
if self.debug_op:
print(">> Translating the PIPS annotation with the invariants")
# Call class to translate PIPS annotation
<|code_end|>
. Write the next line using the current file imports:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and context from other files:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
, which may include functions, classes, or code. Output only the next line. | runtranslatepips = translate_pips.PipsTranslateAnnot() |
Predict the next line after this snippet: <|code_start|> list_paths_to_delete.append(inputCFile)
if args.setInvariantTool == "pips" or args.setInvariantTool == "all":
# Applying the preprocess code - Define a specific format to code
inputCFile = rundepthk.rununcrustify(inputCFile)
# Apply hacking to handle with GNU extensions
# HackGNUext: Generate a copy the analyzed program to a tmp file
# now with the extension replaced from .i to .c
inputCFile = rundepthk.applygnuhack(inputCFile)
#if args.setOnlyCEUse or args.setInvariantTool == "all":
rundepthk.use_counter_example = True
if args.setOnlyCEUse and rundepthk.debug_op:
print(">> Adopting only the ESBMC counterexample to generate assumes")
if(args.setInvariantTool == "all"):
print(">> Adopting PIPS, Pagai and CounterExample to generate assumes")
codewithinv = ""
__invgeneration = args.setInvariantTool
pathcodeinvtranslated = ""
ERROR_FLAG = False
if (not args.setOnlyCEUse or args.setInvariantTool == "all") and (not rundepthk.esbmc_is_termination and not rundepthk.esbmc_is_memory_safety):
try:
# Choose invariant generation __invgeneration
# Applying steps of DepthK
<|code_end|>
using the current file's imports:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and any relevant context from other files:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
. Output only the next line. | runtranspagai = translate_pagai.TranslatePagai() |
Given the following code snippet before the placeholder: <|code_start|> inputCFile = rundepthk.rununcrustify(inputCFile)
# Apply hacking to handle with GNU extensions
# HackGNUext: Generate a copy the analyzed program to a tmp file
# now with the extension replaced from .i to .c
inputCFile = rundepthk.applygnuhack(inputCFile)
#if args.setOnlyCEUse or args.setInvariantTool == "all":
rundepthk.use_counter_example = True
if args.setOnlyCEUse and rundepthk.debug_op:
print(">> Adopting only the ESBMC counterexample to generate assumes")
if(args.setInvariantTool == "all"):
print(">> Adopting PIPS, Pagai and CounterExample to generate assumes")
codewithinv = ""
__invgeneration = args.setInvariantTool
pathcodeinvtranslated = ""
ERROR_FLAG = False
if (not args.setOnlyCEUse or args.setInvariantTool == "all") and (not rundepthk.esbmc_is_termination and not rundepthk.esbmc_is_memory_safety):
try:
# Choose invariant generation __invgeneration
# Applying steps of DepthK
runtranspagai = translate_pagai.TranslatePagai()
if __invgeneration == "pagai" or __invgeneration == "all":
# Generate invariants
if rundepthk.debug_op:
print(">> Running PAGAI to generate the invariants")
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and context including class names, function names, and sometimes code from other files:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
. Output only the next line. | geninvpagai = generate_inv_pagai.GeneratePagaiInv() |
Here is a snippet: <|code_start|> #runtranslatepips.nameoforicprogram = self.nameoforicprogram
runtranslatepips.list_beginnumfuct = listnumbeginfunc
# print(runtranslatepips.instprecondinprog(_cpathpipscode))
# sys.exit()
return runtranslatepips.instprecondinprog(_cpathpipscode)
@staticmethod
def getnumbeginfuncts(_cfilepath):
# result
listbeginnumfuct = []
# get data functions using ctags
textdata = commands.getoutput("ctags -x --c-kinds=f " + _cfilepath)
# generate a list with the data funct
listdatafunct = textdata.split("\n")
for linedfunct in listdatafunct:
# split by space
matchlinefuct = re.search(r'function[ ]+([0-9]+)', linedfunct)
if matchlinefuct:
# consider the line number of index program in the list
listbeginnumfuct.append(int(matchlinefuct.group(1).strip()))
return listbeginnumfuct
def callesbmccheck(self, _cfilepath, _enableforceassume, _enablelastcheckbasecase):
<|code_end|>
. Write the next line using the current file imports:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and context from other files:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
, which may include functions, classes, or code. Output only the next line. | runesbmc = esbmccheck.DepthEsbmcCheck() |
Continue the code snippet: <|code_start|> #
# # delete code with auxiliary code to #init
# if os.path.exists(_pathcodeinit):
# os.remove(_pathcodeinit)
@staticmethod
def checkesbmcsolversupport(_namesolver):
if _namesolver == "z3":
return True
if _namesolver == "boolector":
return True
if _namesolver == "mathsat":
return True
else:
return False
def applygnuhack(self, _inputcfile):
# Mini hack to allow PIPS handle with .i files
# new_namefile = os.path.basename(_inputcfile).replace(".i", self.depthkname_ext)
# pathnewfile = os.path.dirname(_inputcfile) + "/" + new_namefile
filec = open(_inputcfile, 'r')
# if self.debug_gh:
# print(_inputcfile)
# #os.system("cat " + _inputcfile)
# print(filec.read())
# sys.exit()
<|code_end|>
. Use current file imports:
import argparse
import shutil
import sys
import os
import commands
import re
import time
import random
import string
import platform
import time
from pipes import quote
from modules.run_ast import ast
from modules.invariant_tools.pips.translate_pips import translate_pips
from modules.invariant_tools.pagai.translate_inv_pagai import translate_pagai
from modules.invariant_tools.pagai.generate_inv_pagai import generate_inv_pagai
from modules.bmc_check import esbmccheck
from modules.gnu_extension import hack_extensions
and context (classes, functions, or code) from other files:
# Path: modules/run_ast/ast.py
# CPPPATH = 'utils/cpp.exe' if sys.platform == 'win32' else 'cpp'
# ABS_PATH = os.path.dirname(__file__)
# class IdentifyVarDecl(NodeVisitor):
# class RunAstDecl(object):
# def __init__(self):
# def getnumberofline(nodecoord):
# def visit_Decl(self, node):
# def __init__(self, _cfilepath):
# def identify_decl(self):
#
# Path: modules/invariant_tools/pips/translate_pips/translate_pips.py
# class PipsTranslateAnnot(object):
# def __init__(self):
# def instprecondinprog(self, _cprogrampath):
# def hasprecondmorelines(_listcfile, _actualindex):
# def translatepreconditionpips(self, _precondtext):
#
# Path: modules/invariant_tools/pagai/translate_inv_pagai/translate_pagai.py
# class TranslatePagai(object):
# def __init__(self):
# def removenotprintable(self, __listprogram):
# def identifyInv(self, __pathprogram):
# def applyesbmcassume(self, __inv):
# def writeInvPAGAI(self, __pathprogram, addassume):
#
# Path: modules/invariant_tools/pagai/generate_inv_pagai/generate_inv_pagai.py
# class GeneratePagaiInv(object):
# def __init__(self):
# def generate_inv(self, __pathprogram):
#
# Path: modules/bmc_check/esbmccheck.py
# class DepthEsbmcCheck(object):
# def __init__(self):
# def getlastlinenumfromce(_esbmccepath, _indexliststartsearch):
# def translatecedata(self, _listlinesfromce):
# def handletextfrom_ce(self, _stringtxtce, _enablescopecheck):
# def getfunctnamebylinenum(self, _linenum):
# def checkscopeextraassume(self, _linenumber):
# def lastsearchbylinetoassume(_esbmccepath, _indexliststartsearch):
# def getlastdatafromce(self, _esbmccepath):
# def addassumeinprogram(self, _cprogrampath):
# def savelist2file(_pathfile, _list2file):
# def isdefiniedmemlimit(self):
# def hasincorrectopesbmc(_esbmcoutput):
# def hastimeoutfromesbmc(_esbmcoutput):
# def hassuccessfulfromesbmc(_esbmcoutput):
# def checkwithkparallel(self, _cprogrampath, _actual_ce, _listtmpfiles):
# def cleantmpfiles(_listfiles2delete):
# def kinductioncheck(self, _cprogrampath):
# def getnumbeginfuncts(_cfilepath):
# def configureUAPath(self):
# def execUA(self, _cprogrampath, ua_ops):
# def execBaseCase(self, _cprogrampath, actual_ce, lastResult):
# def execForwardCondition(self, _cprogrampath, actual_ce, lastResult, listtmpfiles):
# def execInductiveStep(self, _cprogrampath, actual_ce, lastResult, listtmpfiles, actual_detphver):
# def check_witnessresult(self, _listresultwitness):
# def check_witnessresultUA(self, _listresultwitness):
#
# Path: modules/gnu_extension/hack_extensions.py
# def countwhiledelimiter(_list, _index):
# def make_pycparser_compatible(data):
. Output only the next line. | str_filelines = hack_extensions.make_pycparser_compatible(filec.read()) |
Given the following code snippet before the placeholder: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_ph_instance():
v = HO_PH('testnode', "127.0.0.1", 1337, None, run=False)
return v
def test_instance_ho_ph(ho_ph_instance):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_ph import HO_PH
and context including class names, function names, and sometimes code from other files:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_ph.py
# class HO_PH(HO):
# """Create an horizontal orchestrator to handle agents at the physical
# level.
#
# :return: The HO to gather and react on physical agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_PH, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_PH, self).send(msg)
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
. Output only the next line. | assert isinstance(ho_ph_instance, HO) |
Given snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_ph_instance():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_ph import HO_PH
and context:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_ph.py
# class HO_PH(HO):
# """Create an horizontal orchestrator to handle agents at the physical
# level.
#
# :return: The HO to gather and react on physical agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_PH, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_PH, self).send(msg)
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
which might include code, classes, or functions. Output only the next line. | v = HO_PH('testnode', "127.0.0.1", 1337, None, run=False) |
Using the snippet: <|code_start|>
DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def node_instance():
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import pytest
import sys
import os
from vespa.node import Node
and context (class names, function names, or code) available:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
. Output only the next line. | n = Node('testnode', "127.0.0.1", 1337, None, run=False) |
Here is a snippet: <|code_start|># Module name: agent_controller_pox.py
# Version: 1.0
# Created: 29/04/2014 by Aurélien Wailly <aurelien.wailly@orange.com>
#
# Copyright (C) 2010-2014 Orange
#
# This file is part of VESPA.
#
# VESPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation version 2.1.
#
# VESPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with VESPA. If not, see <http://www.gnu.org/licenses/>.
"""
Agent to wrap the POX python SDN controller. It require some modification on
the other side too. You can follow the mac address blocking tutorial on the
POX website.
"""
mychannel = 'mac_redir'
<|code_end|>
. Write the next line using the current file imports:
from logging import *
from .node import Node
from .agent_controller import Agent_Controller
import Queue
import json
import urllib
import urllib2
import json
import sys
import socket
import argparse
and context from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/agent_controller.py
# class Agent_Controller(Agent):
# """Create an Agent to send a mac address to an OpenFlow controller
#
# :return: The Agent instance to offer the OpenFlow alert_ip function
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=False):
# self.controller_ip = "12.0.0.3"
# self.controller_port = 80
# super(Agent_Controller, self,).__init__(name, host, port, master, run)
# self.backend = self.desc()
#
# def alert_ip(self, ip, mac):
# """Block the mac address on the network
#
# :param str ip: The IP address or domain of the controller
# :param str mac: The mac address to block on the network
# :return: The "Ok" string
# :rtype: str
# """
# url = 'http://%s:%s/' % (self.controller_ip, self.controller_port)
# values = {'mac': mac}
# data = urllib.urlencode(values)
# print '!!!!!!!!!!!!!!!!!!!!! Sending mac %s to %s' % (mac, url)
# req = urllib2.Request(url, data)
# response = urllib2.urlopen(req)
# the_page = response.read()
# return "Ok"
, which may include functions, classes, or code. Output only the next line. | class Agent_Controller_Pox(Agent_Controller): |
Given the code snippet: <|code_start|>
DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT)
sys.path.append(DOSSIER_PARENT)
class TestInit(unittest.TestCase):
def test_instance_node(self):
v = HO('testnode', "127.0.0.1", 1337, None, run=False)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import sys
import os
from vespa.node import Node
from vespa.ho import HO
and context (functions, classes, or occasionally code) from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
. Output only the next line. | self.assertTrue(isinstance(v, Node)) |
Here is a snippet: <|code_start|>
DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT)
sys.path.append(DOSSIER_PARENT)
class TestInit(unittest.TestCase):
def test_instance_node(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
import os
from vespa.node import Node
from vespa.ho import HO
and context from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
, which may include functions, classes, or code. Output only the next line. | v = HO('testnode', "127.0.0.1", 1337, None, run=False) |
Here is a snippet: <|code_start|> quarantine_user +
"@" +
quarantine +
"/system")
domNode = self._get_dom_name(nodeName, conn_local)
domNode.migrate(
conn_quarantine,
libvirt.VIR_MIGRATE_LIVE,
None,
None,
0)
return ["Migrated VM " + nodeName + " to quarantine"]
def contains_vm(self, vm):
try:
conn_local = libvirt.open("qemu+ssh://%s@%s:%s/system" %
(self.libvirt_user,
self.libvirt_host,
self.libvirt_port))
self._get_dom_name(vm, conn_local)
return True
except Exception:
return False
def send_key(self, vm, args):
conn_local = libvirt.open("qemu+ssh://%s@%s:%s/system" %
(self.libvirt_user,
self.libvirt_host,
self.libvirt_port))
wokeup = False
<|code_end|>
. Write the next line using the current file imports:
import socket
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
from .log_pipe import debug1
from .agent import Agent
and context from other files:
# Path: vespa/log_pipe.py
# def debug1(str):
# print repr(str)
# pass
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
, which may include functions, classes, or code. Output only the next line. | debug1( |
Predict the next line for this snippet: <|code_start|># d.blockRebase d.migrate2 d.setMemoryStatsPeriod
# d.blockResize d.migrate3 d.setMetadata
# d.blockStats d.migrateGetCompressionCache d.setNumaParameters
# d.blockStatsFlags d.migrateGetMaxSpeed d.setSchedulerParameters
# d.connec d.migrateSetCompressionCache d.setSchedulerParametersFlags
# d.controlInfo d.migrateSetMaxDowntime d.setVcpus
# d.coreDump d.migrateSetMaxSpeed d.setVcpusFlags
# d.create d.migrateToURI d.shutdown
# d.createWithFiles d.migrateToURI2 d.shutdownFlags
# d.createWithFlags d.migrateToURI3 d.snapshotCreateXML
# d.destroy d.name d.snapshotCurrent
# d.destroyFlags d.numaParameters d.snapshotListNames
# d.detachDevice d.openChannel d.snapshotLookupByName
# d.detachDeviceFlags d.openConsole d.snapshotNum
# d.diskErrors d.openGraphics d.state
# d.emulatorPinInfo d.pMSuspendForDuration d.suspend
# d.fSTrim d.pMWakeup d.undefine
# d.getCPUStats d.pinEmulator d.undefineFlags
# d.hasCurrentSnapshot d.pinVcpu d.updateDeviceFlags
# d.hasManagedSaveImage d.pinVcpuFlags d.vcpuPinInfo
# d.hostname d.reboot d.vcpus
# d.info d.reset d.vcpusFlags
# End Flag
EOT_FLAG = "EndOfTransmission"
LIST_ITEM_SEPARATOR = ':'
LIST_SEPARATOR = '\r'
<|code_end|>
with the help of current file imports:
import socket
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
import libvirt
import sys
import os
import time
import xml.dom.minidom
from .log_pipe import debug1
from .agent import Agent
and context from other files:
# Path: vespa/log_pipe.py
# def debug1(str):
# print repr(str)
# pass
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
, which may contain function names, class names, or code. Output only the next line. | class Agent_Libvirt(Agent): |
Next line prediction: <|code_start|>
DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT)
sys.path.append(DOSSIER_PARENT)
class TestInit(unittest.TestCase):
def test_instance_agent(self):
v = Agent('testnode', "127.0.0.1", 1339, None, run=False)
<|code_end|>
. Use current file imports:
(import unittest
import sys
import os
from vespa.node import Node
from vespa.agent import Agent)
and context including class names, function names, or small code snippets from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
. Output only the next line. | self.assertTrue(isinstance(v, Node)) |
Here is a snippet: <|code_start|>
DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT)
sys.path.append(DOSSIER_PARENT)
class TestInit(unittest.TestCase):
def test_instance_agent(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
import os
from vespa.node import Node
from vespa.agent import Agent
and context from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
, which may include functions, classes, or code. Output only the next line. | v = Agent('testnode', "127.0.0.1", 1339, None, run=False) |
Predict the next line for this snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
class SimpleRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(102400) # token receive
self.request.send("hello")
time.sleep(0.1) # make sure it finishes receiving request before closing
self.request.close()
def serve_data():
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer(('127.0.0.1', 18080), SimpleRequestHandler)
http_server_thread = threading.Thread(target=server.handle_request)
http_server_thread.setDaemon(True)
http_server_thread.start()
return server
@pytest.fixture(scope='module')
def agent_instance():
a = Agent_Controller('testnode', "127.0.0.1", 1340, None, run=False)
s = serve_data()
return a
def test_agent_controller_instance(agent_instance):
<|code_end|>
with the help of current file imports:
import pytest
import unittest
import sys
import os
import SocketServer
import threading
import time
from vespa.node import Node
from vespa.agent import Agent
from vespa.agent_controller import Agent_Controller
and context from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
#
# Path: vespa/agent_controller.py
# class Agent_Controller(Agent):
# """Create an Agent to send a mac address to an OpenFlow controller
#
# :return: The Agent instance to offer the OpenFlow alert_ip function
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=False):
# self.controller_ip = "12.0.0.3"
# self.controller_port = 80
# super(Agent_Controller, self,).__init__(name, host, port, master, run)
# self.backend = self.desc()
#
# def alert_ip(self, ip, mac):
# """Block the mac address on the network
#
# :param str ip: The IP address or domain of the controller
# :param str mac: The mac address to block on the network
# :return: The "Ok" string
# :rtype: str
# """
# url = 'http://%s:%s/' % (self.controller_ip, self.controller_port)
# values = {'mac': mac}
# data = urllib.urlencode(values)
# print '!!!!!!!!!!!!!!!!!!!!! Sending mac %s to %s' % (mac, url)
# req = urllib2.Request(url, data)
# response = urllib2.urlopen(req)
# the_page = response.read()
# return "Ok"
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(agent_instance, Agent) |
Here is a snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
class SimpleRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(102400) # token receive
self.request.send("hello")
time.sleep(0.1) # make sure it finishes receiving request before closing
self.request.close()
def serve_data():
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer(('127.0.0.1', 18080), SimpleRequestHandler)
http_server_thread = threading.Thread(target=server.handle_request)
http_server_thread.setDaemon(True)
http_server_thread.start()
return server
@pytest.fixture(scope='module')
def agent_instance():
<|code_end|>
. Write the next line using the current file imports:
import pytest
import unittest
import sys
import os
import SocketServer
import threading
import time
from vespa.node import Node
from vespa.agent import Agent
from vespa.agent_controller import Agent_Controller
and context from other files:
# Path: vespa/node.py
# class Node(PThread):
# # Overrides threading.Thread.run()
# def run(self):
# profiler = cProfile.Profile()
# try:
# return profiler.runcall(PThread.run, self)
# finally:
# profiler.dump_stats('myprofile-%s.profile' % (self.name))
#
# Path: vespa/agent.py
# class Agent(Node):
# def __init__(self, name, host, port, master, run=True):
# super(Agent, self,).__init__(name, host, port, master, run)
#
# Path: vespa/agent_controller.py
# class Agent_Controller(Agent):
# """Create an Agent to send a mac address to an OpenFlow controller
#
# :return: The Agent instance to offer the OpenFlow alert_ip function
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=False):
# self.controller_ip = "12.0.0.3"
# self.controller_port = 80
# super(Agent_Controller, self,).__init__(name, host, port, master, run)
# self.backend = self.desc()
#
# def alert_ip(self, ip, mac):
# """Block the mac address on the network
#
# :param str ip: The IP address or domain of the controller
# :param str mac: The mac address to block on the network
# :return: The "Ok" string
# :rtype: str
# """
# url = 'http://%s:%s/' % (self.controller_ip, self.controller_port)
# values = {'mac': mac}
# data = urllib.urlencode(values)
# print '!!!!!!!!!!!!!!!!!!!!! Sending mac %s to %s' % (mac, url)
# req = urllib2.Request(url, data)
# response = urllib2.urlopen(req)
# the_page = response.read()
# return "Ok"
, which may include functions, classes, or code. Output only the next line. | a = Agent_Controller('testnode', "127.0.0.1", 1340, None, run=False) |
Using the snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_vm_instance():
v = HO_VM('testnode', "127.0.0.1", 1337, None, run=False)
return v
def test_instance_ho_vm(ho_vm_instance):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_vm import HO_VM
and context (class names, function names, or code) available:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_vm.py
# class HO_VM(HO):
# """Create an horizontal orchestrator to handle agents at the VM level.
#
# :return: The Horizontal Orchestrator to gather and react on VM agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_VM, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_VM, self).send(msg)
# # debug1("%s> Sending %s to %s" % (self.name, msg, self.master) )
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
. Output only the next line. | assert isinstance(ho_vm_instance, HO) |
Based on the snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_vm_instance():
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_vm import HO_VM
and context (classes, functions, sometimes code) from other files:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_vm.py
# class HO_VM(HO):
# """Create an horizontal orchestrator to handle agents at the VM level.
#
# :return: The Horizontal Orchestrator to gather and react on VM agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_VM, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_VM, self).send(msg)
# # debug1("%s> Sending %s to %s" % (self.name, msg, self.master) )
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
. Output only the next line. | v = HO_VM('testnode', "127.0.0.1", 1337, None, run=False) |
Given snippet: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_hy_instance():
v = HO_HY('testnode', "127.0.0.1", 1337, None, run=False)
return v
def test_instance_ho_hy(ho_hy_instance):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_hy import HO_HY
and context:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_hy.py
# class HO_HY(HO):
# """Create an horizontal orchestrator to handle agents at the hypervisor
# level.
#
# :return: The HO to gather and react on hypervisor agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_HY, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_HY, self).send(msg)
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
which might include code, classes, or functions. Output only the next line. | assert isinstance(ho_hy_instance, HO) |
Next line prediction: <|code_start|>
DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__))
DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT)
sys.path.append(DOSSIER_PARENT)
@pytest.fixture(scope='module')
def ho_hy_instance():
<|code_end|>
. Use current file imports:
(import pytest
import sys
import os
from vespa.ho import HO
from vespa.ho_hy import HO_HY)
and context including class names, function names, or small code snippets from other files:
# Path: vespa/ho.py
# class HO(Node):
# def __init__(self, name, host, port, master, run=True):
# super(HO, self,).__init__(name, host, port, master, run)
#
# def findAgent(self, name):
# for agent_name, host, port in self.agents:
# if agent_name == name:
# return (agent_name, host, port)
# raise Exception("Agent %s not present in HO %s." % (name, self.name))
#
# Path: vespa/ho_hy.py
# class HO_HY(HO):
# """Create an horizontal orchestrator to handle agents at the hypervisor
# level.
#
# :return: The HO to gather and react on hypervisor agents.
# :rtype: Node
# """
#
# def __init__(self, name, host, port, master, run=True):
# super(HO_HY, self).__init__(name, host, port, master, run)
# self.have_backend = False
#
# def send(self, msg):
# """Overload the internal send() to capture and send messages to the
# backend
#
# :param str msg: The massage to process and to send
# :return: The backend response
# :rtype: str
# """
# data = super(HO_HY, self).send(msg)
# # self.sendRemote( self.master, data )
# return data
#
# def ninjaMethod(self):
# """Empty function for tests
# """
# pass
. Output only the next line. | v = HO_HY('testnode', "127.0.0.1", 1337, None, run=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.