Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> class TestCommand(TestCase): EMAIL_FOOTER = ('Check your calendar: http://example.com/calendar/\nFound a bug? Have a ' 'feature request? Please let us know: https://github.com/jessamynsmith/' 'eggtimer-server/issues\nDisable email not...
flow_event = FlowEventFactory()
Given snippet: <|code_start|> class TestNullableEnumField(TestCase): def test_to_internal_value_empty(self): field = NullableEnumField(period_models.ClotSize) result = field.to_internal_value('') self.assertIsNone(result) def test_to_internal_value_value(self): field = Null...
self.serializer = FlowEventSerializer(instance=period_models.FlowEvent.objects.first())
Given the code snippet: <|code_start|> class TestNullableEnumField(TestCase): def test_to_internal_value_empty(self): field = NullableEnumField(period_models.ClotSize) result = field.to_internal_value('') self.assertIsNone(result) def test_to_internal_value_value(self): fie...
FlowEventFactory()
Given the following code snippet before the placeholder: <|code_start|>class FlowAdmin(admin.ModelAdmin): list_display = ['user', 'timestamp', 'first_day', 'level', 'color', 'clots', 'cramps'] list_filter = ['timestamp', 'first_day', 'level', 'color', 'clots', 'cramps'] search_fields = ['user__email', 'use...
admin.site.register(models.FlowEvent, FlowAdmin)
Predict the next line after this snippet: <|code_start|> def test_get_full_name(self): self.assertEqual(u'Jessamyn', '%s' % self.user.get_full_name()) def test_get_short_name_email(self): self.assertTrue(re.match(r'user_[\d]+@example.com', '%s' % self.basic_user...
stats = period_models.Statistics.objects.filter(user=self.user).first()
Given the following code snippet before the placeholder: <|code_start|> TIMEZONE = pytz.timezone("US/Eastern") class TestUser(TestCase): def setUp(self): self.user = UserFactory() self.basic_user = UserFactory.build(first_name='') <|code_end|> , predict the next line using imports from the curr...
self.period = FlowEventFactory()
Continue the code snippet: <|code_start|> TIMEZONE = pytz.timezone("US/Eastern") class TestUser(TestCase): def setUp(self): <|code_end|> . Use current file imports: import datetime import pytz import re import requests from django.conf import settings from django.contrib.auth import models as auth_models from ...
self.user = UserFactory()
Using the snippet: <|code_start|> class Command(BaseCommand): help = 'Notify users of upcoming periods' def _format_date(self, date_value): return date_value.strftime('%A %B %d, %Y') def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: import da...
users = period_models.User.objects.filter(
Given the code snippet: <|code_start|> class FlowEventViewSet(viewsets.ModelViewSet): serializer_class = serializers.FlowEventSerializer filter_class = serializers.FlowEventFilter def get_queryset(self): <|code_end|> , generate the next line using the imports in this file: from collections import Coun...
return period_models.FlowEvent.objects.filter(user=self.request.user)
Using the snippet: <|code_start|> PASSWORD = 'bogus_password' class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name = u'Jessamyn' birth_date = pytz.utc.localize(datetime.datetime(1995, 3, 1)) email = factory.Sequence(lambda n: "user_%d@example.com" % ...
model = period_models.FlowEvent
Next line prediction: <|code_start|> TIMEZONE = pytz.timezone("US/Eastern") class TestCommand(TestCase): def setUp(self): self.command = email_active_users.Command() flow_event = FlowEventFactory() self.user = flow_event.user FlowEventFactory(user=self.user, ...
period_models.FlowEvent.objects.all().delete()
Given the following code snippet before the placeholder: <|code_start|> TIMEZONE = pytz.timezone("US/Eastern") class TestCommand(TestCase): def setUp(self): <|code_end|> , predict the next line using imports from the current file: import datetime import pytz from django.test import TestCase from mock import pa...
self.command = email_active_users.Command()
Given snippet: <|code_start|> TIMEZONE = pytz.timezone("US/Eastern") class TestCommand(TestCase): def setUp(self): self.command = email_active_users.Command() <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import pytz from django.test import TestCase...
flow_event = FlowEventFactory()
Given the following code snippet before the placeholder: <|code_start|> class TestEmailSender(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( password='bogus', email='jessamyn@example.com', first_name=u'Jessamyn') @patch('django.core.mail.EmailMultiAlternati...
result = email_sender.send(self.user, 'Hi!', 'good day', None)
Here is a snippet: <|code_start|> class Command(BaseCommand): help = 'Email all active users' def add_arguments(self, parser): parser.add_argument('--noinput', '--no-input', action='store_false', dest='interactive', default=True, help='Tells Dja...
users = period_models.User.objects.filter(
Based on the snippet: <|code_start|>#Author: Miguel Molero <miguel.molero@gmail.com> class FilterWidget(QScrollArea): def __init__(self, *args, **kwargs): super(FilterWidget, self).__init__(*args, **kwargs) filterRequested = Signal() def set_filter(self, func, parms, text, only_apply=False): ...
widget = widget_generator(func=func, parms=parms, text=text, only_apply=only_apply)
Based on the snippet: <|code_start|> self.init_params(parms, text) else: self.init_text(text) def init_apply(self, text): grid = QGridLayout() self.apply_button = QPushButton("Apply") self.apply_button.setObjectName("ap...
item = customWidgets.Extent()
Next line prediction: <|code_start|> self.full_depth = full_depth self.scale = scale self.samples_per_node=samples_per_node self.cg_depth=cg_depth self.enable_polygon_mesh=enable_polygon_mesh self.enable_density = enable_density def set_input(self, input_data): ...
points, normals = get_points_normals_from(self.input_)
Next line prediction: <|code_start|> self.enable_polygon_mesh=enable_polygon_mesh self.enable_density = enable_density def set_input(self, input_data): """ set input data Parameters ---------- input-data : vtkPolyData Returns ------- ...
self.output_ = get_polydata_from(vertices, faces)
Next line prediction: <|code_start|>#Author: Miguel Molero <miguel.molero@gmail.com> __all__=['ReaderTIFF'] class ReaderTIFF(ImageDataBase): def __init__(self, filename): super(ReaderTIFF, self).__init__() self.filename_ = filename def _update(self): dataset = gdal.Open(self.file...
self._imagedata = numpy_to_image(data)
Predict the next line after this snippet: <|code_start|> self._QObj = QObj() def currentView(self): """ Gets the Current View """ return self._current_view def setCurrentView(self, view): """ """ self._current_view = view def getLayers(...
layer = Layer(name)
Given the code snippet: <|code_start|>class OrientedNormalsEstimation(FilterBase): """ NormalEstimation filter estimates normals of a point cloud using PCA Eigen method to fit plane Parameters ---------- number_neighbors: int number of neighbors to be considered in the normals estimation ...
array_with_color = numpy_from_polydata(self.input_)
Given the code snippet: <|code_start|> for i in range(0,len(coord)): d = neigh.kneighbors(coord[i,:3]) for c in range(1,self.number_neighbors): p1 = d[1][0][0] p2 = d[1][0][c] n1 = normals[d[1][0][0],:] n2 = normals[d[1][0][...
self.output_ = copy_polydata_add_normals(self.input_, normals)
Here is a snippet: <|code_start|>class ImageDataBase(DataBase): """ ImageData Base Class Attributes ---------- props_: OrderedDict Dictionary used for the props storing data_: array raw data """ def __init__(self): super(ImageDataBase, self).__init__() ...
self._actor = actor_from_imagedata(self._imagedata)
Based on the snippet: <|code_start|> class PolyDataBase(DataBase): """ PolyData Base Class Attributes --------- data_: Array store array od points of the the point cloud props_: OrderedDict Dictionary used for the props storing """ def __init__(self): super(...
self._actor = actor_from_polydata(self._polydata)
Here is a snippet: <|code_start|> if self._polydata: return self._polydata def set_polydata(self, polydata): self._polydata = polydata self._actor = actor_from_polydata(self._polydata) self.update_props() def update(self): """ Update Reader ""...
self._data = numpy_from_polydata(polydata)
Given snippet: <|code_start|> bounds = self._polydata.GetBounds() self.props_["xmin"] = bounds[0] self.props_["xmax"] = bounds[1] self.props_["ymin"] = bounds[2] self.props_["ymax"] = bounds[3] self.props_["zmin"] = bounds[4] self.props_...
self._polydata = polydata_from_numpy(self.data_)
Next line prediction: <|code_start|> set input data Parameters ---------- input-data : vtkPolyData Returns ------- is_valid: bool Returns True if the input_data is valid for processing """ if isinstance(input_data, vtkPolyData): ...
array_full = numpy_from_polydata(self.input_)
Given the following code snippet before the placeholder: <|code_start|> array_full = numpy_from_polydata(self.input_) array = array_full[:,0:3] color = array_full[:,3:] #KDTree object (sklearn) kDTree = KDTree(array, leaf_size = 5) dx, idx_knn = kDTree.query(array[:, :],...
output = polydata_from_numpy(np.c_[new_array, new_color])
Next line prediction: <|code_start|>""" Class that define a normal estimation method based on vtkPointSetNormalsEstimation by David Doria """ __all__ = ["vtkPointSetNormalsEstimation"] FIXED_NUMBER = 0 RADIUS = 1 <|code_end|> . Use current file imports: (from pcloudpy.core.filters.base import FilterBase from vtk im...
class vtkPointSetNormalsEstimation(FilterBase):
Given the following code snippet before the placeholder: <|code_start|>class ToolBoxesWidget(QWidget): def __init__(self, parent = None): super(ToolBoxesWidget, self).__init__(parent) self._current_item = None layout = QVBoxLayout() self.tree = QTreeView() self.tree.setHead...
item_child = ToolboxStandardItem()
Given snippet: <|code_start|> class NormalsEstimation(FilterBase): """ NormalEstimation filter estimates normals of a point cloud using PCA Eigen method to fit plane Parameters ---------- number_neighbors: int number of neighbors to be considered in the normals estimation Attribut...
array_with_color = numpy_from_polydata(self.input_)
Here is a snippet: <|code_start|> input_: vtkPolyData Input Data to be filtered output_: vtkPolyData Output Data """ def __init__(self, number_neighbors = 10): self.number_neighbors = number_neighbors def update(self): array_with_color = numpy_from_polydata(self....
self.output_ = copy_polydata_add_normals(self.input_, normals)
Next line prediction: <|code_start|> def __init__(self, percent_to_remove): self.percent_to_remove = percent_to_remove def set_input(self, input_data): """ set input data Parameters ---------- input-data : vtkPolyData Returns ------- is...
array_full = numpy_from_polydata(self.input_)
Given the following code snippet before the placeholder: <|code_start|> super(vtkPointSetOutlierEstimation, self).set_input(input_data) return True else: return False def set_percent_to_remove(self, value): self.percent_to_remove = value def update(self): ...
output = polydata_from_numpy(array)
Given the code snippet: <|code_start|> example: reader = ReaderPLY(filename) reader.update() """ def __init__(self, filename): super(ReaderPLY, self).__init__() self.filename_ = filename def _update(self): reader = vtkPLYReader() reader.SetFileName(self.f...
polydata = get_polydata_from(points, tr_re)
Continue the code snippet: <|code_start|> states[1:-1] ) y = self.dense_layer.call(h * states[-1][0]) if 0 < self.dense_dropout: y._uses_learning_phase = True return y, [y] + new_states def get_config(self): config = { 'recurrent_layer': ...
custom_objects['LSTMPeephole'] = LSTMPeephole
Using the snippet: <|code_start|> :note: parsing a name template into a partdict is trivial, so just do it here :note: allow capital part id (to force capitalization) """ #to keep track of the order of the parts... parts_order = '' #split a name template into parts (each part shd have part-designator) tem...
default_citation_template = DEFAULT_CITATION_TEMPLATE.copy()
Continue the code snippet: <|code_start|>""" style1 Edited from bibstuff - jasss_style - details: :contact: http://www.american.edu/cas/econ/faculty/isaac/isaac1.htm :author: Alan G Isaac :license: MIT (see `license.txt`_) :date: 2006-08-01 Modifications Matthew Brett MIT license also """ # import every...
CITATION_TEMPLATE = bbd.CITATION_TEMPLATE.copy()
Predict the next line after this snippet: <|code_start|> `string_or_compiled` : string to compile or compiled regex pattern for searching `field` : string field to search in self (default: search all fields) """ if isinstance(string_or_compiled, str): if ignore_case: reo = re.compile(strin...
bibgrammar.Parse(src, bfile)
Next line prediction: <|code_start|> '''Command-line tool. See jabbrev.py -h for help''' input = sys.stdin output = sys.stdout try: except (ImportError, AttributeError): try: except (ImportError, AttributeError): print "jabbrev needs python 2.3 or Greg Ward's optik ...
bfile = bibfile.BibFile()
Given the following code snippet before the placeholder: <|code_start|> input = sys.stdin output = sys.stdout try: except (ImportError, AttributeError): try: except (ImportError, AttributeError): print "jabbrev needs python 2.3 or Greg Ward's optik module." usag...
bibgrammar.Parse(bib, bfile)
Given the code snippet: <|code_start|> parser.add_option("-V", "--very_verbose", action="store_true", dest="very_verbose", default=False, help="Print DEBUG messages to stdout, default=%default") parser.add_option("-t", "--type", action="store", dest="entry_type", default=''...
bibadd_logger.setLevel(logging.INFO)
Given snippet: <|code_start|> bibfile_name = args[-1] if (os.path.splitext(bibfile_name)[-1]).lower() != ".bib": bib4txt_logger.warning(bibfile_name + " does not appear to be a .bib file") try : bibfile_as_string = open(bibfile_name,'r').read() except : print "Database file not found." sys.exit(1) # re...
entry = make_entry(options.entry_type, options.more_fields, options.MORE_FIELDS)
Continue the code snippet: <|code_start|> except: print "Cannot open: "+options.infile sys.exit(1) # create object to store parsed .bib file bibfile_processor = bibfile.BibFile() #store parsed .bib file in the bibfile_processor # TODO: allow multiple .bib files bibgrammar.Parse(bibfile_as_string, bibfile_...
output.write( html_format(entry) )
Given the code snippet: <|code_start|> sys.exit(1) # create object to store parsed .bib file bibfile_processor = bibfile.BibFile() #store parsed .bib file in the bibfile_processor # TODO: allow multiple .bib files bibgrammar.Parse(bibfile_as_string, bibfile_processor) bfile = bibfile.BibFile() bibgrammar.Pa...
output.write( text_format(entry) )
Continue the code snippet: <|code_start|>from __future__ import absolute_import try: cssmin_available = True except ImportError: cssmin_available = False <|code_end|> . Use current file imports: from cssmin import cssmin from .base import BaseCompressor from ..exceptions import ImproperlyConfigured an...
class CSSMinCompressor(BaseCompressor):
Using the snippet: <|code_start|>from __future__ import absolute_import try: cssmin_available = True except ImportError: cssmin_available = False class CSSMinCompressor(BaseCompressor): def __init__(self): if not cssmin_available: <|code_end|> , determine the next line of code. You have imports...
raise ImproperlyConfigured('cssmin is not available')
Next line prediction: <|code_start|> class DirectivesParserTests(GearsTestCase): fixtures_root = 'directives_parser' def check_asset(self, fixture, directives): source = self.get_source(fixture) output = self.get_output(fixture) <|code_end|> . Use current file imports: (import os from gears....
result = DirectivesParser().parse(source)
Given snippet: <|code_start|> class AssetDependencyTests(GearsTestCase): fixtures_root = 'asset_dependency' def test_dependencies_with_the_same_path_are_equal(self): fixture = 'dependencies_with_the_same_path_are_equal' environment = self.get_environment(fixture) fixture_file = self.f...
dependency1 = Dependency(environment, fixture_file)
Predict the next line for this snippet: <|code_start|> class NeedsSemicolonsTests(TestCase): def test_blank_source(self): self.assertFalse(needs_semicolon(' \t\n')) def test_source_with_semicolon(self): self.assertFalse(needs_semicolon('x;\n ')) def test_source_without_semicolon(self):...
self.assertEqual(str(asset), output)
Continue the code snippet: <|code_start|> class NeedsSemicolonsTests(TestCase): def test_blank_source(self): self.assertFalse(needs_semicolon(' \t\n')) def test_source_with_semicolon(self): self.assertFalse(needs_semicolon('x;\n ')) def test_source_without_semicolon(self): self...
class SemicolonsProcessorTests(GearsTestCase):
Based on the snippet: <|code_start|> class FileBasedCacheTests(TestCase): def setUp(self): self.root = tempfile.mkdtemp() <|code_end|> , predict the immediate next line with the help of imports: import tempfile import shutil from gears.cache import FileBasedCache from unittest2 import TestCase and conte...
self.cache = FileBasedCache(self.root)
Based on the snippet: <|code_start|>from __future__ import absolute_import try: slimit_available = True except ImportError: slimit_available = False <|code_end|> , predict the immediate next line with the help of imports: from slimit import minify from .base import BaseCompressor from ..exceptions impo...
class SlimItCompressor(BaseCompressor):
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import try: slimit_available = True except ImportError: slimit_available = False class SlimItCompressor(BaseCompressor): def __init__(self): if not slimit_available: <|code_end|> with the help of current file...
raise ImproperlyConfigured('Slimit is not available')
Given the code snippet: <|code_start|> def rewrite_paths(source, func): repl = lambda match: 'url({quote}{path}{quote})'.format( quote=match.group(1), path=func(match.group(2)), ) return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = re.compile(r"""ur...
asset = build_asset(self.environment, logical_path)
Predict the next line after this snippet: <|code_start|> def rewrite_paths(source, func): repl = lambda match: 'url({quote}{path}{quote})'.format( quote=match.group(1), path=func(match.group(2)), ) return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = ...
except FileNotFound:
Predict the next line after this snippet: <|code_start|> URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def rewrite_paths(source, func): repl = lambda match: 'url({quote}{path}{quote})'.format( quote=match.group(1), path=func(match.group(2)), ) return URL_RE.sub(repl, source) <...
class HexdigestPathsProcessor(BaseProcessor):
Here is a snippet: <|code_start|> return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset self.environment = self.asset.attributes.environment self.current_d...
elif is_py3:
Given the following code snippet before the placeholder: <|code_start|> path=func(match.group(2)), ) return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset ...
if is_py2:
Based on the snippet: <|code_start|> class BaseFinder(object): def find(self, path): raise NotImplementedError() class FileSystemFinder(BaseFinder): def __init__(self, directories): self.locations = [] if not isinstance(directories, (list, tuple)): <|code_end|> , predict the immedia...
raise ImproperlyConfigured(
Next line prediction: <|code_start|> class BaseFinder(object): def find(self, path): raise NotImplementedError() class FileSystemFinder(BaseFinder): def __init__(self, directories): self.locations = [] if not isinstance(directories, (list, tuple)): raise ImproperlyConfig...
raise FileNotFound(path)
Predict the next line for this snippet: <|code_start|> class FileSystemFinder(BaseFinder): def __init__(self, directories): self.locations = [] if not isinstance(directories, (list, tuple)): raise ImproperlyConfigured( "FileSystemFinder's 'directories' parameter is not ...
path = safe_join(root, path)
Predict the next line after this snippet: <|code_start|> ASSETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'assets')) class FileSystemFinderTests(TestCase): def test_initialization(self): finder = FileSystemFinder(('/first', '/second', '/third', '/first')) self.assertEqual(f...
with self.assertRaises(ImproperlyConfigured):
Given the following code snippet before the placeholder: <|code_start|> def test_if_directories_is_not_iterable(self): with self.assertRaises(ImproperlyConfigured): finder = FileSystemFinder('/first') @patch('os.path.exists') def test_find_location_if_exists(self, exists): exist...
with self.assertRaises(FileNotFound):
Based on the snippet: <|code_start|> ASSETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'assets')) class FileSystemFinderTests(TestCase): def test_initialization(self): <|code_end|> , predict the immediate next line with the help of imports: import os from gears.exceptions import Improperly...
finder = FileSystemFinder(('/first', '/second', '/third', '/first'))
Predict the next line after this snippet: <|code_start|> BLANK_RE = re.compile(r'\A\s*\Z', re.M) SEMICOLON_RE = re.compile(r';\s*\Z', re.M) def needs_semicolon(source): return (BLANK_RE.search(source) is None and SEMICOLON_RE.search(source) is None) <|code_end|> using the current file's imports: ...
class SemicolonsProcessor(BaseProcessor):
Based on the snippet: <|code_start|> class SafeJoinTests(TestCase): def test_if_base_is_not_absolute(self): with self.assertRaisesRegexp(ValueError, 'is not an absolute path'): <|code_end|> , predict the immediate next line with the help of imports: from gears.utils import safe_join from unittest2 import...
safe_join('assets', 'js/script.js')
Given the code snippet: <|code_start|> class RewritePathsTests(TestCase): def check(self, source, expected_result): result = rewrite_paths(source, lambda path: 'new/path') self.assertEqual(result, expected_result) def test_single_quotes(self): self.check("url('../images/logo.png')",...
self.assertEqual(str(asset), output)
Given snippet: <|code_start|> class RewritePathsTests(TestCase): def check(self, source, expected_result): result = rewrite_paths(source, lambda path: 'new/path') self.assertEqual(result, expected_result) def test_single_quotes(self): self.check("url('../images/logo.png')", "url('ne...
class HexdigestPathsProcessorTests(GearsTestCase):
Given the following code snippet before the placeholder: <|code_start|> class AssetDependenciesTests(GearsTestCase): fixtures_root = 'asset_dependencies' def test_adds_dependency_only_once(self): fixture_file = self.find_fixture_file('adds_dependency_only_once', 'dependency') <|code_end|> , predict t...
dependencies = Dependencies(self.get_environment('adds_dependency_only_once'))
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class BaseCompiler(BaseAssetHandler): """Base class for all asset compilers. Subclass's :meth:`__call__` method must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. """ #: MIME type of the asset source code after comp...
class ExecCompiler(BaseCompiler, ExecMixin):
Predict the next line after this snippet: <|code_start|> @mock.patch('gears.compat.builtins.open') class ManifestTests(TestCase): def test_loads_data(self, open): <|code_end|> using the current file's imports: import errno import mock from gears.compat import StringIO from gears.manifest import Manifest from ...
open.return_value.__enter__.return_value = StringIO("""{
Continue the code snippet: <|code_start|> @mock.patch('gears.compat.builtins.open') class ManifestTests(TestCase): def test_loads_data(self, open): open.return_value.__enter__.return_value = StringIO("""{ "files": { "css/style.css": "css/style.123456.css", "js...
manifest = Manifest('manifest.json')
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class AssetAttributes(object): """Provides access to asset path properties. The attributes object is created with environment object and relative (or logical) asset path. Some properties may be useful or not, ...
@cached_property
Based on the snippet: <|code_start|> class Exec(ExecMixin): executable = 'program' class ExecMixinTests(TestCase): @patch('gears.asset_handler.Popen') def test_returns_stdout_on_success(self, Popen): result = Mock() result.returncode = 0 result.communicate.return_value = (b'outpu...
with self.assertRaises(AssetHandlerError):
Next line prediction: <|code_start|>""" Filtering criteria (predicates) """ class Predicate(ABC): @abstractmethod <|code_end|> . Use current file imports: (from abc import ABC, abstractmethod from .qualtrim import expected_errors from .modifiers import ModificationInfo) and context including class names, funct...
def test(self, read, info: ModificationInfo) -> bool:
Predict the next line after this snippet: <|code_start|>""" Adapter finding and trimming classes The ...Adapter classes are responsible for finding adapters. The ...Match classes trim the reads. """ logger = logging.getLogger() class InvalidCharacter(Exception): pass # TODO remove this enum, this should be w...
BACK = EndSkip.QUERY_START | EndSkip.QUERY_STOP | EndSkip.REFERENCE_END
Predict the next line after this snippet: <|code_start|> self.sequence: str = sequence.upper().replace("U", "T") if not self.sequence: raise ValueError("Adapter sequence is empty") if max_errors >= 1 and self.sequence.count("N") != len(self.sequence): max_errors /= len(sel...
def _make_aligner(self, flags: int) -> Aligner:
Given the following code snippet before the placeholder: <|code_start|> # The locate function takes care of uppercasing the sequence alignment = self.aligner.locate(sequence) if self._debug: try: print(self.aligner.dpmatrix) # pragma: no cover except Attri...
return PrefixComparer(
Next line prediction: <|code_start|> if not self.indels: # TODO or if error rate allows 0 errors anyway return PrefixComparer( self.sequence, self.max_error_rate, wildcard_ref=self.adapter_wildcards, wildcard_query=self.read_wildcards, ...
return SuffixComparer(
Predict the next line for this snippet: <|code_start|> if adapter.read_wildcards: raise ValueError("Wildcards in the read not supported") if adapter.adapter_wildcards: raise ValueError("Wildcards in the adapter not supported") k = int(len(adapter) * adapter.max_error_rate)...
environment = edit_environment if adapter.indels else hamming_environment
Given the following code snippet before the placeholder: <|code_start|> if adapter.read_wildcards: raise ValueError("Wildcards in the read not supported") if adapter.adapter_wildcards: raise ValueError("Wildcards in the adapter not supported") k = int(len(adapter) * adapte...
environment = edit_environment if adapter.indels else hamming_environment
Here is a snippet: <|code_start|> class PairedEndStep(ABC): @abstractmethod def __call__( self, read1, read2, info1: ModificationInfo, info2: ModificationInfo ) -> bool: """ Process read pair (read1, read2). Return True if the read pair has been consumed (and should thus not...
def __init__(self, writer, predicate: Predicate):
Using the snippet: <|code_start|>""" Steps of the read output pipeline After all read modifications have been done, a read is written to at most one output file. For this, a pipeline represented as a list of "steps" (SingleEndSteps or PairedEndSteps) is used. Each pipeline step can consume (discard) a read or pass it ...
def __call__(self, read, info: ModificationInfo) -> bool:
Continue the code snippet: <|code_start|>KEEP = False class SingleEndStep(ABC): @abstractmethod def __call__(self, read, info: ModificationInfo) -> bool: """ Process a single read. Return True if the read has been consumed (and should thus not be passed on to subsequent steps). ...
def get_statistics(self) -> ReadLengthStatistics:
Given the code snippet: <|code_start|> print(rest, read.name, file=self._file) return KEEP class WildcardFileWriter(SingleEndStep): def __init__(self, file): self._file = file def __repr__(self): return f"WildcardFileWriter(file={self._file})" def __call__(self, re...
current_read = reverse_complemented_sequence(current_read)
Predict the next line after this snippet: <|code_start|> def avg_pool(input_layer, **kwargs): # hack to work around https://github.com/Theano/Theano/issues/3776 norm = nn.layers.ExpressionLayer(input_layer, lambda X: T.ones_like(X)) norm = nn.layers.Pool2DLayer(norm, mode='average_inc_pad', **kwargs) l...
l1 = conv2dbn(
Based on the snippet: <|code_start|> def conv2dbn(l, name, **kwargs): """ Batch normalized DNN Conv2D Layer """ l = nn.layers.dnn.Conv2DDNNLayer( l, name=name, **kwargs ) <|code_end|> , predict the immediate next line with the help of imports: import lasagne as nn from lasagne.layers impor...
l = batch_norm(l, name='%sbn' % name)
Predict the next line after this snippet: <|code_start|> model = load_model(args.model) net = model.net net.initialize() print 'Loading model weights from %s' % model.model_fname net.load_params_from(model.model_fname) print if args.mean_fname is not None: print 'Loading mean image' ...
tta = TestTimeAutgmentationPredictor(
Predict the next line for this snippet: <|code_start|> assert DEL == tuple() class Test_OrderedComparator: def setup(self): self.comparator = OrderedComparator() def test_extra_in_DEL(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), prese...
self.comparator = UniqueKeyComparator( keys=('name',) )
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- @pytest.fixture def compare_data(request): single = { 'wanted':CmdPathRow({"primary-ntp":"1.1.1.1"}), 'present':CmdPathRow({"primary-ntp":"213.222.193.35"}), 'difference':CmdPathRow({"primary-ntp":"1.1.1.1"}), } default ...
self.comparator = SingleElementComparator()
Based on the snippet: <|code_start|>class Test_SingleComparator: def setup(self): self.comparator = SingleElementComparator() def test_difference_in_SET(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), present=(compare_data['present'],)) as...
self.comparator = OrderedComparator()
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*- @pytest.fixture def compare_data(request): single = { <|code_end|> . Use current file imports: import pytest from mcm.comparators import UniqueKeyComparator, SingleElementComparator, OrderedComparator from mcm.datastructures import CmdPathRow an...
'wanted':CmdPathRow({"primary-ntp":"1.1.1.1"}),
Given snippet: <|code_start|># -*- coding: UTF-8 -*- class Api: def __init__( self, rwo ): self.rwo = rwo def run( self, cmd, args = dict() ): ''' Run any 'non interactive' command. Returns parsed response. cmd Command word eg. /ip/address/print. args Dictionary ...
snt = (cmd,) + mksnt( args )
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*- class Api: def __init__( self, rwo ): self.rwo = rwo def run( self, cmd, args = dict() ): ''' Run any 'non interactive' command. Returns parsed response. cmd Command word eg. /ip/address/print. args Diction...
return parsresp( response )
Given snippet: <|code_start|># -*- coding: UTF-8 -*- class Api: def __init__( self, rwo ): self.rwo = rwo def run( self, cmd, args = dict() ): ''' Run any 'non interactive' command. Returns parsed response. cmd Command word eg. /ip/address/print. args Dictionary ...
trapCheck( response )
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- class Api: def __init__( self, rwo ): self.rwo = rwo def run( self, cmd, args = dict() ): ''' Run any 'non interactive' command. Returns parsed response. cmd Command word eg. /ip/address/print. args Diction...
raiseIfFatal( response )
Given the code snippet: <|code_start|> def _readResponse( self ): ''' Read whole response. returns Read sentences as tuple. ''' snts = [] while True: snt = self.rwo.readSnt() snts.append( snt ) if '!done' in snt: ...
except LibError:
Next line prediction: <|code_start|># -*- coding: UTF-8 -*- def get_password(): try: return environ['MCM_HOST_PASSWORD'] except KeyError: return getpass() class JsonFile: def __call__(self, file): try: with open(file, mode='rt', encoding='UTF-8', errors='strict') a...
description='Mikrotik Configuration Manager. Version ' + str(__version__))