Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'projects', ProjectViewSet) router.register(r'modules', ModuleViewSet) router.register(r'issue_kinds', IssueKindViewSet) <|code_end|> with the help of current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import ProjectViewSet, ModuleViewSet, IssueKindViewSet, IssueViewSet, DirectoryViewSet and context from other files: # Path: server/daprojects_api/views.py # class ProjectViewSet(viewsets.ModelViewSet): # queryset = Project.objects.all() # serializer_class = ProjectSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug',) # # @detail_route(methods=['post']) # def initialize(self, request, pk=None): # project = self.get_object() # if project.modules.exists() or project.directories.exists(): # return Response('The project must be empty', status=status.HTTP_400_BAD_REQUEST) # dir_tree_serializer = DirectoryTreeSerializer(data=request.data, many=True) # if dir_tree_serializer.is_valid(): # init_project(project, dir_tree_serializer.validated_data) # return Response({'status': 'Project initialized'}) # else: # return Response(dir_tree_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # @detail_route(methods=['post']) # def sync_issues(self, request, pk=None): # project = self.get_object() # sync_module_serializer = SyncModuleSerializer(data=request.data, many=True, context={'request': request}) # if sync_module_serializer.is_valid(): # sync_issues(project, sync_module_serializer.validated_data) # return Response({'status': 'Project synchronized'}) # else: # return Response(sync_module_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # class ModuleViewSet(viewsets.ModelViewSet): # queryset = Module.objects.all() # serializer_class = ModuleSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug', 'project', 'parent') # # class IssueKindViewSet(viewsets.ModelViewSet): # queryset = IssueKind.objects.all() # serializer_class = IssueKindSerializer # # class IssueViewSet(viewsets.ModelViewSet): # queryset = Issue.objects.all() # serializer_class = IssueSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('module', 'kind', 'size') # # class DirectoryViewSet(viewsets.ModelViewSet): # queryset = Directory.objects.all() # serializer_class = DirectorySerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug', 'project', 'parent') , which may contain function names, class names, or code. Output only the next line.
router.register(r'issues', IssueViewSet)
Based on the snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'projects', ProjectViewSet) router.register(r'modules', ModuleViewSet) router.register(r'issue_kinds', IssueKindViewSet) router.register(r'issues', IssueViewSet) <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url, include from rest_framework import routers from .views import ProjectViewSet, ModuleViewSet, IssueKindViewSet, IssueViewSet, DirectoryViewSet and context (classes, functions, sometimes code) from other files: # Path: server/daprojects_api/views.py # class ProjectViewSet(viewsets.ModelViewSet): # queryset = Project.objects.all() # serializer_class = ProjectSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug',) # # @detail_route(methods=['post']) # def initialize(self, request, pk=None): # project = self.get_object() # if project.modules.exists() or project.directories.exists(): # return Response('The project must be empty', status=status.HTTP_400_BAD_REQUEST) # dir_tree_serializer = DirectoryTreeSerializer(data=request.data, many=True) # if dir_tree_serializer.is_valid(): # init_project(project, dir_tree_serializer.validated_data) # return Response({'status': 'Project initialized'}) # else: # return Response(dir_tree_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # @detail_route(methods=['post']) # def sync_issues(self, request, pk=None): # project = self.get_object() # sync_module_serializer = SyncModuleSerializer(data=request.data, many=True, context={'request': request}) # if sync_module_serializer.is_valid(): # sync_issues(project, sync_module_serializer.validated_data) # return Response({'status': 'Project synchronized'}) # else: # return Response(sync_module_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # class ModuleViewSet(viewsets.ModelViewSet): # queryset = Module.objects.all() # serializer_class = ModuleSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug', 'project', 'parent') # # class IssueKindViewSet(viewsets.ModelViewSet): # queryset = IssueKind.objects.all() # serializer_class = IssueKindSerializer # # class IssueViewSet(viewsets.ModelViewSet): # queryset = Issue.objects.all() # serializer_class = IssueSerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('module', 'kind', 'size') # # class DirectoryViewSet(viewsets.ModelViewSet): # queryset = Directory.objects.all() # serializer_class = DirectorySerializer # filter_backends = (filters.DjangoFilterBackend,) # filter_fields = ('slug', 'project', 'parent') . Output only the next line.
router.register(r'directories', DirectoryViewSet)
Given snippet: <|code_start|> class TestClient(unittest.TestCase): def test_set_base_url_and_token(self): client = APIClient( host_url = 'https://example.com:9090', auth_token = 'some_token', ) with patch('daprojects_python.client.requests.get') as mock_requests_get: mock_response = Mock() mock_response.json.return_value = [] mock_requests_get.return_value = mock_response <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import json from unittest.mock import Mock, patch from collections import namedtuple from requests import exceptions from .client import APIClient, APIResource from .resources import DAProjectsAPI and context: # Path: client/daprojects_python/daprojects_python/client.py # class APIClient: # def __init__(self, host_url=None, auth_token=None): # if not host_url: # host_url = 'http://localhost:8000' # if not host_url.startswith('http'): # host_url = 'http://' + host_url # self.base_url = host_url.lower().strip() + '/api/v1' # if not auth_token: # auth_token = '' # self.auth_token = auth_token # # def list_resources(self, resource_url, resource_class, filters={}): # response = requests.get( # resource_url, # params=filters, # headers={'Authorization': 'Token {}'.format(self.auth_token)} # ) # response.raise_for_status() # return [resource_class(**resource_data) for resource_data in response.json()] # # def retrieve_resource(self, resource_url, resource_class): # response = requests.get( # resource_url, # headers={'Authorization': 'Token {}'.format(self.auth_token)} # ) # response.raise_for_status() # return resource_class(**response.json()) # # def resource_action(self, action_url, action_data): # response = requests.post( # action_url, # data=json.dumps(action_data), # headers={ # 'content-type': 'application/json', # 'Authorization': 'Token {}'.format(self.auth_token) # } # ) # response.raise_for_status() # return response.json() # # class APIResource: # def __init__(self, **kwargs): # for key, value in kwargs.items(): # setattr(self, key, value) # # Path: client/daprojects_python/daprojects_python/resources.py # class DAProjectsAPI(): # # def __init__(self, *args, **kwargs): # client = APIClient(*args, **kwargs) # self.projects = Projects(client) # self.modules = Modules(client) # self.issue_kinds = IssueKinds(client) # self.issues = Issues(client) # self.directories = Directories(client) which might include code, classes, or functions. Output only the next line.
some_resources = client.list_resources(client.base_url + '/some_resources/', APIResource)
Given the following code snippet before the placeholder: <|code_start|> def test_resource_subclass(self): class SomeResource(APIResource): def some_method(self): return self.a + self.b client = APIClient() with patch('daprojects_python.client.requests.get') as mock_requests_get: mock_response = Mock() mock_response.json.return_value = { "url": 'http://localhost:8000/api/v1/some_resources/1/', "a": 66, "b": 99, } mock_requests_get.return_value = mock_response some_resource = client.retrieve_resource(client.base_url + '/some_resources/1/', SomeResource) mock_requests_get.assert_called_once_with( 'http://localhost:8000/api/v1/some_resources/1/', headers={'Authorization': 'Token '}, ) self.assertTrue(isinstance(some_resource, SomeResource)) self.assertEqual(some_resource.some_method(), 66 + 99) class TestProjects(unittest.TestCase): def test_set_base_url_and_token(self): with patch('daprojects_python.resources.APIClient') as mock_api_client: <|code_end|> , predict the next line using imports from the current file: import unittest import json from unittest.mock import Mock, patch from collections import namedtuple from requests import exceptions from .client import APIClient, APIResource from .resources import DAProjectsAPI and context including class names, function names, and sometimes code from other files: # Path: client/daprojects_python/daprojects_python/client.py # class APIClient: # def __init__(self, host_url=None, auth_token=None): # if not host_url: # host_url = 'http://localhost:8000' # if not host_url.startswith('http'): # host_url = 'http://' + host_url # self.base_url = host_url.lower().strip() + '/api/v1' # if not auth_token: # auth_token = '' # self.auth_token = auth_token # # def list_resources(self, resource_url, resource_class, filters={}): # response = requests.get( # resource_url, # params=filters, # headers={'Authorization': 'Token {}'.format(self.auth_token)} # ) # response.raise_for_status() # return [resource_class(**resource_data) for resource_data in response.json()] # # def retrieve_resource(self, resource_url, resource_class): # response = requests.get( # resource_url, # headers={'Authorization': 'Token {}'.format(self.auth_token)} # ) # response.raise_for_status() # return resource_class(**response.json()) # # def resource_action(self, action_url, action_data): # response = requests.post( # action_url, # data=json.dumps(action_data), # headers={ # 'content-type': 'application/json', # 'Authorization': 'Token {}'.format(self.auth_token) # } # ) # response.raise_for_status() # return response.json() # # class APIResource: # def __init__(self, **kwargs): # for key, value in kwargs.items(): # setattr(self, key, value) # # Path: client/daprojects_python/daprojects_python/resources.py # class DAProjectsAPI(): # # def __init__(self, *args, **kwargs): # client = APIClient(*args, **kwargs) # self.projects = Projects(client) # self.modules = Modules(client) # self.issue_kinds = IssueKinds(client) # self.issues = Issues(client) # self.directories = Directories(client) . Output only the next line.
daprojects_api = DAProjectsAPI(
Next line prediction: <|code_start|># file test_binfile/test_outlookexpress.py # # Copyright 2012 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. TEST_ROOT = os.path.dirname(__file__) # Outlook Express 4.5 Mac folder directory inside fixtures directory FIXTURE_FOLDER = os.path.join(TEST_ROOT, 'fixtures', 'oemacfolder') class TestMacIndex(unittest.TestCase): index_filename = os.path.join(FIXTURE_FOLDER, 'Index') data_filename = os.path.join(FIXTURE_FOLDER, 'Mail') def test_basic_properties(self): <|code_end|> . Use current file imports: (from email import message from eulcommon.binfile import outlookexpress import unittest import os) and context including class names, function names, or small code snippets from other files: # Path: eulcommon/binfile/outlookexpress.py # class MacIndex(binfile.BinaryStructure): # class MacIndexMessage(binfile.BinaryStructure): # class MacMail(binfile.BinaryStructure): # class MacMailMessage(binfile.BinaryStructure): # class MacFolder(object): # MAGIC_NUMBER = 'FMIn' # data file is FMDF # LENGTH = 52 # MAGIC_NUMBER = 'FMDF' # data file (?) # MESSAGE = 'MSum' # DELETED_MESSAGE = 'MDel' # def sanity_check(self): # def messages(self): # def sanity_check(self): # def get_message(self, offset, size): # def __init__(self, size, *args, **kwargs): # def deleted(self): # def data(self): # def as_email(self): # def __init__(self, folder_path): # def count(self): # def raw_messages(self): # def messages(self): # def all_messages(self): # def _messages(self, skip_deleted=True): . Output only the next line.
idx = outlookexpress.MacIndex(self.index_filename)
Continue the code snippet: <|code_start|> class TaskResultAdmin(admin.ModelAdmin): list_display = ('object_id', 'status_icon', 'label', 'created', 'duration', 'result') search_fields = ('object_id', 'label', 'result') list_filter = ('created', ) # disallow creating task results via admin site def has_add_permission(self, request): return False <|code_end|> . Use current file imports: from django.contrib import admin from .models import TaskResult and context (classes, functions, or code) from other files: # Path: eulcommon/djangoextras/taskresult/models.py # class TaskResult(models.Model): # label = models.CharField(max_length=100) # object_id = models.CharField(max_length=50) # url = models.URLField() # created = models.DateTimeField(auto_now_add=True) # task_id = models.CharField(max_length=100) # task_start = models.DateTimeField(blank=True, null=True) # task_end = models.DateTimeField(blank=True, null=True) # # @property # def task(self): # return AsyncResult(self.task_id) # # def __unicode__(self): # return self.label # # @property # def duration(self): # if self.task_end and self.task_start: # return self.task_end - self.task_start # else: # return '-' # # @property # def status(self): # return self.task.status # # @property # def result(self): # return self.task.result or '' # # # use font-awesome icons for short-hand status display? # unknown_icon = 'glyphicon-question-sign' # status_icon_map = { # 'pending': 'glyphicon-time', # 'success': 'glyphicon-ok', # 'failure': 'glyphicon-remove', # # 'failure': 'glyphicon-alert', # doesn't display in keep; version? # '': unknown_icon # } # status_style = { # 'pending': 'text-muted', # 'success': 'text-success', # 'failure': 'text-danger', # '': 'text-warning', # } # # def status_icon(self): # 'glyphicon for task status; requires bootstrap' # icon = self.status_icon_map.get(self.status.lower(), # self.unknown_icon) # style = self.status_style.get(self.status.lower(), '') # return mark_safe( # '<span class="glyphicon %s %s" aria-hidden="true"></span>' % # (icon, style)) # status_icon.short_description = 'Status' . Output only the next line.
admin.site.register(TaskResult, TaskResultAdmin)
Predict the next line after this snippet: <|code_start|># # Copyright 2010,2016 Emory University General Library # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ensure testsettings are loaded # NOTE: could cause problems if tests are run in another context (?) # if django_version < (1, 8): class TaskResultTestCase(TestCase): def test_start_end_duration(self): # create a task and send pre/post run signals to test signal handlers id = 'foo' <|code_end|> using the current file's imports: from time import sleep from celery.signals import task_prerun, task_postrun from django import VERSION as django_version from django.core.urlresolvers import reverse from django.test import TestCase from .models import TaskResult import pytest import test_setup and any relevant context from other files: # Path: eulcommon/djangoextras/taskresult/models.py # class TaskResult(models.Model): # label = models.CharField(max_length=100) # object_id = models.CharField(max_length=50) # url = models.URLField() # created = models.DateTimeField(auto_now_add=True) # task_id = models.CharField(max_length=100) # task_start = models.DateTimeField(blank=True, null=True) # task_end = models.DateTimeField(blank=True, null=True) # # @property # def task(self): # return AsyncResult(self.task_id) # # def __unicode__(self): # return self.label # # @property # def duration(self): # if self.task_end and self.task_start: # return self.task_end - self.task_start # else: # return '-' # # @property # def status(self): # return self.task.status # # @property # def result(self): # return self.task.result or '' # # # use font-awesome icons for short-hand status display? # unknown_icon = 'glyphicon-question-sign' # status_icon_map = { # 'pending': 'glyphicon-time', # 'success': 'glyphicon-ok', # 'failure': 'glyphicon-remove', # # 'failure': 'glyphicon-alert', # doesn't display in keep; version? # '': unknown_icon # } # status_style = { # 'pending': 'text-muted', # 'success': 'text-success', # 'failure': 'text-danger', # '': 'text-warning', # } # # def status_icon(self): # 'glyphicon for task status; requires bootstrap' # icon = self.status_icon_map.get(self.status.lower(), # self.unknown_icon) # style = self.status_style.get(self.status.lower(), '') # return mark_safe( # '<span class="glyphicon %s %s" aria-hidden="true"></span>' % # (icon, style)) # status_icon.short_description = 'Status' . Output only the next line.
tr = TaskResult(label='test task', object_id='id', url='/foo', task_id=id)
Given the following code snippet before the placeholder: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def html_view(request): "a simple view for testing content negotiation" return HttpResponse("HTML") def xml_view(request): return HttpResponse("XML") def json_view(request): return HttpResponse("JSON") class ContentNegotiationTest(TestCase): # known browser accept headers - taken from https://developer.mozilla.org/en/Content_negotiation FIREFOX = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' CHROME = 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' # same Accept header used by both Safari and Google Chrome IE8 = 'image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/msword, */*' def setUp(self): self.request = HttpRequest() # add content negotiation to test view defined above for testing <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase from django.http import HttpResponse, HttpRequest from eulcommon.djangoextras.http import content_negotiation and context including class names, function names, and sometimes code from other files: # Path: eulcommon/djangoextras/http/decorators.py # def content_negotiation(formats, default_type='text/html'): # """ # Provides basic content negotiation and returns a view method based on the # best match of content types as indicated in formats. # # :param formats: dictionary of content types and corresponding methods # :param default_type: string the decorated method is the return type for. # # Example usage:: # # def rdf_view(request, arg): # return RDF_RESPONSE # # @content_negotiation({'application/rdf+xml': rdf_view}) # def html_view(request, arg): # return HTML_RESPONSE # # The above example would return the rdf_view on a request type of # ``application/rdf+xml`` and the normal view for anything else. # # Any :class:`django.http.HttpResponse` returned by the view method chosen # by content negotiation will have a 'Vary: Accept' HTTP header added. # # **NOTE:** Some web browsers do content negotiation poorly, requesting # ``application/xml`` when what they really want is ``application/xhtml+xml`` or # ``text/html``. When this type of Accept request is detected, the default type # will be returned rather than the best match that would be determined by parsing # the Accept string properly (since in some cases the best match is # ``application/xml``, which could return non-html content inappropriate for # display in a web browser). # """ # def _decorator(view_method): # @wraps(view_method) # def _wrapped(request, *args, **kwargs): # # Changed this to be a value passed as a method argument defaulting # # to text/html instead so it's more flexible. # # default_type = 'text/html' # If not specificied assume HTML request. # # # Add text/html for the original method if not already included. # if default_type not in formats: # formats[default_type] = view_method # # try: # req_type = request.META['HTTP_ACCEPT'] # # # If this request is coming from a browser like that, just # # give them our default type instead of honoring the actual best match # # (see note above for more detail) # if '*/*' in req_type: # req_type = default_type # # except KeyError: # req_type = default_type # # # Get the best match for the content type requested. # content_type = mimeparse.best_match(formats.keys(), # req_type) # # # Return the view matching content type or the original view # # if no match. # if not content_type or content_type not in formats: # response = view_method(request, *args, **kwargs) # else: # response = formats[content_type](request, *args, **kwargs) # # # set a Vary header to indicate content may vary based on Accept header # if isinstance(response, HttpResponse): # views should return HttpResponse objects, but check to be sure # # note: using the same utility method used by django's vary_on_headers decorator # patch_vary_headers(response, ['Accept']) # return response # return _wrapped # return _decorator . Output only the next line.
decorator = content_negotiation({'application/xml': xml_view})
Predict the next line for this snippet: <|code_start|># file test_djangoextras/test_validators.py # # Copyright 2012 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestFileTypeValidator(unittest.TestCase): base_dir = os.path.dirname(os.path.abspath(__file__)) pdf_filename = os.path.join(base_dir, 'fixtures', 'test.pdf') def setUp(self): <|code_end|> with the help of current file imports: import unittest import os from django.forms import ValidationError from mock import Mock from eulcommon.djangoextras.validators import FileTypeValidator and context from other files: # Path: eulcommon/djangoextras/validators.py # class FileTypeValidator(object): # '''Validator for a :class:`django.forms.FileField` to check the # mimetype of an uploaded file using :mod:`magic`. Takes a list of # mimetypes and optional message; raises a # :class:`~django.core.exceptions.ValidationError` if the mimetype # of the uploaded file is not in the list of allowed types. # # :param types: list of acceptable mimetypes (defaults to empty list) # :param message: optional error validation error message # # Example use:: # # pdf = forms.FileField(label="PDF", # validators=[FileTypeValidator(types=["application/pdf"], # message="Upload a valid PDF document.")]) # # ''' # allowed_types = [] # # def __init__(self, types=None, message=None): # self.allowed_types = types or [] # if message is not None: # self.message = message # else: # self.message = 'Upload a file in an allowed format: %s' % \ # ', '.join(self.allowed_types) # # self.mime = magic.Magic(mime=True) # # def __call__(self, data): # """ # Validates that the input matches the specified mimetype. # # :param data: file data, expected to be an instance of # :class:`django.core.files.uploadedfile.UploadedFile`; # handles both # :class:`~django.core.files.uploadedfile.TemporaryUploadedFile` # and :class:`~django.core.files.uploadedfile.InMemoryUploadedFile`. # """ # # FIXME: check that data is an instance of # # django.core.files.uploadedfile.UploadedFile ? # # # temporary file uploaded to disk (i.e., handled TemporaryFileUploadHandler) # if hasattr(data, 'temporary_file_path'): # mimetype = self.mime.from_file(data.temporary_file_path()) # # # in-memory file (i.e., handled by MemoryFileUploadHandler) # else: # if hasattr(data, 'read'): # content = data.read() # else: # content = data['content'] # mimetype = self.mime.from_buffer(content) # # mtype, separator, options = mimetype.partition(';') # if mtype not in self.allowed_types: # raise ValidationError(self.message) , which may contain function names, class names, or code. Output only the next line.
self.text_val = FileTypeValidator(types=['text/plain'])
Using the snippet: <|code_start|># file test_binfile/test_eudora.py # # Copyright 2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. TEST_ROOT = os.path.dirname(__file__) def fixture(fname): return os.path.join(TEST_ROOT, 'fixtures', fname) class TestEudora(unittest.TestCase): def test_members(self): fname = fixture('In.toc') <|code_end|> , determine the next line of code. You have imports: import unittest import os from eulcommon.binfile import eudora and context (class names, function names, or code) available: # Path: eulcommon/binfile/eudora.py # class Toc(binfile.BinaryStructure): # class Message(binfile.BinaryStructure): # LENGTH = 278 # LENGTH = 220 # def messages(self): . Output only the next line.
obj = eudora.Toc(fname)
Based on the snippet: <|code_start|>''' Test list creation ''' class testListCreation(unittest.TestCase): ''' Test menu creation ''' def setUp(self): ''' list fixtures for tests ''' <|code_end|> , predict the immediate next line with the help of imports: import unittest from wirecurly.configuration import list, node and context (classes, functions, sometimes code) from other files: # Path: wirecurly/configuration/list.py # class List(object): # def __init__(self,name,default): # def addNode(self,node): # def getNodes(self): # def todict(self): # # Path: wirecurly/configuration/node.py # class Node(object): # def __init__(self,perm,add): # def todict(self): . Output only the next line.
self.list = list.List('gateways','deny')
Next line prediction: <|code_start|>''' Test list creation ''' class testListCreation(unittest.TestCase): ''' Test menu creation ''' def setUp(self): ''' list fixtures for tests ''' self.list = list.List('gateways','deny') def test_list_dict_ok(self): ''' Test that list is properly serialized ''' assert isinstance(self.list.todict(), dict) def test_adding_node(self): ''' Test if a node is properly add to a list ''' <|code_end|> . Use current file imports: (import unittest from wirecurly.configuration import list, node) and context including class names, function names, or small code snippets from other files: # Path: wirecurly/configuration/list.py # class List(object): # def __init__(self,name,default): # def addNode(self,node): # def getNodes(self): # def todict(self): # # Path: wirecurly/configuration/node.py # class Node(object): # def __init__(self,perm,add): # def todict(self): . Output only the next line.
n = node.Node('allow', '10.10.10.10/32')
Given the following code snippet before the placeholder: <|code_start|>''' Test gateway creation ''' class testGatewayCreation(unittest.TestCase): ''' Test gateway creation ''' def setUp(self): ''' gateway fixtures for tests ''' <|code_end|> , predict the next line using imports from the current file: import unittest import pytest from wirecurly.configuration import gateway and context including class names, function names, and sometimes code from other files: # Path: wirecurly/configuration/gateway.py # class Gateway(object): # def __init__(self, name): # def addParameter(self, param, val): # def getParameter(self, param): # def todict(self): . Output only the next line.
self.gw = gateway.Gateway('name')
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- @pytest.mark.parametrize("data,expected", [ ( {'tag': 'domain', 'children': [{'tag': 'params', 'children': []}, {'tag': 'variables', 'children': []}, {'tag': 'users', 'children': []}], 'attrs': {'name': 'wirephone.com.ar'}}, '<domain name="wirephone.com.ar"><users></users><params></params><variables></variables></domain>' ), ( {'tag': 'domain', 'children': [{'tag': 'params', 'children': [{'tag': 'param', 'attrs': {'name': 'test', 'data': True} ,'children': []}]}, {'tag': 'variables', 'children': []}, {'tag': 'users', 'children': []}], 'attrs': {'name': u'wirephone.com.ar'}}, '<domain name="wirephone.com.ar"><users></users><params><param name="test" data="true"/></params><variables></variables></domain>' ) ]) def test_xml_factory(data, expected): <|code_end|> with the help of current file imports: import logging import pytest from lxml import etree from utils import xml2d from wirecurly.serialize import XMLFactory and context from other files: # Path: wirecurly/serialize.py # class XMLFactory(object): # """Base factory for XML generation # # :param data: A dict with the specified format for XML generation # :type data: dict # """ # def __init__(self, data): # super(XMLFactory, self).__init__() # self.data = data # # # def _typecastAttributes(self, d): # ''' Typecast attributes to string or unicode # # :param d: the attributes dictionary # :type d: dict # # :rtype: dict -- The new dict with only strings and unicodes # ''' # for key in d: # val = d[key] # if type(val) == bool: # if val == True: # d[key] = 'true' # else: # d[key] = 'false' # elif type(val) == int: # d[key] = str(val) # elif type(val) == float: # d[key] = str(val) # elif val is None: # d[key] = u'' # return d # # def getXML(self): # '''Get the XML based on the data provided. # # :rtype: str - A string generated XML for `data` # ''' # self.root = etree.Element(self.data.get('tag'), **self._typecastAttributes(self.data.get('attrs', {}))) # if self.data.get('children'): # self._parseChildren(self.data.get('children'), self.root) # # return etree.tostring(self.root, pretty_print=True) # # def _parseChildren(self, children, parent): # ''' # Parse children of the dict to create XML structure # ''' # for child in children: # el = etree.SubElement(parent, child.get('tag'), **self._typecastAttributes(child.get('attrs', {}))) # if child.get('children'): # self._parseChildren(child.get('children'), el) # # def convert(self): # ''' # Abstract method that will serialize the XML as per the factory specification # ''' # raise NotImplementedError , which may contain function names, class names, or code. Output only the next line.
f = XMLFactory(data)
Given the code snippet: <|code_start|>''' Test condition creation for dialplan ''' class AppMock(object): """An application interface mockup""" def __init__(self): super(AppMock, self).__init__() self.app_name = 'test' self.data = '' class testConditionCreation(unittest.TestCase): ''' Test condition creation ''' def setUp(self): ''' Condition fixtures for tests ''' <|code_end|> , generate the next line using the imports in this file: import unittest from wirecurly.dialplan import condition from wirecurly.dialplan.expression import * and context (functions, classes, or occasionally code) from other files: # Path: wirecurly/dialplan/condition.py # class Condition(object): # class or_(object): # def __init__(self,attr=None,val=None,cont=False,expr=None): # def addAction(self,act,val,inline=False): # def addAntiAction(self,act,val,inline=False): # def addApplication(self, app,inline=False): # def existAction(self,act,val,inline=False): # def existAntiAction(self,act,val,inline=False): # def todict(self): # def __init__(self,*args): # def todict(self): . Output only the next line.
self.cond = condition.Condition('destination_number','1000')
Here is a snippet: <|code_start|>''' Test menu creation ''' class testMenuCreation(unittest.TestCase): ''' Test menu creation ''' def setUp(self): ''' menu fixtures for tests ''' <|code_end|> . Write the next line using the current file imports: import unittest import pytest from wirecurly.configuration import menu and context from other files: # Path: wirecurly/configuration/menu.py # class Menu(object): # def __init__(self,name): # def addAttr(self,attr,val): # def getAttr(self,attr): # def addEntry(self,action,digits,param): # def getEntry(self,digits): # def addInclude(self,value): # def todict(self): , which may include functions, classes, or code. Output only the next line.
self.menu = menu.Menu('on_hours')
Predict the next line for this snippet: <|code_start|>''' Test node creation for acls ''' class testNodeCreation(unittest.TestCase): ''' Test node creation ''' def setUp(self): ''' Node fixtures for tests ''' <|code_end|> with the help of current file imports: import unittest from wirecurly.configuration import node and context from other files: # Path: wirecurly/configuration/node.py # class Node(object): # def __init__(self,perm,add): # def todict(self): , which may contain function names, class names, or code. Output only the next line.
self.node = node.Node('allow','100.100.100.100/32')
Using the snippet: <|code_start|># -------------------------------------------------------- # TFFRCNN - Resnet50 # Copyright (c) 2016 # Licensed under The MIT License [see LICENSE for details] # Written by miraclebiu # -------------------------------------------------------- class PVAnet_test(Network): def __init__(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) self.keep_prob = tf.placeholder(tf.float32) self.layers = dict({'data': self.data, 'im_info': self.im_info}) self.trainable = trainable self.setup() def setup(self): <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf from .network import Network from ..fast_rcnn.config import cfg and context (class names, function names, or code) available: # Path: lib/fast_rcnn/config.py # __C = edict() # __C.IS_RPN = True # __C.ANCHOR_SCALES = [8, 16, 32] # __C.NCLASSES = 21 # __C.IS_MULTISCALE = False # __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' # __C.NET_NAME = 'VGGnet' # __C.SUBCLS_NAME = 'voxel_exemplars' # __C.TRAIN = edict() # __C.TRAIN.SOLVER = 'Momentum' # __C.TRAIN.WEIGHT_DECAY = 0.0005 # __C.TRAIN.LEARNING_RATE = 0.001 # __C.TRAIN.MOMENTUM = 0.9 # __C.TRAIN.GAMMA = 0.1 # __C.TRAIN.STEPSIZE = 50000 # __C.TRAIN.DISPLAY = 10 # __C.TRAIN.LOG_IMAGE_ITERS = 100 # __C.TRAIN.OHEM = False # __C.TRAIN.RANDOM_DOWNSAMPLE = False # __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # __C.TRAIN.KERNEL_SIZE = 5 # __C.TRAIN.ASPECTS= (1,) # __C.TRAIN.SCALES = (600,) # __C.TRAIN.MAX_SIZE = 1000 # __C.TRAIN.IMS_PER_BATCH = 2 # __C.TRAIN.BATCH_SIZE = 128 # __C.TRAIN.FG_FRACTION = 0.25 # __C.TRAIN.FG_THRESH = 0.5 # __C.TRAIN.BG_THRESH_HI = 0.5 # __C.TRAIN.BG_THRESH_LO = 0.1 # __C.TRAIN.USE_FLIPPED = True # __C.TRAIN.BBOX_REG = True # __C.TRAIN.BBOX_THRESH = 0.5 # __C.TRAIN.SNAPSHOT_ITERS = 5000 # __C.TRAIN.SNAPSHOT_PREFIX = 'VGGnet_fast_rcnn' # __C.TRAIN.SNAPSHOT_INFIX = '' # __C.TRAIN.USE_PREFETCH = False # __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True # __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) # __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # __C.TRAIN.PROPOSAL_METHOD = 'selective_search' # __C.TRAIN.ASPECT_GROUPING = True # __C.TRAIN.DONTCARE_AREA_INTERSECTION_HI = 0.5 # __C.TRAIN.PRECLUDE_HARD_SAMPLES = True # __C.TRAIN.HAS_RPN = True # __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # __C.TRAIN.RPN_CLOBBER_POSITIVES = False # __C.TRAIN.RPN_FG_FRACTION = 0.5 # __C.TRAIN.RPN_BATCHSIZE = 256 # __C.TRAIN.RPN_NMS_THRESH = 0.7 # __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # __C.TRAIN.RPN_MIN_SIZE = 16 # __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # __C.TEST = edict() # __C.TEST.SCALES = (600,) # __C.TEST.MAX_SIZE = 1000 # __C.TEST.NMS = 0.3 # __C.TEST.SVM = False # __C.TEST.BBOX_REG = True # __C.TEST.HAS_RPN = True # __C.TEST.PROPOSAL_METHOD = 'selective_search' # __C.TEST.RPN_NMS_THRESH = 0.7 # __C.TEST.RPN_PRE_NMS_TOP_N = 6000 # __C.TEST.RPN_POST_NMS_TOP_N = 300 # __C.TEST.RPN_MIN_SIZE = 16 # __C.DEDUP_BOXES = 1./16. # __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # __C.RNG_SEED = 3 # __C.EPS = 1e-14 # __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # __C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc')) # __C.MATLAB = 'matlab' # __C.EXP_DIR = 'default' # __C.LOG_DIR = 'default' # __C.USE_GPU_NMS = True # __C.GPU_ID = 0 # def get_output_dir(imdb, weights_filename): # def get_log_dir(imdb): # def _merge_a_into_b(a, b): # def cfg_from_file(filename): # def cfg_from_list(cfg_list): . Output only the next line.
n_classes = cfg.NCLASSES
Here is a snippet: <|code_start|># -------------------------------------------------------- # TFFRCNN - Resnet50 # Copyright (c) 2016 # Licensed under The MIT License [see LICENSE for details] # Written by miraclebiu # -------------------------------------------------------- class Resnet101_test(Network): def __init__(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) self.keep_prob = tf.placeholder(tf.float32) self.layers = dict({'data':self.data, 'im_info':self.im_info}) self.trainable = trainable self.setup() def setup(self): <|code_end|> . Write the next line using the current file imports: import tensorflow as tf import pdb from .network import Network from ..fast_rcnn.config import cfg and context from other files: # Path: lib/fast_rcnn/config.py # __C = edict() # __C.IS_RPN = True # __C.ANCHOR_SCALES = [8, 16, 32] # __C.NCLASSES = 21 # __C.IS_MULTISCALE = False # __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' # __C.NET_NAME = 'VGGnet' # __C.SUBCLS_NAME = 'voxel_exemplars' # __C.TRAIN = edict() # __C.TRAIN.SOLVER = 'Momentum' # __C.TRAIN.WEIGHT_DECAY = 0.0005 # __C.TRAIN.LEARNING_RATE = 0.001 # __C.TRAIN.MOMENTUM = 0.9 # __C.TRAIN.GAMMA = 0.1 # __C.TRAIN.STEPSIZE = 50000 # __C.TRAIN.DISPLAY = 10 # __C.TRAIN.LOG_IMAGE_ITERS = 100 # __C.TRAIN.OHEM = False # __C.TRAIN.RANDOM_DOWNSAMPLE = False # __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # __C.TRAIN.KERNEL_SIZE = 5 # __C.TRAIN.ASPECTS= (1,) # __C.TRAIN.SCALES = (600,) # __C.TRAIN.MAX_SIZE = 1000 # __C.TRAIN.IMS_PER_BATCH = 2 # __C.TRAIN.BATCH_SIZE = 128 # __C.TRAIN.FG_FRACTION = 0.25 # __C.TRAIN.FG_THRESH = 0.5 # __C.TRAIN.BG_THRESH_HI = 0.5 # __C.TRAIN.BG_THRESH_LO = 0.1 # __C.TRAIN.USE_FLIPPED = True # __C.TRAIN.BBOX_REG = True # __C.TRAIN.BBOX_THRESH = 0.5 # __C.TRAIN.SNAPSHOT_ITERS = 5000 # __C.TRAIN.SNAPSHOT_PREFIX = 'VGGnet_fast_rcnn' # __C.TRAIN.SNAPSHOT_INFIX = '' # __C.TRAIN.USE_PREFETCH = False # __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True # __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) # __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # __C.TRAIN.PROPOSAL_METHOD = 'selective_search' # __C.TRAIN.ASPECT_GROUPING = True # __C.TRAIN.DONTCARE_AREA_INTERSECTION_HI = 0.5 # __C.TRAIN.PRECLUDE_HARD_SAMPLES = True # __C.TRAIN.HAS_RPN = True # __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # __C.TRAIN.RPN_CLOBBER_POSITIVES = False # __C.TRAIN.RPN_FG_FRACTION = 0.5 # __C.TRAIN.RPN_BATCHSIZE = 256 # __C.TRAIN.RPN_NMS_THRESH = 0.7 # __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # __C.TRAIN.RPN_MIN_SIZE = 16 # __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # __C.TEST = edict() # __C.TEST.SCALES = (600,) # __C.TEST.MAX_SIZE = 1000 # __C.TEST.NMS = 0.3 # __C.TEST.SVM = False # __C.TEST.BBOX_REG = True # __C.TEST.HAS_RPN = True # __C.TEST.PROPOSAL_METHOD = 'selective_search' # __C.TEST.RPN_NMS_THRESH = 0.7 # __C.TEST.RPN_PRE_NMS_TOP_N = 6000 # __C.TEST.RPN_POST_NMS_TOP_N = 300 # __C.TEST.RPN_MIN_SIZE = 16 # __C.DEDUP_BOXES = 1./16. # __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # __C.RNG_SEED = 3 # __C.EPS = 1e-14 # __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # __C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc')) # __C.MATLAB = 'matlab' # __C.EXP_DIR = 'default' # __C.LOG_DIR = 'default' # __C.USE_GPU_NMS = True # __C.GPU_ID = 0 # def get_output_dir(imdb, weights_filename): # def get_log_dir(imdb): # def _merge_a_into_b(a, b): # def cfg_from_file(filename): # def cfg_from_list(cfg_list): , which may include functions, classes, or code. Output only the next line.
n_classes = cfg.NCLASSES
Given the code snippet: <|code_start|># -------------------------------------------------------- # TFFRCNN - Resnet50 # Copyright (c) 2016 # Licensed under The MIT License [see LICENSE for details] # Written by miraclebiu # -------------------------------------------------------- class Resnet50_test(Network): def __init__(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) self.keep_prob = tf.placeholder(tf.float32) self.layers = dict({'data':self.data, 'im_info':self.im_info}) self.trainable = trainable self.setup() def setup(self): <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf from .network import Network from ..fast_rcnn.config import cfg and context (functions, classes, or occasionally code) from other files: # Path: lib/fast_rcnn/config.py # __C = edict() # __C.IS_RPN = True # __C.ANCHOR_SCALES = [8, 16, 32] # __C.NCLASSES = 21 # __C.IS_MULTISCALE = False # __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' # __C.NET_NAME = 'VGGnet' # __C.SUBCLS_NAME = 'voxel_exemplars' # __C.TRAIN = edict() # __C.TRAIN.SOLVER = 'Momentum' # __C.TRAIN.WEIGHT_DECAY = 0.0005 # __C.TRAIN.LEARNING_RATE = 0.001 # __C.TRAIN.MOMENTUM = 0.9 # __C.TRAIN.GAMMA = 0.1 # __C.TRAIN.STEPSIZE = 50000 # __C.TRAIN.DISPLAY = 10 # __C.TRAIN.LOG_IMAGE_ITERS = 100 # __C.TRAIN.OHEM = False # __C.TRAIN.RANDOM_DOWNSAMPLE = False # __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # __C.TRAIN.KERNEL_SIZE = 5 # __C.TRAIN.ASPECTS= (1,) # __C.TRAIN.SCALES = (600,) # __C.TRAIN.MAX_SIZE = 1000 # __C.TRAIN.IMS_PER_BATCH = 2 # __C.TRAIN.BATCH_SIZE = 128 # __C.TRAIN.FG_FRACTION = 0.25 # __C.TRAIN.FG_THRESH = 0.5 # __C.TRAIN.BG_THRESH_HI = 0.5 # __C.TRAIN.BG_THRESH_LO = 0.1 # __C.TRAIN.USE_FLIPPED = True # __C.TRAIN.BBOX_REG = True # __C.TRAIN.BBOX_THRESH = 0.5 # __C.TRAIN.SNAPSHOT_ITERS = 5000 # __C.TRAIN.SNAPSHOT_PREFIX = 'VGGnet_fast_rcnn' # __C.TRAIN.SNAPSHOT_INFIX = '' # __C.TRAIN.USE_PREFETCH = False # __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True # __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) # __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # __C.TRAIN.PROPOSAL_METHOD = 'selective_search' # __C.TRAIN.ASPECT_GROUPING = True # __C.TRAIN.DONTCARE_AREA_INTERSECTION_HI = 0.5 # __C.TRAIN.PRECLUDE_HARD_SAMPLES = True # __C.TRAIN.HAS_RPN = True # __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # __C.TRAIN.RPN_CLOBBER_POSITIVES = False # __C.TRAIN.RPN_FG_FRACTION = 0.5 # __C.TRAIN.RPN_BATCHSIZE = 256 # __C.TRAIN.RPN_NMS_THRESH = 0.7 # __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # __C.TRAIN.RPN_MIN_SIZE = 16 # __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # __C.TEST = edict() # __C.TEST.SCALES = (600,) # __C.TEST.MAX_SIZE = 1000 # __C.TEST.NMS = 0.3 # __C.TEST.SVM = False # __C.TEST.BBOX_REG = True # __C.TEST.HAS_RPN = True # __C.TEST.PROPOSAL_METHOD = 'selective_search' # __C.TEST.RPN_NMS_THRESH = 0.7 # __C.TEST.RPN_PRE_NMS_TOP_N = 6000 # __C.TEST.RPN_POST_NMS_TOP_N = 300 # __C.TEST.RPN_MIN_SIZE = 16 # __C.DEDUP_BOXES = 1./16. # __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # __C.RNG_SEED = 3 # __C.EPS = 1e-14 # __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # __C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc')) # __C.MATLAB = 'matlab' # __C.EXP_DIR = 'default' # __C.LOG_DIR = 'default' # __C.USE_GPU_NMS = True # __C.GPU_ID = 0 # def get_output_dir(imdb, weights_filename): # def get_log_dir(imdb): # def _merge_a_into_b(a, b): # def cfg_from_file(filename): # def cfg_from_list(cfg_list): . Output only the next line.
n_classes = cfg.NCLASSES
Given snippet: <|code_start|> class VGGnet_test(Network): def __init__(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) self.keep_prob = tf.placeholder(tf.float32) self.layers = dict({'data':self.data, 'im_info':self.im_info}) self.trainable = trainable self.setup() def setup(self): # n_classes = 21 <|code_end|> , continue by predicting the next line. Consider current file imports: import tensorflow as tf from .network import Network from ..fast_rcnn.config import cfg and context: # Path: lib/fast_rcnn/config.py # __C = edict() # __C.IS_RPN = True # __C.ANCHOR_SCALES = [8, 16, 32] # __C.NCLASSES = 21 # __C.IS_MULTISCALE = False # __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' # __C.NET_NAME = 'VGGnet' # __C.SUBCLS_NAME = 'voxel_exemplars' # __C.TRAIN = edict() # __C.TRAIN.SOLVER = 'Momentum' # __C.TRAIN.WEIGHT_DECAY = 0.0005 # __C.TRAIN.LEARNING_RATE = 0.001 # __C.TRAIN.MOMENTUM = 0.9 # __C.TRAIN.GAMMA = 0.1 # __C.TRAIN.STEPSIZE = 50000 # __C.TRAIN.DISPLAY = 10 # __C.TRAIN.LOG_IMAGE_ITERS = 100 # __C.TRAIN.OHEM = False # __C.TRAIN.RANDOM_DOWNSAMPLE = False # __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # __C.TRAIN.KERNEL_SIZE = 5 # __C.TRAIN.ASPECTS= (1,) # __C.TRAIN.SCALES = (600,) # __C.TRAIN.MAX_SIZE = 1000 # __C.TRAIN.IMS_PER_BATCH = 2 # __C.TRAIN.BATCH_SIZE = 128 # __C.TRAIN.FG_FRACTION = 0.25 # __C.TRAIN.FG_THRESH = 0.5 # __C.TRAIN.BG_THRESH_HI = 0.5 # __C.TRAIN.BG_THRESH_LO = 0.1 # __C.TRAIN.USE_FLIPPED = True # __C.TRAIN.BBOX_REG = True # __C.TRAIN.BBOX_THRESH = 0.5 # __C.TRAIN.SNAPSHOT_ITERS = 5000 # __C.TRAIN.SNAPSHOT_PREFIX = 'VGGnet_fast_rcnn' # __C.TRAIN.SNAPSHOT_INFIX = '' # __C.TRAIN.USE_PREFETCH = False # __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True # __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) # __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # __C.TRAIN.PROPOSAL_METHOD = 'selective_search' # __C.TRAIN.ASPECT_GROUPING = True # __C.TRAIN.DONTCARE_AREA_INTERSECTION_HI = 0.5 # __C.TRAIN.PRECLUDE_HARD_SAMPLES = True # __C.TRAIN.HAS_RPN = True # __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # __C.TRAIN.RPN_CLOBBER_POSITIVES = False # __C.TRAIN.RPN_FG_FRACTION = 0.5 # __C.TRAIN.RPN_BATCHSIZE = 256 # __C.TRAIN.RPN_NMS_THRESH = 0.7 # __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # __C.TRAIN.RPN_MIN_SIZE = 16 # __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # __C.TEST = edict() # __C.TEST.SCALES = (600,) # __C.TEST.MAX_SIZE = 1000 # __C.TEST.NMS = 0.3 # __C.TEST.SVM = False # __C.TEST.BBOX_REG = True # __C.TEST.HAS_RPN = True # __C.TEST.PROPOSAL_METHOD = 'selective_search' # __C.TEST.RPN_NMS_THRESH = 0.7 # __C.TEST.RPN_PRE_NMS_TOP_N = 6000 # __C.TEST.RPN_POST_NMS_TOP_N = 300 # __C.TEST.RPN_MIN_SIZE = 16 # __C.DEDUP_BOXES = 1./16. # __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # __C.RNG_SEED = 3 # __C.EPS = 1e-14 # __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # __C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc')) # __C.MATLAB = 'matlab' # __C.EXP_DIR = 'default' # __C.LOG_DIR = 'default' # __C.USE_GPU_NMS = True # __C.GPU_ID = 0 # def get_output_dir(imdb, weights_filename): # def get_log_dir(imdb): # def _merge_a_into_b(a, b): # def cfg_from_file(filename): # def cfg_from_list(cfg_list): which might include code, classes, or functions. Output only the next line.
n_classes = cfg.NCLASSES
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @login_required @ensure_csrf_cookie def home(request): if not request.session.get('django_language', None): request.session['django_language'] = get_language() me = request.user.member following = me.following.all().count() followers = me.followers.all().count() nodwits = Dwit.objects.filter(member=me).count() context_vars={'me':me,'following':following,'followers':followers,'nodwits':nodwits,'navbar':'home'} if request.GET.get('tag'): context_vars.update({'tag':request.GET['tag']}) template_name='home.html' context = RequestContext(request) return render_to_response(template_name,context_vars,context_instance=context) @login_required def getflow(request, nfd): nod = settings.NUMBER_OF_DWITS context_vars = {} if request.GET.get('tag'): dwits = Dwit.objects.filter(tags__name=request.GET.get('tag'))[int(nfd):int(nfd)+int(nod)] elif request.GET.get('username'): <|code_end|> , determine the next line of code. You have imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (class names, function names, or code) available: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
me = get_object_or_404(Member, user__username=request.GET['username'])
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @login_required @ensure_csrf_cookie def home(request): if not request.session.get('django_language', None): request.session['django_language'] = get_language() me = request.user.member following = me.following.all().count() followers = me.followers.all().count() <|code_end|> , determine the next line of code. You have imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (class names, function names, or code) available: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
nodwits = Dwit.objects.filter(member=me).count()
Given snippet: <|code_start|> followers = me.followers.all().count() nodwits = Dwit.objects.filter(member=me).count() context_vars={'me':me,'following':following,'followers':followers,'nodwits':nodwits,'navbar':'home'} if request.GET.get('tag'): context_vars.update({'tag':request.GET['tag']}) template_name='home.html' context = RequestContext(request) return render_to_response(template_name,context_vars,context_instance=context) @login_required def getflow(request, nfd): nod = settings.NUMBER_OF_DWITS context_vars = {} if request.GET.get('tag'): dwits = Dwit.objects.filter(tags__name=request.GET.get('tag'))[int(nfd):int(nfd)+int(nod)] elif request.GET.get('username'): me = get_object_or_404(Member, user__username=request.GET['username']) dwits = Dwit.objects.filter(member = me)[int(nfd):int(nfd)+int(nod)] context_vars.update({'profile':True}) elif request.GET.get('hash'): form = SearchForm(request.GET) if form.is_valid(): if form.cleaned_data.get('hash'): hashes = form.cleaned_data['hash'] hashes = hashes.replace(',','') hashes_array = hashes.split() dwits = Dwit.objects.filter(tags__name__in=hashes_array).distinct()[int(nfd):int(nfd)+int(nod)] context_vars.update({'search':True}) else: me = request.user.member <|code_end|> , continue by predicting the next line. Consider current file imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) which might include code, classes, or functions. Output only the next line.
dwitspf = DPF.objects.filter(member = me)[int(nfd):int(nfd)+int(nod)]
Given the code snippet: <|code_start|> return render_to_response(template_name,context_vars,context_instance=context) @login_required def dwit(request): if request.method != 'POST': response = HttpResponse(mimetype="text/html") response['content-type']="text/html; charset=UTF-8" response.write(u"POST only!.") return response me = request.user.member if request.POST.get('dwit'): content = escape(request.POST['dwit']) direct = False if re.match('^\@\w+',content): try: Member.objects.get(user__username=re.match('^\@\w+',content).group(0)[1:]) direct = True except Member.DoesNotExist: response = HttpResponse(mimetype="application/json") response.write(u'{"status":"error","message":"'+_('No sush user.')+'"}') return response tags = re.findall(r' #\w+',content) try: replyto = Dwit.objects.get(pk = request.POST.get('dwitid',None)) except Dwit.DoesNotExist: replyto = None dwit = Dwit.objects.create(member = me, content = content, replyto = replyto, direct=direct) for tag in tags: dwit.tags.add(tag[2:]) rendered = render_to_string('flow.html',{'dwits':[dwit]}) <|code_end|> , generate the next line using the imports in this file: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (functions, classes, or occasionally code) from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
celery_dwitsaved.delay(dwit, rendered)
Continue the code snippet: <|code_start|> context_vars={'m':m,'fing':fing,'fers':fers,'action':action,'nodwits':nodwits,'following':following,'followers':followers,'navbar':'profile'} if not action: if request.method == 'POST': form = MemberForm(request.POST, request.FILES, instance=m) if form.is_valid(): if request.LANGUAGE_CODE != form.cleaned_data['language']: request.session['django_language'] = form.cleaned_data['language'] translation.activate(form.cleaned_data['language']) form.save() context_vars.update({'success':_('Changes saved'),'form':form,'current_lang':m.language}) else: ferrors = '' for field in form: if field.errors: ferrors += '<b>'+field.label+'</b>: ' for error in field.errors: ferrors += error+'<br />' context_vars.update({'ferrors':ferrors,'form':form,'current_lang':m.language}) else: form = MemberForm(instance=m) context_vars.update({'form':form,'current_lang':m.language}) template_name='profile.html' context = RequestContext(request) return render_to_response(template_name,context_vars,context_instance=context) @login_required def follow(request, username): m = get_object_or_404(Member, user__username=username) me = request.user.member me.following.add(m) <|code_end|> . Use current file imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (classes, functions, or code) from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
celery_follow.delay(me, m)
Given snippet: <|code_start|> ferrors = '' for field in form: if field.errors: ferrors += '<b>'+field.label+'</b>: ' for error in field.errors: ferrors += error+'<br />' context_vars.update({'ferrors':ferrors,'form':form,'current_lang':m.language}) else: form = MemberForm(instance=m) context_vars.update({'form':form,'current_lang':m.language}) template_name='profile.html' context = RequestContext(request) return render_to_response(template_name,context_vars,context_instance=context) @login_required def follow(request, username): m = get_object_or_404(Member, user__username=username) me = request.user.member me.following.add(m) celery_follow.delay(me, m) response = HttpResponse(mimetype="text/html") response['content-type']="text/html; charset=UTF-8" response.write(_('You follow %s') % username) return response @login_required def unfollow(request, username): m = get_object_or_404(Member, user__username=username) me = request.user.member me.following.remove(m) <|code_end|> , continue by predicting the next line. Consider current file imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) which might include code, classes, or functions. Output only the next line.
celery_unfollow.delay(me,m)
Based on the snippet: <|code_start|> if dwit.tags: tags = dwit.tags.all() newdwit.tags.add(*tags) rendered = render_to_string('flow.html',{'dwits':[newdwit]}) celery_dwitsaved.delay(newdwit, rendered) response = HttpResponse(mimetype="application/json") response.write('{"status":"success","message":"'+_('Dwit published.')+'"}') return response @login_required @ensure_csrf_cookie def profile(request,username): m = get_object_or_404(Member, user__username=username) nodwits = Dwit.objects.filter(member=m).count() fing = m.following.all() following = len(fing) if request.user.username != username: me = request.user.member me_fing = me.following.all() if m in me_fing: action = 'unfollow' else: action = 'follow' else: action = None fers = m.followers.all() followers = len(fers) context_vars={'m':m,'fing':fing,'fers':fers,'action':action,'nodwits':nodwits,'following':following,'followers':followers,'navbar':'profile'} if not action: if request.method == 'POST': <|code_end|> , predict the immediate next line with the help of imports: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (classes, functions, sometimes code) from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
form = MemberForm(request.POST, request.FILES, instance=m)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- @login_required @ensure_csrf_cookie def home(request): if not request.session.get('django_language', None): request.session['django_language'] = get_language() me = request.user.member following = me.following.all().count() followers = me.followers.all().count() nodwits = Dwit.objects.filter(member=me).count() context_vars={'me':me,'following':following,'followers':followers,'nodwits':nodwits,'navbar':'home'} if request.GET.get('tag'): context_vars.update({'tag':request.GET['tag']}) template_name='home.html' context = RequestContext(request) return render_to_response(template_name,context_vars,context_instance=context) @login_required def getflow(request, nfd): nod = settings.NUMBER_OF_DWITS context_vars = {} if request.GET.get('tag'): dwits = Dwit.objects.filter(tags__name=request.GET.get('tag'))[int(nfd):int(nfd)+int(nod)] elif request.GET.get('username'): me = get_object_or_404(Member, user__username=request.GET['username']) dwits = Dwit.objects.filter(member = me)[int(nfd):int(nfd)+int(nod)] context_vars.update({'profile':True}) elif request.GET.get('hash'): <|code_end|> , generate the next line using the imports in this file: import re from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import ensure_csrf_cookie from django.conf import settings from django.utils.html import escape from django.utils.translation import ugettext as _ from django.utils.translation import get_language from dwitter.main.models import Member, Dwit, DPF from dwitter.main.tasks import celery_dwitsaved, celery_follow, celery_unfollow from dwitter.main.forms import MemberForm, SearchForm from django.utils import translation and context (functions, classes, or occasionally code) from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] # # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # Path: dwitter/main/tasks.py # @task # def celery_dwitsaved(dwit, rendered): # if dwit.direct: # fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) # else: # fers = dwit.member.followers.all() # for fer in fers: # DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) # emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) # tags = dwit.tags.all() # if tags: # for tag in tags: # emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) # # @task # def celery_follow(me, m): # dwits = Dwit.objects.filter(member=m).exclude(direct=True) # for dwit in dwits: # DPF.objects.create(member = me, dwit = dwit, stamp = dwit.stamp) # # @task # def celery_unfollow(me, m): # DPF.objects.filter(member = me, dwit__member=m).delete() # # Path: dwitter/main/forms.py # class MemberForm(ModelForm): # image = forms.ImageField(label=u'Εικόνα', required=False) # class Meta: # model = Member # exclude = ('user','following') # widgets = {'descr':widgets.Textarea(attrs={'rows':'3','class':'input-xlarge'})} # # class SearchForm(forms.Form): # member = forms.CharField(label=_(u'Users'), required=False, help_text=_(u'Words seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Users'),'class':'input-xlarge'})) # hash = forms.CharField(label=_(u'Hash tags'), required=False, help_text=_(u'Tags without # seperated with spaces.'), # widget = widgets.TextInput(attrs={'placeholder':_(u'Hash tags'),'class':'input-xlarge'})) . Output only the next line.
form = SearchForm(request.GET)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class MemberIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): <|code_end|> , predict the immediate next line with the help of imports: from haystack import indexes from dwitter.main.models import Member and context (classes, functions, sometimes code) from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username . Output only the next line.
return Member
Given the code snippet: <|code_start|> # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj) def has_perms(self, perm_list, obj=None): """ Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object. """ for perm in perm_list: if not self.has_perm(perm, obj): return False return True def has_module_perms(self, app_label): """ Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label) def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ <|code_end|> , generate the next line using the imports in this file: import urllib from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.manager import EmptyManager from django.utils.crypto import get_random_string from django.utils.encoding import smart_str from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib import auth from auth.hashers import ( check_password, make_password, is_password_usable, UNUSABLE_PASSWORD) from auth.signals import user_logged_in from django.contrib.contenttypes.models import ContentType from dwitter.main.tasks import celery_send_mail from django.conf import settings and context (functions, classes, or occasionally code) from other files: # Path: dwitter/main/tasks.py # @task # def celery_send_mail(subject, message, from_email, to_email): # send_mail(subject, message, from_email, [to_email]) . Output only the next line.
celery_send_mail.delay(subject, message, from_email, [self.email])
Next line prediction: <|code_start|> class RegistrationAdmin(admin.ModelAdmin): actions = ['activate_users', 'resend_activation_email'] list_display = ('user', 'activation_key', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name', 'user__last_name') def activate_users(self, request, queryset): """ Activates the selected users, if they are not alrady activated. """ for profile in queryset: <|code_end|> . Use current file imports: (from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from registration.models import RegistrationProfile) and context including class names, function names, or small code snippets from other files: # Path: registration/models.py # class RegistrationProfile(models.Model): # """ # A simple profile which stores an activation key for use during # user account registration. # # Generally, you will not want to interact directly with instances # of this model; the provided manager includes methods # for creating and activating new accounts, as well as for cleaning # out accounts which have never been activated. # # While it is possible to use this model as the value of the # ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do # so. This model's sole purpose is to store data temporarily during # account registration and activation. # # """ # ACTIVATED = u"ALREADY_ACTIVATED" # # user = models.ForeignKey(User, unique=True, verbose_name=_('user')) # activation_key = models.CharField(_('activation key'), max_length=40) # language = models.CharField(_(u'Language'), max_length=5, default='en') # objects = RegistrationManager() # # class Meta: # verbose_name = _('registration profile') # verbose_name_plural = _('registration profiles') # # def __unicode__(self): # return u"Registration information for %s" % self.user # # def activation_key_expired(self): # """ # Determine whether this ``RegistrationProfile``'s activation # key has expired, returning a boolean -- ``True`` if the key # has expired. # # Key expiration is determined by a two-step process: # # 1. If the user has already activated, the key will have been # reset to the string constant ``ACTIVATED``. Re-activating # is not permitted, and so this method returns ``True`` in # this case. # # 2. Otherwise, the date the user signed up is incremented by # the number of days specified in the setting # ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of # days after signup during which a user is allowed to # activate their account); if the result is less than or # equal to the current date, the key has expired and this # method returns ``True``. # # """ # expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) # return self.activation_key == self.ACTIVATED or \ # (self.user.date_joined + expiration_date <= datetime_now()) # activation_key_expired.boolean = True # # def send_activation_email(self, site): # """ # Send an activation email to the user associated with this # ``RegistrationProfile``. # # The activation email will make use of two templates: # # ``registration/activation_email_subject.txt`` # This template will be used for the subject line of the # email. Because it is used as the subject line of an email, # this template's output **must** be only a single line of # text; output longer than one line will be forcibly joined # into only a single line. # # ``registration/activation_email.txt`` # This template will be used for the body of the email. # # These templates will each receive the following context # variables: # # ``activation_key`` # The activation key for the new account. # # ``expiration_days`` # The number of days remaining during which the account may # be activated. # # ``site`` # An object representing the site on which the user # registered; depending on whether ``django.contrib.sites`` # is installed, this may be an instance of either # ``django.contrib.sites.models.Site`` (if the sites # application is installed) or # ``django.contrib.sites.models.RequestSite`` (if # not). Consult the documentation for the Django sites # framework for details regarding these objects' interfaces. # # """ # ctx_dict = {'activation_key': self.activation_key, # 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, # 'site': site} # subject = render_to_string('registration/activation_email_subject.txt', # ctx_dict) # # Email subject *must not* contain newlines # subject = ''.join(subject.splitlines()) # # message = render_to_string('registration/activation_email.txt', # ctx_dict) # # celery_send_mail.delay(subject, message, settings.DEFAULT_FROM_EMAIL, self.user.email) . Output only the next line.
RegistrationProfile.objects.activate_user(profile.activation_key)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- class MemberForm(ModelForm): image = forms.ImageField(label=u'Εικόνα', required=False) class Meta: <|code_end|> with the help of current file imports: from django.forms import ModelForm from django import forms from django.forms import widgets from django.utils.translation import ugettext_lazy as _ from dwitter.main.models import Member and context from other files: # Path: dwitter/main/models.py # class Member(models.Model): # user = models.OneToOneField(User) # following = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followers') # nick = models.CharField(_(u'Name'), max_length=50) # descr = models.TextField(_(u'Description'),blank=True) # image = models.ImageField(_(u'Image'), upload_to=uploadto, default='none.png') # language = models.CharField(_(u'Language'), max_length=5, default='en') # # def __unicode__(self): # return self.user.username , which may contain function names, class names, or code. Output only the next line.
model = Member
Based on the snippet: <|code_start|> @never_cache def remote_user_auth_view(request): "Dummy view for remote user tests" t = Template("Username is {{ user }}.") c = RequestContext(request, {}) return HttpResponse(t.render(c)) def auth_processor_no_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_no_access.html', <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns, url from auth import context_processors from auth.urls import urlpatterns from auth.views import password_reset from auth.decorators import login_required from django.contrib.messages.api import info from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import Template, RequestContext from django.views.decorators.cache import never_cache and context (classes, functions, sometimes code) from other files: # Path: auth/context_processors.py # class PermLookupDict(object): # class PermWrapper(object): # def __init__(self, user, module_name): # def __repr__(self): # def __getitem__(self, perm_name): # def __nonzero__(self): # def __init__(self, user): # def __getitem__(self, module_name): # def __iter__(self): # def auth(request): # # Path: auth/views.py # @csrf_protect # def password_reset(request, is_admin_site=False, # template_name='registration/password_reset_form.html', # email_template_name='registration/password_reset_email.html', # subject_template_name='registration/password_reset_subject.txt', # password_reset_form=PasswordResetForm, # token_generator=default_token_generator, # post_reset_redirect=None, # from_email=None, # current_app=None, # extra_context=None): # if post_reset_redirect is None: # post_reset_redirect = reverse('auth.views.password_reset_done') # if request.method == "POST": # form = password_reset_form(request.POST) # if form.is_valid(): # opts = { # 'use_https': request.is_secure(), # 'token_generator': token_generator, # 'from_email': from_email, # 'email_template_name': email_template_name, # 'subject_template_name': subject_template_name, # 'request': request, # } # if is_admin_site: # opts = dict(opts, domain_override=request.META['HTTP_HOST']) # form.save(**opts) # return HttpResponseRedirect(post_reset_redirect) # else: # form = password_reset_form() # context = { # 'form': form, # } # if extra_context is not None: # context.update(extra_context) # return TemplateResponse(request, template_name, context, # current_app=current_app) . Output only the next line.
RequestContext(request, {}, processors=[context_processors.auth]))
Predict the next line for this snippet: <|code_start|> {'session_accessed':request.session.accessed}) def auth_processor_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_access.html', RequestContext(request, {}, processors=[context_processors.auth])) return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed':request.session.accessed}) def auth_processor_user(request): return render_to_response('context_processors/auth_attrs_user.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_perms(request): return render_to_response('context_processors/auth_attrs_perms.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_messages(request): info(request, "Message 1") return render_to_response('context_processors/auth_attrs_messages.html', RequestContext(request, {}, processors=[context_processors.auth])) def userpage(request): pass # special urls for auth test cases urlpatterns = urlpatterns + patterns('', (r'^logout/custom_query/$', 'auth.views.logout', dict(redirect_field_name='follow')), (r'^logout/next_page/$', 'auth.views.logout', dict(next_page='/somewhere/')), (r'^remote_user/$', remote_user_auth_view), (r'^password_reset_from_email/$', 'auth.views.password_reset', dict(from_email='staffmember@example.com')), <|code_end|> with the help of current file imports: from django.conf.urls import patterns, url from auth import context_processors from auth.urls import urlpatterns from auth.views import password_reset from auth.decorators import login_required from django.contrib.messages.api import info from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import Template, RequestContext from django.views.decorators.cache import never_cache and context from other files: # Path: auth/context_processors.py # class PermLookupDict(object): # class PermWrapper(object): # def __init__(self, user, module_name): # def __repr__(self): # def __getitem__(self, perm_name): # def __nonzero__(self): # def __init__(self, user): # def __getitem__(self, module_name): # def __iter__(self): # def auth(request): # # Path: auth/views.py # @csrf_protect # def password_reset(request, is_admin_site=False, # template_name='registration/password_reset_form.html', # email_template_name='registration/password_reset_email.html', # subject_template_name='registration/password_reset_subject.txt', # password_reset_form=PasswordResetForm, # token_generator=default_token_generator, # post_reset_redirect=None, # from_email=None, # current_app=None, # extra_context=None): # if post_reset_redirect is None: # post_reset_redirect = reverse('auth.views.password_reset_done') # if request.method == "POST": # form = password_reset_form(request.POST) # if form.is_valid(): # opts = { # 'use_https': request.is_secure(), # 'token_generator': token_generator, # 'from_email': from_email, # 'email_template_name': email_template_name, # 'subject_template_name': subject_template_name, # 'request': request, # } # if is_admin_site: # opts = dict(opts, domain_override=request.META['HTTP_HOST']) # form.save(**opts) # return HttpResponseRedirect(post_reset_redirect) # else: # form = password_reset_form() # context = { # 'form': form, # } # if extra_context is not None: # context.update(extra_context) # return TemplateResponse(request, template_name, context, # current_app=current_app) , which may contain function names, class names, or code. Output only the next line.
(r'^login_required/$', login_required(password_reset)),
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @task def celery_dwitsaved(dwit, rendered): if dwit.direct: fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) else: fers = dwit.member.followers.all() for fer in fers: DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) <|code_end|> , determine the next line of code. You have imports: from django.core.mail import send_mail from django.conf import settings from celery import task from dwitter.main.utils import emit_to_channel from dwitter.main.models import DPF, Dwit import json import re import subprocess and context (class names, function names, or code) available: # Path: dwitter/main/utils.py # def emit_to_channel(channel, event, *data): # r = redis_connection() # args = list(data) # r.publish('socketio_%s' % channel, json.dumps({'name': event, 'args': args})) # # Path: dwitter/main/models.py # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] . Output only the next line.
emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered}))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @task def celery_dwitsaved(dwit, rendered): if dwit.direct: fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) else: fers = dwit.member.followers.all() for fer in fers: <|code_end|> . Write the next line using the current file imports: from django.core.mail import send_mail from django.conf import settings from celery import task from dwitter.main.utils import emit_to_channel from dwitter.main.models import DPF, Dwit import json import re import subprocess and context from other files: # Path: dwitter/main/utils.py # def emit_to_channel(channel, event, *data): # r = redis_connection() # args = list(data) # r.publish('socketio_%s' % channel, json.dumps({'name': event, 'args': args})) # # Path: dwitter/main/models.py # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] , which may include functions, classes, or code. Output only the next line.
DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- @task def celery_dwitsaved(dwit, rendered): if dwit.direct: fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:]) else: fers = dwit.member.followers.all() for fer in fers: DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) tags = dwit.tags.all() if tags: for tag in tags: emit_to_channel(tag.name, 'newdwit', json.dumps({'content':rendered})) @task def celery_follow(me, m): <|code_end|> using the current file's imports: from django.core.mail import send_mail from django.conf import settings from celery import task from dwitter.main.utils import emit_to_channel from dwitter.main.models import DPF, Dwit import json import re import subprocess and any relevant context from other files: # Path: dwitter/main/utils.py # def emit_to_channel(channel, event, *data): # r = redis_connection() # args = list(data) # r.publish('socketio_%s' % channel, json.dumps({'name': event, 'args': args})) # # Path: dwitter/main/models.py # class DPF(models.Model): #Dwit Per Follower # member = models.ForeignKey(Member, db_index=True) # dwit = models.ForeignKey(Dwit) # stamp = models.DateTimeField() # # class Meta: # ordering = ['-stamp'] # # class Dwit(models.Model): # content = models.TextField() # member = models.ForeignKey(Member) # stamp = models.DateTimeField(auto_now_add=True) # tags = TaggableManager(blank=True) # redwit = models.ForeignKey(Member, blank=True, null=True, related_name='redwitby') # replyto = models.ForeignKey('self', blank=True, null=True, related_name='replyfrom') # direct = models.BooleanField(blank=True) # # def _dwitter_stamp(self): # t = datetime.now() - self.stamp # if t.days > 0: # return _(u'%dd') % t.days # else: # h = t.seconds / 3600 # if h > 0: # return _(u'%dh') % h # else: # m = t.seconds / 60 # if m == 0: m = 1 # return _(u'%dm') % m # # dwitter_stamp = property(_dwitter_stamp) # # class Meta: # ordering = ['-stamp'] . Output only the next line.
dwits = Dwit.objects.filter(member=m).exclude(direct=True)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- @namespace('/dwits') class DwitsNamespace(BaseNamespace, RoomsMixin): def initialize(self): self.logger = logging.getLogger("socketio.dwits") self.log("Socketio session started") def log(self, message): self.logger.info("[{0}] {1}".format(self.socket.sessid, message)) def listener(self, room): <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import json from socketio.namespace import BaseNamespace from socketio.mixins import RoomsMixin from socketio.sdjango import namespace from dwitter.main.utils import redis_connection and context: # Path: dwitter/main/utils.py # def redis_connection(): # """ # Returns a redis connection from one of our pools. # """ # pool = ConnectionPoolManager.connection_pool(**CONNECTION_KWARGS) # return Redis(connection_pool=pool) which might include code, classes, or functions. Output only the next line.
r = redis_connection().pubsub()
Given the following code snippet before the placeholder: <|code_start|> def test_frozendict(): my_dict = { 'key': 'DEFAULT', } <|code_end|> , predict the next line using imports from the current file: import pytest from ckan_api_client.utils import freeze, FrozenDict, FrozenList and context including class names, function names, and sometimes code from other files: # Path: ckan_api_client/utils.py # def freeze(obj): # """ # Returns the "frozen" version of a mutable type. # # :raises TypeError: # if a frozen version for that object doesn't exist # """ # if obj is None: # return None # if isinstance(obj, (basestring, int, float, bool)): # return obj # if isinstance(obj, dict): # return FrozenDict(obj) # if isinstance(obj, list): # return FrozenList(obj) # if isinstance(obj, tuple): # return FrozenTuple(obj) # raise TypeError("I don't know how to freeze this!") # # class FrozenDict(MutableMapping): # """ # Frozen dictionary. # Acts as a read-only dictionary, preventing changes # and returning frozen objects when asked for values. # """ # # def __init__(self, *a, **kw): # self.__wrapped = dict(*a, **kw) # # def __getitem__(self, name): # return freeze(self.__wrapped[name]) # # def __setitem__(self, name, value): # raise TypeError("FrozenDict doesn't support item assignment") # # def __delitem__(self, name): # raise TypeError("FrozenDict doesn't support item deletion") # # def __iter__(self): # return iter(self.__wrapped) # # def __len__(self): # return len(self.__wrapped) # # class FrozenList(FrozenSequence): # """Immutable list-like.""" # pass . Output only the next line.
my_frozen_dict = freeze(my_dict)
Given the code snippet: <|code_start|> def test_frozendict(): my_dict = { 'key': 'DEFAULT', } my_frozen_dict = freeze(my_dict) assert my_dict == my_frozen_dict <|code_end|> , generate the next line using the imports in this file: import pytest from ckan_api_client.utils import freeze, FrozenDict, FrozenList and context (functions, classes, or occasionally code) from other files: # Path: ckan_api_client/utils.py # def freeze(obj): # """ # Returns the "frozen" version of a mutable type. # # :raises TypeError: # if a frozen version for that object doesn't exist # """ # if obj is None: # return None # if isinstance(obj, (basestring, int, float, bool)): # return obj # if isinstance(obj, dict): # return FrozenDict(obj) # if isinstance(obj, list): # return FrozenList(obj) # if isinstance(obj, tuple): # return FrozenTuple(obj) # raise TypeError("I don't know how to freeze this!") # # class FrozenDict(MutableMapping): # """ # Frozen dictionary. # Acts as a read-only dictionary, preventing changes # and returning frozen objects when asked for values. # """ # # def __init__(self, *a, **kw): # self.__wrapped = dict(*a, **kw) # # def __getitem__(self, name): # return freeze(self.__wrapped[name]) # # def __setitem__(self, name, value): # raise TypeError("FrozenDict doesn't support item assignment") # # def __delitem__(self, name): # raise TypeError("FrozenDict doesn't support item deletion") # # def __iter__(self): # return iter(self.__wrapped) # # def __len__(self): # return len(self.__wrapped) # # class FrozenList(FrozenSequence): # """Immutable list-like.""" # pass . Output only the next line.
assert isinstance(my_frozen_dict, FrozenDict)
Next line prediction: <|code_start|> my_list.append('bacon') assert my_list == ['egg', 'spam', 'bacon'] assert list(my_frozen_list) == ['egg', 'spam', 'bacon'] with pytest.raises(TypeError): my_frozen_list[1] = 'SPAM!!' with pytest.raises(AttributeError): my_frozen_list.pop(0) with pytest.raises(AttributeError): my_frozen_list.extend(['spam'] * 10) def test_frozen_nested(): frozobj = freeze({ 'a list': [1, 2, 'a', 'b'], 'a dict': { 'key1': 'val1', 'key2': 'val2', }, 'another list': [ {'name': 'eggs', 'price': 1}, {'name': 'spam', 'price': 2}, {'name': 'bacon', 'price': 3}, ] }) assert isinstance(frozobj, FrozenDict) <|code_end|> . Use current file imports: (import pytest from ckan_api_client.utils import freeze, FrozenDict, FrozenList) and context including class names, function names, or small code snippets from other files: # Path: ckan_api_client/utils.py # def freeze(obj): # """ # Returns the "frozen" version of a mutable type. # # :raises TypeError: # if a frozen version for that object doesn't exist # """ # if obj is None: # return None # if isinstance(obj, (basestring, int, float, bool)): # return obj # if isinstance(obj, dict): # return FrozenDict(obj) # if isinstance(obj, list): # return FrozenList(obj) # if isinstance(obj, tuple): # return FrozenTuple(obj) # raise TypeError("I don't know how to freeze this!") # # class FrozenDict(MutableMapping): # """ # Frozen dictionary. # Acts as a read-only dictionary, preventing changes # and returning frozen objects when asked for values. # """ # # def __init__(self, *a, **kw): # self.__wrapped = dict(*a, **kw) # # def __getitem__(self, name): # return freeze(self.__wrapped[name]) # # def __setitem__(self, name, value): # raise TypeError("FrozenDict doesn't support item assignment") # # def __delitem__(self, name): # raise TypeError("FrozenDict doesn't support item deletion") # # def __iter__(self): # return iter(self.__wrapped) # # def __len__(self): # return len(self.__wrapped) # # class FrozenList(FrozenSequence): # """Immutable list-like.""" # pass . Output only the next line.
assert isinstance(frozobj['a list'], FrozenList)
Given the code snippet: <|code_start|> def test_diff_dicts(): dct1 = { 'one': 'VAL-1', 'two': 'VAL-2', 'three': 'VAL-3', 'four': 'VAL-4', 'five': 'VAL-5', } dct2 = { 'three': 'VAL-3', 'four': 'VAL-4-2', 'five': 'VAL-5-2', 'six': 'VAL-6', 'seven': 'VAL-7', 'eight': 'VAL-8', } <|code_end|> , generate the next line using the imports in this file: from ckan_api_client.tests.utils.diff import diff_mappings, diff_sequences and context (functions, classes, or occasionally code) from other files: # Path: ckan_api_client/tests/utils/diff.py # def diff_mappings(left, right): # """ # Compares two mappings, returning a dictionary of # sets of keys describing differences. # # Dictionary keys are as follows: # # - ``common`` -- keys in both mappings # - ``differing`` -- keys that are in both mappings, but # whose values differ # - ``left`` -- keys only in the "left" object # - ``right`` -- keys only in the "right" object # # :param dict-like left: "left" object to compare # :param dict-like right: "right" object to compare # :rtype: dict # """ # # left_keys = set(left.iterkeys()) # right_keys = set(right.iterkeys()) # # common_keys = left_keys & right_keys # left_only_keys = left_keys - right_keys # right_only_keys = right_keys - left_keys # # differing = set(k for k in common_keys if left[k] != right[k]) # # return { # 'common': common_keys, # 'left': left_only_keys, # 'right': right_only_keys, # 'differing': differing, # } # # def diff_sequences(left, right): # """ # Compare two sequences, return a dict containing differences # """ # # return { # 'length_match': len(left) == len(right), # 'differing': set([ # i for i, (l, r) in enumerate(zip(left, right)) # if l != r # ])} . Output only the next line.
diff = diff_mappings(dct1, dct2)
Based on the snippet: <|code_start|> def test_diff_dicts(): dct1 = { 'one': 'VAL-1', 'two': 'VAL-2', 'three': 'VAL-3', 'four': 'VAL-4', 'five': 'VAL-5', } dct2 = { 'three': 'VAL-3', 'four': 'VAL-4-2', 'five': 'VAL-5-2', 'six': 'VAL-6', 'seven': 'VAL-7', 'eight': 'VAL-8', } diff = diff_mappings(dct1, dct2) assert diff['common'] == set(['three', 'four', 'five']) assert diff['left'] == set(['one', 'two']) assert diff['right'] == set(['six', 'seven', 'eight']) assert diff['differing'] == set(['four', 'five']) def test_diff_sequences(): <|code_end|> , predict the immediate next line with the help of imports: from ckan_api_client.tests.utils.diff import diff_mappings, diff_sequences and context (classes, functions, sometimes code) from other files: # Path: ckan_api_client/tests/utils/diff.py # def diff_mappings(left, right): # """ # Compares two mappings, returning a dictionary of # sets of keys describing differences. # # Dictionary keys are as follows: # # - ``common`` -- keys in both mappings # - ``differing`` -- keys that are in both mappings, but # whose values differ # - ``left`` -- keys only in the "left" object # - ``right`` -- keys only in the "right" object # # :param dict-like left: "left" object to compare # :param dict-like right: "right" object to compare # :rtype: dict # """ # # left_keys = set(left.iterkeys()) # right_keys = set(right.iterkeys()) # # common_keys = left_keys & right_keys # left_only_keys = left_keys - right_keys # right_only_keys = right_keys - left_keys # # differing = set(k for k in common_keys if left[k] != right[k]) # # return { # 'common': common_keys, # 'left': left_only_keys, # 'right': right_only_keys, # 'differing': differing, # } # # def diff_sequences(left, right): # """ # Compare two sequences, return a dict containing differences # """ # # return { # 'length_match': len(left) == len(right), # 'differing': set([ # i for i, (l, r) in enumerate(zip(left, right)) # if l != r # ])} . Output only the next line.
diff = diff_sequences([1, 2, 3], [1, 2, 9])
Predict the next line for this snippet: <|code_start|>""" Test some simple harvesting scenarios, generating data on-the-fly """ # import os # import pytest # from ckan_api_client.syncing import CkanDataImportClient # from .utils.harvest_source import HarvestSource def generate_data(): organizations = generate_organizations(5) groups = generate_groups(10) datasets = generate_datasets( groups=groups, organizations=organizations, amount=20) return { 'organization': organizations, 'group': groups, 'dataset': datasets, } def generate_organizations(amount=10): organizations = {} for i in xrange(3): <|code_end|> with the help of current file imports: import random from ckan_api_client.tests.utils.generate import ( generate_organization, generate_group, generate_dataset, generate_id) and context from other files: # Path: ckan_api_client/tests/utils/generate.py # def generate_organization(): # """ # Generate a random organization object, with: # # - ``name``, random, example: ``"org-abc123"`` # - ``title``, random, example: ``"Organization abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "org-{0}".format(random_id), # Used as key # "title": "Organization {0}".format(random_id), # "description": "Description of organization {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_group(): # """ # Generate a random group object, with: # # - ``name``, random, example: ``"grp-abc123"`` # - ``title``, random, example: ``"Group abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "grp-{0}".format(random_id), # Used as key # "title": "Group {0}".format(random_id), # "description": "Description of group {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_dataset(): # """ # Generate a dataset, populated with random data. # # **Fields:** # # - ``name`` -- random string, in the form ``dataset-{random}`` # - ``title`` -- random string, in the form ``Dataset {random}`` # # - ``author`` -- random-generated name # - ``author_email`` -- random-generated email address # - ``license_id`` -- random license id. One of ``cc-by``, ``cc-zero``, # ``cc-by-sa`` or ``notspecified``. # - ``maintainer`` -- random-generated name # - ``maintainer_email`` -- random-generated email address # - ``notes`` -- random string, containing some markdown # - ``owner_org`` -- set to None # - ``private`` -- Fixed to ``False`` # - ``tags`` -- random list of tags (strings) # - ``type`` -- fixed string: ``"dataset"`` # - ``url`` -- random url of dataset on an "external source" # # - ``extras`` -- dictionary containing random key / value pairs # - ``groups`` -- empty list # - ``resources`` -- list of random resources # - ``relationships`` -- empty list # # .. note:: # The ``owner_org`` and ``groups`` fields will be blank, # as they must match with existing groups / organizations # and we don't have access to database from here (nor # is it in the scope of this function!) # """ # # random_id = gen_random_id(15) # license_id = random.choice(( # 'cc-by', 'cc-zero', 'cc-by-sa', 'notspecified')) # resources = [] # for i in xrange(random.randint(1, 8)): # resources.append(generate_resource()) # return { # # ------------------------------------------------------------ # # WARNING! This is the **internal** id of the external # # service, which will need to be moved to # # dataset['extras']['_harvest_source_id'] # # ------------------------------------------------------------ # # "id": random_id, # # # Name should be taken as a "suggestion": in case of naming conflict # # with an existing dataset, it just be changed (todo: how?) # "name": "dataset-{0}".format(random_id), # # "title": "Dataset {0}".format(random_id), # "url": "http://www.example.com/dataset/{0}".format(random_id), # "type": "dataset", # # "maintainer_email": "maintainer-{0}@example.com".format(random_id), # "maintainer": "Maintainer {0}".format(random_id), # # "author_email": "author-{0}@example.com".format(random_id), # "author": "Author {0}".format(random_id), # # "license_id": license_id, # # "private": False, # "notes": "Notes for **dataset** {0}.".format(random_id), # # # "state": "active", # automatic # # # Let's generate some tags # "tags": generate_tags(random.randint(0, 10)), # # # Let's put some random stuff in here.. # "extras": generate_extras(random.randint(0, 30)), # # # Some dummy resources # "resources": resources, # # # Need to be randomized later, to match existing groups # "groups": [], # # # Need to be randomized later, to match existing orgs # "owner_org": None, # # # WTF is this thing? # "relationships": [], # } # # def generate_id(length=10): # pool = string.ascii_lowercase + string.digits # return ''.join(random.choice(pool) for _ in xrange(length)) , which may contain function names, class names, or code. Output only the next line.
org = generate_organization()
Using the snippet: <|code_start|># from ckan_api_client.syncing import CkanDataImportClient # from .utils.harvest_source import HarvestSource def generate_data(): organizations = generate_organizations(5) groups = generate_groups(10) datasets = generate_datasets( groups=groups, organizations=organizations, amount=20) return { 'organization': organizations, 'group': groups, 'dataset': datasets, } def generate_organizations(amount=10): organizations = {} for i in xrange(3): org = generate_organization() org['id'] = org['name'] = 'org-{0}'.format(generate_id()) organizations[org['name']] = org return organizations def generate_groups(amount=10): groups = {} for i in xrange(10): <|code_end|> , determine the next line of code. You have imports: import random from ckan_api_client.tests.utils.generate import ( generate_organization, generate_group, generate_dataset, generate_id) and context (class names, function names, or code) available: # Path: ckan_api_client/tests/utils/generate.py # def generate_organization(): # """ # Generate a random organization object, with: # # - ``name``, random, example: ``"org-abc123"`` # - ``title``, random, example: ``"Organization abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "org-{0}".format(random_id), # Used as key # "title": "Organization {0}".format(random_id), # "description": "Description of organization {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_group(): # """ # Generate a random group object, with: # # - ``name``, random, example: ``"grp-abc123"`` # - ``title``, random, example: ``"Group abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "grp-{0}".format(random_id), # Used as key # "title": "Group {0}".format(random_id), # "description": "Description of group {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_dataset(): # """ # Generate a dataset, populated with random data. # # **Fields:** # # - ``name`` -- random string, in the form ``dataset-{random}`` # - ``title`` -- random string, in the form ``Dataset {random}`` # # - ``author`` -- random-generated name # - ``author_email`` -- random-generated email address # - ``license_id`` -- random license id. One of ``cc-by``, ``cc-zero``, # ``cc-by-sa`` or ``notspecified``. # - ``maintainer`` -- random-generated name # - ``maintainer_email`` -- random-generated email address # - ``notes`` -- random string, containing some markdown # - ``owner_org`` -- set to None # - ``private`` -- Fixed to ``False`` # - ``tags`` -- random list of tags (strings) # - ``type`` -- fixed string: ``"dataset"`` # - ``url`` -- random url of dataset on an "external source" # # - ``extras`` -- dictionary containing random key / value pairs # - ``groups`` -- empty list # - ``resources`` -- list of random resources # - ``relationships`` -- empty list # # .. note:: # The ``owner_org`` and ``groups`` fields will be blank, # as they must match with existing groups / organizations # and we don't have access to database from here (nor # is it in the scope of this function!) # """ # # random_id = gen_random_id(15) # license_id = random.choice(( # 'cc-by', 'cc-zero', 'cc-by-sa', 'notspecified')) # resources = [] # for i in xrange(random.randint(1, 8)): # resources.append(generate_resource()) # return { # # ------------------------------------------------------------ # # WARNING! This is the **internal** id of the external # # service, which will need to be moved to # # dataset['extras']['_harvest_source_id'] # # ------------------------------------------------------------ # # "id": random_id, # # # Name should be taken as a "suggestion": in case of naming conflict # # with an existing dataset, it just be changed (todo: how?) # "name": "dataset-{0}".format(random_id), # # "title": "Dataset {0}".format(random_id), # "url": "http://www.example.com/dataset/{0}".format(random_id), # "type": "dataset", # # "maintainer_email": "maintainer-{0}@example.com".format(random_id), # "maintainer": "Maintainer {0}".format(random_id), # # "author_email": "author-{0}@example.com".format(random_id), # "author": "Author {0}".format(random_id), # # "license_id": license_id, # # "private": False, # "notes": "Notes for **dataset** {0}.".format(random_id), # # # "state": "active", # automatic # # # Let's generate some tags # "tags": generate_tags(random.randint(0, 10)), # # # Let's put some random stuff in here.. # "extras": generate_extras(random.randint(0, 30)), # # # Some dummy resources # "resources": resources, # # # Need to be randomized later, to match existing groups # "groups": [], # # # Need to be randomized later, to match existing orgs # "owner_org": None, # # # WTF is this thing? # "relationships": [], # } # # def generate_id(length=10): # pool = string.ascii_lowercase + string.digits # return ''.join(random.choice(pool) for _ in xrange(length)) . Output only the next line.
grp = generate_group()
Given snippet: <|code_start|> groups=groups, organizations=organizations, amount=20) return { 'organization': organizations, 'group': groups, 'dataset': datasets, } def generate_organizations(amount=10): organizations = {} for i in xrange(3): org = generate_organization() org['id'] = org['name'] = 'org-{0}'.format(generate_id()) organizations[org['name']] = org return organizations def generate_groups(amount=10): groups = {} for i in xrange(10): grp = generate_group() grp['id'] = grp['name'] = 'group-{0}'.format(generate_id()) groups[grp['id']] = grp return groups def generate_datasets(groups, organizations, amount=20): datasets = {} for i in xrange(amount): <|code_end|> , continue by predicting the next line. Consider current file imports: import random from ckan_api_client.tests.utils.generate import ( generate_organization, generate_group, generate_dataset, generate_id) and context: # Path: ckan_api_client/tests/utils/generate.py # def generate_organization(): # """ # Generate a random organization object, with: # # - ``name``, random, example: ``"org-abc123"`` # - ``title``, random, example: ``"Organization abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "org-{0}".format(random_id), # Used as key # "title": "Organization {0}".format(random_id), # "description": "Description of organization {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_group(): # """ # Generate a random group object, with: # # - ``name``, random, example: ``"grp-abc123"`` # - ``title``, random, example: ``"Group abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "grp-{0}".format(random_id), # Used as key # "title": "Group {0}".format(random_id), # "description": "Description of group {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_dataset(): # """ # Generate a dataset, populated with random data. # # **Fields:** # # - ``name`` -- random string, in the form ``dataset-{random}`` # - ``title`` -- random string, in the form ``Dataset {random}`` # # - ``author`` -- random-generated name # - ``author_email`` -- random-generated email address # - ``license_id`` -- random license id. One of ``cc-by``, ``cc-zero``, # ``cc-by-sa`` or ``notspecified``. # - ``maintainer`` -- random-generated name # - ``maintainer_email`` -- random-generated email address # - ``notes`` -- random string, containing some markdown # - ``owner_org`` -- set to None # - ``private`` -- Fixed to ``False`` # - ``tags`` -- random list of tags (strings) # - ``type`` -- fixed string: ``"dataset"`` # - ``url`` -- random url of dataset on an "external source" # # - ``extras`` -- dictionary containing random key / value pairs # - ``groups`` -- empty list # - ``resources`` -- list of random resources # - ``relationships`` -- empty list # # .. note:: # The ``owner_org`` and ``groups`` fields will be blank, # as they must match with existing groups / organizations # and we don't have access to database from here (nor # is it in the scope of this function!) # """ # # random_id = gen_random_id(15) # license_id = random.choice(( # 'cc-by', 'cc-zero', 'cc-by-sa', 'notspecified')) # resources = [] # for i in xrange(random.randint(1, 8)): # resources.append(generate_resource()) # return { # # ------------------------------------------------------------ # # WARNING! This is the **internal** id of the external # # service, which will need to be moved to # # dataset['extras']['_harvest_source_id'] # # ------------------------------------------------------------ # # "id": random_id, # # # Name should be taken as a "suggestion": in case of naming conflict # # with an existing dataset, it just be changed (todo: how?) # "name": "dataset-{0}".format(random_id), # # "title": "Dataset {0}".format(random_id), # "url": "http://www.example.com/dataset/{0}".format(random_id), # "type": "dataset", # # "maintainer_email": "maintainer-{0}@example.com".format(random_id), # "maintainer": "Maintainer {0}".format(random_id), # # "author_email": "author-{0}@example.com".format(random_id), # "author": "Author {0}".format(random_id), # # "license_id": license_id, # # "private": False, # "notes": "Notes for **dataset** {0}.".format(random_id), # # # "state": "active", # automatic # # # Let's generate some tags # "tags": generate_tags(random.randint(0, 10)), # # # Let's put some random stuff in here.. # "extras": generate_extras(random.randint(0, 30)), # # # Some dummy resources # "resources": resources, # # # Need to be randomized later, to match existing groups # "groups": [], # # # Need to be randomized later, to match existing orgs # "owner_org": None, # # # WTF is this thing? # "relationships": [], # } # # def generate_id(length=10): # pool = string.ascii_lowercase + string.digits # return ''.join(random.choice(pool) for _ in xrange(length)) which might include code, classes, or functions. Output only the next line.
dataset = generate_dataset()
Using the snippet: <|code_start|>""" Test some simple harvesting scenarios, generating data on-the-fly """ # import os # import pytest # from ckan_api_client.syncing import CkanDataImportClient # from .utils.harvest_source import HarvestSource def generate_data(): organizations = generate_organizations(5) groups = generate_groups(10) datasets = generate_datasets( groups=groups, organizations=organizations, amount=20) return { 'organization': organizations, 'group': groups, 'dataset': datasets, } def generate_organizations(amount=10): organizations = {} for i in xrange(3): org = generate_organization() <|code_end|> , determine the next line of code. You have imports: import random from ckan_api_client.tests.utils.generate import ( generate_organization, generate_group, generate_dataset, generate_id) and context (class names, function names, or code) available: # Path: ckan_api_client/tests/utils/generate.py # def generate_organization(): # """ # Generate a random organization object, with: # # - ``name``, random, example: ``"org-abc123"`` # - ``title``, random, example: ``"Organization abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "org-{0}".format(random_id), # Used as key # "title": "Organization {0}".format(random_id), # "description": "Description of organization {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_group(): # """ # Generate a random group object, with: # # - ``name``, random, example: ``"grp-abc123"`` # - ``title``, random, example: ``"Group abc123"`` # - ``description``, random # - ``image``, url pointing to a random-generated pic # """ # # random_id = gen_random_id(10) # return { # "name": "grp-{0}".format(random_id), # Used as key # "title": "Group {0}".format(random_id), # "description": "Description of group {0}".format(random_id), # "image_url": gen_picture(random_id), # # "extras": [], # # "tags": [], # } # # def generate_dataset(): # """ # Generate a dataset, populated with random data. # # **Fields:** # # - ``name`` -- random string, in the form ``dataset-{random}`` # - ``title`` -- random string, in the form ``Dataset {random}`` # # - ``author`` -- random-generated name # - ``author_email`` -- random-generated email address # - ``license_id`` -- random license id. One of ``cc-by``, ``cc-zero``, # ``cc-by-sa`` or ``notspecified``. # - ``maintainer`` -- random-generated name # - ``maintainer_email`` -- random-generated email address # - ``notes`` -- random string, containing some markdown # - ``owner_org`` -- set to None # - ``private`` -- Fixed to ``False`` # - ``tags`` -- random list of tags (strings) # - ``type`` -- fixed string: ``"dataset"`` # - ``url`` -- random url of dataset on an "external source" # # - ``extras`` -- dictionary containing random key / value pairs # - ``groups`` -- empty list # - ``resources`` -- list of random resources # - ``relationships`` -- empty list # # .. note:: # The ``owner_org`` and ``groups`` fields will be blank, # as they must match with existing groups / organizations # and we don't have access to database from here (nor # is it in the scope of this function!) # """ # # random_id = gen_random_id(15) # license_id = random.choice(( # 'cc-by', 'cc-zero', 'cc-by-sa', 'notspecified')) # resources = [] # for i in xrange(random.randint(1, 8)): # resources.append(generate_resource()) # return { # # ------------------------------------------------------------ # # WARNING! This is the **internal** id of the external # # service, which will need to be moved to # # dataset['extras']['_harvest_source_id'] # # ------------------------------------------------------------ # # "id": random_id, # # # Name should be taken as a "suggestion": in case of naming conflict # # with an existing dataset, it just be changed (todo: how?) # "name": "dataset-{0}".format(random_id), # # "title": "Dataset {0}".format(random_id), # "url": "http://www.example.com/dataset/{0}".format(random_id), # "type": "dataset", # # "maintainer_email": "maintainer-{0}@example.com".format(random_id), # "maintainer": "Maintainer {0}".format(random_id), # # "author_email": "author-{0}@example.com".format(random_id), # "author": "Author {0}".format(random_id), # # "license_id": license_id, # # "private": False, # "notes": "Notes for **dataset** {0}.".format(random_id), # # # "state": "active", # automatic # # # Let's generate some tags # "tags": generate_tags(random.randint(0, 10)), # # # Let's put some random stuff in here.. # "extras": generate_extras(random.randint(0, 30)), # # # Some dummy resources # "resources": resources, # # # Need to be randomized later, to match existing groups # "groups": [], # # # Need to be randomized later, to match existing orgs # "owner_org": None, # # # WTF is this thing? # "relationships": [], # } # # def generate_id(length=10): # pool = string.ascii_lowercase + string.digits # return ''.join(random.choice(pool) for _ in xrange(length)) . Output only the next line.
org['id'] = org['name'] = 'org-{0}'.format(generate_id())
Given the following code snippet before the placeholder: <|code_start|>"""Make sure tests setup & fixtures are all fine""" # todo: we should check all fixtures in here! def test_site_read(ckan_url): """GET /site_read/ should return 200""" api_url = ckan_url('/api/3/action/site_read') response = requests.get(api_url) <|code_end|> , predict the next line using imports from the current file: import requests from .utils.http import check_response_ok and context including class names, function names, and sometimes code from other files: # Path: ckan_api_client/tests/utils/http.py # def check_response_ok(response, status_code=200): # """ # .. warning:: deprecated function. Use :py:func:`check_api_v3_response`. # """ # warnings.warn( # "check_response_ok() is deprecated -- use check_api_v3_response()", # DeprecationWarning) # return check_api_v3_response(response, status_code=status_code) . Output only the next line.
data = check_response_ok(response)
Given the code snippet: <|code_start|>""" Tests to pin-point exact behavior of datasets CRUD, in particular updates. """ def test_dataset_simple_crud(ckan_client_ll): # Let's try creating a dataset now = datetime.datetime.now() now_str = now.strftime('%F %T') _dataset = { <|code_end|> , generate the next line using the imports in this file: import datetime import copy import pytest from ckan_api_client.exceptions import HTTPError from ckan_api_client.tests.utils.generate import generate_dataset from ckan_api_client.tests.utils.strings import gen_random_id from ckan_api_client.tests.utils.validation import check_dataset and context (functions, classes, or occasionally code) from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # Path: ckan_api_client/tests/utils/generate.py # def generate_dataset(): # """ # Generate a dataset, populated with random data. # # **Fields:** # # - ``name`` -- random string, in the form ``dataset-{random}`` # - ``title`` -- random string, in the form ``Dataset {random}`` # # - ``author`` -- random-generated name # - ``author_email`` -- random-generated email address # - ``license_id`` -- random license id. One of ``cc-by``, ``cc-zero``, # ``cc-by-sa`` or ``notspecified``. # - ``maintainer`` -- random-generated name # - ``maintainer_email`` -- random-generated email address # - ``notes`` -- random string, containing some markdown # - ``owner_org`` -- set to None # - ``private`` -- Fixed to ``False`` # - ``tags`` -- random list of tags (strings) # - ``type`` -- fixed string: ``"dataset"`` # - ``url`` -- random url of dataset on an "external source" # # - ``extras`` -- dictionary containing random key / value pairs # - ``groups`` -- empty list # - ``resources`` -- list of random resources # - ``relationships`` -- empty list # # .. note:: # The ``owner_org`` and ``groups`` fields will be blank, # as they must match with existing groups / organizations # and we don't have access to database from here (nor # is it in the scope of this function!) # """ # # random_id = gen_random_id(15) # license_id = random.choice(( # 'cc-by', 'cc-zero', 'cc-by-sa', 'notspecified')) # resources = [] # for i in xrange(random.randint(1, 8)): # resources.append(generate_resource()) # return { # # ------------------------------------------------------------ # # WARNING! This is the **internal** id of the external # # service, which will need to be moved to # # dataset['extras']['_harvest_source_id'] # # ------------------------------------------------------------ # # "id": random_id, # # # Name should be taken as a "suggestion": in case of naming conflict # # with an existing dataset, it just be changed (todo: how?) # "name": "dataset-{0}".format(random_id), # # "title": "Dataset {0}".format(random_id), # "url": "http://www.example.com/dataset/{0}".format(random_id), # "type": "dataset", # # "maintainer_email": "maintainer-{0}@example.com".format(random_id), # "maintainer": "Maintainer {0}".format(random_id), # # "author_email": "author-{0}@example.com".format(random_id), # "author": "Author {0}".format(random_id), # # "license_id": license_id, # # "private": False, # "notes": "Notes for **dataset** {0}.".format(random_id), # # # "state": "active", # automatic # # # Let's generate some tags # "tags": generate_tags(random.randint(0, 10)), # # # Let's put some random stuff in here.. # "extras": generate_extras(random.randint(0, 30)), # # # Some dummy resources # "resources": resources, # # # Need to be randomized later, to match existing groups # "groups": [], # # # Need to be randomized later, to match existing orgs # "owner_org": None, # # # WTF is this thing? # "relationships": [], # } # # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # Path: ckan_api_client/tests/utils/validation.py # def check_dataset(dataset, expected): # """Make sure ``dataset`` matches the ``expected`` one""" # from ckan_api_client.objects import CkanDataset # return _check_obj(CkanDataset, dataset, expected) . Output only the next line.
'name': 'dataset-{0}'.format(gen_random_id()),
Given the code snippet: <|code_start|>#!/usr/bin/env python # Generate some dummy data, for testing purposes def generate_organization(): """ Generate a random organization object, with: - ``name``, random, example: ``"org-abc123"`` - ``title``, random, example: ``"Organization abc123"`` - ``description``, random - ``image``, url pointing to a random-generated pic """ <|code_end|> , generate the next line using the imports in this file: import json import random import string import os import sys from .strings import gen_random_id, gen_picture and context (functions, classes, or occasionally code) from other files: # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # def gen_picture(s, size=200): # """Generate URL to picture from some text hash""" # return gen_robohash(s, size) . Output only the next line.
random_id = gen_random_id(10)
Given snippet: <|code_start|>#!/usr/bin/env python # Generate some dummy data, for testing purposes def generate_organization(): """ Generate a random organization object, with: - ``name``, random, example: ``"org-abc123"`` - ``title``, random, example: ``"Organization abc123"`` - ``description``, random - ``image``, url pointing to a random-generated pic """ random_id = gen_random_id(10) return { "name": "org-{0}".format(random_id), # Used as key "title": "Organization {0}".format(random_id), "description": "Description of organization {0}".format(random_id), <|code_end|> , continue by predicting the next line. Consider current file imports: import json import random import string import os import sys from .strings import gen_random_id, gen_picture and context: # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # def gen_picture(s, size=200): # """Generate URL to picture from some text hash""" # return gen_robohash(s, size) which might include code, classes, or functions. Output only the next line.
"image_url": gen_picture(random_id),
Here is a snippet: <|code_start|> created = client.post_group(group) check_group(created, group) group_id = created['id'] # Retrieve & check retrieved = client.get_group(group_id) assert retrieved == created # Update & check updated = client.put_group({'id': group_id, 'title': 'My Group'}) assert updated['name'] == group['name'] assert updated['title'] == 'My Group' # Check differences expected = copy.deepcopy(created) expected['title'] = 'My Group' check_group(updated, expected) # Retrieve & double-check retrieved = client.get_group(group_id) assert retrieved == updated # Delete # ------------------------------------------------------------ # Note: it's impossible to actually delete a group. # The only hint it has been deleted is its "state" # is set to "deleted". # ------------------------------------------------------------ client.delete_group(group_id) <|code_end|> . Write the next line using the current file imports: import copy import pytest from ckan_api_client.exceptions import HTTPError from ckan_api_client.tests.utils.strings import gen_random_id from ckan_api_client.tests.utils.validation import check_group and context from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # Path: ckan_api_client/tests/utils/validation.py # def check_group(group, expected): # """Make sure ``group`` matches the ``expected`` one""" # from ckan_api_client.objects import CkanGroup # return _check_obj(CkanGroup, group, expected) , which may include functions, classes, or code. Output only the next line.
with pytest.raises(HTTPError) as excinfo:
Next line prediction: <|code_start|> @pytest.mark.xfail(run=False, reason='Work in progress') def test_group_crud(ckan_client_ll): client = ckan_client_ll <|code_end|> . Use current file imports: (import copy import pytest from ckan_api_client.exceptions import HTTPError from ckan_api_client.tests.utils.strings import gen_random_id from ckan_api_client.tests.utils.validation import check_group) and context including class names, function names, or small code snippets from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # Path: ckan_api_client/tests/utils/validation.py # def check_group(group, expected): # """Make sure ``group`` matches the ``expected`` one""" # from ckan_api_client.objects import CkanGroup # return _check_obj(CkanGroup, group, expected) . Output only the next line.
code = gen_random_id()
Continue the code snippet: <|code_start|> @pytest.mark.xfail(run=False, reason='Work in progress') def test_group_crud(ckan_client_ll): client = ckan_client_ll code = gen_random_id() group = { 'name': 'group-{0}'.format(code), 'title': 'Group {0}'.format(code), } created = client.post_group(group) <|code_end|> . Use current file imports: import copy import pytest from ckan_api_client.exceptions import HTTPError from ckan_api_client.tests.utils.strings import gen_random_id from ckan_api_client.tests.utils.validation import check_group and context (classes, functions, or code) from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # Path: ckan_api_client/tests/utils/strings.py # def gen_random_id(length=10): # """Generate a random id, made of lowercase ascii letters + digits""" # charset = string.ascii_lowercase + string.digits # return ''.join(random.choice(charset) for _ in xrange(length)) # # Path: ckan_api_client/tests/utils/validation.py # def check_group(group, expected): # """Make sure ``group`` matches the ``expected`` one""" # from ckan_api_client.objects import CkanGroup # return _check_obj(CkanGroup, group, expected) . Output only the next line.
check_group(created, group)
Using the snippet: <|code_start|>class ListField(MutableFieldMixin, BaseField): default = staticmethod(lambda: []) def validate(self, instance, name, value): value = super(ListField, self).validate(instance, name, value) if not isinstance(value, SEQUENCE_TYPES): raise ValueError("{0} must be a list".format(name)) return value class SetField(MutableFieldMixin, BaseField): default = staticmethod(lambda: []) def validate(self, instance, name, value): value = super(SetField, self).validate(instance, name, value) if isinstance(value, set): return value if not isinstance(value, SEQUENCE_TYPES): raise ValueError("{0} must be a set or list".format(name)) return set(value) def serialize(self, instance, name): return copy.deepcopy(list(self.get(instance, name))) class DictField(MutableFieldMixin, BaseField): default = staticmethod(lambda: {}) def validate(self, instance, name, value): value = super(DictField, self).validate(instance, name, value) <|code_end|> , determine the next line of code. You have imports: import copy from .base import BaseField, MAPPING_TYPES, SEQUENCE_TYPES and context (class names, function names, or code) available: # Path: ckan_api_client/objects/base.py # class BaseField(object): # """ # Pseudo-descriptor, accepting field names along with instance, # to allow better retrieving data for the instance itself. # # .. warning:: # Beware that fields shouldn't carry state of their own, a part # from the one used for generic field configuration, as they # are shared between instances. # """ # # default = None # is_key = False # # def __init__(self, default=NOTSET, is_key=NOTSET, required=False): # """ # :param default: # Default value (if not callable) or function # returning default value (if callable). # :param is_key: # Boolean indicating whether this is a key field # or not. Key fields are ignored when comparing # using :py:meth:`is_equivalent` # """ # # # todo: refactor to use kwargs # # if default is not NOTSET: # self.default = default # if is_key is not NOTSET: # self.is_key = is_key # self.required = required # # self._conf = { # 'default': self.default, # 'is_key': self.is_key, # 'required': self.required, # } # # def get(self, instance, name): # """ # Get the value for the field from the main instace, # by looking at the first found in: # # - the updated value # - the initial value # - the default value # """ # # if name in instance._updates: # return instance._updates[name] # # if name in instance._values: # return instance._values[name] # # return self.get_default() # # def get_default(self): # if callable(self.default): # return self.default() # return self.default # # def validate(self, instance, name, value): # """ # The validate method should be the (updated) # value to be used as the field value, or raise # an exception in case it is not acceptable at all. # """ # return value # # def set_initial(self, instance, name, value): # """Set the initial value for a field""" # value = self.validate(instance, name, value) # instance._values[name] = value # # def set(self, instance, name, value): # """Set the modified value for a field""" # value = self.validate(instance, name, value) # instance._updates[name] = value # # def delete(self, instance, name): # """ # Delete the modified value for a field (logically # restores the original one) # """ # # We don't want an exception here, as we just restore # # field to its initial value.. # instance._updates.pop(name, None) # # def serialize(self, instance, name): # """ # Returns the "serialized" (json-encodable) version of # the object. # """ # return self.get(instance, name) # # def is_modified(self, instance, name): # """ # Check whether this field has been modified on the # main instance. # """ # return name in instance._updates # # def is_equivalent(self, instance, name, other, ignore_key=True): # if ignore_key and self.is_key: # # # If we want to ignore keys from comparison, # # key comparison should always return True # # for fields marked as keys. # # # -------------------------------------------------- # # NOTE: This should not be needed, as this part # # won't even be called in case it is a key **and** # # ignore_key=True. Its main purpose is to be # # used recursively by fields containing related # # objects. # # -------------------------------------------------- # # return True # # # Just perform simple comparison between values # myvalue = getattr(instance, name) # othervalue = getattr(other, name) # if myvalue is None: # myvalue = self.get_default() # if othervalue is None: # othervalue = self.get_default() # return myvalue == othervalue # # def __repr__(self): # myname = self.__class__.__name__ # kwargs = ', '.join('{0}={1!r}'.format(key, value) # for key, value in self._conf.iteritems()) # return "{0}({1})".format(myname, kwargs) # # MAPPING_TYPES = (dict, collections.Mapping) # # SEQUENCE_TYPES = (list, tuple, collections.Sequence) . Output only the next line.
if not isinstance(value, MAPPING_TYPES):
Based on the snippet: <|code_start|> # to be extra safe, make copy here, even on # default values, which might get shared.. instance._updates[name] = copy.deepcopy( self.validate(instance, name, value)) return instance._updates[name] def serialize(self, instance, name): # Copy to prevent unwanted mutation return copy.deepcopy(self.get(instance, name)) def is_modified(self, instance, name): if name not in instance._updates: return False # Otherwise, compare values to check whether # field has been modified. if name in instance._values: default = instance._values[name] else: default = self.get_default() return default != instance._updates[name] class ListField(MutableFieldMixin, BaseField): default = staticmethod(lambda: []) def validate(self, instance, name, value): value = super(ListField, self).validate(instance, name, value) <|code_end|> , predict the immediate next line with the help of imports: import copy from .base import BaseField, MAPPING_TYPES, SEQUENCE_TYPES and context (classes, functions, sometimes code) from other files: # Path: ckan_api_client/objects/base.py # class BaseField(object): # """ # Pseudo-descriptor, accepting field names along with instance, # to allow better retrieving data for the instance itself. # # .. warning:: # Beware that fields shouldn't carry state of their own, a part # from the one used for generic field configuration, as they # are shared between instances. # """ # # default = None # is_key = False # # def __init__(self, default=NOTSET, is_key=NOTSET, required=False): # """ # :param default: # Default value (if not callable) or function # returning default value (if callable). # :param is_key: # Boolean indicating whether this is a key field # or not. Key fields are ignored when comparing # using :py:meth:`is_equivalent` # """ # # # todo: refactor to use kwargs # # if default is not NOTSET: # self.default = default # if is_key is not NOTSET: # self.is_key = is_key # self.required = required # # self._conf = { # 'default': self.default, # 'is_key': self.is_key, # 'required': self.required, # } # # def get(self, instance, name): # """ # Get the value for the field from the main instace, # by looking at the first found in: # # - the updated value # - the initial value # - the default value # """ # # if name in instance._updates: # return instance._updates[name] # # if name in instance._values: # return instance._values[name] # # return self.get_default() # # def get_default(self): # if callable(self.default): # return self.default() # return self.default # # def validate(self, instance, name, value): # """ # The validate method should be the (updated) # value to be used as the field value, or raise # an exception in case it is not acceptable at all. # """ # return value # # def set_initial(self, instance, name, value): # """Set the initial value for a field""" # value = self.validate(instance, name, value) # instance._values[name] = value # # def set(self, instance, name, value): # """Set the modified value for a field""" # value = self.validate(instance, name, value) # instance._updates[name] = value # # def delete(self, instance, name): # """ # Delete the modified value for a field (logically # restores the original one) # """ # # We don't want an exception here, as we just restore # # field to its initial value.. # instance._updates.pop(name, None) # # def serialize(self, instance, name): # """ # Returns the "serialized" (json-encodable) version of # the object. # """ # return self.get(instance, name) # # def is_modified(self, instance, name): # """ # Check whether this field has been modified on the # main instance. # """ # return name in instance._updates # # def is_equivalent(self, instance, name, other, ignore_key=True): # if ignore_key and self.is_key: # # # If we want to ignore keys from comparison, # # key comparison should always return True # # for fields marked as keys. # # # -------------------------------------------------- # # NOTE: This should not be needed, as this part # # won't even be called in case it is a key **and** # # ignore_key=True. Its main purpose is to be # # used recursively by fields containing related # # objects. # # -------------------------------------------------- # # return True # # # Just perform simple comparison between values # myvalue = getattr(instance, name) # othervalue = getattr(other, name) # if myvalue is None: # myvalue = self.get_default() # if othervalue is None: # othervalue = self.get_default() # return myvalue == othervalue # # def __repr__(self): # myname = self.__class__.__name__ # kwargs = ', '.join('{0}={1!r}'.format(key, value) # for key, value in self._conf.iteritems()) # return "{0}({1})".format(myname, kwargs) # # MAPPING_TYPES = (dict, collections.Mapping) # # SEQUENCE_TYPES = (list, tuple, collections.Sequence) . Output only the next line.
if not isinstance(value, SEQUENCE_TYPES):
Based on the snippet: <|code_start|> assert len(actual) == len(actual_resources) for res_id in expected_resources: expected_resource = expected_resources[res_id] actual_resource = actual_resources[res_id] for key_id in expected_resource: assert expected_resource[key_id] \ == actual_resource[key_id] def check_dataset_tags(expected, actual): # Tags have a lot of extra fields, we only care about some of them.. expected_tags = sorted(x['name'] for x in expected) actual_tags = sorted(x['name'] for x in actual) assert actual_tags == expected_tags @pytest.fixture(params=sorted(DUMMY_PACKAGES.keys())) def dummy_package(request): return DUMMY_PACKAGES[request.param] # Actual test functions # ------------------------------------------------------------ def test_simple_package_crud(ckan_instance): API_KEY = ckan_instance.get_sysadmin_api_key() with ckan_instance.serve(): <|code_end|> , predict the immediate next line with the help of imports: import cgi import pytest from .utils import CkanClient and context (classes, functions, sometimes code) from other files: # Path: ckan_api_client/tests/functional/ckan_api/utils.py # class CkanClient(object): # """Simple client for the Ckan API""" # # def __init__(self, url, api_key=None): # self.url = url # self.api_key = api_key # # def request(self, method, path, **kw): # kw = copy.deepcopy(kw) # if 'headers' not in kw: # kw['headers'] = CaseInsensitiveDict() # elif not isinstance(kw['headers'], CaseInsensitiveDict): # kw['headers'] = CaseInsensitiveDict(kw['headers']) # if 'data' in kw: # kw['data'] = json.dumps(kw['data']) # kw['headers']['Content-type'] = 'application/json' # if self.api_key is not None: # kw['headers']['Authorization'] = self.api_key # url = urlparse.urljoin(self.url, path) # return requests.request(method, url, **kw) # # def get(self, *a, **kw): # return self.request('get', *a, **kw) # # def post(self, *a, **kw): # return self.request('post', *a, **kw) . Output only the next line.
client = CkanClient(ckan_instance.server_url, api_key=API_KEY)
Next line prediction: <|code_start|> :return: a requests response object """ headers = kwargs.get('headers') or {} kwargs['headers'] = headers # Update headers for authorization if self.api_key is not None: headers['Authorization'] = self.api_key # Serialize data to json, if not already if 'data' in kwargs: if not isinstance(kwargs['data'], basestring): kwargs['data'] = json.dumps(kwargs['data']) headers['content-type'] = 'application/json' if isinstance(path, (list, tuple)): path = '/'.join(path) url = urlparse.urljoin(self.base_url, path) response = requests.request(method, url, **kwargs) if not response.ok: # ------------------------------------------------------------ # todo: attach message, if any available.. # ------------------------------------------------------------ # todo: we should find a way to figure out how to attach # original text message to the exception # as it might be: json string, part of json object, # part of html document # ------------------------------------------------------------ <|code_end|> . Use current file imports: (import json import urlparse import requests from .exceptions import HTTPError, BadApiError from .utils import SuppressExceptionIf) and context including class names, function names, or small code snippets from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # class BadApiError(Exception): # """Exception used to mark bad behavior from the API""" # pass # # Path: ckan_api_client/utils.py # class SuppressExceptionIf(object): # """ # Context manager used to suppress exceptions if they match # a given condition. # # Usage example:: # # is_404 = lambda x: isinstance(x, HTTPError) and x.status_code == 404 # with SuppressExceptionIf(is_404): # client.request(...) # """ # # def __init__(self, cond): # self.cond = cond # # def __enter__(self): # pass # # def __exit__(self, exc_type, exc_value, traceback): # if exc_value is None: # return # if callable(self.cond): # # If the callable returns True, exception # # will be suppressed # return self.cond(exc_value) # return self.cond . Output only the next line.
raise HTTPError(
Predict the next line after this snippet: <|code_start|> def _figure_out_error_message(self, response): """ We have a response, which probably contains an error message, but we need to figure that out.. Usual places for errors are: - a json message, with {'error': {'message': ..., '__type': ...}} - a html page, usually when things went seriously bad """ with SuppressExceptionIf(True): return self._figure_out_error_from_json(response.json()) def _figure_out_error_from_json(self, data): if isinstance(data, dict) and 'error' in data: with SuppressExceptionIf(True): return '{0}: {1}'.format(data['error']['__type'], data['error']['message']) with SuppressExceptionIf(True): return '{0}'.format(data['error']['message']) raise ValueError("Unable to find message in JSON data") # ============================================================ # Validation helpers # ============================================================ def _validate_response_idlist(self, response, name='object'): if not isinstance(response, list): <|code_end|> using the current file's imports: import json import urlparse import requests from .exceptions import HTTPError, BadApiError from .utils import SuppressExceptionIf and any relevant context from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # class BadApiError(Exception): # """Exception used to mark bad behavior from the API""" # pass # # Path: ckan_api_client/utils.py # class SuppressExceptionIf(object): # """ # Context manager used to suppress exceptions if they match # a given condition. # # Usage example:: # # is_404 = lambda x: isinstance(x, HTTPError) and x.status_code == 404 # with SuppressExceptionIf(is_404): # client.request(...) # """ # # def __init__(self, cond): # self.cond = cond # # def __enter__(self): # pass # # def __exit__(self, exc_type, exc_value, traceback): # if exc_value is None: # return # if callable(self.cond): # # If the callable returns True, exception # # will be suppressed # return self.cond(exc_value) # return self.cond . Output only the next line.
raise BadApiError(
Predict the next line after this snippet: <|code_start|> url = urlparse.urljoin(self.base_url, path) response = requests.request(method, url, **kwargs) if not response.ok: # ------------------------------------------------------------ # todo: attach message, if any available.. # ------------------------------------------------------------ # todo: we should find a way to figure out how to attach # original text message to the exception # as it might be: json string, part of json object, # part of html document # ------------------------------------------------------------ raise HTTPError( status_code=response.status_code, message="Error while performing request", original=self._figure_out_error_message(response)) return response def _figure_out_error_message(self, response): """ We have a response, which probably contains an error message, but we need to figure that out.. Usual places for errors are: - a json message, with {'error': {'message': ..., '__type': ...}} - a html page, usually when things went seriously bad """ <|code_end|> using the current file's imports: import json import urlparse import requests from .exceptions import HTTPError, BadApiError from .utils import SuppressExceptionIf and any relevant context from other files: # Path: ckan_api_client/exceptions.py # class HTTPError(Exception): # """ # Exception representing an HTTP response error. # # .. attribute:: status_code # # HTTP status code # # .. attribute:: message # # Informative error message, if available # """ # # def __init__(self, status_code, message, original=None): # self.args = (status_code, message, original) # # @property # def status_code(self): # return self.args[0] # # @property # def message(self): # return self.args[1] # # @property # def original(self): # return self.args[2] # # def __str__(self): # return ("{0}({1!r}, {2!r}, original={3!r})" # .format(self.__class__.__name__, # self.status_code, self.message, self.original)) # # class BadApiError(Exception): # """Exception used to mark bad behavior from the API""" # pass # # Path: ckan_api_client/utils.py # class SuppressExceptionIf(object): # """ # Context manager used to suppress exceptions if they match # a given condition. # # Usage example:: # # is_404 = lambda x: isinstance(x, HTTPError) and x.status_code == 404 # with SuppressExceptionIf(is_404): # client.request(...) # """ # # def __init__(self, cond): # self.cond = cond # # def __enter__(self): # pass # # def __exit__(self, exc_type, exc_value, traceback): # if exc_value is None: # return # if callable(self.cond): # # If the callable returns True, exception # # will be suppressed # return self.cond(exc_value) # return self.cond . Output only the next line.
with SuppressExceptionIf(True):
Given the following code snippet before the placeholder: <|code_start|> # Add included file to stack, checking for cycles in the process. link_stack.push(filename) # Process the block's file if it hasn't been processed before. if not block_map.has_block(filename, block_name): with open(filename, 'r') as f: content = f.read() convert_lines_to_block(content.splitlines(), block_map, link_stack, filename) # If the block is not in the map even after converting, then the block doesn't exist. if not block_map.has_block(filename, block_name): raise IncludeNonExistentBlock( source_path + ' tried to include a non-existent block: ' + filename + ':' + block_name) link_stack.pop() # Convert the Block to a string and indent. return indent(str(block_map.get_block(filename, block_name)), leading_whitespace) def indent(content, whitespace): lines = content.splitlines() indented_lines = map(lambda line: whitespace + line, lines) return '\n'.join(indented_lines) ############## # Exceptions # ############## <|code_end|> , predict the next line using imports from the current file: from templar.exceptions import TemplarError import os import re and context including class names, function names, and sometimes code from other files: # Path: templar/exceptions.py # class TemplarError(Exception): # """Top-level exception for Templar.""" # pass . Output only the next line.
class InvalidBlockName(TemplarError):
Next line prediction: <|code_start|> class MarkdownToHtmlRule(core.Rule): def __init__(self, src=r'\.md', dst=r'\.html'): super().__init__(src, dst) def apply(self, content): # TODO(wualbert): rewrite markdown parser, or use a library. <|code_end|> . Use current file imports: (from templar import markdown from templar.api.rules import core) and context including class names, function names, or small code snippets from other files: # Path: templar/markdown.py # def convert(text): # def __init__(self, text, pre_hook=None, post_hook=None): # def convert(self, text, footnotes=False): # def __add__(self, other): # def __radd__(self, other): # def __getitem__(self, index): # def __setitem__(self, key, value): # def __repr__(self): # def escape(text): # def preprocess(text, markdown_obj): # def sub_retab(match): # def handle_whitespace(text): # def get_variables(text): # def get_references(text): # def get_footnote_backreferences(text, markdown_obj): # def remove_pandoc_comments(text): # def space_out_block_tags(text): # def apply_hashes(text, markdown_obj): # def hash_text(s, label): # def hash_blocks(text, hashes): # def sub(match): # def hash_lists(text, hashes, markdown_obj): # def hash_codeblocks(text, hashes): # def sub(match): # def hash_blockquotes(text, hashes, markdown_obj): # def sub(match): # def hash_tables(text, hashes, markdown_obj): # def sub(match): # def hash_codes(text, hashes): # def sub(match): # def hash_inline_links(text, hashes, markdown_obj): # def sub(match): # def hash_reference_links(text, hashes, markdown_obj): # def sub(match): # def hash_footnote_reference(text, hashes, markdown_obj): # def sub(match): # def hash_tags(text, hashes): # def sub(match): # def unhash(text, hashes): # def retrieve_match(match): # def apply_substitutions(text): # def hr_sub(match): # def emphasis_sub(match): # def auto_escape_sub(match): # def escapes_sub(match): # def atx_header_sub(match): # def setext_header_sub(match): # def paragraph_sub(match): # def postprocess(text, markdown_obj, footnotes=False): # def slug_sub(match): # def generate_footnotes(markdown_obj): # def cmd_options(parser): # def main(args=None): # class Markdown: # TAB_SIZE = 4 # SALT = bytes(randint(0, 1000000)) # # Path: templar/api/rules/core.py # class Rule: # class SubstitutionRule(Rule): # class VariableRule(Rule): # class InvalidRule(TemplarError): # def __init__(self, src=None, dst=None): # def applies(self, src, dst): # def apply(self, content): # def substitute(self, match): # def apply(self, content): # def extract(self, content): # def apply(self, content): . Output only the next line.
return markdown.convert(content)
Given snippet: <|code_start|> = """ expect = '<h1 id="hello-world">Hello World!</h1>' self.assertMarkdown(simple, expect) simple = """ With some 1337 hax0r = """ expect = '<h1 id="with-some-1337-hax0r">With some 1337 hax0r</h1>' self.assertMarkdown(simple, expect) def testPunctuation(self): simple = """ He!1. ^0#r$ = """ expect = '<h1 id="he-1-0-r">He!1. ^0#r$</h1>' self.assertMarkdown(simple, expect) def testWhitespace(self): simple = """ Lots of whitespace = """ expect = '<h1 id="lots-of-whitespace">Lots of whitespace</h1>' self.assertMarkdown(simple, expect) simple = ' leading whitespace\n=' expect = '<h1 id="leading-whitespace">leading whitespace</h1>' <|code_end|> , continue by predicting the next line. Consider current file imports: from tests.markdown_test.test_utils import MarkdownTest from templar.markdown import convert, Markdown and context: # Path: tests/markdown_test/test_utils.py # class MarkdownTest(TemplarTest): # def setUp(self): # pass # # def tearDown(self): # pass # # def assertMarkdown(self, markdown, output): # markdown = self.dedent(markdown) # output = self.dedent(output) # try: # self.assertEqual(output + '\n', convert(markdown) + '\n') # except AssertionError: # raise # # def assertMarkdownNotEqual(self, markdown, output): # markdown = self.dedent(markdown) # output = self.dedent(output) # try: # self.assertNotEqual(output, convert(markdown)) # except AssertionError: # raise # # def assertMarkdownIgnoreWS(self, markdown, output): # markdown = self.dedent(markdown) # try: # self.assertEqual(self.ignoreWhitespace(output), # self.ignoreWhitespace(convert(markdown))) # except AssertionError: # raise # # Path: templar/markdown.py # def convert(text): # return Markdown(text).text # # class Markdown: # def __init__(self, text, pre_hook=None, post_hook=None): # if pre_hook: # text = pre_hook(text) # self.text, self.variables, self.references, self.footnotes = preprocess(text, self) # self.text = self.convert(self.text, footnotes=True).strip() # if post_hook: # self.text = post_hook(self.text) # # def convert(self, text, footnotes=False): # text, hashes = apply_hashes(text, self) # text = apply_substitutions(text) # text = unhash(text, hashes) # text = postprocess(text, self, footnotes) # return text # # def __add__(self, other): # if type(other) not in (Markdown, str): # raise ValueError('Cannot add {} to Markdown object'.format( # other)) # return self.text + other # # def __radd__(self, other): # return self + other # # def __getitem__(self, index): # if type(index) == int: # return self.text[index] # elif type(index) == str: # return self.variables[index] # else: # raise KeyError('Invalid index/key for Markdown object: {}'.format(index)) # # def __setitem__(self, key, value): # if type(key) != str: # raise KeyError('Invalid key for Markdown object: {}'.format(index)) # self.variables[key] = value # # def __repr__(self): # return self.text which might include code, classes, or functions. Output only the next line.
self.assertEqual(expect, convert(simple))
Continue the code snippet: <|code_start|> return self def add_variable(self, variable, value): if not isinstance(variable, str): raise ConfigBuilderError( 'variable must be a string, but instead was: ' + repr(variable)) # TODO: Coerce value into some string (possibly unicode, depending on Jinja) self._variables[variable] = value return self def add_variables(self, variable_map): # Loop through variables instead of using dict.update so we can validate each variable. for variable, value in variable_map.items(): self.add_variable(variable, value) return self def set_recursively_evaluate_jinja_expressions(self, recursively_evaluate_jinja_expressions): if not isinstance(recursively_evaluate_jinja_expressions, bool): raise ConfigBuilderError( 'recursively_evaluate_jinja_expressions must be a boolean, ' 'but instead was: ' + repr(recursively_evaluate_jinja_expressions)) self._recursively_evaluate_jinja_expressions = recursively_evaluate_jinja_expressions return self def clear_variables(self): self._variables = {} return self def append_compiler_rules(self, *compiler_rules): for rule in compiler_rules: <|code_end|> . Use current file imports: from templar.api.rules.core import Rule from templar.exceptions import TemplarError import importlib.machinery import os.path and context (classes, functions, or code) from other files: # Path: templar/api/rules/core.py # class Rule: # """Represents a preprocessor or postprocessor rule. Rules are applied in the order that they # are listed in the Config. # # When constructing a rule, the arguments `src` and `dst` are regular expressions; Templar will # only apply a rule if the source and destination of the publishing pipeline match the regexes. # """ # def __init__(self, src=None, dst=None): # if src is not None and not isinstance(src, str): # raise InvalidRule( # "Rule's source pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # if dst is not None and not isinstance(dst, str): # raise InvalidRule( # "Rule's destination pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # self._src_pattern = src # self._dst_pattern = dst # # def applies(self, src, dst): # """Checks if this rule applies to the given src and dst paths, based on the src pattern and # dst pattern given in the constructor. # # If src pattern was None, this rule will apply to any given src path (same for dst). # """ # if self._src_pattern and (src is None or re.search(self._src_pattern, src) is None): # return False # elif self._dst_pattern and (dst is None or re.search(self._dst_pattern, dst) is None): # return False # return True # # def apply(self, content): # """Applies this rule to the given content. A rule can do one or more of the following: # # - Return a string; this is taken to be the transformed version of content, and will be used # as the new content after applying this rule. # - Modify variables (a dict). Usually, Rules that modify this dictionary will add new # variables. However, a Rule can also delete or update key/value pairs in the dictionary. # """ # raise NotImplementedError # # Path: templar/exceptions.py # class TemplarError(Exception): # """Top-level exception for Templar.""" # pass . Output only the next line.
if not isinstance(rule, Rule):
Here is a snippet: <|code_start|> def to_builder(self): return ConfigBuilder( self._template_dirs, self._variables, self._recursively_evaluate_jinja_expressions, self._compiler_rules, self._preprocess_rules, self._postprocess_rules) def import_config(config_path): """Import a Config from a given path, relative to the current directory. The module specified by the config file must contain a variable called `configuration` that is assigned to a Config object. """ if not os.path.isfile(config_path): raise ConfigBuilderError( 'Could not find config file: ' + config_path) loader = importlib.machinery.SourceFileLoader(config_path, config_path) module = loader.load_module() if not hasattr(module, 'config') or not isinstance(module.config, Config): raise ConfigBuilderError( 'Could not load config file "{}": config files must contain ' 'a variable called "config" that is ' 'assigned to a Config object.'.format(config_path)) return module.config <|code_end|> . Write the next line using the current file imports: from templar.api.rules.core import Rule from templar.exceptions import TemplarError import importlib.machinery import os.path and context from other files: # Path: templar/api/rules/core.py # class Rule: # """Represents a preprocessor or postprocessor rule. Rules are applied in the order that they # are listed in the Config. # # When constructing a rule, the arguments `src` and `dst` are regular expressions; Templar will # only apply a rule if the source and destination of the publishing pipeline match the regexes. # """ # def __init__(self, src=None, dst=None): # if src is not None and not isinstance(src, str): # raise InvalidRule( # "Rule's source pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # if dst is not None and not isinstance(dst, str): # raise InvalidRule( # "Rule's destination pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # self._src_pattern = src # self._dst_pattern = dst # # def applies(self, src, dst): # """Checks if this rule applies to the given src and dst paths, based on the src pattern and # dst pattern given in the constructor. # # If src pattern was None, this rule will apply to any given src path (same for dst). # """ # if self._src_pattern and (src is None or re.search(self._src_pattern, src) is None): # return False # elif self._dst_pattern and (dst is None or re.search(self._dst_pattern, dst) is None): # return False # return True # # def apply(self, content): # """Applies this rule to the given content. A rule can do one or more of the following: # # - Return a string; this is taken to be the transformed version of content, and will be used # as the new content after applying this rule. # - Modify variables (a dict). Usually, Rules that modify this dictionary will add new # variables. However, a Rule can also delete or update key/value pairs in the dictionary. # """ # raise NotImplementedError # # Path: templar/exceptions.py # class TemplarError(Exception): # """Top-level exception for Templar.""" # pass , which may include functions, classes, or code. Output only the next line.
class ConfigBuilderError(TemplarError):
Predict the next line after this snippet: <|code_start|>"""End-to-end test for templar/cli/templar.py""" STAGING_DIR = os.path.join('tests', 'cli', 'staging') TEST_DATA = os.path.join('tests', 'cli', 'test_data') class TemplarTest(unittest.TestCase): def setUp(self): os.mkdir(STAGING_DIR) def tearDown(self): shutil.rmtree(STAGING_DIR) def testConfigNotFound(self): <|code_end|> using the current file's imports: from templar.api.config import ConfigBuilderError from templar.cli import templar import io import mock import os.path import shutil import unittest and any relevant context from other files: # Path: templar/api/config.py # class ConfigBuilderError(TemplarError): # pass # # Path: templar/cli/templar.py # LOGGING_FORMAT = '%(levelname)s %(filename)s:%(lineno)d> %(message)s' # def flags(args=None): # def run(args): # def main(): . Output only the next line.
with self.assertRaises(ConfigBuilderError) as cm:
Using the snippet: <|code_start|>"""End-to-end test for templar/cli/templar.py""" STAGING_DIR = os.path.join('tests', 'cli', 'staging') TEST_DATA = os.path.join('tests', 'cli', 'test_data') class TemplarTest(unittest.TestCase): def setUp(self): os.mkdir(STAGING_DIR) def tearDown(self): shutil.rmtree(STAGING_DIR) def testConfigNotFound(self): with self.assertRaises(ConfigBuilderError) as cm: <|code_end|> , determine the next line of code. You have imports: from templar.api.config import ConfigBuilderError from templar.cli import templar import io import mock import os.path import shutil import unittest and context (class names, function names, or code) available: # Path: templar/api/config.py # class ConfigBuilderError(TemplarError): # pass # # Path: templar/cli/templar.py # LOGGING_FORMAT = '%(levelname)s %(filename)s:%(lineno)d> %(message)s' # def flags(args=None): # def run(args): # def main(): . Output only the next line.
templar.run(templar.flags([
Here is a snippet: <|code_start|>"""Tests templar/api/rules/core.py""" class RuleTest(unittest.TestCase): def testApplies_withSrcRegex(self): rule = Rule(src='.html') self.assertTrue(rule.applies('source.html', 'destination')) self.assertFalse(rule.applies('source.py', 'destination')) def testApplies_withDestRegex(self): rule = Rule(dst='.html') self.assertTrue(rule.applies('source', 'destination.html')) self.assertFalse(rule.applies('source', 'destination.py')) def testApplies_withDstNone(self): # No destination pattern, so matches everything, even no destination. rule = Rule() self.assertTrue(rule.applies('source.html', None)) self.assertTrue(rule.applies('source.html', 'destination.html')) # Destination pattern, so cannot match destination of None. rule = Rule(dst='.html') self.assertFalse(rule.applies('source.html', None)) class SubstitutionRuleTest(unittest.TestCase): def testInvalidPattern(self): <|code_end|> . Write the next line using the current file imports: from templar.api.rules.core import Rule from templar.api.rules.core import SubstitutionRule from templar.api.rules.core import InvalidRule import re import unittest and context from other files: # Path: templar/api/rules/core.py # class Rule: # """Represents a preprocessor or postprocessor rule. Rules are applied in the order that they # are listed in the Config. # # When constructing a rule, the arguments `src` and `dst` are regular expressions; Templar will # only apply a rule if the source and destination of the publishing pipeline match the regexes. # """ # def __init__(self, src=None, dst=None): # if src is not None and not isinstance(src, str): # raise InvalidRule( # "Rule's source pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # if dst is not None and not isinstance(dst, str): # raise InvalidRule( # "Rule's destination pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # self._src_pattern = src # self._dst_pattern = dst # # def applies(self, src, dst): # """Checks if this rule applies to the given src and dst paths, based on the src pattern and # dst pattern given in the constructor. # # If src pattern was None, this rule will apply to any given src path (same for dst). # """ # if self._src_pattern and (src is None or re.search(self._src_pattern, src) is None): # return False # elif self._dst_pattern and (dst is None or re.search(self._dst_pattern, dst) is None): # return False # return True # # def apply(self, content): # """Applies this rule to the given content. A rule can do one or more of the following: # # - Return a string; this is taken to be the transformed version of content, and will be used # as the new content after applying this rule. # - Modify variables (a dict). Usually, Rules that modify this dictionary will add new # variables. However, a Rule can also delete or update key/value pairs in the dictionary. # """ # raise NotImplementedError # # Path: templar/api/rules/core.py # class SubstitutionRule(Rule): # """An abstract class that represents a rule that transforms the content that is being processed, # based on a regex pattern and a substitution function. The substitution behaves exactly like # re.sub. # """ # pattern = None # Subclasses should override this variable with a string or compiled regex. # # def substitute(self, match): # """A substitution function that returns the text with which to replace the given match. # Subclasses should implement this method. # """ # raise InvalidRule( # '{} must implement the substitute method to be ' # 'a valid SubstitutionRule'.format(type(self).__name__)) # # def apply(self, content): # if isinstance(self.pattern, str): # return re.sub(self.pattern, self.substitute, content) # elif hasattr(self.pattern, 'sub') and callable(self.pattern.sub): # return self.pattern.sub(self.substitute, content) # raise InvalidRule( # "{}'s pattern has type '{}', but expected a string or " # "compiled regex.".format(type(self).__name__, type(self.pattern).__name__)) # # Path: templar/api/rules/core.py # class InvalidRule(TemplarError): # pass , which may include functions, classes, or code. Output only the next line.
class TestRule(SubstitutionRule):
Here is a snippet: <|code_start|> class RuleTest(unittest.TestCase): def testApplies_withSrcRegex(self): rule = Rule(src='.html') self.assertTrue(rule.applies('source.html', 'destination')) self.assertFalse(rule.applies('source.py', 'destination')) def testApplies_withDestRegex(self): rule = Rule(dst='.html') self.assertTrue(rule.applies('source', 'destination.html')) self.assertFalse(rule.applies('source', 'destination.py')) def testApplies_withDstNone(self): # No destination pattern, so matches everything, even no destination. rule = Rule() self.assertTrue(rule.applies('source.html', None)) self.assertTrue(rule.applies('source.html', 'destination.html')) # Destination pattern, so cannot match destination of None. rule = Rule(dst='.html') self.assertFalse(rule.applies('source.html', None)) class SubstitutionRuleTest(unittest.TestCase): def testInvalidPattern(self): class TestRule(SubstitutionRule): pattern = 3 rule = TestRule() <|code_end|> . Write the next line using the current file imports: from templar.api.rules.core import Rule from templar.api.rules.core import SubstitutionRule from templar.api.rules.core import InvalidRule import re import unittest and context from other files: # Path: templar/api/rules/core.py # class Rule: # """Represents a preprocessor or postprocessor rule. Rules are applied in the order that they # are listed in the Config. # # When constructing a rule, the arguments `src` and `dst` are regular expressions; Templar will # only apply a rule if the source and destination of the publishing pipeline match the regexes. # """ # def __init__(self, src=None, dst=None): # if src is not None and not isinstance(src, str): # raise InvalidRule( # "Rule's source pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # if dst is not None and not isinstance(dst, str): # raise InvalidRule( # "Rule's destination pattern must be a string or None, " # "but was type '{}'".format(type(src).__name__)) # self._src_pattern = src # self._dst_pattern = dst # # def applies(self, src, dst): # """Checks if this rule applies to the given src and dst paths, based on the src pattern and # dst pattern given in the constructor. # # If src pattern was None, this rule will apply to any given src path (same for dst). # """ # if self._src_pattern and (src is None or re.search(self._src_pattern, src) is None): # return False # elif self._dst_pattern and (dst is None or re.search(self._dst_pattern, dst) is None): # return False # return True # # def apply(self, content): # """Applies this rule to the given content. A rule can do one or more of the following: # # - Return a string; this is taken to be the transformed version of content, and will be used # as the new content after applying this rule. # - Modify variables (a dict). Usually, Rules that modify this dictionary will add new # variables. However, a Rule can also delete or update key/value pairs in the dictionary. # """ # raise NotImplementedError # # Path: templar/api/rules/core.py # class SubstitutionRule(Rule): # """An abstract class that represents a rule that transforms the content that is being processed, # based on a regex pattern and a substitution function. The substitution behaves exactly like # re.sub. # """ # pattern = None # Subclasses should override this variable with a string or compiled regex. # # def substitute(self, match): # """A substitution function that returns the text with which to replace the given match. # Subclasses should implement this method. # """ # raise InvalidRule( # '{} must implement the substitute method to be ' # 'a valid SubstitutionRule'.format(type(self).__name__)) # # def apply(self, content): # if isinstance(self.pattern, str): # return re.sub(self.pattern, self.substitute, content) # elif hasattr(self.pattern, 'sub') and callable(self.pattern.sub): # return self.pattern.sub(self.substitute, content) # raise InvalidRule( # "{}'s pattern has type '{}', but expected a string or " # "compiled regex.".format(type(self).__name__, type(self.pattern).__name__)) # # Path: templar/api/rules/core.py # class InvalidRule(TemplarError): # pass , which may include functions, classes, or code. Output only the next line.
with self.assertRaises(InvalidRule) as cm:
Given the following code snippet before the placeholder: <|code_start|>"""Tests template/linker/blocks.py""" class LinkTest(unittest.TestCase): def setUp(self): self.is_file_patcher = mock.patch('os.path.isfile') self.mock_is_file = self.is_file_patcher.start() self.mock_is_file.return_value = True def tearDown(self): self.is_file_patcher.stop() def testNonExistentSourceFile(self): self.mock_is_file.return_value = False with self.assertRaises(SourceNotFound) as cm: <|code_end|> , predict the next line using imports from the current file: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context including class names, function names, and sometimes code from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) . Output only the next line.
link('no/such/path')
Given the code snippet: <|code_start|> def side_effect(filename, *options): assert filename in file_map, 'File ' + filename + ' not found in ' + str(list(file_map)) return mock.mock_open(read_data=file_map[filename])(filename, *options) self.mock_is_file.side_effect = lambda f: f in file_map return mock.patch('builtins.open', mock.Mock(side_effect=side_effect)) def assertBlockEqual(self, expected, actual): self.assertEqual(expected.source_path, actual.source_path) self.assertEqual(expected.name, actual.name) self.assertEqual(len(expected.segments), len(actual.segments)) for expected_segment, actual_segment in zip(expected.segments, actual.segments): if isinstance(expected_segment, str): self.assertEqual(expected_segment, actual_segment) elif isinstance(expected_segment, Block): self.assertBlockEqual(expected_segment, actual_segment) else: self.fail('Encountered segment of type "{}"'.format(expected_segment)) def join_lines(self, *lines): """Concatenates multiple strings together with newlines in between. Using this method is cleaner than using multiline strings (since we need to handle indentation and leading/trailing newlines). """ return '\n'.join(lines) class GetBlockDictTest(unittest.TestCase): def testNoNestedBlocks(self): block_all = Block('some/path', 'all', ['all content']) <|code_end|> , generate the next line using the imports in this file: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context (functions, classes, or occasionally code) from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) . Output only the next line.
block_dict = get_block_dict(block_all)
Predict the next line after this snippet: <|code_start|>"""Tests template/linker/blocks.py""" class LinkTest(unittest.TestCase): def setUp(self): self.is_file_patcher = mock.patch('os.path.isfile') self.mock_is_file = self.is_file_patcher.start() self.mock_is_file.return_value = True def tearDown(self): self.is_file_patcher.stop() def testNonExistentSourceFile(self): self.mock_is_file.return_value = False with self.assertRaises(SourceNotFound) as cm: link('no/such/path') self.assertEqual('Could not find source file: no/such/path', str(cm.exception)) def testNoBlocksAndIncludes(self): data = self.join_lines( 'Hello world', 'Second line') with self.mock_open({'some/path': data}): block, variables = link('some/path') self.assertEqual({}, variables) <|code_end|> using the current file's imports: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and any relevant context from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) . Output only the next line.
block_all = Block('some/path', 'all', [data])
Predict the next line for this snippet: <|code_start|>"""Tests template/linker/blocks.py""" class LinkTest(unittest.TestCase): def setUp(self): self.is_file_patcher = mock.patch('os.path.isfile') self.mock_is_file = self.is_file_patcher.start() self.mock_is_file.return_value = True def tearDown(self): self.is_file_patcher.stop() def testNonExistentSourceFile(self): self.mock_is_file.return_value = False <|code_end|> with the help of current file imports: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) , which may contain function names, class names, or code. Output only the next line.
with self.assertRaises(SourceNotFound) as cm:
Here is a snippet: <|code_start|> block_all = Block('some/path', 'all', [block_foo]) self.assertBlockEqual(block_all, block) def testBlocks_nested(self): data = self.join_lines( '<block outer>', 'outer content', '<block inner>', 'inner content', '</block inner>', 'outer content', '</block outer>') with self.mock_open({'some/path': data}): block, variables = link('some/path') self.assertEqual({}, variables) block_inner = Block('some/path', 'inner', ['inner content']) block_outer = Block('some/path', 'outer', [ 'outer content', block_inner, 'outer content']) block_all = Block('some/path', 'all', [block_outer]) self.assertBlockEqual(block_all, block) def testBlocks_preventBlockCalledAll(self): data = self.join_lines( '<block all>', 'content', '</block all>') with self.mock_open({'some/path': data}): <|code_end|> . Write the next line using the current file imports: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) , which may include functions, classes, or code. Output only the next line.
with self.assertRaises(InvalidBlockName) as cm:
Given snippet: <|code_start|> def testIncludes_relativeToSource(self): mock_open = self.mock_open({ 'path/to/docA.md': '<include docB.md>', 'path/to/docB.md': 'content', }) with mock_open: block, variables = link('path/to/docA.md') self.assertEqual({}, variables) block_all = Block('path/to/docA.md', 'all', ['content']) self.assertBlockEqual(block_all, block) def testIncludes_leadingWhitespace(self): mock_open = self.mock_open({ 'docA.md': ' <include docB.md>', # Indented four spaces 'docB.md': 'content', }) with mock_open: block, variables = link('docA.md') self.assertEqual({}, variables) block_all = Block('docA.md', 'all', [' content']) self.assertBlockEqual(block_all, block) def testIncludes_preventNonExistentFile(self): mock_open = self.mock_open({ 'docA.md': '<include docB.md>', # docB.md doesn't exist. }) with mock_open: <|code_end|> , continue by predicting the next line. Consider current file imports: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) which might include code, classes, or functions. Output only the next line.
with self.assertRaises(IncludeNonExistentBlock) as cm:
Given the following code snippet before the placeholder: <|code_start|> self.assertBlockEqual(block_all, block) def testIncludes_preventNonExistentFile(self): mock_open = self.mock_open({ 'docA.md': '<include docB.md>', # docB.md doesn't exist. }) with mock_open: with self.assertRaises(IncludeNonExistentBlock) as cm: link('docA.md') self.assertEqual('docA.md tried to include a non-existent file: docB.md', str(cm.exception)) def testIncludes_preventNonExistentBlock(self): mock_open = self.mock_open({ 'docA.md': '<include docB.md:foo>', # docB.md:foo doesn't exist. 'docB.md': 'contents', }) with mock_open: with self.assertRaises(IncludeNonExistentBlock) as cm: link('docA.md') self.assertEqual( 'docA.md tried to include a non-existent block: docB.md:foo', str(cm.exception)) def testIncludes_preventCycle(self): mock_open = self.mock_open({ 'docA.md': '<include docB.md>', 'docB.md': '<include docC.md>', 'docC.md': '<include docB.md>', }) with mock_open: <|code_end|> , predict the next line using imports from the current file: from templar.linker import link from templar.linker import get_block_dict from templar.linker import Block from templar.linker import SourceNotFound from templar.linker import InvalidBlockName from templar.linker import IncludeNonExistentBlock from templar.linker import CyclicalIncludeError import unittest import mock and context including class names, function names, and sometimes code from other files: # Path: templar/linker.py # def link(source_path): # """Links the content found at source_path and represents a Block that represents the content.""" # if not os.path.isfile(source_path): # raise SourceNotFound(source_path) # with open(source_path, 'r') as f: # content = f.read() # block_map = BlockMap() # The map will be populated with the following function call. # all_block = convert_lines_to_block( # content.splitlines(), block_map, LinkStack(source_path), source_path) # return all_block, block_map.get_variables() # # Path: templar/linker.py # def get_block_dict(top_level_block): # """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as # well as the original block itself. # # The block_dict argument is only used for recursive calls and should not # """ # block_stack = [top_level_block] # block_dict = {} # while block_stack: # block = block_stack.pop() # block_dict[block.name] = str(block) # for segment in block.segments: # if isinstance(segment, Block): # block_stack.append(segment) # return block_dict # # Path: templar/linker.py # class Block(object): # def __init__(self, source_path, name, segments): # self.source_path = source_path # self.name = name # self.segments = segments # self._str = None # Cache the str representation of this block. # # def apply_rule(self, rule): # self._str = None # Clear str cache. # for i, segment in enumerate(self.segments): # assert isinstance(segment, str) or isinstance(segment, Block) # if isinstance(segment, str): # self.segments[i] = rule.apply(segment) # else: # segment.apply_rule(rule) # Recursively apply rule onto nested blocks. # # def __str__(self): # if self._str is None: # self._str = '\n'.join(str(segment) for segment in self.segments) # return self._str # # Path: templar/linker.py # class SourceNotFound(TemplarError): # def __init__(self, source_path): # super().__init__('Could not find source file: ' + source_path) # # Path: templar/linker.py # class InvalidBlockName(TemplarError): # pass # # Path: templar/linker.py # class IncludeNonExistentBlock(TemplarError): # pass # # Path: templar/linker.py # class CyclicalIncludeError(TemplarError): # def __init__(self, link_stack, last_file): # super().__init__(' -> '.join(link_stack + [last_file])) . Output only the next line.
with self.assertRaises(CyclicalIncludeError) as cm:
Using the snippet: <|code_start|> class TemplarTest(unittest.TestCase): def dedent(self, text): return textwrap.dedent(text).lstrip('\n').rstrip() def ignoreWhitespace(self, text): text = self.dedent(text) return re.sub('\s+', '', text, flags=re.S) class MarkdownTest(TemplarTest): def setUp(self): pass def tearDown(self): pass def assertMarkdown(self, markdown, output): markdown = self.dedent(markdown) output = self.dedent(output) try: <|code_end|> , determine the next line of code. You have imports: import os import unittest import re import textwrap from templar.markdown import convert, Markdown and context (class names, function names, or code) available: # Path: templar/markdown.py # def convert(text): # return Markdown(text).text # # class Markdown: # def __init__(self, text, pre_hook=None, post_hook=None): # if pre_hook: # text = pre_hook(text) # self.text, self.variables, self.references, self.footnotes = preprocess(text, self) # self.text = self.convert(self.text, footnotes=True).strip() # if post_hook: # self.text = post_hook(self.text) # # def convert(self, text, footnotes=False): # text, hashes = apply_hashes(text, self) # text = apply_substitutions(text) # text = unhash(text, hashes) # text = postprocess(text, self, footnotes) # return text # # def __add__(self, other): # if type(other) not in (Markdown, str): # raise ValueError('Cannot add {} to Markdown object'.format( # other)) # return self.text + other # # def __radd__(self, other): # return self + other # # def __getitem__(self, index): # if type(index) == int: # return self.text[index] # elif type(index) == str: # return self.variables[index] # else: # raise KeyError('Invalid index/key for Markdown object: {}'.format(index)) # # def __setitem__(self, key, value): # if type(key) != str: # raise KeyError('Invalid key for Markdown object: {}'.format(index)) # self.variables[key] = value # # def __repr__(self): # return self.text . Output only the next line.
self.assertEqual(output + '\n', convert(markdown) + '\n')
Given snippet: <|code_start|> elif hasattr(self.pattern, 'sub') and callable(self.pattern.sub): return self.pattern.sub(self.substitute, content) raise InvalidRule( "{}'s pattern has type '{}', but expected a string or " "compiled regex.".format(type(self).__name__, type(self.pattern).__name__)) class VariableRule(Rule): """An abstract class that represents a rule that constructs variables given the content. For VariableRules, the apply method returns a dictionary mapping str -> str instead of returning transformed content (a string). """ def extract(self, content): """A substitution function that returns the text with which to replace the given match. Subclasses should implement this method. """ raise InvalidRule( '{} must implement the extract method to be ' 'a valid VariableRule'.format(type(self).__name__)) def apply(self, content): variables = self.extract(content) if not isinstance(variables, dict): raise InvalidRule( "{} is a VariableRule, so its extract method should return a dict. Instead, it " "returned type '{}'".format(type(self).__name__, type(variables).__name__)) return variables <|code_end|> , continue by predicting the next line. Consider current file imports: from templar.exceptions import TemplarError import re and context: # Path: templar/exceptions.py # class TemplarError(Exception): # """Top-level exception for Templar.""" # pass which might include code, classes, or functions. Output only the next line.
class InvalidRule(TemplarError):
Next line prediction: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Represents a connection to the EMR service """ class EmrConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'emr_version', '2009-03-31') DefaultRegionName = boto.config.get('Boto', 'emr_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'emr_region_endpoint', 'elasticmapreduce.amazonaws.com') <|code_end|> . Use current file imports: (import types import boto import boto.utils from boto.ec2.regioninfo import RegionInfo from boto.emr.emrobject import JobFlow, RunJobFlowResponse from boto.emr.emrobject import AddInstanceGroupsResponse, ModifyInstanceGroupsResponse from boto.emr.step import JarStep from boto.connection import AWSQueryConnection from boto.exception import EmrResponseError) and context including class names, function names, or small code snippets from other files: # Path: boto/exception.py # class EmrResponseError(BotoServerError): # """ # Error in response from EMR # """ # pass . Output only the next line.
ResponseError = EmrResponseError
Using the snippet: <|code_start|> status = self.connection.revoke_security_group(self.name, src_group_name, src_group_owner_id, ip_protocol, from_port, to_port, cidr_ip) if status: self.remove_rule(ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip) return status def copy_to_region(self, region, name=None): """ Create a copy of this security group in another region. Note that the new security group will be a separate entity and will not stay in sync automatically after the copy operation. :type region: :class:`boto.ec2.regioninfo.RegionInfo` :param region: The region to which this security group will be copied. :type name: string :param name: The name of the copy. If not supplied, the copy will have the same name as this security group. :rtype: :class:`boto.ec2.securitygroup.SecurityGroup` :return: The new security group. """ if region.name == self.region: <|code_end|> , determine the next line of code. You have imports: from boto.ec2.ec2object import TaggedEC2Object from boto.exception import BotoClientError and context (class names, function names, or code) available: # Path: boto/exception.py # class BotoClientError(StandardError): # """ # General Boto Client error (error accessing AWS) # """ # # def __init__(self, reason, *args): # StandardError.__init__(self, reason, *args) # self.reason = reason # # def __repr__(self): # return 'BotoClientError: %s' % self.reason # # def __str__(self): # return 'BotoClientError: %s' % self.reason . Output only the next line.
raise BotoClientError('Unable to copy to the same Region')
Based on the snippet: <|code_start|> if value.lower() == 'true': self.delete_on_termination = True else: self.delete_on_termination = False else: setattr(self, name, value) class NetworkInterface(TaggedEC2Object): def __init__(self, connection=None): TaggedEC2Object.__init__(self, connection) self.id = None self.subnet_id = None self.vpc_id = None self.availability_zone = None self.description = None self.owner_id = None self.requester_managed = False self.status = None self.mac_address = None self.private_ip_address = None self.source_dest_check = None self.groups = [] self.attachment = None def __repr__(self): return 'NetworkInterface:%s' % self.id def startElement(self, name, attrs, connection): if name == 'groupSet': <|code_end|> , predict the immediate next line with the help of imports: from boto.ec2.ec2object import TaggedEC2Object from boto.resultset import ResultSet from boto.ec2.instance import Group and context (classes, functions, sometimes code) from other files: # Path: boto/ec2/instance.py # class Group: # # def __init__(self, parent=None): # self.id = None # self.name = None # # def startElement(self, name, attrs, connection): # return None # # def endElement(self, name, value, connection): # if name == 'groupId': # self.id = value # elif name == 'groupName': # self.name = value # else: # setattr(self, name, value) . Output only the next line.
self.groups = ResultSet([('item', Group)])
Given the code snippet: <|code_start|>""" Exceptions that are specific to the dynamodb module. """ class DynamoDBExpiredTokenError(BotoServerError): """ Raised when a DynamoDB security token expires. This is generally boto's (or the user's) notice to renew their DynamoDB security tokens. """ pass <|code_end|> , generate the next line using the imports in this file: from boto.exception import BotoServerError, BotoClientError and context (functions, classes, or occasionally code) from other files: # Path: boto/exception.py # class BotoServerError(StandardError): # # def __init__(self, status, reason, body=None, *args): # StandardError.__init__(self, status, reason, body, *args) # self.status = status # self.reason = reason # self.body = body or '' # self.request_id = None # self.error_code = None # self.error_message = None # self.box_usage = None # # # Attempt to parse the error response. If body isn't present, # # then just ignore the error response. # if self.body: # try: # h = handler.XmlHandler(self, self) # xml.sax.parseString(self.body, h) # except (TypeError, xml.sax.SAXParseException), pe: # # Remove unparsable message body so we don't include garbage # # in exception. But first, save self.body in self.error_message # # because occasionally we get error messages from Eucalyptus # # that are just text strings that we want to preserve. # self.error_message = self.body # self.body = None # # def __getattr__(self, name): # if name == 'message': # return self.error_message # if name == 'code': # return self.error_code # raise AttributeError # # def __repr__(self): # return '%s: %s %s\n%s' % (self.__class__.__name__, # self.status, self.reason, self.body) # # def __str__(self): # return '%s: %s %s\n%s' % (self.__class__.__name__, # self.status, self.reason, self.body) # # def startElement(self, name, attrs, connection): # pass # # def endElement(self, name, value, connection): # if name in ('RequestId', 'RequestID'): # self.request_id = value # elif name == 'Code': # self.error_code = value # elif name == 'Message': # self.error_message = value # elif name == 'BoxUsage': # self.box_usage = value # return None # # def _cleanupParsedProperties(self): # self.request_id = None # self.error_code = None # self.error_message = None # self.box_usage = None # # class BotoClientError(StandardError): # """ # General Boto Client error (error accessing AWS) # """ # # def __init__(self, reason, *args): # StandardError.__init__(self, reason, *args) # self.reason = reason # # def __repr__(self): # return 'BotoClientError: %s' % self.reason # # def __str__(self): # return 'BotoClientError: %s' % self.reason . Output only the next line.
class DynamoDBKeyNotFoundError(BotoClientError):
Predict the next line for this snippet: <|code_start|> statement_id = fields.Many2one( 'l10n.de.tax.statement', 'Statement' ) currency_id = fields.Many2one( 'res.currency', related='statement_id.company_id.currency_id', readonly=True, help='Utility field to express amount currency' ) base = fields.Monetary() tax = fields.Monetary() format_base = fields.Char(compute='_compute_amount_format') format_tax = fields.Char(compute='_compute_amount_format') is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: <|code_end|> with the help of current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) , which may contain function names, class names, or code. Output only the next line.
base_display = _base_display_2018()
Here is a snippet: <|code_start|> statement_id = fields.Many2one( 'l10n.de.tax.statement', 'Statement' ) currency_id = fields.Many2one( 'res.currency', related='statement_id.company_id.currency_id', readonly=True, help='Utility field to express amount currency' ) base = fields.Monetary() tax = fields.Monetary() format_base = fields.Char(compute='_compute_amount_format') format_tax = fields.Char(compute='_compute_amount_format') is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: base_display = _base_display_2018() <|code_end|> . Write the next line using the current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) , which may include functions, classes, or code. Output only the next line.
tax_display = _tax_display_2018()
Given the code snippet: <|code_start|> is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: base_display = _base_display_2018() tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': group_display = _group_display_2019() total_display = _total_display_2019() else: <|code_end|> , generate the next line using the imports in this file: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context (functions, classes, or occasionally code) from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) . Output only the next line.
group_display = _group_display_2018()
Using the snippet: <|code_start|> state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: base_display = _base_display_2018() tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': group_display = _group_display_2019() total_display = _total_display_2019() else: group_display = _group_display_2018() <|code_end|> , determine the next line of code. You have imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context (class names, function names, or code) available: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) . Output only the next line.
total_display = _total_display_2018()
Given snippet: <|code_start|> tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': group_display = _group_display_2019() total_display = _total_display_2019() else: group_display = _group_display_2018() total_display = _total_display_2018() line.is_group = line.code in group_display line.is_total = line.code in total_display @api.multi @api.depends('code') def _compute_is_readonly(self): for line in self: if line.statement_id.version == '2019': editable_display = _editable_display_2019() else: <|code_end|> , continue by predicting the next line. Consider current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) which might include code, classes, or functions. Output only the next line.
editable_display = _editable_display_2018()
Predict the next line for this snippet: <|code_start|> name = fields.Char() code = fields.Char() statement_id = fields.Many2one( 'l10n.de.tax.statement', 'Statement' ) currency_id = fields.Many2one( 'res.currency', related='statement_id.company_id.currency_id', readonly=True, help='Utility field to express amount currency' ) base = fields.Monetary() tax = fields.Monetary() format_base = fields.Char(compute='_compute_amount_format') format_tax = fields.Char(compute='_compute_amount_format') is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': <|code_end|> with the help of current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) , which may contain function names, class names, or code. Output only the next line.
base_display = _base_display_2019()
Based on the snippet: <|code_start|> name = fields.Char() code = fields.Char() statement_id = fields.Many2one( 'l10n.de.tax.statement', 'Statement' ) currency_id = fields.Many2one( 'res.currency', related='statement_id.company_id.currency_id', readonly=True, help='Utility field to express amount currency' ) base = fields.Monetary() tax = fields.Monetary() format_base = fields.Char(compute='_compute_amount_format') format_tax = fields.Char(compute='_compute_amount_format') is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() <|code_end|> , predict the immediate next line with the help of imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context (classes, functions, sometimes code) from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) . Output only the next line.
tax_display = _tax_display_2019()
Here is a snippet: <|code_start|> is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: base_display = _base_display_2018() tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': <|code_end|> . Write the next line using the current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context from other files: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) , which may include functions, classes, or code. Output only the next line.
group_display = _group_display_2019()
Given snippet: <|code_start|> is_group = fields.Boolean(compute='_compute_is_group') is_total = fields.Boolean(compute='_compute_is_group') is_readonly = fields.Boolean(compute='_compute_is_readonly') state = fields.Selection(related='statement_id.state') @api.multi @api.depends('base', 'tax', 'code') def _compute_amount_format(self): for line in self: if line.statement_id.version == '2019': base_display = _base_display_2019() tax_display = _tax_display_2019() else: base_display = _base_display_2018() tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': group_display = _group_display_2019() <|code_end|> , continue by predicting the next line. Consider current file imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) which might include code, classes, or functions. Output only the next line.
total_display = _total_display_2019()
Using the snippet: <|code_start|> else: base_display = _base_display_2018() tax_display = _tax_display_2018() base = formatLang(self.env, line.base, monetary=True) tax = formatLang(self.env, line.tax, monetary=True) if line.code in base_display: line.format_base = base if line.code in tax_display: line.format_tax = tax @api.multi @api.depends('code') def _compute_is_group(self): for line in self: if line.statement_id.version == '2019': group_display = _group_display_2019() total_display = _total_display_2019() else: group_display = _group_display_2018() total_display = _total_display_2018() line.is_group = line.code in group_display line.is_total = line.code in total_display @api.multi @api.depends('code') def _compute_is_readonly(self): for line in self: if line.statement_id.version == '2019': <|code_end|> , determine the next line of code. You have imports: from odoo import _, api, fields, models from odoo.osv import expression from odoo.exceptions import UserError from odoo.tools.misc import formatLang from .l10n_de_tax_statement_2018 import \ _base_display_2018, _tax_display_2018, \ _group_display_2018, _total_display_2018, _editable_display_2018 from .l10n_de_tax_statement_2019 import \ _base_display_2019, _tax_display_2019, \ _group_display_2019, _total_display_2019, _editable_display_2019 and context (class names, function names, or code) available: # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2018.py # def _base_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # ) # # def _tax_display_2018(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', '52', '53', '55', # '56', '57', '58', '59', # '60', '61', '62', '64', '65', '66', '67', # ) # # def _group_display_2018(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '54', '63', # ) # # def _total_display_2018(): # return ( # '53', '62', # ) # # def _editable_display_2018(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '51', '52', # '64', '65', '67', # ) # # Path: l10n_de_tax_statement/models/l10n_de_tax_statement_2019.py # def _base_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '48', # '49', '50', # ) # # def _tax_display_2019(): # return ( # '26', '27', '28', '30', # '33', '34', '35', '36', # '48', '49', '50', '51', # '53', '54', '55', '56', # '57', '58', '59', '60', # '62', '63', '64', '65', # ) # # def _group_display_2019(): # return ( # '17', '18', '19', # '25', '31', '37', # '47', '52', '61', # ) # # def _total_display_2019(): # return ( # '51', '60', # ) # # def _editable_display_2019(): # return ( # '20', '21', '22', '23', '24', # '26', '27', '28', '29', '30', # '32', '33', '34', '35', '36', # '38', '39', '40', '41', '42', # '48', '49', '50', '64', '65', # ) . Output only the next line.
editable_display = _editable_display_2019()
Continue the code snippet: <|code_start|>def send_backups_via_email(): result = setup_simple_command( "send_backups_via_email", "Report information about users and their passwords.", ) if isinstance(result, int): return result else: settings, closer, env, args = result try: request = env['request'] if len(args) == 0: user_iterator = get_all_users(request) else: user_iterator = get_selected_users(request, *args) tx = transaction.begin() public_url_root = settings['public_url_root'] preferences_link = urlparse.urljoin( public_url_root, request.route_path('user_preferences')) backups_link = urlparse.urljoin( public_url_root, request.route_path('backups_index')) for user in user_iterator: if user['email']: <|code_end|> . Use current file imports: import transaction from yithlibraryserver.backups.email import send_passwords from yithlibraryserver.compat import urlparse from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context (classes, functions, or code) from other files: # Path: yithlibraryserver/backups/email.py # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
sent = send_passwords(request, user,
Given snippet: <|code_start|> def get_selected_users(request, *emails): for email in emails: for user in request.db.users.find({ 'email': email, }).sort('date_joined'): yield user def send_backups_via_email(): result = setup_simple_command( "send_backups_via_email", "Report information about users and their passwords.", ) if isinstance(result, int): return result else: settings, closer, env, args = result try: request = env['request'] if len(args) == 0: user_iterator = get_all_users(request) else: user_iterator = get_selected_users(request, *args) tx = transaction.begin() public_url_root = settings['public_url_root'] <|code_end|> , continue by predicting the next line. Consider current file imports: import transaction from yithlibraryserver.backups.email import send_passwords from yithlibraryserver.compat import urlparse from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context: # Path: yithlibraryserver/backups/email.py # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) which might include code, classes, or functions. Output only the next line.
preferences_link = urlparse.urljoin(
Predict the next line after this snippet: <|code_start|> "Report information about users and their passwords.", ) if isinstance(result, int): return result else: settings, closer, env, args = result try: request = env['request'] if len(args) == 0: user_iterator = get_all_users(request) else: user_iterator = get_selected_users(request, *args) tx = transaction.begin() public_url_root = settings['public_url_root'] preferences_link = urlparse.urljoin( public_url_root, request.route_path('user_preferences')) backups_link = urlparse.urljoin( public_url_root, request.route_path('backups_index')) for user in user_iterator: if user['email']: sent = send_passwords(request, user, preferences_link, backups_link) if sent: <|code_end|> using the current file's imports: import transaction from yithlibraryserver.backups.email import send_passwords from yithlibraryserver.compat import urlparse from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and any relevant context from other files: # Path: yithlibraryserver/backups/email.py # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
safe_print('Passwords sent to %s' %
Here is a snippet: <|code_start|> def get_all_users(request): day = request.date_service.today().day return request.db.users.find({ 'send_passwords_periodically': True, 'email_verified': True, '$where': ''' function () { var i, sum; sum = 0; for (i = 0; i < this._id.str.length; i += 1) { sum += this._id.str.charCodeAt(i); } return sum %% 28 === %d; } ''' % day }).sort('date_joined') def get_selected_users(request, *emails): for email in emails: for user in request.db.users.find({ 'email': email, }).sort('date_joined'): yield user def send_backups_via_email(): <|code_end|> . Write the next line using the current file imports: import transaction from yithlibraryserver.backups.email import send_passwords from yithlibraryserver.compat import urlparse from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/backups/email.py # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) , which may include functions, classes, or code. Output only the next line.
result = setup_simple_command(
Using the snippet: <|code_start|> ) if isinstance(result, int): return result else: settings, closer, env, args = result try: request = env['request'] if len(args) == 0: user_iterator = get_all_users(request) else: user_iterator = get_selected_users(request, *args) tx = transaction.begin() public_url_root = settings['public_url_root'] preferences_link = urlparse.urljoin( public_url_root, request.route_path('user_preferences')) backups_link = urlparse.urljoin( public_url_root, request.route_path('backups_index')) for user in user_iterator: if user['email']: sent = send_passwords(request, user, preferences_link, backups_link) if sent: safe_print('Passwords sent to %s' % <|code_end|> , determine the next line of code. You have imports: import transaction from yithlibraryserver.backups.email import send_passwords from yithlibraryserver.compat import urlparse from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context (class names, function names, or code) available: # Path: yithlibraryserver/backups/email.py # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
get_user_display_name(user))
Given the following code snippet before the placeholder: <|code_start|> }, multi=True, safe=True) # copy authorized_apps from user2 to user1 updates = { '$addToSet': { 'authorized_apps': { '$each': user2['authorized_apps'], }, }, } # copy the providers for provider in get_available_providers(): key = provider + '_id' if key in user2 and key not in user1: sets = updates.setdefault('$set', {}) sets[key] = user2[key] db.users.update({'_id': user1['_id']}, updates, safe=True) # remove user2 db.users.remove(user2['_id']) def notify_admins_of_account_removal(request, user, reason): context = { 'reason': reason or 'no reason was given', 'user': user, 'home_link': request.route_url('home'), } <|code_end|> , predict the next line using imports from the current file: import bson from yithlibraryserver.email import send_email_to_admins and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/email.py # def send_email_to_admins(request, template, context, subject, # attachments=None, extra_headers=None): # admin_emails = request.registry.settings['admin_emails'] # if admin_emails: # return send_email(request, template, context, subject, admin_emails, # attachments, extra_headers) . Output only the next line.
return send_email_to_admins(
Based on the snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthorizationTests(testing.TestCase): clean_collections = ('authorization_codes', 'access_codes', 'users') def test_authorization_codes(self): <|code_end|> , predict the immediate next line with the help of imports: from yithlibraryserver import testing from yithlibraryserver.oauth2.authorization import AuthorizationCodes from yithlibraryserver.oauth2.authorization import AccessCodes from yithlibraryserver.oauth2.authorization import Authorizator and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/authorization.py # class AuthorizationCodes(Codes): # # collection_name = 'authorization_codes' # # def get_redirect_url(self, code, uri, state=None): # parameters = ['code=%s' % code] # if state: # parameters.append('state=%s' % state) # return '%s?%s' % (uri, '&'.join(parameters)) # # def create(self, user_id, client_id, scope): # return super(AuthorizationCodes, self).create(user_id, # scope=scope, # client_id=client_id) # # Path: yithlibraryserver/oauth2/authorization.py # class AccessCodes(Codes): # # collection_name = 'access_codes' # # def create(self, user_id, grant): # return super(AccessCodes, self).create(user_id, # scope=grant['scope'], # client_id=grant['client_id']) # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) . Output only the next line.
codes = AuthorizationCodes(self.db)