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 notifications: ' 'http://example.com/accounts/profile/\n') def setUp(self): self.command = notify_upcoming_period.Command() <|code_end|> , generate the next line using the imports in this file: import datetime import pytz from django.conf import settings from django.test import TestCase from mock import ANY, patch from periods import models as period_models from periods.management.commands import notify_upcoming_period from periods.tests.factories import FlowEventFactory and context (functions, classes, or occasionally code) from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/management/commands/notify_upcoming_period.py # class Command(BaseCommand): # def _format_date(self, date_value): # def handle(self, *args, **options): # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True . Output only the next line.
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 = NullableEnumField(period_models.ClotSize) result = field.to_internal_value('1') self.assertEqual(1, result) class TestFlowEventViewSet(TestCase): def setUp(self): FlowEventFactory() <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import TestCase from rest_framework.renderers import JSONRenderer from periods import models as period_models from periods.serializers import FlowEventSerializer, NullableEnumField from periods.tests.factories import FlowEventFactory and context: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/serializers.py # class FlowEventSerializer(serializers.ModelSerializer): # clots = NullableEnumField(period_models.ClotSize) # cramps = NullableEnumField(period_models.CrampLevel) # # class Meta: # model = period_models.FlowEvent # exclude = ('user',) # # class NullableEnumField(serializers.ChoiceField): # """ # Field that handles empty entries for EnumFields # """ # # def __init__(self, enum, **kwargs): # super(NullableEnumField, self).__init__(enum.choices(), allow_blank=True, required=False) # # def to_internal_value(self, data): # if data == '' and self.allow_blank: # return None # # return super(NullableEnumField, self).to_internal_value(data) # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True which might include code, classes, or functions. Output only the next line.
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): field = NullableEnumField(period_models.ClotSize) result = field.to_internal_value('1') self.assertEqual(1, result) class TestFlowEventViewSet(TestCase): def setUp(self): <|code_end|> , generate the next line using the imports in this file: from django.test import TestCase from rest_framework.renderers import JSONRenderer from periods import models as period_models from periods.serializers import FlowEventSerializer, NullableEnumField from periods.tests.factories import FlowEventFactory and context (functions, classes, or occasionally code) from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/serializers.py # class FlowEventSerializer(serializers.ModelSerializer): # clots = NullableEnumField(period_models.ClotSize) # cramps = NullableEnumField(period_models.CrampLevel) # # class Meta: # model = period_models.FlowEvent # exclude = ('user',) # # class NullableEnumField(serializers.ChoiceField): # """ # Field that handles empty entries for EnumFields # """ # # def __init__(self, enum, **kwargs): # super(NullableEnumField, self).__init__(enum.choices(), allow_blank=True, required=False) # # def to_internal_value(self, data): # if data == '' and self.allow_blank: # return None # # return super(NullableEnumField, self).to_internal_value(data) # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True . Output only the next line.
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', 'user__first_name', 'user__last_name', 'timestamp', 'level', 'color', 'clots', 'cramps', 'comment'] class StatisticsAdmin(admin.ModelAdmin): list_display = ['__str__', 'average_cycle_length'] search_fields = ['user__email', 'user__first_name', 'user__last_name'] class UserAdmin(EmailUserAdmin): list_display = ['email', 'first_name', 'last_name', 'cycle_count', 'date_joined', 'is_active', 'send_emails'] fieldsets = ( (None, {'fields': ('first_name', 'last_name', 'email', 'password')}), (_('Settings'), {'fields': ('_timezone', 'send_emails', 'luteal_phase_length', 'birth_date')}), (_('General Information'), {'fields': ('last_login', 'date_joined', 'cycle_count')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) search_fields = ['email', 'first_name', 'last_name'] readonly_fields = ['cycle_count'] <|code_end|> , predict the next line using imports from the current file: from custom_user.admin import EmailUserAdmin from django.contrib import admin from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from periods import models and context including class names, function names, and sometimes code from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 . Output only the next line.
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.get_short_name())) def test_get_short_name(self): self.assertEqual(u'Jessamyn', '%s' % self.user.get_short_name()) def test_str(self): self.assertTrue(re.match(r'user_[\d]+@example.com \(user_[\d]+@example.com\)', '%s' % self.basic_user)) class TestFlowEvent(TestCase): def setUp(self): self.period = FlowEventFactory() def test_str(self): self.assertEqual('Jessamyn Medium (2014-01-31 17:00:00+00:00)', '%s' % self.period) class TestStatistics(TestCase): def setUp(self): self.user = UserFactory() self.period = FlowEventFactory() def test_str(self): <|code_end|> using the current file's imports: import datetime import pytz import re import requests from django.conf import settings from django.contrib.auth import models as auth_models from django.test import TestCase from mock import MagicMock, patch from periods import models as period_models from periods.tests.factories import FlowEventFactory, UserFactory and any relevant context from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True # # 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" % n) # password = factory.PostGenerationMethodCall('set_password', PASSWORD) # last_login = pytz.utc.localize(datetime.datetime(2015, 3, 1)) . Output only the next line.
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 current file: import datetime import pytz import re import requests from django.conf import settings from django.contrib.auth import models as auth_models from django.test import TestCase from mock import MagicMock, patch from periods import models as period_models from periods.tests.factories import FlowEventFactory, UserFactory and context including class names, function names, and sometimes code from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True # # 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" % n) # password = factory.PostGenerationMethodCall('set_password', PASSWORD) # last_login = pytz.utc.localize(datetime.datetime(2015, 3, 1)) . Output only the next line.
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 django.test import TestCase from mock import MagicMock, patch from periods import models as period_models from periods.tests.factories import FlowEventFactory, UserFactory and context (classes, functions, or code) from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True # # 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" % n) # password = factory.PostGenerationMethodCall('set_password', PASSWORD) # last_login = pytz.utc.localize(datetime.datetime(2015, 3, 1)) . Output only the next line.
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 datetime from django.conf import settings from django.core.management.base import BaseCommand from django.template.loader import get_template from periods import models as period_models, email_sender, helpers and context (class names, function names, or code) available: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/email_sender.py # def send(recipient, subject, text_body, html_body): # # Path: periods/helpers.py # def get_full_domain(): . Output only the next line.
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 Counter from django.conf import settings from django.contrib import auth from django.contrib.auth.mixins import LoginRequiredMixin from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.dateparse import parse_datetime from django.views.generic import CreateView, TemplateView, UpdateView from extra_views import ModelFormSetView from jsonview.views import JsonView from rest_framework import permissions, status, viewsets from rest_framework.authtoken.models import Token from rest_framework.response import Response from rest_framework.views import APIView from periods import forms as period_forms, models as period_models, serializers import datetime import itertools import math import pytz and context (functions, classes, or occasionally code) from other files: # Path: periods/forms.py # class PeriodForm(forms.ModelForm): # class Meta: # # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/serializers.py # class NullableEnumField(serializers.ChoiceField): # class FlowEventSerializer(serializers.ModelSerializer): # class Meta: # class FlowEventFilter(django_filters.FilterSet): # class Meta: # class StatisticsSerializer(serializers.ModelSerializer): # class Meta: # def __init__(self, enum, **kwargs): # def to_internal_value(self, data): . Output only the next line.
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" % n) password = factory.PostGenerationMethodCall('set_password', PASSWORD) last_login = pytz.utc.localize(datetime.datetime(2015, 3, 1)) class FlowEventFactory(factory.DjangoModelFactory): class Meta: <|code_end|> , determine the next line of code. You have imports: import datetime import factory import pytz from django.contrib.auth import get_user_model from periods import models as period_models and context (class names, function names, or code) available: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 . Output only the next line.
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, timestamp=TIMEZONE.localize(datetime.datetime(2014, 2, 28))) @patch('django.core.mail.EmailMultiAlternatives.send') def test_email_active_users_no_periods(self, mock_send): <|code_end|> . Use current file imports: (import datetime import pytz from django.test import TestCase from mock import patch from periods import models as period_models from periods.management.commands import email_active_users from periods.tests.factories import FlowEventFactory) and context including class names, function names, or small code snippets from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/management/commands/email_active_users.py # class Command(BaseCommand): # def add_arguments(self, parser): # def handle(self, *args, **options): # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True . Output only the next line.
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 patch from periods import models as period_models from periods.management.commands import email_active_users from periods.tests.factories import FlowEventFactory and context including class names, function names, and sometimes code from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/management/commands/email_active_users.py # class Command(BaseCommand): # def add_arguments(self, parser): # def handle(self, *args, **options): # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True . Output only the next line.
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 from mock import patch from periods import models as period_models from periods.management.commands import email_active_users from periods.tests.factories import FlowEventFactory and context: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/management/commands/email_active_users.py # class Command(BaseCommand): # def add_arguments(self, parser): # def handle(self, *args, **options): # # Path: periods/tests/factories.py # class FlowEventFactory(factory.DjangoModelFactory): # class Meta: # model = period_models.FlowEvent # # user = factory.SubFactory(UserFactory) # timestamp = pytz.utc.localize(datetime.datetime(2014, 1, 31, 17, 0, 0)) # first_day = True which might include code, classes, or functions. Output only the next line.
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.EmailMultiAlternatives.send') def test_send_text_only(self, mock_send): <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import get_user_model from django.test import TestCase from mock import patch from periods import email_sender and context including class names, function names, and sometimes code from other files: # Path: periods/email_sender.py # def send(recipient, subject, text_body, html_body): . Output only the next line.
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 Django to NOT prompt the user for input of any kind.') def handle(self, *args, **options): interactive = options.get('interactive') <|code_end|> . Write the next line using the current file imports: from django.core.management.base import BaseCommand from django.template.loader import get_template from periods import models as period_models, email_sender and context from other files: # Path: periods/models.py # def today(): # def timezone(self): # def first_days(self): # def cycle_count(self): # def get_previous_period(self, previous_to): # def get_next_period(self, after=None): # def get_cache_key(self, data_type): # def get_cycle_lengths(self): # def get_sorted_cycle_lengths(self): # def get_full_name(self): # def get_short_name(self): # def __str__(self): # def choices(cls, blank=False): # def __str__(self): # def _get_ordinal_value(self, index): # def cycle_length_minimum(self): # def cycle_length_maximum(self): # def _get_statistics_value(self, method_name, num_values_required=1): # def cycle_length_mean(self): # def cycle_length_median(self): # def cycle_length_mode(self): # def cycle_length_standard_deviation(self): # def current_cycle_length(self): # def first_date(self): # def first_day(self): # def set_start_date_and_day(self, min_timestamp): # def predicted_events(self): # def __str__(self): # def get_from_server(from_date): # def get_for_date(cls, from_date, to_date): # def create_auth_token(sender, instance=None, created=False, **kwargs): # def add_to_permissions_group(sender, instance, **kwargs): # def create_statistics(sender, instance, **kwargs): # def update_statistics(sender, instance, **kwargs): # class User(AbstractEmailUser): # class LabelChoicesEnum(enum.Enum): # class FlowLevel(LabelChoicesEnum): # class FlowColor(LabelChoicesEnum): # class ClotSize(LabelChoicesEnum): # class CrampLevel(LabelChoicesEnum): # class FlowEvent(models.Model): # class Statistics(models.Model): # class Meta: # class AerisData(models.Model): # SPOTTING = 0 # LIGHT = 1 # MEDIUM = 2 # HEAVY = 3 # VERY_HEAVY = 4 # PINK = 0 # LIGHT_RED = 1 # RED = 2 # DARK_RED = 3 # BROWN = 4 # BLACK = 5 # SMALL = 0 # MEDIUM = 1 # LARGE = 2 # SLIGHT = 0 # MODERATE = 1 # SEVERE = 2 # # Path: periods/email_sender.py # def send(recipient, subject, text_body, html_body): , which may include functions, classes, or code. Output only the next line.
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): self.remove_filter() <|code_end|> , predict the immediate next line with the help of imports: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import pyqtSignal as Signal from .widgetGenerator import widget_generator and context (classes, functions, sometimes code) from other files: # Path: pcloudpy/gui/components/widgetGenerator.py # def widget_generator(func, parms, text="", only_apply=False): # # class TemplateWidget(QWidget): # def __init__(self, parent=None, func=None, parms=None, text="", only_apply=False): # super(TemplateWidget, self).__init__(parent) # self.parms = None # self.func = func # self.only_apply = only_apply # # if only_apply: # self.init_apply(text) # else: # if parms is not None: # 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("apply") # self.apply_button.setFixedSize(60,60) # grid.addWidget(self.apply_button, 0, 0) # # html = markdown2.markdown(str(text)) # textEdit = QTextEdit(html) # textEdit.setMinimumWidth(350) # textEdit.setMinimumHeight(350) # textEdit.setReadOnly(True) # grid.addWidget(textEdit,1, 0, 1, 5) # # self.setLayout(grid) # # # def init_params(self, parms, text): # self.parms = dict(parms) # # grid = QGridLayout() # index = 0 # for (k,v) in parms.items(): # # if v['type'] == "Extent": # item = customWidgets.Extent() # item.setObjectName(k) # grid.addWidget(item, index, 0, 1, 1) # else: # item = getattr(customWidgets, v['type'])() # item.setObjectName(k) # item.set_values(*map(float,v['values'].strip().split(','))) # item.setToolTip(v.get('tooltip', "")) # # grid.addWidget(QLabel(k), index, 0, 1, 1) # grid.addWidget(item, index, 1, 1, 1) # # index += 1 # # self.apply_button = QPushButton("Apply") # self.apply_button.setObjectName("apply") # self.apply_button.setFixedSize(60,60) # # grid.addWidget(self.apply_button, 0, 3, index, 3) # # html = markdown2.markdown(str(text)) # textEdit = QTextEdit(html) # textEdit.setMinimumWidth(350) # textEdit.setMinimumHeight(350) # textEdit.setReadOnly(True) # grid.addWidget(textEdit,index, 0, 1, 5) # # self.setLayout(grid) # # def init_text(self, text): # # html = markdown2.markdown(str(text)) # # textEdit = QTextEdit(html) # textEdit.setMinimumWidth(350) # textEdit.setMinimumHeight(350) # textEdit.setReadOnly(True) # # vBox = QVBoxLayout() # vBox.addWidget(textEdit) # # self.setLayout(vBox) # # def get_parms(self): # # if self.only_apply: # return self.func, dict() # # if self.parms: # d = dict() # for (k,v) in self.parms.items(): # if v['type'] =="Extent": # d[k] = self.findChild(customWidgets.Extent, k).get_extent() # else: # item = self.findChild(getattr(customWidgets, v['type']), k) # d[k] = item.get_values() # return self.func, d # # return TemplateWidget(None, func, parms, text=text, only_apply=only_apply) . Output only the next line.
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("apply") self.apply_button.setFixedSize(60,60) grid.addWidget(self.apply_button, 0, 0) html = markdown2.markdown(str(text)) textEdit = QTextEdit(html) textEdit.setMinimumWidth(350) textEdit.setMinimumHeight(350) textEdit.setReadOnly(True) grid.addWidget(textEdit,1, 0, 1, 5) self.setLayout(grid) def init_params(self, parms, text): self.parms = dict(parms) grid = QGridLayout() index = 0 for (k,v) in parms.items(): if v['type'] == "Extent": <|code_end|> , predict the immediate next line with the help of imports: import markdown2 from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import pyqtSignal as Signal from pcloudpy.gui.components import customWidgets and context (classes, functions, sometimes code) from other files: # Path: pcloudpy/gui/components/customWidgets.py # class LineEdit(QLineEdit): # class SpinBox(QSpinBox): # class DoubleSpinBox(QDoubleSpinBox): # class CheckBox(QCheckBox): # class Extent(QWidget): # def __init__(self, parent=None): # def __init__(self, parent=None): # def set_values(self, vmin, vmax, step, value): # def get_values(self): # def __init__(self, parent=None): # def set_values(self, vmin, vmax, step, value): # def get_values(self): # def __init__(self, parent=None): # def set_values(self, value): # def get_values(self): # def __init__(self, parent=None): # def get_extent(self): . Output only the next line.
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): """ 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): super(ScreenedPoisson, self).set_input(input_data) return True else: return False def update(self): <|code_end|> . Use current file imports: (import numpy as np from vtk import vtkPolyData from pcloudpy.core.filters.base import FilterBase from ..io.converters import get_points_normals_from, get_polydata_from from pypoisson import poisson_reconstruction) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def get_points_normals_from(polydata): # # nodes_vtk_array = polydata.GetPoints().GetData() # array = vtk_to_numpy(nodes_vtk_array) # # numberArrays = polydata.GetPointData().GetNumberOfArrays() # for i in range(numberArrays): # if polydata.GetPointData().GetArrayName(i) == "Normals": # array_normals = vtk_to_numpy(polydata.GetPointData().GetScalars("Normals")) # return array, array_normals # else: # raise Exception("No available Normals") # # def get_polydata_from(points, tr_re): # # numberPoints = len(points) # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(numberPoints) # Points.SetData(points_vtk) # # Triangles = vtkCellArray() # for item in tr_re: # Triangle = vtkTriangle() # Triangle.GetPointIds().SetId(0,item[0]) # Triangle.GetPointIds().SetId(1,item[1]) # Triangle.GetPointIds().SetId(2,item[2]) # Triangles.InsertNextCell(Triangle) # # polydata = vtkPolyData() # polydata.SetPoints(Points) # polydata.SetPolys(Triangles) # # polydata.Modified() # polydata.Update() # # return polydata . Output only the next line.
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 ------- is_valid: bool Returns True if the input_data is valid for processing """ if isinstance(input_data, vtkPolyData): super(ScreenedPoisson, self).set_input(input_data) return True else: return False def update(self): points, normals = get_points_normals_from(self.input_) faces, vertices = poisson_reconstruction(points, normals, depth=self.depth) <|code_end|> . Use current file imports: (import numpy as np from vtk import vtkPolyData from pcloudpy.core.filters.base import FilterBase from ..io.converters import get_points_normals_from, get_polydata_from from pypoisson import poisson_reconstruction) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def get_points_normals_from(polydata): # # nodes_vtk_array = polydata.GetPoints().GetData() # array = vtk_to_numpy(nodes_vtk_array) # # numberArrays = polydata.GetPointData().GetNumberOfArrays() # for i in range(numberArrays): # if polydata.GetPointData().GetArrayName(i) == "Normals": # array_normals = vtk_to_numpy(polydata.GetPointData().GetScalars("Normals")) # return array, array_normals # else: # raise Exception("No available Normals") # # def get_polydata_from(points, tr_re): # # numberPoints = len(points) # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(numberPoints) # Points.SetData(points_vtk) # # Triangles = vtkCellArray() # for item in tr_re: # Triangle = vtkTriangle() # Triangle.GetPointIds().SetId(0,item[0]) # Triangle.GetPointIds().SetId(1,item[1]) # Triangle.GetPointIds().SetId(2,item[2]) # Triangles.InsertNextCell(Triangle) # # polydata = vtkPolyData() # polydata.SetPoints(Points) # polydata.SetPolys(Triangles) # # polydata.Modified() # polydata.Update() # # return polydata . Output only the next line.
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.filename_) band = dataset.GetRasterBand(1) self.data_ = band.ReadAsArray().astype(np.float32) vmin = self.data_.min() data = np.uint8(255*(self.data_-vmin)/ float(self.data_.max()-vmin)) <|code_end|> . Use current file imports: (import gdal import numpy as np from ..utils.vtkhelpers import numpy_to_image from .base import ImageDataBase) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def numpy_to_image(numpy_array): # """ # @brief Convert a numpy 2D or 3D array to a vtkImageData object # @param numpy_array 2D or 3D numpy array containing image data # @return vtkImageData with the numpy_array content # """ # # shape = numpy_array.shape # if len(shape) < 2: # raise Exception('numpy array must have dimensionality of at least 2') # # h, w = shape[0], shape[1] # c = 1 # if len(shape) == 3: # c = shape[2] # # # Reshape 2D image to 1D array suitable for conversion to a # # vtkArray with numpy_support.numpy_to_vtk() # linear_array = np.reshape(numpy_array, (w*h, c)) # vtk_array = numpy_to_vtk(linear_array) # # image = vtkImageData() # image.SetDimensions(w, h, 1) # image.AllocateScalars() # image.GetPointData().GetScalars().DeepCopy(vtk_array) # # return image # # Path: pcloudpy/core/io/base.py # 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.type_ = DataType.IMAGEDATA # # def get_imagedata(self): # """ # Gets ImageData # """ # if self._imagedata: # return self._imagedata # # def set_imagedata(self, imagedata): # """ # Sets ImageData # """ # self._imagedata = imagedata # self._actor = actor_from_imagedata(self._imagedata) # self.update_props() # # def _update(self): # pass # # def update(self): # self._update() # self.set_imagedata(self._imagedata) # self.update_props() # # def clone(self): # """ # Returns a Clone of an ImageDataBase instance # """ # imagedata = vtkImageData() # imagedata.DeepCopy(self._imagedata) # clone = copy.copy(self) # clone.set_imagedata(imagedata) # clone.set_actor(actor_from_imagedata(self._imagedata)) # return clone # # def update_props(self): # # if self._imagedata: # self.props_ = OrderedDict() # self.props_["Number of Points"] = self._imagedata.GetNumberOfPoints() # bounds = self._imagedata.GetBounds() # # self.props_["xmin"] = bounds[0] # self.props_["xmax"] = bounds[1] # self.props_["ymin"] = bounds[2] # self.props_["ymax"] = bounds[3] # self.props_["zmin"] = np.min(self.data_) # self.props_["zmax"] = np.max(self.data_) . Output only the next line.
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(self): """ """ if self._current_view: return self._current_view.manager_layer.layers() def addObject(self, obj, name): """ """ <|code_end|> using the current file's imports: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import pyqtSignal as Signal from pcloudpy.gui.ManagerLayer import Layer and any relevant context from other files: # Path: pcloudpy/gui/ManagerLayer.py # class Layer(object): # """ # Layer Class # # Attributes # ---------- # # _container: pcloudpy.core.io.base.DataBase # # _current_view: pcloudpy.gui.components.ViewWidget # # _is_visible: Bool # # _name: String # # # """ # def __init__(self, name): # # self._name = name # self._is_visible = True # self._current_view = None # self._container = None # # def set_name(self, name): # self._name = name # # def get_name(self): # return self._name # # def set_current_view(self, view): # self._current_view = view # # def get_current_view(self): # return self._current_view # # def get_visibility(self): # return self._is_visible # # def set_visibility(self, state): # self._is_visible = state # # def set_container(self, container): # self._container = container # # def get_container(self): # if self._container: # return self._container # # def copy(self): # layer = copy.copy(self) # layer.set_name(self._name + "_clone") # layer.set_container(self._container.clone()) # return layer . Output only the next line.
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 Attributes ---------- 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): <|code_end|> , generate the next line using the imports in this file: import numpy as np import networkx as nx from scipy.linalg import eigh from sklearn.neighbors import NearestNeighbors from pcloudpy.core.filters.base import FilterBase from ..io.converters import numpy_from_polydata, copy_polydata_add_normals and context (functions, classes, or occasionally code) from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def copy_polydata_add_normals(polydata, normals): # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # normals_vtk = numpy_to_vtk(np.asarray(normals[:,0:3], order='C',dtype=ntype), deep=1) # normals_vtk.SetName("Normals") # # output = vtkPolyData() # output.ShallowCopy(polydata) # output.GetPointData().SetNormals(normals_vtk) # return output . Output only the next line.
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][c],:] dot = np.dot(n1,n2) G.add_edge(p1,p2,weight =1-np.abs(dot)) T = nx.minimum_spanning_tree(G) x=[] for i in nx.dfs_edges(T,z_max_point): x+=i inds = np.where(np.diff(x))[0] out = np.split(x,inds[np.diff(inds)==1][1::2]+1) for j in range(0,len(out)): for i in range(0,len(out[j])-1): n1 = normals[out[j][i],:] n2 = normals[out[j][i+1],:] if np.dot(n2,n1)<0: normals[out[j][i+1],:]=-normals[out[j][i+1],:] <|code_end|> , generate the next line using the imports in this file: import numpy as np import networkx as nx from scipy.linalg import eigh from sklearn.neighbors import NearestNeighbors from pcloudpy.core.filters.base import FilterBase from ..io.converters import numpy_from_polydata, copy_polydata_add_normals and context (functions, classes, or occasionally code) from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def copy_polydata_add_normals(polydata, normals): # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # normals_vtk = numpy_to_vtk(np.asarray(normals[:,0:3], order='C',dtype=ntype), deep=1) # normals_vtk.SetName("Normals") # # output = vtkPolyData() # output.ShallowCopy(polydata) # output.GetPointData().SetNormals(normals_vtk) # return output . Output only the next line.
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.type_ = DataType.IMAGEDATA def get_imagedata(self): """ Gets ImageData """ if self._imagedata: return self._imagedata def set_imagedata(self, imagedata): """ Sets ImageData """ self._imagedata = imagedata <|code_end|> . Write the next line using the current file imports: from collections import OrderedDict from vtk import vtkPolyData, vtkImageData from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy import copy import numpy as np and context from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData , which may include functions, classes, or code. Output only the next line.
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(PolyDataBase, self).__init__() self.type_ = DataType.POLYDATA def get_polydata(self): """ Gets PolyData (vtkPolyData) """ if self._polydata: return self._polydata def set_polydata(self, polydata): self._polydata = polydata <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from vtk import vtkPolyData, vtkImageData from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy import copy import numpy as np and context (classes, functions, sometimes code) from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData . Output only the next line.
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._update() self.set_polydata(self._polydata) self.update_props() def _update(self): pass def clone(self): polydata = vtkPolyData() polydata.DeepCopy(self._polydata) clone = copy.copy(self) clone.set_polydata(polydata) clone.set_actor(actor_from_polydata(polydata)) return clone def update_data_from(self, polydata): <|code_end|> . Write the next line using the current file imports: from collections import OrderedDict from vtk import vtkPolyData, vtkImageData from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy import copy import numpy as np and context from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData , which may include functions, classes, or code. Output only the next line.
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_["zmax"] = bounds[5] class PointsCloudBase(PolyDataBase): """ Point Cloud Base Class Attributes ---------- data_: Array store array od points of the the point cloud """ def __init__(self, *args, **kwargs): super(PointsCloudBase, self).__init__(*args, **kwargs) self.type_ = DataType.POINTCLOUD def update(self): self._update() <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import OrderedDict from vtk import vtkPolyData, vtkImageData from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy import copy import numpy as np and context: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData which might include code, classes, or functions. Output only the next line.
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): super(StatisticalOutlierRemovalFilter, self).set_input(input_data) return True else: return False def set_mean_k(self, value): self.mean_k = value def set_std_dev(self, value): self.std_dev = value def update(self): """ Compute filter. """ <|code_end|> . Use current file imports: (import numpy as np from vtk import vtkPoints, vtkCellArray, vtkPolyData from sklearn.neighbors import KDTree from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy from pcloudpy.core.filters.base import FilterBase) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData # # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass . Output only the next line.
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[:, :], k = self.mean_k + 1) dx, idx_knn = dx[:,1:], idx_knn[:,1:] den = (self.mean_k - 1.0) if den == 0: den = 1 distances = np.sum(dx, axis=1)/den valid_distances = np.shape(distances)[0] #Estimate the mean and the standard deviation of the distance vector sum = np.sum(distances) sq_sum = np.sum(distances**2) mean = sum / float(valid_distances) variance = (sq_sum - sum * sum / float(valid_distances)) / (float(valid_distances) - 1) stddev = np.sqrt (variance) # a distance that is bigger than this signals an outlier distance_threshold = mean + self.std_dev * stddev idx = np.nonzero(distances < distance_threshold) new_array = np.copy(array[idx]) new_color = np.copy(color[idx]) <|code_end|> , predict the next line using imports from the current file: import numpy as np from vtk import vtkPoints, vtkCellArray, vtkPolyData from sklearn.neighbors import KDTree from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy from pcloudpy.core.filters.base import FilterBase and context including class names, function names, and sometimes code from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData # # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass . Output only the next line.
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 import vtkPolyDataAlgorithm, vtkFloatArray, vtkKdTree, vtkPlane, vtkPolyData, vtkIdList from scipy.linalg import eigh import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass . Output only the next line.
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.setHeaderHidden(True) self.tree.setObjectName("Toolbox-Tree") layout.addWidget(self.tree) self.setLayout(layout) self.tree.clicked.connect(self.click_item) currentItemClicked = Signal() currentItemSelected = Signal() def init_tree(self, data): model = QStandardItemModel() root = model.invisibleRootItem() for key in data.keys(): item = QStandardItem(key) item.setIcon(QIcon(":/toolbox-icon.png")) item.setFlags(item.flags() & ~Qt.ItemIsEditable) root.appendRow(item) for child in data[key]: <|code_end|> , predict the next line using imports from the current file: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import pyqtSignal as Signal from ..resources_rc import * from .toolboxTreeWidgetItem import ToolBoxTreeWidgetItem from .toolboxStandardItem import ToolboxStandardItem and context including class names, function names, and sometimes code from other files: # Path: pcloudpy/gui/components/toolboxTreeWidgetItem.py # class ToolBoxTreeWidgetItem(QTreeWidgetItem): # def __init__(self, parent=None, type=QTreeWidgetItem.UserType + 2): # super(ToolBoxTreeWidgetItem, self).__init__(parent, type) # # self.setIcon(0,QIcon(":/Toolbox-50.png")) # self._objectName = None # self._metadata = None # # def setText(self, column, text): # super(ToolBoxTreeWidgetItem, self).setText(column, text) # self.setObjectName(text.replace(" ","-")) # # def setMetadata(self, metadata): # self._metadata = metadata # # def metadata(self): # return self._metadata # # # def setObjectName(self, name): # self._objectName = name # # def objectName(self): # return self._objectName # # Path: pcloudpy/gui/components/toolboxStandardItem.py # class ToolboxStandardItem(QStandardItem): # def __init__(self, *args, **kwargs): # super(ToolboxStandardItem, self).__init__(*args, **kwargs) # # self._metadata = None # self.setFlags(self.flags() & ~Qt.ItemIsEditable) # self.setIcon(QIcon(":/Toolbox-50.png")) # self._objectName = None # self._metadata = None # # def setText(self, text): # super(ToolboxStandardItem, self).setText(text) # self.setObjectName(text.replace(" ","-")) # # def setMetadata(self, metadata): # self._metadata = metadata # # def metadata(self): # return self._metadata # # def setObjectName(self, name): # self._objectName = name # # def objectName(self): # return self._objectName . Output only the next line.
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 Attributes ---------- 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): <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from scipy.linalg import eigh from sklearn.neighbors import NearestNeighbors from pcloudpy.core.filters.base import FilterBase from ..io.converters import numpy_from_polydata, copy_polydata_add_normals and context: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def copy_polydata_add_normals(polydata, normals): # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # normals_vtk = numpy_to_vtk(np.asarray(normals[:,0:3], order='C',dtype=ntype), deep=1) # normals_vtk.SetName("Normals") # # output = vtkPolyData() # output.ShallowCopy(polydata) # output.GetPointData().SetNormals(normals_vtk) # return output which might include code, classes, or functions. Output only the next line.
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.input_) normals = np.empty_like(array_with_color[:,0:3]) coord = array_with_color[:,0:3] neigh = NearestNeighbors(self.number_neighbors) neigh.fit(coord) for i in range(0,len(coord)): #Determine the neighbours of point d = neigh.kneighbors(coord[i]) #Add coordinates of neighbours , dont include center point to array. Determine coordinate by the index of the neighbours. y = np.zeros((self.number_neighbors-1,3)) y = coord[d[1][0][1:self.number_neighbors],0:3] #Get information content #Assign information content to each point i.e xyzb normals[i,0:3] = self.get_normals(y) <|code_end|> . Write the next line using the current file imports: import numpy as np from scipy.linalg import eigh from sklearn.neighbors import NearestNeighbors from pcloudpy.core.filters.base import FilterBase from ..io.converters import numpy_from_polydata, copy_polydata_add_normals and context from other files: # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def copy_polydata_add_normals(polydata, normals): # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # normals_vtk = numpy_to_vtk(np.asarray(normals[:,0:3], order='C',dtype=ntype), deep=1) # normals_vtk.SetName("Normals") # # output = vtkPolyData() # output.ShallowCopy(polydata) # output.GetPointData().SetNormals(normals_vtk) # return output , which may include functions, classes, or code. Output only the next line.
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_valid: bool Returns True if the input_data is valid for processing """ if isinstance(input_data, vtkPolyData): 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): <|code_end|> . Use current file imports: (import numpy as np from vtk import vtkPoints, vtkCellArray, vtkPolyData, vtkIdList from vtk import vtkKdTreePointLocator from vtk import vtkSphereSource, vtkXMLPolyDataWriter, vtkVertexGlyphFilter from sklearn.neighbors import KDTree from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy from pcloudpy.core.filters.base import FilterBase) and context including class names, function names, or small code snippets from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData # # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass . Output only the next line.
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): array_full = numpy_from_polydata(self.input_) array = array_full[:,0:3] color = array_full[:,3:] #KDTree object (sklearn) kDTree = KDTree(array) dx, _ = kDTree.query(array[:, :], k = 2) dx = dx[:,1:].ravel() Indices = np.argsort(dx, axis=0) Npts = np.shape(Indices)[0] numberToKeep = int( (1 - self.percent_to_remove ) * Npts) idx = Indices[0:numberToKeep] new_array = np.copy(array[idx]) new_color = np.copy(color[idx]) array = np.c_[new_array, new_color] <|code_end|> , predict the next line using imports from the current file: import numpy as np from vtk import vtkPoints, vtkCellArray, vtkPolyData, vtkIdList from vtk import vtkKdTreePointLocator from vtk import vtkSphereSource, vtkXMLPolyDataWriter, vtkVertexGlyphFilter from sklearn.neighbors import KDTree from ..utils.vtkhelpers import actor_from_imagedata, actor_from_polydata from ..io.converters import numpy_from_polydata, polydata_from_numpy from pcloudpy.core.filters.base import FilterBase and context including class names, function names, and sometimes code from other files: # Path: pcloudpy/core/utils/vtkhelpers.py # def actor_from_imagedata(imagedata): # actor = vtkImageActor() # actor.SetInputData(imagedata) # actor.InterpolateOff() # return actor # # def actor_from_polydata(PolyData): # """ # Returns the VTK Actor from vtkPolyData Structure # """ # mapper = vtkPolyDataMapper() # mapper.SetInputData(PolyData) # actor = vtkActor() # actor.SetMapper(mapper) # #actor.GetProperty().SetPointSize(2) # return actor # # Path: pcloudpy/core/io/converters.py # def numpy_from_polydata(polydata): # """ # Converts vtkPolyData to Numpy Array # # Parameters # ---------- # # polydata: vtkPolyData # Input Polydata # # """ # # nodes_vtk_array = polydata.GetPoints().GetData() # nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) # # if polydata.GetPointData().GetScalars(): # nodes_numpy_array_colors = vtk_to_numpy(polydata.GetPointData().GetScalars("colors")) # return np.c_[nodes_numpy_array, nodes_numpy_array_colors] # else: # return nodes_numpy_array # # def polydata_from_numpy(coords): # """ # Converts Numpy Array to vtkPolyData # # Parameters # ---------- # coords: array, shape= [number of points, point features] # array containing the point cloud in which each point has three coordinares [x, y, z] # and none, one or three values corresponding to colors. # # Returns: # -------- # PolyData: vtkPolyData # concrete dataset represents vertices, lines, polygons, and triangle strips # # """ # # Npts, Ndim = np.shape(coords) # # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(Npts) # Points.SetData(coords_vtk) # # Cells = vtkCellArray() # ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) # IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) # ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) # # Cells.SetNumberOfCells(Npts) # Cells.SetCells(Npts,ids_vtk) # # if Ndim == 4: # color = [128]*len(coords) # color = np.c_[color, color, color] # elif Ndim == 6: # color = coords[:,3:] # else: # color = [[128, 128, 128]]*len(coords) # # color_vtk = numpy_to_vtk( # np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), # deep=True) # # color_vtk.SetName("colors") # # PolyData = vtkPolyData() # PolyData.SetPoints(Points) # PolyData.SetVerts(Cells) # PolyData.GetPointData().SetScalars(color_vtk) # return PolyData # # Path: pcloudpy/core/filters/base.py # class FilterBase(BaseObject): # """ # Base Class for all Filter Objects # # Attributes # ---------- # input_: vtkPolyData # Input Data to be filtered # # output_: vtkPolyData # Output Data # # """ # # def __init__(self): # # self.input_ = None # self.output_ = None # # def set_input(self, input_data): # # """ # 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): # self.input_ = input_data # return True # else: # return False # # # def get_output(self): # # if self.output_: # return self.output_ # # def update(self): # pass . Output only the next line.
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.filename_) reader.Update() self._polydata = reader.GetOutput() class WriterPLY: """ Function library for exporting different data into PLY format - from_numpy - from_polydata """ @staticmethod def from_numpy(points, tr_re, output_filename): <|code_end|> , generate the next line using the imports in this file: import numpy as np from vtk import vtkPLYReader, vtkPolyData, vtkPLYWriter from .base import PolyDataBase from .converters import get_polydata_from and context (functions, classes, or occasionally code) from other files: # Path: pcloudpy/core/io/base.py # 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(PolyDataBase, self).__init__() # self.type_ = DataType.POLYDATA # # def get_polydata(self): # """ # Gets PolyData (vtkPolyData) # """ # 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._update() # self.set_polydata(self._polydata) # self.update_props() # # def _update(self): # pass # # def clone(self): # polydata = vtkPolyData() # polydata.DeepCopy(self._polydata) # # clone = copy.copy(self) # clone.set_polydata(polydata) # clone.set_actor(actor_from_polydata(polydata)) # return clone # # def update_data_from(self, polydata): # # self._data = numpy_from_polydata(polydata) # self._polydata = polydata # self._actor = actor_from_polydata(self._polydata) # self.update_props() # # def update_props(self): # # if self._polydata: # self.props_ = OrderedDict() # self.props_["Number of Points"] = self._polydata.GetNumberOfPoints() # # if isinstance(self._polydata, vtkPolyData): # polys = self._polydata.GetNumberOfPolys() # lines = self._polydata.GetNumberOfLines() # # if polys !=0: # self.props_["Number of Polygons"] = polys # if lines !=0: # self.props_["Number of Lines"] = lines # # verts = self._polydata.GetNumberOfVerts() # if verts !=0: # self.props_["Number of Vertices"] = verts # # strips = self._polydata.GetNumberOfStrips() # if strips !=0: # self.props_["Number of Triangles"] = strips # # 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_["zmax"] = bounds[5] # # Path: pcloudpy/core/io/converters.py # def get_polydata_from(points, tr_re): # # numberPoints = len(points) # Points = vtkPoints() # ntype = get_numpy_array_type(Points.GetDataType()) # points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1) # Points.SetNumberOfPoints(numberPoints) # Points.SetData(points_vtk) # # Triangles = vtkCellArray() # for item in tr_re: # Triangle = vtkTriangle() # Triangle.GetPointIds().SetId(0,item[0]) # Triangle.GetPointIds().SetId(1,item[1]) # Triangle.GetPointIds().SetId(2,item[2]) # Triangles.InsertNextCell(Triangle) # # polydata = vtkPolyData() # polydata.SetPoints(Points) # polydata.SetPolys(Triangles) # # polydata.Modified() # polydata.Update() # # return polydata . Output only the next line.
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': { 'class_name': self.recurrent_layer.__class__.__name__, 'config': self.recurrent_layer.get_config() }, 'dense_layer': { 'class_name': self.dense_layer.__class__.__name__, 'config': self.dense_layer.get_config() }, 'dense_dropout': self.dense_dropout, 'go_backwards':self.go_backwards, } base_config = super(RNNCell, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): if custom_objects is None: custom_objects = {} <|code_end|> . Use current file imports: import numpy as np import keras.backend as K import yklz.backend as YK from keras.layers import activations from keras.layers import initializers from keras.layers import regularizers from keras.layers import constraints from keras.engine import InputSpec from keras.layers import Layer from .lstm_peephole import LSTMPeephole from keras.layers import deserialize as deserialize_layer and context (classes, functions, or code) from other files: # Path: yklz/recurrent/lstm_peephole.py # class LSTMPeephole(LSTM): # def __init__(self, units, # activation='tanh', # recurrent_activation='hard_sigmoid', # use_bias=True, # kernel_initializer='glorot_uniform', # recurrent_initializer='orthogonal', # bias_initializer='zeros', # unit_forget_bias=True, # kernel_regularizer=None, # recurrent_regularizer=None, # bias_regularizer=None, # activity_regularizer=None, # kernel_constraint=None, # recurrent_constraint=None, # bias_constraint=None, # dropout=0., # recurrent_dropout=0., # **kwargs): # super(LSTMPeephole, self).__init__( # units=units, # activation=activation, # recurrent_activation=recurrent_activation, # use_bias=use_bias, # kernel_initializer=kernel_initializer, # recurrent_initializer=recurrent_initializer, # bias_initializer=bias_initializer, # unit_forget_bias=unit_forget_bias, # kernel_regularizer=kernel_regularizer, # recurrent_regularizer=recurrent_regularizer, # bias_regularizer=bias_regularizer, # activity_regularizer=activity_regularizer, # kernel_constraint=kernel_constraint, # recurrent_constraint=recurrent_constraint, # bias_constraint=bias_constraint, # dropout=dropout, # recurrent_dropout=recurrent_dropout, # **kwargs # ) # # def build(self, input_shape): # super(LSTMPeephole, self).build(input_shape) # self.recurrent_kernel_c = K.zeros_like(self.recurrent_kernel_c) # # def step(self, inputs, states): # h_tm1 = states[0] # c_tm1 = states[1] # dp_mask = states[2] # rec_dp_mask = states[3] # # if self.implementation == 2: # z = K.dot(inputs * dp_mask[0], self.kernel) # z += K.dot(c_tm1 * rec_dp_mask[0], self.recurrent_kernel) # if self.use_bias: # z = K.bias_add(z, self.bias) # # z0 = z[:, :self.units] # z1 = z[:, self.units: 2 * self.units] # z2 = z[:, 2 * self.units: 3 * self.units] # z3 = z[:, 3 * self.units:] # # i = self.recurrent_activation(z0) # f = self.recurrent_activation(z1) # c = f * c_tm1 + i * self.activation(z2) # o = self.recurrent_activation(z3) # else: # if self.implementation == 0: # x_i = inputs[:, :self.units] # x_f = inputs[:, self.units: 2 * self.units] # x_c = inputs[:, 2 * self.units: 3 * self.units] # x_o = inputs[:, 3 * self.units:] # elif self.implementation == 1: # x_i = K.dot(inputs * dp_mask[0], self.kernel_i) + self.bias_i # x_f = K.dot(inputs * dp_mask[1], self.kernel_f) + self.bias_f # x_c = K.dot(inputs * dp_mask[2], self.kernel_c) + self.bias_c # x_o = K.dot(inputs * dp_mask[3], self.kernel_o) + self.bias_o # else: # raise ValueError('Unknown `implementation` mode.') # # i = self.recurrent_activation( # x_i + K.dot(c_tm1 * rec_dp_mask[0], self.recurrent_kernel_i) # ) # f = self.recurrent_activation( # x_f + K.dot(c_tm1 * rec_dp_mask[1], self.recurrent_kernel_f) # ) # c = f * c_tm1 + i * self.activation( # x_c + K.dot(c_tm1 * rec_dp_mask[2], self.recurrent_kernel_c) # ) # o = self.recurrent_activation( # x_o + K.dot(c_tm1 * rec_dp_mask[3], self.recurrent_kernel_o) # ) # h = o * c # if 0 < self.dropout + self.recurrent_dropout: # h._uses_learning_phase = True # return h, [h, c] . Output only the next line.
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) template_parts = template.split('|') partdict = {} for part in template_parts: for partid in 'FVLJfvlj': if partid in part: parts_order += partid pre, temp = part.split(partid) if temp and temp[0] == '{': #found a partsep partsep,post = temp[1:].split('}') else: post = temp partsep = self.default_partsep partdict[partid] = dict(pre=pre,post=post,partsep=partsep) break shared_logger.debug("template2dict: name formatting template parsed to:\n"+str(partdict)) partdict['parts_order'] = parts_order return partdict class CitationManager(object): """ :TODO: possibly useful for bibsearch.py """ <|code_end|> , determine the next line of code. You have imports: import logging, re import simpleparse import simpleparse.dispatchprocessor from .default_templates import DEFAULT_CITATION_TEMPLATE and context (class names, function names, or code) available: # Path: bibstuff/bibstyles/default_templates.py # DEFAULT_CITATION_TEMPLATE = dict( # book = '(%(year)s) *%(title)s*. %(address)s: %(publisher)s.', # article = '%(year)s. %(title)s. *%(journal)s* %(volume)s, %(pages)s.', # techreport = '(%(year)s) "%(title)s". %(institution)s %(type)s %(number)s. %(url)s', # inproceedings = '(%(year)s) "%(title)s". In %(editor)s (Eds.) *%(booktitle)s*, %(address)s: %(publisher)s.', # incollection = '(%(year)s) "%(title)s". In %(editor)s (Eds.) *%(booktitle)s*, %(address)s: %(publisher)s.', # misc = '%(year)s. %(title)s.', # default_type = ' %(year)s. %(title)s.', # name_first = 'v |l,| j,| f', # name_other = 'f |v |l|, j', # name_name_sep = (', ',', and '), # etal = ', et al.', # initials = '', # max_citation_names = 3, # indent_left = 3, # citation_sep = "\n\n", # names_details_sep = '. ', # post_processor = default_post_processor # ) . Output only the next line.
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 everything from a useful style ######## ADJUST CITATION TEMPLATE FOR NEW STYLE ########### ######## note: see help for bibstyles.shared.NameFormatter for name details <|code_end|> . Use current file imports: from bibstuff.bibstyles import default as bbd and context (classes, functions, or code) from other files: # Path: bibstuff/bibstyles/default.py # CITEREF_TEMPLATE = default_templates.DEFAULT_CITEREF_TEMPLATE.copy() # CITATION_TEMPLATE = shared.CitationManager.default_citation_template # class CitationManager(shared.CitationManager): # def format_inline_cite(self, cite_key_list): # def get_citation_label(self,entry,citation_template=None): # def sortkey(self,bibentry): # def format_inline_cite(entry_list, citation_manager): . Output only the next line.
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(string_or_compiled, re.MULTILINE | re.IGNORECASE) else: reo = re.compile(string_or_compiled, re.MULTILINE) else: #->must have a compiled regular expression reo = string_or_compiled """ Find regex in bib_entry. If field is omitted, search is through all fields. :note: used by bibsearch.py """ ls = [entry for entry in self.entries if entry.search_fields(string_or_compiled=reo, field=field, ignore_case=ignore_case)] return ls # self test # ------------------------- # usage: bibfile.py DATABASE_FILE if __name__ == "__main__": if len(sys.argv) > 1 : src = open(sys.argv[1]).read() bfile = BibFile() <|code_end|> using the current file's imports: import re import sys import logging import sys from simpleparse.dispatchprocessor import dispatch, DispatchProcessor, getString, lines from bibstuff import bibgrammar from bibstuff.bibstyles.shared import reformat_para from bibstuff import bibname #ai: shd move all bibname into here? possibly and any relevant context from other files: # Path: bibstuff/bibgrammar.py # def Parse(src, processor=None) : # # Path: bibstuff/bibstyles/shared.py # def reformat_para(para='', left=0, right=72, just='LEFT'): # """Simple paragraph reformatter. Allows specification # of left and right margins, and of justification style # (using constants defined in module). # :note: Adopted by Schwilk from David Mertz's example in TPiP # :see: Mertz, David, *Text Processing in Python* (TPiP) # """ # LEFT, RIGHT, CENTER = 'LEFT', 'RIGHT', 'CENTER' # words = para.split() # lines = [] # line = '' # word = 0 # end_words = 0 # while not end_words: # if len(words[word]) > right-left: # Handle very long words # line = words[word] # word +=1 # if word >= len(words): # end_words = 1 # else: # Compose line of words # while len(line)+len(words[word]) <= right-left: # line += words[word]+' ' # word += 1 # if word >= len(words): # end_words = 1 # break # lines.append(line) # line = '' # if just.upper() == CENTER: # r, l = right, left # return '\n'.join([' '*left+ln.center(r-l) for ln in lines]) # elif just.upper() == RIGHT: # return '\n'.join([line.rjust(right) for line in lines]) # else: # left justify # return '\n'.join([' '*left+line for line in lines]) . Output only the next line.
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 module." usage = "usage: %prog [options] DATABASE_FILE [ABBREVIATION_FILE] " parser = OptionParser(usage=usage, version ="%prog " + __version__) (options, args) = parser.parse_args() if len(args) > 2 : print "Too many arguments" sys.exit(1) try : # bibtex file is last argument bib = open(args[0]).read() except : print "No bibtex file found." sys.exit(1) if len(args) == 2 : input = open(args[1]) else : input = sys.stdin.read() <|code_end|> . Use current file imports: (import string, sys, re from simpleparse.parser import Parser from simpleparse.dispatchprocessor import * from bibstuff import bibfile, bibgrammar from optparse import OptionParser from optik import OptionParser) and context including class names, function names, or small code snippets from other files: # Path: bibstuff/bibfile.py # MONTH_DICT = dict( zip(monthmacros_en, months_en) ) # class BibEntry(dict): # class BibFile( DispatchProcessor ): # def __init__(self,*args,**kwargs): # def __repr__(self): # def __setitem__(self, key, val): # def __getitem__(self, field): #field is usually a BibTeX field but can be a citekey # def __delitem__(self,key) : # def set_entry_type(self, val): # def get_entry_type(self): # def set_citekey(self, val): # def get_citekey(self): # def get_fields(self): # def set_fields(self, lst): # def search_fields(self, string_or_compiled, field='', ignore_case=True): # def format_names(self, names_formatter): # def get_names(self, entry_formatter=None, try_fields=None): # def make_names(self, entry_formatter=None, try_fields=None): # def format_with(self, entry_formatter): # def __init__(self) : # def get_entrylist(self, citekeys, discard=True): # def get_entry_by_citekey(self, citekey): # def string(self, (tag,start,stop,subtags), buffer ): # def number(self, (tag,start,stop,subtags), buffer ): # def entry_type( self, (tag,start,stop,subtags), buffer ): # def citekey( self, (tag,start,stop,subtags), buffer ): # def name(self, (tag,start,stop,subtags), buffer ): # def field(self, (tag,start,stop,subtags), buffer ): # def entry( self, (tag,start,stop,subtags), buffer ): # def macro( self, (tag,start,stop,subtags), buffer ): # def preamble( self, (tag,start,stop,subtags), buffer ): # def comment_entry( self, (tag,start,stop,subtags), buffer ): # def search_entries(self, string_or_compiled, field='', ignore_case=True): # # Path: bibstuff/bibgrammar.py # def Parse(src, processor=None) : . Output only the next line.
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." usage = "usage: %prog [options] DATABASE_FILE [ABBREVIATION_FILE] " parser = OptionParser(usage=usage, version ="%prog " + __version__) (options, args) = parser.parse_args() if len(args) > 2 : print "Too many arguments" sys.exit(1) try : # bibtex file is last argument bib = open(args[0]).read() except : print "No bibtex file found." sys.exit(1) if len(args) == 2 : input = open(args[1]) else : input = sys.stdin.read() bfile = bibfile.BibFile() <|code_end|> , predict the next line using imports from the current file: import string, sys, re from simpleparse.parser import Parser from simpleparse.dispatchprocessor import * from bibstuff import bibfile, bibgrammar from optparse import OptionParser from optik import OptionParser and context including class names, function names, and sometimes code from other files: # Path: bibstuff/bibfile.py # MONTH_DICT = dict( zip(monthmacros_en, months_en) ) # class BibEntry(dict): # class BibFile( DispatchProcessor ): # def __init__(self,*args,**kwargs): # def __repr__(self): # def __setitem__(self, key, val): # def __getitem__(self, field): #field is usually a BibTeX field but can be a citekey # def __delitem__(self,key) : # def set_entry_type(self, val): # def get_entry_type(self): # def set_citekey(self, val): # def get_citekey(self): # def get_fields(self): # def set_fields(self, lst): # def search_fields(self, string_or_compiled, field='', ignore_case=True): # def format_names(self, names_formatter): # def get_names(self, entry_formatter=None, try_fields=None): # def make_names(self, entry_formatter=None, try_fields=None): # def format_with(self, entry_formatter): # def __init__(self) : # def get_entrylist(self, citekeys, discard=True): # def get_entry_by_citekey(self, citekey): # def string(self, (tag,start,stop,subtags), buffer ): # def number(self, (tag,start,stop,subtags), buffer ): # def entry_type( self, (tag,start,stop,subtags), buffer ): # def citekey( self, (tag,start,stop,subtags), buffer ): # def name(self, (tag,start,stop,subtags), buffer ): # def field(self, (tag,start,stop,subtags), buffer ): # def entry( self, (tag,start,stop,subtags), buffer ): # def macro( self, (tag,start,stop,subtags), buffer ): # def preamble( self, (tag,start,stop,subtags), buffer ): # def comment_entry( self, (tag,start,stop,subtags), buffer ): # def search_entries(self, string_or_compiled, field='', ignore_case=True): # # Path: bibstuff/bibgrammar.py # def Parse(src, processor=None) : . Output only the next line.
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='', help="set type of entry", metavar="ENTRYTYPE") parser.add_option("-o", "--outfile", action="store", type="string", dest="outfile", help="Write formatted references to FILE", metavar="FILE") parser.add_option("-n", "--nuke", action="store_true", dest="overwrite", default=False, help="CAUTION! silently overwrite outfile, default=%default") parser.add_option("-b", "--backup", action="store_true", dest="backup", default=False, help="backup FILE to FILE.bak, default=%default") """ #TODO: parser.add_option("-I", "--ISBN", action="store", dest="ISBN", default=False, help="use pyaws to add one entry by ISBN, default=%default") parser.add_option("-m", "--maxnames", action="store", type="int", dest="maxnames", default = 2, help="Max names to add to key") parser.add_option("-e", "--etal", action="store", type="string", \ dest="etal", default = 'etal',help="What to add after max names") parser.add_option("-i", "--infile", action="store", type="string", dest="infile", help="Parse FILE for citation references.", metavar="FILE") parser.add_option("-s", "--stylefile", action="store", dest="stylefile", default="default.py", help="Specify user-chosen style file",metavar="FILE") """ # get options (options, args) = parser.parse_args() if options.verbose: <|code_end|> , generate the next line using the imports in this file: import os import sys import shutil import logging from bibstuff.bibadd import (bibadd_logger, make_entry, html_format, text_format) from optparse import OptionParser and context (functions, classes, or occasionally code) from other files: # Path: bibstuff/bibadd.py # def make_entry(choosetype='', options=False, extras=False): # def make_entry_citekey(entry, used_citekeys,style=label_style1): # def is_macro(s): # def text_format(entry): # def get_journal(entry, jrnl_lst=None): #TODO: extract fr journal list # def get_volnum(entry): # def get_pages(entry,dash='--',pagespref=('p. ','pp. ')): # def html_format(entry): . Output only the next line.
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) # read input file (default: stdin) if options.infile: try: input = open(options.infile,'r') 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_processor) bfile = bibfile.BibFile() bibgrammar.Parse(src, bfile) used_citekeys = [] # stores created keys ''' <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import shutil import logging from bibstuff.bibadd import (bibadd_logger, make_entry, html_format, text_format) from optparse import OptionParser and context: # Path: bibstuff/bibadd.py # def make_entry(choosetype='', options=False, extras=False): # def make_entry_citekey(entry, used_citekeys,style=label_style1): # def is_macro(s): # def text_format(entry): # def get_journal(entry, jrnl_lst=None): #TODO: extract fr journal list # def get_volnum(entry): # def get_pages(entry,dash='--',pagespref=('p. ','pp. ')): # def html_format(entry): which might include code, classes, or functions. Output only the next line.
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_processor) bfile = bibfile.BibFile() bibgrammar.Parse(src, bfile) used_citekeys = [] # stores created keys ''' entry = make_entry(options.entry_type, options.more_fields, options.MORE_FIELDS) # open output file for writing (default: stdout) if options.outfile: if options.backup and os.path.exists(options.outfile): shutil.copyfile(options.outfile, options.outfile+".bak") if options.overwrite or not os.path.exists(options.outfile): output = open(options.outfile,'w') else: bibadd_logger.info("Appending to %s.\n(Use -n option to nuke (overwrite) the old output file.)" %options.outfile) output = open(options.outfile,'a') output.write(str(entry)) #print entry if 'h' in options.format: <|code_end|> . Use current file imports: import os import sys import shutil import logging from bibstuff.bibadd import (bibadd_logger, make_entry, html_format, text_format) from optparse import OptionParser and context (classes, functions, or code) from other files: # Path: bibstuff/bibadd.py # def make_entry(choosetype='', options=False, extras=False): # def make_entry_citekey(entry, used_citekeys,style=label_style1): # def is_macro(s): # def text_format(entry): # def get_journal(entry, jrnl_lst=None): #TODO: extract fr journal list # def get_volnum(entry): # def get_pages(entry,dash='--',pagespref=('p. ','pp. ')): # def html_format(entry): . Output only the next line.
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.Parse(src, bfile) used_citekeys = [] # stores created keys ''' entry = make_entry(options.entry_type, options.more_fields, options.MORE_FIELDS) # open output file for writing (default: stdout) if options.outfile: if options.backup and os.path.exists(options.outfile): shutil.copyfile(options.outfile, options.outfile+".bak") if options.overwrite or not os.path.exists(options.outfile): output = open(options.outfile,'w') else: bibadd_logger.info("Appending to %s.\n(Use -n option to nuke (overwrite) the old output file.)" %options.outfile) output = open(options.outfile,'a') output.write(str(entry)) #print entry if 'h' in options.format: output.write( html_format(entry) ) if 't' in options.format: <|code_end|> , generate the next line using the imports in this file: import os import sys import shutil import logging from bibstuff.bibadd import (bibadd_logger, make_entry, html_format, text_format) from optparse import OptionParser and context (functions, classes, or occasionally code) from other files: # Path: bibstuff/bibadd.py # def make_entry(choosetype='', options=False, extras=False): # def make_entry_citekey(entry, used_citekeys,style=label_style1): # def is_macro(s): # def text_format(entry): # def get_journal(entry, jrnl_lst=None): #TODO: extract fr journal list # def get_volnum(entry): # def get_pages(entry,dash='--',pagespref=('p. ','pp. ')): # def html_format(entry): . Output only the next line.
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 and context (classes, functions, or code) from other files: # Path: gears/compressors/base.py # class BaseCompressor(BaseAssetHandler): # """Base class for all asset compressors. Subclass's :meth:`__call__` method # must return compressed :attr:`~gears.assets.Asset.bundled_source` attribute. # """ # # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass . Output only the next line.
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: from cssmin import cssmin from .base import BaseCompressor from ..exceptions import ImproperlyConfigured and context (class names, function names, or code) available: # Path: gears/compressors/base.py # class BaseCompressor(BaseAssetHandler): # """Base class for all asset compressors. Subclass's :meth:`__call__` method # must return compressed :attr:`~gears.assets.Asset.bundled_source` attribute. # """ # # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass . Output only the next line.
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.directives_parser import DirectivesParser from unittest2 import TestCase from .helpers import GearsTestCase) and context including class names, function names, or small code snippets from other files: # Path: gears/directives_parser.py # class DirectivesParser(object): # # header_re = re.compile(r""" # ^( \s* ( # ( /\* .*? \*/ ) | # multiline comment # ( // [^\n]* )+ | # slash comment # ( \# [^\n]* )+ # dash comment # ) )+ # """, re.S | re.X) # # directive_re = re.compile(r""" # ^ \s* (?:\*|//|\#) \s* = \s* ( \w+ [=*?\[\]./'"\s\w-]* ) $ # """, re.X) # # def split_source(self, source): # header_match = self.header_re.match(source) # if not header_match: # return '', source # header = header_match.group(0) # source = source[len(header):] # return header, source # # def split_header(self, header): # directives = [] # header_lines = [] # for line in header.splitlines(): # directive_match = self.directive_re.match(line) # if directive_match: # directives.append(directive_match.group(1)) # else: # header_lines.append(line) # return directives, '\n'.join(header_lines) # # def parse(self, source): # header, source = self.split_source(source) # directives, header = self.split_header(header) # return directives, ''.join([header, source]).strip() + '\n' # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) . Output only the next line.
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.find_fixture_file(fixture, 'dependency') <|code_end|> , continue by predicting the next line. Consider current file imports: import os from gears.assets import Dependency from .helpers import GearsTestCase and context: # Path: gears/assets.py # class Dependency(object): # # def __init__(self, environment, absolute_path): # self.environment = environment # self.absolute_path = absolute_path # if self.expired: # self._save_to_cache() # # def __eq__(self, other): # return self.absolute_path == other.absolute_path # # def __hash__(self): # return hash(self.absolute_path) # # @cached_property # def source(self): # if os.path.isdir(self.absolute_path): # source = ', '.join(sorted(os.listdir(self.absolute_path))) # return source.encode('utf-8') if is_py3 else source # with open(self.absolute_path, 'rb') as f: # return f.read() # # @cached_property # def mtime(self): # return os.stat(self.absolute_path).st_mtime # # @cached_property # def hexdigest(self): # return hashlib.sha1(self.source).hexdigest() # # @cached_property # def expired(self): # data = self.environment.cache.get(self._get_cache_key()) # return (data is None or # self.mtime > data['mtime'] or # self.hexdigest > data['hexdigest']) # # def to_dict(self): # return {'mtime': self.mtime, 'hexdigest': self.hexdigest} # # def _save_to_cache(self): # self.environment.cache.set(self._get_cache_key(), self.to_dict()) # # def _get_cache_key(self): # return 'dependency:%s' % self.absolute_path # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) which might include code, classes, or functions. Output only the next line.
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.assertTrue(needs_semicolon('x\n')) class SemicolonsProcessorTests(GearsTestCase): fixtures_root = 'semicolons_processor' def test_process(self): asset = self.get_asset('process') output = self.get_output('process') <|code_end|> with the help of current file imports: from unittest2 import TestCase from gears.compat import str from gears.processors.semicolons import needs_semicolon from .helpers import GearsTestCase and context from other files: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/processors/semicolons.py # def needs_semicolon(source): # return (BLANK_RE.search(source) is None and # SEMICOLON_RE.search(source) is None) # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) , which may contain function names, class names, or code. Output only the next line.
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.assertTrue(needs_semicolon('x\n')) <|code_end|> . Use current file imports: from unittest2 import TestCase from gears.compat import str from gears.processors.semicolons import needs_semicolon from .helpers import GearsTestCase and context (classes, functions, or code) from other files: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/processors/semicolons.py # def needs_semicolon(source): # return (BLANK_RE.search(source) is None and # SEMICOLON_RE.search(source) is None) # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) . Output only the next line.
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 context (classes, functions, sometimes code) from other files: # Path: gears/cache.py # class FileBasedCache(object): # # def __init__(self, root): # self.root = root # # def set(self, key, value): # filepath = self._get_filepath(key) # # dirname = os.path.dirname(filepath) # if not os.path.exists(dirname): # try: # os.makedirs(dirname) # except OSError: # return # # try: # with open(filepath, 'wb') as f: # pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) # except IOError: # pass # # def get(self, key): # filepath = self._get_filepath(key) # try: # with open(filepath, 'rb') as f: # return pickle.load(f) # except (IOError, OSError, EOFError, pickle.PickleError): # return None # # def _get_filepath(self, key): # relpath = hashlib.sha1(key.encode('utf-8')).hexdigest() # relpath = os.path.join(relpath[:2], relpath[2:4], relpath[4:]) # return os.path.join(self.root, relpath) . Output only the next line.
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 import ImproperlyConfigured and context (classes, functions, sometimes code) from other files: # Path: gears/compressors/base.py # class BaseCompressor(BaseAssetHandler): # """Base class for all asset compressors. Subclass's :meth:`__call__` method # must return compressed :attr:`~gears.assets.Asset.bundled_source` attribute. # """ # # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass . Output only the next line.
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 imports: from slimit import minify from .base import BaseCompressor from ..exceptions import ImproperlyConfigured and context from other files: # Path: gears/compressors/base.py # class BaseCompressor(BaseAssetHandler): # """Base class for all asset compressors. Subclass's :meth:`__call__` method # must return compressed :attr:`~gears.assets.Asset.bundled_source` attribute. # """ # # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass , which may contain function names, class names, or code. Output only the next line.
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"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset self.environment = self.asset.attributes.environment self.current_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: <|code_end|> , generate the next line using the imports in this file: import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor from ..compat import is_py3, is_py2 and context (functions, classes, or occasionally code) from other files: # Path: gears/assets.py # def build_asset(environment, path, check=False): # path = strip_fingerprint(path) # asset_attributes = AssetAttributes(environment, path) # asset_attributes, absolute_path = environment.find(asset_attributes, True) # if not asset_attributes.processors: # return StaticAsset(asset_attributes, absolute_path) # if check: # return CheckAsset(asset_attributes, absolute_path) # return Asset(asset_attributes, absolute_path) # # Path: gears/exceptions.py # class FileNotFound(Exception): # pass # # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ # # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): . Output only the next line.
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 = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset self.environment = self.asset.attributes.environment self.current_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: asset = build_asset(self.environment, logical_path) <|code_end|> using the current file's imports: import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor from ..compat import is_py3, is_py2 and any relevant context from other files: # Path: gears/assets.py # def build_asset(environment, path, check=False): # path = strip_fingerprint(path) # asset_attributes = AssetAttributes(environment, path) # asset_attributes, absolute_path = environment.find(asset_attributes, True) # if not asset_attributes.processors: # return StaticAsset(asset_attributes, absolute_path) # if check: # return CheckAsset(asset_attributes, absolute_path) # return Asset(asset_attributes, absolute_path) # # Path: gears/exceptions.py # class FileNotFound(Exception): # pass # # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ # # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): . Output only the next line.
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) <|code_end|> using the current file's imports: import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor from ..compat import is_py3, is_py2 and any relevant context from other files: # Path: gears/assets.py # def build_asset(environment, path, check=False): # path = strip_fingerprint(path) # asset_attributes = AssetAttributes(environment, path) # asset_attributes, absolute_path = environment.find(asset_attributes, True) # if not asset_attributes.processors: # return StaticAsset(asset_attributes, absolute_path) # if check: # return CheckAsset(asset_attributes, absolute_path) # return Asset(asset_attributes, absolute_path) # # Path: gears/exceptions.py # class FileNotFound(Exception): # pass # # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ # # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): . Output only the next line.
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_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: asset = build_asset(self.environment, logical_path) except FileNotFound: return path self.asset.dependencies.add(asset.absolute_path) relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir)) if is_py2: return relpath.encode('string-escape') <|code_end|> . Write the next line using the current file imports: import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor from ..compat import is_py3, is_py2 and context from other files: # Path: gears/assets.py # def build_asset(environment, path, check=False): # path = strip_fingerprint(path) # asset_attributes = AssetAttributes(environment, path) # asset_attributes, absolute_path = environment.find(asset_attributes, True) # if not asset_attributes.processors: # return StaticAsset(asset_attributes, absolute_path) # if check: # return CheckAsset(asset_attributes, absolute_path) # return Asset(asset_attributes, absolute_path) # # Path: gears/exceptions.py # class FileNotFound(Exception): # pass # # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ # # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): , which may include functions, classes, or code. Output only the next line.
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 self.environment = self.asset.attributes.environment self.current_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: asset = build_asset(self.environment, logical_path) except FileNotFound: return path self.asset.dependencies.add(asset.absolute_path) relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir)) <|code_end|> , predict the next line using imports from the current file: import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor from ..compat import is_py3, is_py2 and context including class names, function names, and sometimes code from other files: # Path: gears/assets.py # def build_asset(environment, path, check=False): # path = strip_fingerprint(path) # asset_attributes = AssetAttributes(environment, path) # asset_attributes, absolute_path = environment.find(asset_attributes, True) # if not asset_attributes.processors: # return StaticAsset(asset_attributes, absolute_path) # if check: # return CheckAsset(asset_attributes, absolute_path) # return Asset(asset_attributes, absolute_path) # # Path: gears/exceptions.py # class FileNotFound(Exception): # pass # # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ # # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): . Output only the next line.
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 immediate next line with the help of imports: import os import glob2 from .exceptions import ImproperlyConfigured, FileNotFound from .utils import safe_join and context (classes, functions, sometimes code) from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/utils.py # def safe_join(base, *paths): # if not os.path.isabs(base): # raise ValueError("%r is not an absolute path." % base) # base = os.path.normpath(base) # path = os.path.normpath(os.path.join(base, *paths)) # if not path.startswith(base): # raise ValueError("Path %r is outside of %r" % (path, base)) # return path . Output only the next line.
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 ImproperlyConfigured( "FileSystemFinder's 'directories' parameter is not a " "tuple or list; perhaps you forgot a trailing comma?") for directory in directories: if directory not in self.locations: self.locations.append(directory) @property def paths(self): return self.locations def find(self, path): for matched_path in self.find_all(path): return matched_path <|code_end|> . Use current file imports: (import os import glob2 from .exceptions import ImproperlyConfigured, FileNotFound from .utils import safe_join) and context including class names, function names, or small code snippets from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/utils.py # def safe_join(base, *paths): # if not os.path.isabs(base): # raise ValueError("%r is not an absolute path." % base) # base = os.path.normpath(base) # path = os.path.normpath(os.path.join(base, *paths)) # if not path.startswith(base): # raise ValueError("Path %r is outside of %r" % (path, base)) # return path . Output only the next line.
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 a " "tuple or list; perhaps you forgot a trailing comma?") for directory in directories: if directory not in self.locations: self.locations.append(directory) @property def paths(self): return self.locations def find(self, path): for matched_path in self.find_all(path): return matched_path raise FileNotFound(path) def find_all(self, path): for root in self.locations: matched_path = self.find_location(root, path) if matched_path: yield matched_path def find_location(self, root, path): <|code_end|> with the help of current file imports: import os import glob2 from .exceptions import ImproperlyConfigured, FileNotFound from .utils import safe_join and context from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/utils.py # def safe_join(base, *paths): # if not os.path.isabs(base): # raise ValueError("%r is not an absolute path." % base) # base = os.path.normpath(base) # path = os.path.normpath(os.path.join(base, *paths)) # if not path.startswith(base): # raise ValueError("Path %r is outside of %r" % (path, base)) # return path , which may contain function names, class names, or code. Output only the next line.
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(finder.locations, ['/first', '/second', '/third']) def test_if_directories_is_not_iterable(self): <|code_end|> using the current file's imports: import os from gears.exceptions import ImproperlyConfigured, FileNotFound from gears.finders import FileSystemFinder from mock import patch, Mock from unittest2 import TestCase and any relevant context from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/finders.py # class FileSystemFinder(BaseFinder): # # def __init__(self, directories): # self.locations = [] # if not isinstance(directories, (list, tuple)): # raise ImproperlyConfigured( # "FileSystemFinder's 'directories' parameter is not a " # "tuple or list; perhaps you forgot a trailing comma?") # for directory in directories: # if directory not in self.locations: # self.locations.append(directory) # # @property # def paths(self): # return self.locations # # def find(self, path): # for matched_path in self.find_all(path): # return matched_path # raise FileNotFound(path) # # def find_all(self, path): # for root in self.locations: # matched_path = self.find_location(root, path) # if matched_path: # yield matched_path # # def find_location(self, root, path): # path = safe_join(root, path) # if os.path.exists(path): # return path # # def list(self, path): # for root in self.locations: # for absolute_path in glob2.iglob(safe_join(root, path)): # if os.path.isfile(absolute_path): # logical_path = os.path.relpath(absolute_path, root) # yield logical_path, absolute_path . Output only the next line.
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): exists.return_value = True finder = FileSystemFinder(('/assets',)) location = finder.find_location('/assets', 'js/script.js') self.assertEqual(location, '/assets/js/script.js') exists.assert_called_once_with('/assets/js/script.js') @patch('os.path.exists') def test_find_location_if_does_not_exist(self, exists): exists.return_value = False finder = FileSystemFinder(('/assets',)) self.assertIsNone(finder.find_location('/assets', 'js/script.js')) exists.assert_called_once_with('/assets/js/script.js') def test_find_if_exists(self): finder = FileSystemFinder(('/first', '/second', '/third')) finder.find_all = Mock(return_value=( '/second/js/script.js', '/third/js/script.js')) self.assertEqual(finder.find('js/script.js'), '/second/js/script.js') finder.find_all.assert_called_once_with('js/script.js') def test_find_if_does_not_exist(self): finder = FileSystemFinder(('/first', '/second', '/third')) finder.find_all = Mock(return_value=()) <|code_end|> , predict the next line using imports from the current file: import os from gears.exceptions import ImproperlyConfigured, FileNotFound from gears.finders import FileSystemFinder from mock import patch, Mock from unittest2 import TestCase and context including class names, function names, and sometimes code from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/finders.py # class FileSystemFinder(BaseFinder): # # def __init__(self, directories): # self.locations = [] # if not isinstance(directories, (list, tuple)): # raise ImproperlyConfigured( # "FileSystemFinder's 'directories' parameter is not a " # "tuple or list; perhaps you forgot a trailing comma?") # for directory in directories: # if directory not in self.locations: # self.locations.append(directory) # # @property # def paths(self): # return self.locations # # def find(self, path): # for matched_path in self.find_all(path): # return matched_path # raise FileNotFound(path) # # def find_all(self, path): # for root in self.locations: # matched_path = self.find_location(root, path) # if matched_path: # yield matched_path # # def find_location(self, root, path): # path = safe_join(root, path) # if os.path.exists(path): # return path # # def list(self, path): # for root in self.locations: # for absolute_path in glob2.iglob(safe_join(root, path)): # if os.path.isfile(absolute_path): # logical_path = os.path.relpath(absolute_path, root) # yield logical_path, absolute_path . Output only the next line.
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 ImproperlyConfigured, FileNotFound from gears.finders import FileSystemFinder from mock import patch, Mock from unittest2 import TestCase and context (classes, functions, sometimes code) from other files: # Path: gears/exceptions.py # class ImproperlyConfigured(Exception): # pass # # class FileNotFound(Exception): # pass # # Path: gears/finders.py # class FileSystemFinder(BaseFinder): # # def __init__(self, directories): # self.locations = [] # if not isinstance(directories, (list, tuple)): # raise ImproperlyConfigured( # "FileSystemFinder's 'directories' parameter is not a " # "tuple or list; perhaps you forgot a trailing comma?") # for directory in directories: # if directory not in self.locations: # self.locations.append(directory) # # @property # def paths(self): # return self.locations # # def find(self, path): # for matched_path in self.find_all(path): # return matched_path # raise FileNotFound(path) # # def find_all(self, path): # for root in self.locations: # matched_path = self.find_location(root, path) # if matched_path: # yield matched_path # # def find_location(self, root, path): # path = safe_join(root, path) # if os.path.exists(path): # return path # # def list(self, path): # for root in self.locations: # for absolute_path in glob2.iglob(safe_join(root, path)): # if os.path.isfile(absolute_path): # logical_path = os.path.relpath(absolute_path, root) # yield logical_path, absolute_path . Output only the next line.
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: import re from .base import BaseProcessor and any relevant context from other files: # Path: gears/processors/base.py # class BaseProcessor(BaseAssetHandler): # """Base class for all asset processors. Subclass's :meth:`__call__` method # must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. # """ . Output only the next line.
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 TestCase and context (classes, functions, sometimes code) from other files: # Path: gears/utils.py # def safe_join(base, *paths): # if not os.path.isabs(base): # raise ValueError("%r is not an absolute path." % base) # base = os.path.normpath(base) # path = os.path.normpath(os.path.join(base, *paths)) # if not path.startswith(base): # raise ValueError("Path %r is outside of %r" % (path, base)) # return path . Output only the next line.
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')", "url('new/path')") def test_double_quotes(self): self.check('url("../images/logo.png")', 'url("new/path")') def test_without_quotes(self): self.check('url(../images/logo.png)', 'url(new/path)') class HexdigestPathsProcessorTests(GearsTestCase): fixtures_root = 'hexdigest_paths_processor' def test_process(self): asset = self.get_asset('process') output = self.get_output('process') <|code_end|> , generate the next line using the imports in this file: from unittest2 import TestCase from gears.compat import str from gears.processors.hexdigest_paths import rewrite_paths from .helpers import GearsTestCase and context (functions, classes, or occasionally code) from other files: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/processors/hexdigest_paths.py # 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) # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) . Output only the next line.
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('new/path')") def test_double_quotes(self): self.check('url("../images/logo.png")', 'url("new/path")') def test_without_quotes(self): self.check('url(../images/logo.png)', 'url(new/path)') <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest2 import TestCase from gears.compat import str from gears.processors.hexdigest_paths import rewrite_paths from .helpers import GearsTestCase and context: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/processors/hexdigest_paths.py # 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) # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) which might include code, classes, or functions. Output only the next line.
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 the next line using imports from the current file: import os from gears.assets import Dependencies from .helpers import GearsTestCase and context including class names, function names, and sometimes code from other files: # Path: gears/assets.py # class Dependencies(object): # # def __init__(self, environment): # self.environment = environment # self._registry = set() # # @classmethod # def from_list(cls, environment, data): # self = cls(environment) # for absolute_path in data: # self.add(absolute_path) # return self # # @cached_property # def expired(self): # return any(d.expired for d in self._registry) # # @cached_property # def mtime(self): # if not self._registry: # return None # return max(d.mtime for d in self._registry) # # def add(self, absolute_path): # self._registry.add(Dependency(self.environment, absolute_path)) # # def clear(self): # self._registry.clear() # # def to_list(self): # return [d.absolute_path for d in self._registry] # # Path: tests/helpers.py # class GearsTestCase(unittest2.TestCase): # # fixtures_root = None # # def get_fixture_path(self, fixture): # return os.path.join(FIXTURES_DIR, self.fixtures_root, fixture) # # def find_fixture_file(self, fixture, name): # fixture_path = self.get_fixture_path(fixture) # for dirpath, dirnames, filenames in os.walk(fixture_path): # for filename in filenames: # if filename.split('.')[0] == name: # return os.path.join(dirpath, filename) # return None # # def get_source_path(self, fixture): # return self.find_fixture_file(fixture, 'source') # # def get_source(self, fixture): # return read(self.get_source_path(fixture)) # # def get_output(self, fixture, name='output'): # return read(self.find_fixture_file(fixture, name)) # # def get_finder(self, fixture): # fixture_path = self.get_fixture_path(fixture) # return FileSystemFinder([fixture_path]) # # def get_environment(self, fixture): # finder = self.get_finder(fixture) # environment = Environment(os.path.join(TESTS_DIR, 'static')) # environment.finders.register(finder) # environment.register_defaults() # return environment # # def get_asset(self, fixture, environment=None, asset_class=Asset): # source_path = self.get_source_path(fixture) # if environment is None: # environment = self.get_environment(fixture) # # fixture_path = self.get_fixture_path(fixture) # logical_path = os.path.relpath(source_path, fixture_path) # asset_attributes = AssetAttributes(environment, logical_path) # # return asset_class(asset_attributes, source_path) # # def get_static_asset(self, fixture, environment=None): # return self.get_asset(fixture, environment, asset_class=StaticAsset) . Output only the next line.
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 compiling. result_mimetype = None @classmethod def as_handler(cls, **initkwargs): handler = super(BaseCompiler, cls).as_handler(**initkwargs) handler.result_mimetype = cls.result_mimetype return handler <|code_end|> , predict the immediate next line with the help of imports: from ..asset_handler import BaseAssetHandler, ExecMixin and context (classes, functions, sometimes code) from other files: # Path: gears/asset_handler.py # class BaseAssetHandler(object): # """Base class for all asset handlers (processors, compilers and # compressors). A subclass has to implement :meth:`__call__` which is called # with asset as argument. # """ # # supports_check_mode = False # # def __call__(self, asset): # """Subclasses have to override this method to implement the actual # handler function code. This method is called with asset as argument. # Depending on the type of the handler, this method must change asset # state (as it does in :class:`~gears.processors.Directivesprocessor`) # or return some value (in case of asset compressors). # """ # raise NotImplementedError # # @classmethod # def as_handler(cls, **initkwargs): # """Converts the class into an actual handler function that can be used # when registering different types of processors in # :class:`~gears.environment.Environment` class instance. # # The arguments passed to :meth:`as_handler` are forwarded to the # constructor of the class. # """ # @wraps(cls, updated=()) # def handler(asset, *args, **kwargs): # return handler.handler_class(**initkwargs)(asset, *args, **kwargs) # handler.handler_class = cls # handler.supports_check_mode = cls.supports_check_mode # return handler # # class ExecMixin(object): # """Provides the ability to process asset through external command.""" # # #: The name of the executable to run. It must be a command name, if it is # #: available in the PATH environment variable, or a path to the executable. # executable = None # # #: The list of executable parameters. # params = [] # # def run(self, input): # """Runs :attr:`executable` with ``input`` as stdin. # :class:`AssetHandlerError` exception is raised, if execution is failed, # otherwise stdout is returned. # """ # p = self.get_process() # output, errors = p.communicate(input=input.encode('utf-8')) # if p.returncode != 0: # raise AssetHandlerError(errors) # return output.decode('utf-8') # # def get_process(self): # """Returns :class:`subprocess.Popen` instance with args from # :meth:`get_args` result and piped stdin, stdout and stderr. # """ # return Popen(self.get_args(), stdin=PIPE, stdout=PIPE, stderr=PIPE) # # def get_args(self): # """Returns the list of :class:`subprocess.Popen` arguments.""" # return [self.executable] + self.params . Output only the next line.
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 unittest2 import TestCase and any relevant context from other files: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/manifest.py # class Manifest(object): # # def __init__(self, path): # self.path = path # self.data = {} # if self.path: # self.load() # # @property # def files(self): # return self.data.setdefault('files', {}) # # def load(self): # try: # with open(self.path) as f: # self.data = json.load(f) # except IOError as e: # if e.errno != errno.ENOENT: # raise # # def dump(self): # if not self.path: # return # dirpath = os.path.dirname(self.path) # if not os.path.exists(dirpath): # os.makedirs(dirpath) # with open(self.path, 'w') as f: # json.dump(self.data, f, indent=2) . Output only the next line.
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/script.js": "js/script.654321.js" } }""") <|code_end|> . Use current file imports: import errno import mock from gears.compat import StringIO from gears.manifest import Manifest from unittest2 import TestCase and context (classes, functions, or code) from other files: # Path: gears/compat.py # class UnicodeMixin(object): # def __str__(self): # def bytes(obj): # # Path: gears/manifest.py # class Manifest(object): # # def __init__(self, path): # self.path = path # self.data = {} # if self.path: # self.load() # # @property # def files(self): # return self.data.setdefault('files', {}) # # def load(self): # try: # with open(self.path) as f: # self.data = json.load(f) # except IOError as e: # if e.errno != errno.ENOENT: # raise # # def dump(self): # if not self.path: # return # dirpath = os.path.dirname(self.path) # if not os.path.exists(dirpath): # os.makedirs(dirpath) # with open(self.path, 'w') as f: # json.dump(self.data, f, indent=2) . Output only the next line.
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, depending on the type of passed path. If it is a relative asset path, you can use all properties except :attr:`search_paths`. In case of a logical asset path it makes sense to use only those properties that are not related to processors and compressor. :param environment: an instance of :class:`~gears.environment.Environment` class. :param path: a relative or logical path of the asset. """ def __init__(self, environment, path): #: Used to access the registries of compilers, processors, etc. #: It can be also used by asset. See #: :class:`~gears.environment.Environment` for more information. self.environment = environment #: The relative (or logical) path to asset. self.path = path #: The relative path to the directory the asset. self.dirname = os.path.dirname(path) <|code_end|> , predict the next line using imports from the current file: import os import re from .utils import cached_property and context including class names, function names, and sometimes code from other files: # Path: gears/utils.py # class cached_property(object): # # def __init__(self, func): # self.func = func # self.__name__ = func.__name__ # self.__doc__ = func.__doc__ # self.__module__ = func.__module__ # # def __get__(self, obj, type=None): # if obj is None: # return self # value = obj.__dict__.get(self.__name__, missing) # if value is missing: # value = self.func(obj) # obj.__dict__[self.__name__] = value # return value . Output only the next line.
@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'output', b'') Popen.return_value = result self.assertEqual(Exec().run('input'), 'output') @patch('gears.asset_handler.Popen') def test_raises_stderr_on_failure(self, Popen): result = Mock() result.returncode = 1 result.communicate.return_value = (b'', b'error') Popen.return_value = result <|code_end|> , predict the immediate next line with the help of imports: from gears.asset_handler import AssetHandlerError, ExecMixin from mock import patch, Mock from unittest2 import TestCase and context (classes, functions, sometimes code) from other files: # Path: gears/asset_handler.py # class AssetHandlerError(Exception): # pass # # class ExecMixin(object): # """Provides the ability to process asset through external command.""" # # #: The name of the executable to run. It must be a command name, if it is # #: available in the PATH environment variable, or a path to the executable. # executable = None # # #: The list of executable parameters. # params = [] # # def run(self, input): # """Runs :attr:`executable` with ``input`` as stdin. # :class:`AssetHandlerError` exception is raised, if execution is failed, # otherwise stdout is returned. # """ # p = self.get_process() # output, errors = p.communicate(input=input.encode('utf-8')) # if p.returncode != 0: # raise AssetHandlerError(errors) # return output.decode('utf-8') # # def get_process(self): # """Returns :class:`subprocess.Popen` instance with args from # :meth:`get_args` result and piped stdin, stdout and stderr. # """ # return Popen(self.get_args(), stdin=PIPE, stdout=PIPE, stderr=PIPE) # # def get_args(self): # """Returns the list of :class:`subprocess.Popen` arguments.""" # return [self.executable] + self.params . Output only the next line.
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, function names, or small code snippets from other files: # Path: src/cutadapt/modifiers.py # class ModificationInfo: # """ # An object of this class is created for each read that passes through the pipeline. # Any information (except the read itself) that needs to be passed from one modifier # to one later in the pipeline or from one modifier to the filters is recorded here. # """ # # __slots__ = ["matches", "original_read", "cut_prefix", "cut_suffix", "is_rc"] # # def __init__(self, read): # self.matches = [] # type: List[Match] # self.original_read = read # self.cut_prefix = None # self.cut_suffix = None # self.is_rc = None # # def __repr__(self): # return ( # "ModificationInfo(" # f"matches={self.matches!r}, " # f"original_read={self.original_read}, " # f"cut_prefix={self.cut_prefix}, " # f"cut_suffix={self.cut_suffix}, " # f"is_rc={self.is_rc})" # ) . Output only the next line.
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 within each Adapter class class Where(IntFlag): """ Aligner flag combinations for all adapter types. "REFERENCE" is the adapter sequence, "QUERY" is the read sequence """ <|code_end|> using the current file's imports: import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, ) and any relevant context from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: . Output only the next line.
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(self.sequence) - self.sequence.count("N") self.max_error_rate: float = max_errors self.min_overlap: int = min(min_overlap, len(self.sequence)) iupac = frozenset("ABCDGHKMNRSTUVWXY") if adapter_wildcards and not set(self.sequence) <= iupac: for c in self.sequence: if c not in iupac: if c == "I": extra = ( "For inosine, consider using N instead and please comment " "on <https://github.com/marcelm/cutadapt/issues/546>." ) else: extra = "Use only characters 'ABCDGHKMNRSTUVWXY'." raise InvalidCharacter( f"Character '{c}' in adapter sequence '{self.sequence}' is " f"not a valid IUPAC code. {extra}" ) # Optimization: Use non-wildcard matching if only ACGT is used self.adapter_wildcards: bool = adapter_wildcards and not set( self.sequence ) <= set("ACGT") self.read_wildcards: bool = read_wildcards self.indels: bool = indels self.aligner = self._aligner() <|code_end|> using the current file's imports: import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, ) and any relevant context from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: . Output only the next line.
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 AttributeError: pass if alignment is None: return None return RemoveAfterMatch(*alignment, adapter=self, sequence=sequence) # type: ignore def spec(self) -> str: return f"{self.sequence}X" class PrefixAdapter(NonInternalFrontAdapter): """An anchored 5' adapter""" description = "anchored 5'" allows_partial_matches = False def __init__(self, sequence: str, *args, **kwargs): kwargs["min_overlap"] = len(sequence) super().__init__(sequence, *args, **kwargs) def descriptive_identifier(self) -> str: return "anchored_five_prime" def _aligner(self): if not self.indels: # TODO or if error rate allows 0 errors anyway <|code_end|> , predict the next line using imports from the current file: import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, ) and context including class names, function names, and sometimes code from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: . Output only the next line.
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, min_overlap=self.min_overlap, ) else: return self._make_aligner(Where.PREFIX.value) def spec(self) -> str: return f"^{self.sequence}..." class SuffixAdapter(NonInternalBackAdapter): """An anchored 3' adapter""" description = "anchored 3'" allows_partial_matches = False def __init__(self, sequence: str, *args, **kwargs): kwargs["min_overlap"] = len(sequence) super().__init__(sequence, *args, **kwargs) def descriptive_identifier(self) -> str: return "anchored_three_prime" def _aligner(self): if not self.indels: # TODO or if error rate allows 0 errors anyway <|code_end|> . Use current file imports: (import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, )) and context including class names, function names, or small code snippets from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: . Output only the next line.
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) if k > 2: raise ValueError("Error rate too high") @classmethod def is_acceptable(cls, adapter): """ Return whether this adapter is acceptable for being used in an index Adapters are not acceptable if they allow wildcards, allow too many errors, or would lead to a very large index. """ try: cls._accept(adapter) except ValueError: return False return True def _make_index(self) -> Tuple[List[int], "AdapterIndex"]: logger.info("Building index of %s adapters ...", len(self._adapters)) index: Dict[str, Tuple[SingleAdapter, int, int]] = dict() lengths = set() has_warned = False for adapter in self._adapters: sequence = adapter.sequence k = int(adapter.max_error_rate * len(sequence)) <|code_end|> with the help of current file imports: import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, ) and context from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: , which may contain function names, class names, or code. Output only the next line.
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) * adapter.max_error_rate) if k > 2: raise ValueError("Error rate too high") @classmethod def is_acceptable(cls, adapter): """ Return whether this adapter is acceptable for being used in an index Adapters are not acceptable if they allow wildcards, allow too many errors, or would lead to a very large index. """ try: cls._accept(adapter) except ValueError: return False return True def _make_index(self) -> Tuple[List[int], "AdapterIndex"]: logger.info("Building index of %s adapters ...", len(self._adapters)) index: Dict[str, Tuple[SingleAdapter, int, int]] = dict() lengths = set() has_warned = False for adapter in self._adapters: sequence = adapter.sequence k = int(adapter.max_error_rate * len(sequence)) <|code_end|> , predict the next line using imports from the current file: import logging from enum import IntFlag from collections import defaultdict from typing import Optional, Tuple, Sequence, Dict, Any, List, Union from abc import ABC, abstractmethod from .align import ( EndSkip, Aligner, PrefixComparer, SuffixComparer, edit_environment, hamming_environment, ) and context including class names, function names, and sometimes code from other files: # Path: src/cutadapt/align.py # START_WITHIN_SEQ1 = 1 # START_WITHIN_SEQ2 = 2 # STOP_WITHIN_SEQ1 = 4 # STOP_WITHIN_SEQ2 = 8 # SEMIGLOBAL = 15 # REFERENCE_START = 1 # a prefix of the reference may be skipped at no cost # QUERY_START = 2 # a prefix of the query may be skipped at no cost # REFERENCE_END = 4 # a suffix of the reference may be skipeed at no cost # QUERY_STOP = 8 # a suffix of the query may be skipeed at no cost # SEMIGLOBAL = 15 # all of the above # class EndSkip(IntFlag): # def edit_distance(s: str, t: str) -> int: # def hamming_sphere(s: str, k: int) -> Iterator[str]: # def hamming_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def naive_edit_environment(s: str, k: int) -> Iterator[str]: # def edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: # def slow_edit_environment(s: str, k: int) -> Iterator[Tuple[str, int, int]]: . Output only the next line.
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 be passed on to subsequent steps). """ class HasStatistics(ABC): """ Used for the final steps (sinks), which also need to keep track of read length statistics """ @abstractmethod def get_statistics(self) -> ReadLengthStatistics: pass class SingleEndFilter(SingleEndStep): """ A pipeline step that can filter reads, can redirect filtered ones to a writer, and counts how many were filtered. """ <|code_end|> . Write the next line using the current file imports: from abc import ABC, abstractmethod from typing import Tuple, Dict, Optional, Any from .filters import Predicate from .modifiers import ModificationInfo from .statistics import ReadLengthStatistics from .utils import reverse_complemented_sequence and context from other files: # Path: src/cutadapt/filters.py # class Predicate(ABC): # @abstractmethod # def test(self, read, info: ModificationInfo) -> bool: # """ # Return True if the filtering criterion matches. # """ # # @classmethod # def descriptive_identifier(cls) -> str: # """ # Return a short name for this predicate based on the class name such as "too_long", # "too_many_expected_errors". # This is used as identifier in the JSON report. # """ # return "".join( # ("_" + ch.lower() if ch.isupper() else ch) for ch in cls.__name__ # )[1:] # # Path: src/cutadapt/modifiers.py # class ModificationInfo: # """ # An object of this class is created for each read that passes through the pipeline. # Any information (except the read itself) that needs to be passed from one modifier # to one later in the pipeline or from one modifier to the filters is recorded here. # """ # # __slots__ = ["matches", "original_read", "cut_prefix", "cut_suffix", "is_rc"] # # def __init__(self, read): # self.matches = [] # type: List[Match] # self.original_read = read # self.cut_prefix = None # self.cut_suffix = None # self.is_rc = None # # def __repr__(self): # return ( # "ModificationInfo(" # f"matches={self.matches!r}, " # f"original_read={self.original_read}, " # f"cut_prefix={self.cut_prefix}, " # f"cut_suffix={self.cut_suffix}, " # f"is_rc={self.is_rc})" # ) # # Path: src/cutadapt/statistics.py # class ReadLengthStatistics: # """ # Keep track of the lengths of written reads or read pairs # """ # # def __init__(self) -> None: # # It would be more natural to use a Counter, but a # # defaultdict is much faster # self._written_lengths1: DefaultDict[int, int] = defaultdict(int) # self._written_lengths2: DefaultDict[int, int] = defaultdict(int) # # def update(self, read) -> None: # """Add a single-end read to the statistics""" # self._written_lengths1[len(read)] += 1 # # def update2(self, read1, read2) -> None: # """Add a paired-end read to the statistics""" # self._written_lengths1[len(read1)] += 1 # self._written_lengths2[len(read2)] += 1 # # def written_reads(self) -> int: # """Return number of written reads or read pairs""" # return sum(self._written_lengths1.values()) # # def written_bp(self) -> Tuple[int, int]: # return ( # self._compute_total_bp(self._written_lengths1), # self._compute_total_bp(self._written_lengths2), # ) # # def written_lengths(self) -> Tuple[Counter, Counter]: # return (Counter(self._written_lengths1), Counter(self._written_lengths2)) # # @staticmethod # def _compute_total_bp(counts: DefaultDict[int, int]) -> int: # return sum(length * count for length, count in counts.items()) # # def __iadd__(self, other): # written_lengths1, written_lengths2 = other.written_lengths() # for length, count in written_lengths1.items(): # self._written_lengths1[length] += count # for length, count in written_lengths2.items(): # self._written_lengths2[length] += count # return self # # Path: src/cutadapt/utils.py # def reverse_complemented_sequence(sequence: dnaio.Sequence): # if sequence.qualities is None: # qualities = None # else: # qualities = sequence.qualities[::-1] # return dnaio.Sequence( # sequence.name, reverse_complement(sequence.sequence), qualities # ) , which may include functions, classes, or code. Output only the next line.
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 on to the next step. Steps are added to the pipeline in a certain order: 1. First RestFileWriter, InfoFileWriter, WildcardFileWriter because they should see all reads before filtering. 2. Filters come next. These are implemented as SingleEndFilter or PairedEndFilter instances with an appropriate Predicate. Filters can optionally send each consumed/filtered read to an output file. 3. The last pipeline step should be one of the "Sinks", which consume all reads. Demultiplexers are sinks, for example. """ # Constants used when returning from a step’s __call__ method to improve # readability (it is unintuitive that "return True" means "discard the read"). DISCARD = True KEEP = False class SingleEndStep(ABC): @abstractmethod <|code_end|> , determine the next line of code. You have imports: from abc import ABC, abstractmethod from typing import Tuple, Dict, Optional, Any from .filters import Predicate from .modifiers import ModificationInfo from .statistics import ReadLengthStatistics from .utils import reverse_complemented_sequence and context (class names, function names, or code) available: # Path: src/cutadapt/filters.py # class Predicate(ABC): # @abstractmethod # def test(self, read, info: ModificationInfo) -> bool: # """ # Return True if the filtering criterion matches. # """ # # @classmethod # def descriptive_identifier(cls) -> str: # """ # Return a short name for this predicate based on the class name such as "too_long", # "too_many_expected_errors". # This is used as identifier in the JSON report. # """ # return "".join( # ("_" + ch.lower() if ch.isupper() else ch) for ch in cls.__name__ # )[1:] # # Path: src/cutadapt/modifiers.py # class ModificationInfo: # """ # An object of this class is created for each read that passes through the pipeline. # Any information (except the read itself) that needs to be passed from one modifier # to one later in the pipeline or from one modifier to the filters is recorded here. # """ # # __slots__ = ["matches", "original_read", "cut_prefix", "cut_suffix", "is_rc"] # # def __init__(self, read): # self.matches = [] # type: List[Match] # self.original_read = read # self.cut_prefix = None # self.cut_suffix = None # self.is_rc = None # # def __repr__(self): # return ( # "ModificationInfo(" # f"matches={self.matches!r}, " # f"original_read={self.original_read}, " # f"cut_prefix={self.cut_prefix}, " # f"cut_suffix={self.cut_suffix}, " # f"is_rc={self.is_rc})" # ) # # Path: src/cutadapt/statistics.py # class ReadLengthStatistics: # """ # Keep track of the lengths of written reads or read pairs # """ # # def __init__(self) -> None: # # It would be more natural to use a Counter, but a # # defaultdict is much faster # self._written_lengths1: DefaultDict[int, int] = defaultdict(int) # self._written_lengths2: DefaultDict[int, int] = defaultdict(int) # # def update(self, read) -> None: # """Add a single-end read to the statistics""" # self._written_lengths1[len(read)] += 1 # # def update2(self, read1, read2) -> None: # """Add a paired-end read to the statistics""" # self._written_lengths1[len(read1)] += 1 # self._written_lengths2[len(read2)] += 1 # # def written_reads(self) -> int: # """Return number of written reads or read pairs""" # return sum(self._written_lengths1.values()) # # def written_bp(self) -> Tuple[int, int]: # return ( # self._compute_total_bp(self._written_lengths1), # self._compute_total_bp(self._written_lengths2), # ) # # def written_lengths(self) -> Tuple[Counter, Counter]: # return (Counter(self._written_lengths1), Counter(self._written_lengths2)) # # @staticmethod # def _compute_total_bp(counts: DefaultDict[int, int]) -> int: # return sum(length * count for length, count in counts.items()) # # def __iadd__(self, other): # written_lengths1, written_lengths2 = other.written_lengths() # for length, count in written_lengths1.items(): # self._written_lengths1[length] += count # for length, count in written_lengths2.items(): # self._written_lengths2[length] += count # return self # # Path: src/cutadapt/utils.py # def reverse_complemented_sequence(sequence: dnaio.Sequence): # if sequence.qualities is None: # qualities = None # else: # qualities = sequence.qualities[::-1] # return dnaio.Sequence( # sequence.name, reverse_complement(sequence.sequence), qualities # ) . Output only the next line.
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). """ 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 be passed on to subsequent steps). """ class HasStatistics(ABC): """ Used for the final steps (sinks), which also need to keep track of read length statistics """ @abstractmethod <|code_end|> . Use current file imports: from abc import ABC, abstractmethod from typing import Tuple, Dict, Optional, Any from .filters import Predicate from .modifiers import ModificationInfo from .statistics import ReadLengthStatistics from .utils import reverse_complemented_sequence and context (classes, functions, or code) from other files: # Path: src/cutadapt/filters.py # class Predicate(ABC): # @abstractmethod # def test(self, read, info: ModificationInfo) -> bool: # """ # Return True if the filtering criterion matches. # """ # # @classmethod # def descriptive_identifier(cls) -> str: # """ # Return a short name for this predicate based on the class name such as "too_long", # "too_many_expected_errors". # This is used as identifier in the JSON report. # """ # return "".join( # ("_" + ch.lower() if ch.isupper() else ch) for ch in cls.__name__ # )[1:] # # Path: src/cutadapt/modifiers.py # class ModificationInfo: # """ # An object of this class is created for each read that passes through the pipeline. # Any information (except the read itself) that needs to be passed from one modifier # to one later in the pipeline or from one modifier to the filters is recorded here. # """ # # __slots__ = ["matches", "original_read", "cut_prefix", "cut_suffix", "is_rc"] # # def __init__(self, read): # self.matches = [] # type: List[Match] # self.original_read = read # self.cut_prefix = None # self.cut_suffix = None # self.is_rc = None # # def __repr__(self): # return ( # "ModificationInfo(" # f"matches={self.matches!r}, " # f"original_read={self.original_read}, " # f"cut_prefix={self.cut_prefix}, " # f"cut_suffix={self.cut_suffix}, " # f"is_rc={self.is_rc})" # ) # # Path: src/cutadapt/statistics.py # class ReadLengthStatistics: # """ # Keep track of the lengths of written reads or read pairs # """ # # def __init__(self) -> None: # # It would be more natural to use a Counter, but a # # defaultdict is much faster # self._written_lengths1: DefaultDict[int, int] = defaultdict(int) # self._written_lengths2: DefaultDict[int, int] = defaultdict(int) # # def update(self, read) -> None: # """Add a single-end read to the statistics""" # self._written_lengths1[len(read)] += 1 # # def update2(self, read1, read2) -> None: # """Add a paired-end read to the statistics""" # self._written_lengths1[len(read1)] += 1 # self._written_lengths2[len(read2)] += 1 # # def written_reads(self) -> int: # """Return number of written reads or read pairs""" # return sum(self._written_lengths1.values()) # # def written_bp(self) -> Tuple[int, int]: # return ( # self._compute_total_bp(self._written_lengths1), # self._compute_total_bp(self._written_lengths2), # ) # # def written_lengths(self) -> Tuple[Counter, Counter]: # return (Counter(self._written_lengths1), Counter(self._written_lengths2)) # # @staticmethod # def _compute_total_bp(counts: DefaultDict[int, int]) -> int: # return sum(length * count for length, count in counts.items()) # # def __iadd__(self, other): # written_lengths1, written_lengths2 = other.written_lengths() # for length, count in written_lengths1.items(): # self._written_lengths1[length] += count # for length, count in written_lengths2.items(): # self._written_lengths2[length] += count # return self # # Path: src/cutadapt/utils.py # def reverse_complemented_sequence(sequence: dnaio.Sequence): # if sequence.qualities is None: # qualities = None # else: # qualities = sequence.qualities[::-1] # return dnaio.Sequence( # sequence.name, reverse_complement(sequence.sequence), qualities # ) . Output only the next line.
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, read, info) -> bool: # TODO this fails with linked adapters if info.matches: print(info.matches[-1].wildcards(), read.name, file=self._file) return KEEP class InfoFileWriter(SingleEndStep): RC_MAP = {None: "", True: "1", False: "0"} def __init__(self, file): self._file = file def __repr__(self): return f"InfoFileWriter(file={self._file})" def __call__(self, read, info: ModificationInfo): current_read = info.original_read if info.is_rc: <|code_end|> , generate the next line using the imports in this file: from abc import ABC, abstractmethod from typing import Tuple, Dict, Optional, Any from .filters import Predicate from .modifiers import ModificationInfo from .statistics import ReadLengthStatistics from .utils import reverse_complemented_sequence and context (functions, classes, or occasionally code) from other files: # Path: src/cutadapt/filters.py # class Predicate(ABC): # @abstractmethod # def test(self, read, info: ModificationInfo) -> bool: # """ # Return True if the filtering criterion matches. # """ # # @classmethod # def descriptive_identifier(cls) -> str: # """ # Return a short name for this predicate based on the class name such as "too_long", # "too_many_expected_errors". # This is used as identifier in the JSON report. # """ # return "".join( # ("_" + ch.lower() if ch.isupper() else ch) for ch in cls.__name__ # )[1:] # # Path: src/cutadapt/modifiers.py # class ModificationInfo: # """ # An object of this class is created for each read that passes through the pipeline. # Any information (except the read itself) that needs to be passed from one modifier # to one later in the pipeline or from one modifier to the filters is recorded here. # """ # # __slots__ = ["matches", "original_read", "cut_prefix", "cut_suffix", "is_rc"] # # def __init__(self, read): # self.matches = [] # type: List[Match] # self.original_read = read # self.cut_prefix = None # self.cut_suffix = None # self.is_rc = None # # def __repr__(self): # return ( # "ModificationInfo(" # f"matches={self.matches!r}, " # f"original_read={self.original_read}, " # f"cut_prefix={self.cut_prefix}, " # f"cut_suffix={self.cut_suffix}, " # f"is_rc={self.is_rc})" # ) # # Path: src/cutadapt/statistics.py # class ReadLengthStatistics: # """ # Keep track of the lengths of written reads or read pairs # """ # # def __init__(self) -> None: # # It would be more natural to use a Counter, but a # # defaultdict is much faster # self._written_lengths1: DefaultDict[int, int] = defaultdict(int) # self._written_lengths2: DefaultDict[int, int] = defaultdict(int) # # def update(self, read) -> None: # """Add a single-end read to the statistics""" # self._written_lengths1[len(read)] += 1 # # def update2(self, read1, read2) -> None: # """Add a paired-end read to the statistics""" # self._written_lengths1[len(read1)] += 1 # self._written_lengths2[len(read2)] += 1 # # def written_reads(self) -> int: # """Return number of written reads or read pairs""" # return sum(self._written_lengths1.values()) # # def written_bp(self) -> Tuple[int, int]: # return ( # self._compute_total_bp(self._written_lengths1), # self._compute_total_bp(self._written_lengths2), # ) # # def written_lengths(self) -> Tuple[Counter, Counter]: # return (Counter(self._written_lengths1), Counter(self._written_lengths2)) # # @staticmethod # def _compute_total_bp(counts: DefaultDict[int, int]) -> int: # return sum(length * count for length, count in counts.items()) # # def __iadd__(self, other): # written_lengths1, written_lengths2 = other.written_lengths() # for length, count in written_lengths1.items(): # self._written_lengths1[length] += count # for length, count in written_lengths2.items(): # self._written_lengths2[length] += count # return self # # Path: src/cutadapt/utils.py # def reverse_complemented_sequence(sequence: dnaio.Sequence): # if sequence.qualities is None: # qualities = None # else: # qualities = sequence.qualities[::-1] # return dnaio.Sequence( # sequence.name, reverse_complement(sequence.sequence), qualities # ) . Output only the next line.
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 = nn.layers.Pool2DLayer(input_layer, mode='average_inc_pad', **kwargs) l = nn.layers.ElemwiseMergeLayer([l, norm], T.true_div) return l def inceptionA(input_layer, name, nfilt): <|code_end|> using the current file's imports: import lasagne as nn import theano.tensor as T from utils.layer_macros import conv2dbn and any relevant context from other files: # Path: utils/layer_macros.py # def conv2dbn(l, name, **kwargs): # """ Batch normalized DNN Conv2D Layer """ # l = nn.layers.dnn.Conv2DDNNLayer( # l, name=name, # **kwargs # ) # l = batch_norm(l, name='%sbn' % name) # return l . Output only the next line.
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 import dnn from utils.layers import batch_norm2 as batch_norm and context (classes, functions, sometimes code) from other files: # Path: utils/layers.py # def batch_norm2(layer, **kwargs): # nonlinearity = getattr(layer, 'nonlinearity', None) # if nonlinearity is not None: # layer.nonlinearity = nn.nonlinearities.identity # if hasattr(layer, 'b') and layer.b is not None: # del layer.params[layer.b] # layer.b = None # layer = BatchNormLayer(layer, **kwargs) # if nonlinearity is not None: # from lasagne.layers.special import NonlinearityLayer # layer = NonlinearityLayer(layer, nonlinearity, name='%s_nl' % layer.name) # return layer . Output only the next line.
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' X_mean = load_mean(args.mean_fname, args.as_grey) if X_mean is None: print 'Failed to load mean file from', args.mean_fname sys.exit(1) net.batch_iterator_train.mean = X_mean net.batch_iterator_test.mean = X_mean print 'Injected mean image' print print 'Predicting...' if args.tta: print 'Using test time augmentation' scale_choices = [0.9, 1, 1.1] # shear_choices = [-0.25, 0, 0.25] rotation_choices = [0, 90, 180, 270] translation_choices = [-12, 0, 12] # scale_choices = [1] # shear_choices = [0] # rotation_choices = [0] # translation_choices = [0] <|code_end|> using the current file's imports: import argparse import importlib import os import sys import cPickle as pickle import numpy as np import pandas as pd from time import strftime from utils.test_time_augmentation import TestTimeAutgmentationPredictor and any relevant context from other files: # Path: utils/test_time_augmentation.py # class TestTimeAutgmentationPredictor(BaseEstimator): # def __init__(self, net, n_jobs=2, # scale_choices=[1], shear_choices=[0], # rotation_choices=[0], translation_choices=[0]): # self.net = net # self.pool = multiprocessing.Pool(processes=n_jobs) # self.scale_choices = scale_choices # self.shear_choices = shear_choices # self.rotation_choices = rotation_choices # self.translation_choices = translation_choices # # def predict_proba(self, X): # tf_args = list(itertools.product( # self.scale_choices, self.shear_choices, # self.rotation_choices, self.translation_choices # )) # # print 'Number of combinations', len(tf_args) # # X_probas = [] # # for x in tqdm(X, total=len(X)): # tta_transform_x = functools.partial(tta_transform, x) # x_tf = np.asarray(self.pool.map(tta_transform_x, tf_args)) # # x_tf_pred_probas = self.net.predict_proba(x_tf) # # x_tf_pred_proba = x_tf_pred_probas.sum(axis=0) # x_tf_pred_proba /= x_tf_pred_proba.sum() # # X_probas.append(x_tf_pred_proba) # # return np.vstack(X_probas) . Output only the next line.
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'],), present=(compare_data['present'],compare_data['extra'])) assert DEL == (compare_data['extra'],) def test_present_in_DEL_when_empty_wanted(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(), present=(compare_data['present'], compare_data['extra'])) assert DEL == (compare_data['present'], compare_data['extra']) def test_empty_ADD_when_empty_wanted(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(), present=(compare_data['present'],)) assert ADD == tuple() def test_difference_in_SET(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), present=(compare_data['present'],)) assert SET == (compare_data['difference'],) class Test_UniqueKeyComparator: def setup(self): <|code_end|> with the help of current file imports: import pytest from mcm.comparators import UniqueKeyComparator, SingleElementComparator, OrderedComparator from mcm.datastructures import CmdPathRow and context from other files: # Path: mcm/comparators.py # class UniqueKeyComparator: # # # def __init__(self, keys): # # self.keys = keys # self.SET = [] # self.ADD = [] # self.NO_DELETE = [] # # # def compare(self, wanted, present): # # for wanted_rule in wanted: # present_rule = self.findPair(searched=wanted_rule, present=present) # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # DEL = set(present) - set(self.NO_DELETE) # return tuple(self.ADD), tuple(self.SET), tuple(DEL) # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif wanted and difference and present: # self.NO_DELETE.append(present) # difference['.id'] = present['.id'] # self.SET.append( difference ) # elif wanted and not difference and present: # self.NO_DELETE.append(present) # # # def findPair(self, searched, present): # # for row in present: # if row.isunique(other=searched, keys=self.keys): # return row # else: # return CmdPathRow(dict()) # # class SingleElementComparator: # # # def compare(self, wanted, present): # SET = tuple() # for wanted_row, present_row in zip(wanted, present): # diff = wanted_row - present_row # SET = (diff,) if diff else tuple() # # return tuple(), SET, tuple() # # class OrderedComparator: # # # def __init__(self): # # self.DEL = [] # self.SET= [] # self.ADD = [] # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif not wanted and not difference and present: # self.DEL.append( present ) # elif wanted and difference and present: # difference['.id'] = present['.id'] # self.SET.append( difference ) # # # def compare(self, wanted, present): # # fillval = CmdPathRow(dict()) # for wanted_rule, present_rule in zip_longest(wanted, present, fillvalue=fillval): # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # return tuple(self.ADD), tuple(self.SET), tuple(self.DEL) # # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) , which may contain function names, class names, or code. Output only the next line.
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 = { 'wanted':CmdPathRow({'name':'admin', 'group':'read'}), 'present':CmdPathRow({'name':'admin', 'group':'full', '.id':'*2'}), 'extra':CmdPathRow({'name':'operator', 'group':'read', '.id':'*3'}), 'difference':CmdPathRow({'group':'read', '.id':'*2'}), } if 'single' in request.cls.__name__.lower(): return single else: return default class Test_SingleComparator: def setup(self): <|code_end|> , predict the immediate next line with the help of imports: import pytest from mcm.comparators import UniqueKeyComparator, SingleElementComparator, OrderedComparator from mcm.datastructures import CmdPathRow and context (classes, functions, sometimes code) from other files: # Path: mcm/comparators.py # class UniqueKeyComparator: # # # def __init__(self, keys): # # self.keys = keys # self.SET = [] # self.ADD = [] # self.NO_DELETE = [] # # # def compare(self, wanted, present): # # for wanted_rule in wanted: # present_rule = self.findPair(searched=wanted_rule, present=present) # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # DEL = set(present) - set(self.NO_DELETE) # return tuple(self.ADD), tuple(self.SET), tuple(DEL) # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif wanted and difference and present: # self.NO_DELETE.append(present) # difference['.id'] = present['.id'] # self.SET.append( difference ) # elif wanted and not difference and present: # self.NO_DELETE.append(present) # # # def findPair(self, searched, present): # # for row in present: # if row.isunique(other=searched, keys=self.keys): # return row # else: # return CmdPathRow(dict()) # # class SingleElementComparator: # # # def compare(self, wanted, present): # SET = tuple() # for wanted_row, present_row in zip(wanted, present): # diff = wanted_row - present_row # SET = (diff,) if diff else tuple() # # return tuple(), SET, tuple() # # class OrderedComparator: # # # def __init__(self): # # self.DEL = [] # self.SET= [] # self.ADD = [] # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif not wanted and not difference and present: # self.DEL.append( present ) # elif wanted and difference and present: # difference['.id'] = present['.id'] # self.SET.append( difference ) # # # def compare(self, wanted, present): # # fillval = CmdPathRow(dict()) # for wanted_rule, present_rule in zip_longest(wanted, present, fillvalue=fillval): # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # return tuple(self.ADD), tuple(self.SET), tuple(self.DEL) # # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) . Output only the next line.
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'],)) assert SET == (compare_data['difference'],) def test_empty_SET_when_same_data(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), present=(compare_data['wanted'],)) assert SET == tuple() def test_empty_SET_when_empty_wanted(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=tuple(), present=(compare_data['present'],)) assert SET == tuple() def test_empty_ADD(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), present=(compare_data['present'],)) assert ADD == tuple() def test_empty_DEL(self, compare_data): ADD, SET, DEL = self.comparator.compare(wanted=(compare_data['wanted'],), present=(compare_data['present'],)) assert DEL == tuple() class Test_OrderedComparator: def setup(self): <|code_end|> , predict the immediate next line with the help of imports: import pytest from mcm.comparators import UniqueKeyComparator, SingleElementComparator, OrderedComparator from mcm.datastructures import CmdPathRow and context (classes, functions, sometimes code) from other files: # Path: mcm/comparators.py # class UniqueKeyComparator: # # # def __init__(self, keys): # # self.keys = keys # self.SET = [] # self.ADD = [] # self.NO_DELETE = [] # # # def compare(self, wanted, present): # # for wanted_rule in wanted: # present_rule = self.findPair(searched=wanted_rule, present=present) # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # DEL = set(present) - set(self.NO_DELETE) # return tuple(self.ADD), tuple(self.SET), tuple(DEL) # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif wanted and difference and present: # self.NO_DELETE.append(present) # difference['.id'] = present['.id'] # self.SET.append( difference ) # elif wanted and not difference and present: # self.NO_DELETE.append(present) # # # def findPair(self, searched, present): # # for row in present: # if row.isunique(other=searched, keys=self.keys): # return row # else: # return CmdPathRow(dict()) # # class SingleElementComparator: # # # def compare(self, wanted, present): # SET = tuple() # for wanted_row, present_row in zip(wanted, present): # diff = wanted_row - present_row # SET = (diff,) if diff else tuple() # # return tuple(), SET, tuple() # # class OrderedComparator: # # # def __init__(self): # # self.DEL = [] # self.SET= [] # self.ADD = [] # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif not wanted and not difference and present: # self.DEL.append( present ) # elif wanted and difference and present: # difference['.id'] = present['.id'] # self.SET.append( difference ) # # # def compare(self, wanted, present): # # fillval = CmdPathRow(dict()) # for wanted_rule, present_rule in zip_longest(wanted, present, fillvalue=fillval): # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # return tuple(self.ADD), tuple(self.SET), tuple(self.DEL) # # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) . Output only the next line.
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 and context (classes, functions, or code) from other files: # Path: mcm/comparators.py # class UniqueKeyComparator: # # # def __init__(self, keys): # # self.keys = keys # self.SET = [] # self.ADD = [] # self.NO_DELETE = [] # # # def compare(self, wanted, present): # # for wanted_rule in wanted: # present_rule = self.findPair(searched=wanted_rule, present=present) # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # DEL = set(present) - set(self.NO_DELETE) # return tuple(self.ADD), tuple(self.SET), tuple(DEL) # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif wanted and difference and present: # self.NO_DELETE.append(present) # difference['.id'] = present['.id'] # self.SET.append( difference ) # elif wanted and not difference and present: # self.NO_DELETE.append(present) # # # def findPair(self, searched, present): # # for row in present: # if row.isunique(other=searched, keys=self.keys): # return row # else: # return CmdPathRow(dict()) # # class SingleElementComparator: # # # def compare(self, wanted, present): # SET = tuple() # for wanted_row, present_row in zip(wanted, present): # diff = wanted_row - present_row # SET = (diff,) if diff else tuple() # # return tuple(), SET, tuple() # # class OrderedComparator: # # # def __init__(self): # # self.DEL = [] # self.SET= [] # self.ADD = [] # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif not wanted and not difference and present: # self.DEL.append( present ) # elif wanted and difference and present: # difference['.id'] = present['.id'] # self.SET.append( difference ) # # # def compare(self, wanted, present): # # fillval = CmdPathRow(dict()) # for wanted_rule, present_rule in zip_longest(wanted, present, fillvalue=fillval): # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # return tuple(self.ADD), tuple(self.SET), tuple(self.DEL) # # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) . Output only the next line.
'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 with key, value pairs. ''' <|code_end|> , continue by predicting the next line. Consider current file imports: from mcm.librouteros.datastructures import mksnt, parsresp, trapCheck, raiseIfFatal from mcm.librouteros.exceptions import LibError and context: # Path: mcm/librouteros/datastructures.py # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # Path: mcm/librouteros/exceptions.py # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' which might include code, classes, or functions. Output only the next line.
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 Dictionary with key, value pairs. ''' snt = (cmd,) + mksnt( args ) self.rwo.writeSnt( snt ) response = self._readResponse() trapCheck( response ) raiseIfFatal( response ) <|code_end|> . Write the next line using the current file imports: from mcm.librouteros.datastructures import mksnt, parsresp, trapCheck, raiseIfFatal from mcm.librouteros.exceptions import LibError and context from other files: # Path: mcm/librouteros/datastructures.py # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # Path: mcm/librouteros/exceptions.py # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' , which may include functions, classes, or code. Output only the next line.
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 with key, value pairs. ''' snt = (cmd,) + mksnt( args ) self.rwo.writeSnt( snt ) response = self._readResponse() <|code_end|> , continue by predicting the next line. Consider current file imports: from mcm.librouteros.datastructures import mksnt, parsresp, trapCheck, raiseIfFatal from mcm.librouteros.exceptions import LibError and context: # Path: mcm/librouteros/datastructures.py # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # Path: mcm/librouteros/exceptions.py # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' which might include code, classes, or functions. Output only the next line.
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 Dictionary with key, value pairs. ''' snt = (cmd,) + mksnt( args ) self.rwo.writeSnt( snt ) response = self._readResponse() trapCheck( response ) <|code_end|> , determine the next line of code. You have imports: from mcm.librouteros.datastructures import mksnt, parsresp, trapCheck, raiseIfFatal from mcm.librouteros.exceptions import LibError and context (class names, function names, or code) available: # Path: mcm/librouteros/datastructures.py # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # Path: mcm/librouteros/exceptions.py # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' . Output only the next line.
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: break return tuple( snts ) def close( self ): ''' Send /quit and close the connection. ''' try: self.rwo.writeSnt( ('/quit',) ) self.rwo.readSnt() <|code_end|> , generate the next line using the imports in this file: from mcm.librouteros.datastructures import mksnt, parsresp, trapCheck, raiseIfFatal from mcm.librouteros.exceptions import LibError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/datastructures.py # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # Path: mcm/librouteros/exceptions.py # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' . Output only the next line.
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') as fp: return json_load(fp) except (OSError, IOError) as error: msg = 'Can not open {!r}. {}'.format raise ArgumentTypeError(msg(file, error)) except ValueError as error: msg = 'Error when parsing config file {!r}. {}'.format raise ArgumentTypeError(msg(file, error)) def get_arguments(): argparser = ArgumentParser(prog='mcm', epilog='By default program will issue a password prompt. If you don\'t want that, store it in MCM_HOST_PASSWORD environment variable.', <|code_end|> . Use current file imports: (from argparse import ArgumentParser, ArgumentTypeError from json import load as json_load from os import environ from getpass import getpass from mcm import __version__) and context including class names, function names, or small code snippets from other files: # Path: mcm.py . Output only the next line.
description='Mikrotik Configuration Manager. Version ' + str(__version__))