Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
@pytest.mark.django_db
class TestRegistrationBulkUploadJob:
@pytest.fixture()
def payload_hash(self):
return str(uuid.uuid4()).replace('-', '')
@pytest.fixture()
<|code_end|>
using the current file's imports:
import uuid
import pytest
from django.db.utils import IntegrityError
from osf.models import RegistrationBulkUploadJob
from osf.models.registration_bulk_upload_job import JobState
from osf_tests.factories import UserFactory, RegistrationProviderFactory, get_default_metaschema
and any relevant context from other files:
# Path: osf/models/registration_bulk_upload_job.py
# class JobState(IntEnum):
# """Defines the six states of registration bulk upload jobs.
# """
#
# PENDING = 0 # Database preparation is in progress
# INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up
# PICKED_UP = 2 # Registration creation is in progress
# DONE_FULL = 3 # All (draft) registrations have been successfully created
# DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process
# DONE_ERROR = 5 # All (draft) registrations have failed
#
# Path: osf_tests/factories.py
# class UserFactory(DjangoModelFactory):
# # TODO: Change this to only generate long names and see what breaks
# fullname = factory.Sequence(lambda n: 'Freddie Mercury{0}'.format(n))
#
# username = factory.LazyFunction(fake_email)
# password = factory.PostGenerationMethodCall('set_password',
# 'queenfan86')
# is_registered = True
# date_confirmed = factory.Faker('date_time_this_decade', tzinfo=pytz.utc)
# merged_by = None
# verification_key = None
#
# class Meta:
# model = models.OSFUser
#
# @classmethod
# def _build(cls, target_class, *args, **kwargs):
# emails = kwargs.pop('emails', [])
# instance = super(DjangoModelFactory, cls)._build(target_class, *args, **kwargs)
# if emails:
# # Save for M2M population
# instance.set_unusable_password()
# instance.save()
# for email in emails:
# instance.emails.create(address=email)
# return instance
#
# @classmethod
# def _create(cls, target_class, *args, **kwargs):
# emails = kwargs.pop('emails', [])
# instance = super(DjangoModelFactory, cls)._create(target_class, *args, **kwargs)
# if emails and not instance.pk:
# # Save for M2M population
# instance.set_unusable_password()
# instance.save()
# for email in emails:
# instance.emails.create(address=email)
# return instance
#
# @factory.post_generation
# def set_names(self, create, extracted):
# parsed = impute_names_model(self.fullname)
# for key, value in parsed.items():
# setattr(self, key, value)
#
# @factory.post_generation
# def set_emails(self, create, extracted):
# if not self.emails.filter(address=self.username).exists():
# if not self.id:
# if create:
# # Perform implicit save to populate M2M
# self.save(clean=False)
# else:
# # This might lead to strange behavior
# return
# self.emails.create(address=str(self.username).lower())
#
# class RegistrationProviderFactory(DjangoModelFactory):
# name = factory.Faker('company')
# description = factory.Faker('bs')
# external_url = factory.Faker('url')
# access_token = factory.Faker('bs')
# share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n))
#
# class Meta:
# model = models.RegistrationProvider
#
# @classmethod
# def _create(cls, *args, **kwargs):
# user = kwargs.pop('creator', None)
# _id = kwargs.pop('_id', None)
# try:
# obj = cls._build(*args, **kwargs)
# except IntegrityError as e:
# # This is to ensure legacy tests don't fail when their _ids aren't unique
# if _id == models.RegistrationProvider.default__id:
# pass
# else:
# raise e
# if _id and _id != 'osf':
# obj._id = _id
#
# obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection
# obj.save()
# return obj
#
# def get_default_metaschema():
# """This needs to be a method so it gets called after the test database is set up"""
# return models.RegistrationSchema.objects.first()
. Output only the next line. | def initiator(self): |
Given the following code snippet before the placeholder: <|code_start|> save=True,
category='spam',
date=date - timedelta(seconds=4)
)
self.comment_3.report_abuse(
user=self.user_2,
save=True,
category='spam',
date=date - timedelta(seconds=3)
)
self.comment_4.report_abuse(
user=self.user_2,
save=True,
category='spam',
date=date - timedelta(seconds=2)
)
self.comment_5.report_abuse(
user=self.user_1,
save=True,
category='spam',
date=date - timedelta(seconds=1)
)
self.comment_6.report_abuse(user=self.user_1, save=True,
category='spam')
self.request = RequestFactory().get('/fake_path')
self.view = CommentList()
self.view = setup_view(self.view, self.request, user_id=self.user_1._id)
def test_get_spam(self):
res = list(self.view.get_queryset())
<|code_end|>
, predict the next line using imports from the current file:
from django.test import RequestFactory
from django.utils import timezone
from nose import tools as nt
from datetime import timedelta
from osf.models import Comment
from tests.base import AdminTestCase
from osf_tests.factories import AuthUserFactory, ProjectFactory
from osf_tests.factories import CommentFactory
from admin_tests.utilities import setup_view
from admin.comments.views import (
CommentList,
UserCommentList,
)
and context including class names, function names, and sometimes code from other files:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class ProjectFactory(BaseNodeFactory):
# category = 'project'
#
# Path: osf_tests/factories.py
# class CommentFactory(DjangoModelFactory):
# class Meta:
# model = models.Comment
#
# content = factory.Sequence(lambda n: 'Comment {0}'.format(n))
#
# @classmethod
# def _build(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# return instance
#
# @classmethod
# def _create(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# instance.save()
# return instance
. Output only the next line. | nt.assert_equal(len(res), 6) |
Given the following code snippet before the placeholder: <|code_start|> def setUp(self):
super(TestUserCommentListView, self).setUp()
self.project = ProjectFactory(is_public=True)
self.user_1 = AuthUserFactory()
self.user_2 = AuthUserFactory()
self.project.add_contributor(self.user_1)
self.project.add_contributor(self.user_2)
self.project.save()
self.user_1.save()
self.user_2.save()
self.comment_1 = CommentFactory(node=self.project, user=self.user_1)
self.comment_2 = CommentFactory(node=self.project, user=self.user_1)
self.comment_3 = CommentFactory(node=self.project, user=self.user_1)
self.comment_4 = CommentFactory(node=self.project, user=self.user_1)
self.comment_5 = CommentFactory(node=self.project, user=self.user_2)
self.comment_6 = CommentFactory(node=self.project, user=self.user_2)
self.comment_1.report_abuse(user=self.user_2, save=True,
category='spam')
self.comment_2.report_abuse(user=self.user_2, save=True,
category='spam')
self.comment_3.report_abuse(user=self.user_2, save=True,
category='spam')
self.comment_4.report_abuse(user=self.user_2, save=True,
category='spam')
self.comment_5.report_abuse(user=self.user_1, save=True,
category='spam')
self.comment_6.report_abuse(user=self.user_1, save=True,
category='spam')
self.request = RequestFactory().get('/fake_path')
self.view = UserCommentList()
<|code_end|>
, predict the next line using imports from the current file:
from django.test import RequestFactory
from django.utils import timezone
from nose import tools as nt
from datetime import timedelta
from osf.models import Comment
from tests.base import AdminTestCase
from osf_tests.factories import AuthUserFactory, ProjectFactory
from osf_tests.factories import CommentFactory
from admin_tests.utilities import setup_view
from admin.comments.views import (
CommentList,
UserCommentList,
)
and context including class names, function names, and sometimes code from other files:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class ProjectFactory(BaseNodeFactory):
# category = 'project'
#
# Path: osf_tests/factories.py
# class CommentFactory(DjangoModelFactory):
# class Meta:
# model = models.Comment
#
# content = factory.Sequence(lambda n: 'Comment {0}'.format(n))
#
# @classmethod
# def _build(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# return instance
#
# @classmethod
# def _create(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# instance.save()
# return instance
. Output only the next line. | self.view = setup_view(self.view, self.request, user_guid=self.user_1._id) |
Given snippet: <|code_start|> date=date - timedelta(seconds=4)
)
self.comment_3.report_abuse(
user=self.user_2,
save=True,
category='spam',
date=date - timedelta(seconds=3)
)
self.comment_4.report_abuse(
user=self.user_2,
save=True,
category='spam',
date=date - timedelta(seconds=2)
)
self.comment_5.report_abuse(
user=self.user_1,
save=True,
category='spam',
date=date - timedelta(seconds=1)
)
self.comment_6.report_abuse(user=self.user_1, save=True,
category='spam')
self.request = RequestFactory().get('/fake_path')
self.view = CommentList()
self.view = setup_view(self.view, self.request, user_id=self.user_1._id)
def test_get_spam(self):
res = list(self.view.get_queryset())
nt.assert_equal(len(res), 6)
response_list = [r._id for r in res]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import RequestFactory
from django.utils import timezone
from nose import tools as nt
from datetime import timedelta
from osf.models import Comment
from tests.base import AdminTestCase
from osf_tests.factories import AuthUserFactory, ProjectFactory
from osf_tests.factories import CommentFactory
from admin_tests.utilities import setup_view
from admin.comments.views import (
CommentList,
UserCommentList,
)
and context:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class ProjectFactory(BaseNodeFactory):
# category = 'project'
#
# Path: osf_tests/factories.py
# class CommentFactory(DjangoModelFactory):
# class Meta:
# model = models.Comment
#
# content = factory.Sequence(lambda n: 'Comment {0}'.format(n))
#
# @classmethod
# def _build(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# return instance
#
# @classmethod
# def _create(cls, target_class, *args, **kwargs):
# node = kwargs.pop('node', None) or NodeFactory()
# user = kwargs.pop('user', None) or node.creator
# target = kwargs.pop('target', None) or models.Guid.load(node._id)
# content = kwargs.pop('content', None) or 'Test comment.'
# instance = target_class(
# node=node,
# user=user,
# target=target,
# content=content,
# *args, **kwargs
# )
# if isinstance(target.referent, target_class):
# instance.root_target = target.referent.root_target
# else:
# instance.root_target = target
# instance.save()
# return instance
which might include code, classes, or functions. Output only the next line. | should_be = [ |
Given snippet: <|code_start|> def test_exceeds_size_limit(self, app, user, url_allow_bulk_upload, file_content_exceeds_limit):
resp = app.request(
url_allow_bulk_upload,
method='PUT',
expect_errors=True,
body=file_content_exceeds_limit,
headers=_add_auth(user.auth, None),
content_type='text/csv',
)
assert len(resp.json['errors']) == 1
assert resp.json['errors'][0]['type'] == 'sizeExceedsLimit'
assert resp.status_code == 413
def test_wrong_content_type(self, app, user, url_allow_bulk_upload, file_content_legit):
resp = app.request(
url_allow_bulk_upload,
method='PUT',
expect_errors=True,
body=file_content_legit,
headers=_add_auth(user.auth, None),
content_type='text/plain',
)
assert len(resp.json['errors']) == 1
assert resp.json['errors'][0]['type'] == 'invalidFileType'
assert resp.status_code == 413
def test_bulk_upload_job_exists(self, app, user, url_allow_bulk_upload, file_content_legit):
file_hash = hashlib.md5()
file_hash.update(file_content_legit)
RegistrationBulkUploadJobFactory(payload_hash=file_hash.hexdigest())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import mock
import hashlib
from rest_framework.exceptions import NotFound
from osf.registrations.utils import DuplicateHeadersError, FileUploadNotSupportedError, InvalidHeadersError
from api.base.settings import BULK_SETTINGS
from osf_tests.factories import (
AuthUserFactory,
RegistrationProviderFactory,
RegistrationBulkUploadJobFactory,
)
from webtest_plus.app import _add_auth
and context:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class RegistrationProviderFactory(DjangoModelFactory):
# name = factory.Faker('company')
# description = factory.Faker('bs')
# external_url = factory.Faker('url')
# access_token = factory.Faker('bs')
# share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n))
#
# class Meta:
# model = models.RegistrationProvider
#
# @classmethod
# def _create(cls, *args, **kwargs):
# user = kwargs.pop('creator', None)
# _id = kwargs.pop('_id', None)
# try:
# obj = cls._build(*args, **kwargs)
# except IntegrityError as e:
# # This is to ensure legacy tests don't fail when their _ids aren't unique
# if _id == models.RegistrationProvider.default__id:
# pass
# else:
# raise e
# if _id and _id != 'osf':
# obj._id = _id
#
# obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection
# obj.save()
# return obj
#
# class RegistrationBulkUploadJobFactory(DjangoModelFactory):
# class Meta:
# model = models.RegistrationBulkUploadJob
which might include code, classes, or functions. Output only the next line. | resp = app.request( |
Based on the snippet: <|code_start|> def test_unauthorized_user(self, app, unauthorized_user, url_not_allow_bulk_upload, url_allow_bulk_upload):
resp = app.put(url_allow_bulk_upload, auth=unauthorized_user.auth, expect_errors=True)
assert resp.status_code == 403
resp = app.put(url_not_allow_bulk_upload, auth=unauthorized_user.auth, expect_errors=True)
assert resp.status_code == 403
def test_bulk_upload_not_allowed(self, app, user, url_not_allow_bulk_upload):
resp = app.put(url_not_allow_bulk_upload, auth=user.auth, expect_errors=True)
assert len(resp.json['errors']) == 1
assert resp.json['errors'][0]['type'] == 'bulkUploadNotAllowed'
def test_exceeds_size_limit(self, app, user, url_allow_bulk_upload, file_content_exceeds_limit):
resp = app.request(
url_allow_bulk_upload,
method='PUT',
expect_errors=True,
body=file_content_exceeds_limit,
headers=_add_auth(user.auth, None),
content_type='text/csv',
)
assert len(resp.json['errors']) == 1
assert resp.json['errors'][0]['type'] == 'sizeExceedsLimit'
assert resp.status_code == 413
def test_wrong_content_type(self, app, user, url_allow_bulk_upload, file_content_legit):
resp = app.request(
url_allow_bulk_upload,
method='PUT',
expect_errors=True,
body=file_content_legit,
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import mock
import hashlib
from rest_framework.exceptions import NotFound
from osf.registrations.utils import DuplicateHeadersError, FileUploadNotSupportedError, InvalidHeadersError
from api.base.settings import BULK_SETTINGS
from osf_tests.factories import (
AuthUserFactory,
RegistrationProviderFactory,
RegistrationBulkUploadJobFactory,
)
from webtest_plus.app import _add_auth
and context (classes, functions, sometimes code) from other files:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class RegistrationProviderFactory(DjangoModelFactory):
# name = factory.Faker('company')
# description = factory.Faker('bs')
# external_url = factory.Faker('url')
# access_token = factory.Faker('bs')
# share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n))
#
# class Meta:
# model = models.RegistrationProvider
#
# @classmethod
# def _create(cls, *args, **kwargs):
# user = kwargs.pop('creator', None)
# _id = kwargs.pop('_id', None)
# try:
# obj = cls._build(*args, **kwargs)
# except IntegrityError as e:
# # This is to ensure legacy tests don't fail when their _ids aren't unique
# if _id == models.RegistrationProvider.default__id:
# pass
# else:
# raise e
# if _id and _id != 'osf':
# obj._id = _id
#
# obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection
# obj.save()
# return obj
#
# class RegistrationBulkUploadJobFactory(DjangoModelFactory):
# class Meta:
# model = models.RegistrationBulkUploadJob
. Output only the next line. | headers=_add_auth(user.auth, None), |
Continue the code snippet: <|code_start|> provider = RegistrationProviderFactory()
provider.allow_bulk_uploads = True
provider.add_to_group(user, 'admin')
provider.save()
return provider
@pytest.fixture()
def provider_not_allow_bulk(self, user):
provider = RegistrationProviderFactory()
provider.allow_bulk_uploads = False
provider.add_to_group(user, 'admin')
provider.save()
return provider
@pytest.fixture()
def url_allow_bulk_upload(self, provider_allow_bulk):
return f'/_/registries/{provider_allow_bulk._id}/bulk_create/file.csv/'
@pytest.fixture()
def url_not_allow_bulk_upload(self, provider_not_allow_bulk):
return f'/_/registries/{provider_not_allow_bulk._id}/bulk_create/file.csv/'
@pytest.fixture()
def file_content_exceeds_limit(self):
return ('a' * BULK_SETTINGS['DEFAULT_BULK_LIMIT'] * 10001).encode()
@pytest.fixture()
def file_content_legit(self):
return ('a' * BULK_SETTINGS['DEFAULT_BULK_LIMIT'] * 1).encode()
<|code_end|>
. Use current file imports:
import pytest
import mock
import hashlib
from rest_framework.exceptions import NotFound
from osf.registrations.utils import DuplicateHeadersError, FileUploadNotSupportedError, InvalidHeadersError
from api.base.settings import BULK_SETTINGS
from osf_tests.factories import (
AuthUserFactory,
RegistrationProviderFactory,
RegistrationBulkUploadJobFactory,
)
from webtest_plus.app import _add_auth
and context (classes, functions, or code) from other files:
# Path: osf_tests/factories.py
# class AuthUserFactory(UserFactory):
# """A user that automatically has an api key, for quick authentication.
#
# Example: ::
# user = AuthUserFactory()
# res = self.app.get(url, auth=user.auth) # user is "logged in"
# """
#
# @factory.post_generation
# def add_auth(self, create, extracted):
# self.auth = (self.username, 'queenfan86')
#
# class RegistrationProviderFactory(DjangoModelFactory):
# name = factory.Faker('company')
# description = factory.Faker('bs')
# external_url = factory.Faker('url')
# access_token = factory.Faker('bs')
# share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n))
#
# class Meta:
# model = models.RegistrationProvider
#
# @classmethod
# def _create(cls, *args, **kwargs):
# user = kwargs.pop('creator', None)
# _id = kwargs.pop('_id', None)
# try:
# obj = cls._build(*args, **kwargs)
# except IntegrityError as e:
# # This is to ensure legacy tests don't fail when their _ids aren't unique
# if _id == models.RegistrationProvider.default__id:
# pass
# else:
# raise e
# if _id and _id != 'osf':
# obj._id = _id
#
# obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection
# obj.save()
# return obj
#
# class RegistrationBulkUploadJobFactory(DjangoModelFactory):
# class Meta:
# model = models.RegistrationBulkUploadJob
. Output only the next line. | def test_unauthorized_user(self, app, unauthorized_user, url_not_allow_bulk_upload, url_allow_bulk_upload): |
Predict the next line for this snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
return preprint
<|code_end|>
with the help of current file imports:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context from other files:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
, which may contain function names, class names, or code. Output only the next line. | def get_success_url(self): |
Continue the code snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
<|code_end|>
. Use current file imports:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context (classes, functions, or code) from other files:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
. Output only the next line. | return preprint |
Given the code snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
return preprint
def get_success_url(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context (functions, classes, or occasionally code) from other files:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
. Output only the next line. | return reverse_lazy('preprints:preprint', kwargs={'guid': self.kwargs['guid']}) |
Using the snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
<|code_end|>
, determine the next line of code. You have imports:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context (class names, function names, or code) available:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
. Output only the next line. | return preprint |
Continue the code snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
<|code_end|>
. Use current file imports:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context (classes, functions, or code) from other files:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
. Output only the next line. | return preprint |
Given the code snippet: <|code_start|>
class PreprintMixin(PermissionRequiredMixin):
def get_object(self):
preprint = Preprint.objects.get(guids___id=self.kwargs['guid'])
# Django template does not like attributes with underscores for some reason
preprint.guid = preprint._id
return preprint
def get_success_url(self):
return reverse_lazy('preprints:preprint', kwargs={'guid': self.kwargs['guid']})
<|code_end|>
, generate the next line using the imports in this file:
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
from django.views.generic import (
View,
ListView,
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from admin.nodes.views import NodeRemoveContributorView
from admin.preprints.forms import ChangeProviderForm
from api.share.utils import update_share
from osf.exceptions import PreprintStateError
from osf.models import (
SpamStatus,
Preprint,
PreprintLog,
PreprintRequest,
PreprintProvider
)
from osf.models.admin_log_entry import (
update_admin_log,
REINDEX_ELASTIC,
REINDEX_SHARE,
PREPRINT_REMOVED,
PREPRINT_RESTORED,
CONFIRM_SPAM,
CONFIRM_HAM,
APPROVE_WITHDRAWAL,
REJECT_WITHDRAWAL,
UNFLAG_SPAM,
)
from website import search, settings
and context (functions, classes, or occasionally code) from other files:
# Path: admin/nodes/views.py
# class NodeRemoveContributorView(NodeMixin, View):
# """ Allows authorized users to remove contributors from nodes.
# """
# permission_required = ('osf.view_node', 'osf.change_node')
# raise_exception = True
#
# def post(self, request, *args, **kwargs):
# node = self.get_object()
# user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
# if not node._get_admin_contributors_query(node._contributors.all()).exclude(user=user).exists():
# messages.error(self.request, 'Must be at least one admin on this node.')
# return redirect(self.get_success_url())
#
# if node.remove_contributor(user, None, log=False):
# update_admin_log(
# user_id=self.request.user.id,
# object_id=node.pk,
# object_repr='Contributor',
# message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
# action_flag=CONTRIBUTOR_REMOVED
# )
# # Log invisibly on the OSF.
# self.add_contributor_removed_log(node, user)
# return redirect(self.get_success_url())
#
# def add_contributor_removed_log(self, node, user):
# NodeLog(
# action=NodeLog.CONTRIB_REMOVED,
# user=None,
# params={
# 'project': node.parent_id,
# 'node': node.pk,
# 'contributors': user.pk
# },
# date=timezone.now(),
# should_hide=True,
# ).save()
#
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
# AdminLogEntry.objects.log_action(
# user_id=user_id,
# content_type_id=None,
# object_id=object_id,
# object_repr=object_repr,
# change_message=message,
# action_flag=action_flag
# )
#
# REINDEX_ELASTIC = 51
#
# REINDEX_SHARE = 50
#
# PREPRINT_REMOVED = 70
#
# PREPRINT_RESTORED = 71
#
# CONFIRM_SPAM = 20
#
# CONFIRM_HAM = 21
#
# APPROVE_WITHDRAWAL = 60
#
# REJECT_WITHDRAWAL = 61
#
# UNFLAG_SPAM = 22
. Output only the next line. | class PreprintView(PreprintMixin, GuidView): |
Predict the next line for this snippet: <|code_start|>
retraction.to_MODERATOR_REJECTED()
registration.refresh_from_db()
assert registration.moderation_state == RegistrationModerationStates.EMBARGO.db_name
retraction.to_REJECTED()
registration.refresh_from_db()
assert registration.moderation_state == RegistrationModerationStates.EMBARGO.db_name
embargo.to_COMPLETED()
registration.refresh_from_db()
assert registration.moderation_state == RegistrationModerationStates.ACCEPTED.db_name
retraction.to_MODERATOR_REJECTED()
registration.refresh_from_db()
assert registration.moderation_state == RegistrationModerationStates.ACCEPTED.db_name
def test_embargo_termination_states(self, embargo_termination):
registration = embargo_termination.target_registration
assert registration.moderation_state == RegistrationModerationStates.PENDING_EMBARGO_TERMINATION.db_name
embargo_termination.to_REJECTED()
registration.update_moderation_state()
assert registration.moderation_state == RegistrationModerationStates.EMBARGO.db_name
embargo_termination.to_APPROVED()
registration.update_moderation_state()
assert registration.moderation_state == RegistrationModerationStates.ACCEPTED.db_name
def test_retraction_states_over_embargo_termination(self, embargo_termination):
<|code_end|>
with the help of current file imports:
import mock
import pytest
from addons.wiki.models import WikiVersion
from django.core.exceptions import ValidationError
from django.utils import timezone
from framework.auth.core import Auth
from framework.exceptions import PermissionsError
from nose.tools import assert_raises
from osf.models import Node, Registration, Sanction, RegistrationSchema, NodeLog
from addons.wiki.models import WikiPage
from osf.utils.permissions import ADMIN
from osf.registrations.utils import get_registration_provider_submissions_url
from website import settings
from . import factories
from .utils import assert_datetime_equal, mock_archive
from osf_tests.factories import get_default_metaschema, DraftRegistrationFactory
from addons.wiki.tests.factories import WikiFactory, WikiVersionFactory
from api.providers.workflows import Workflows
from osf.migrations import update_provider_auth_groups
from osf.models.action import RegistrationAction
from osf_tests.management_commands.test_migration_registration_responses import (
prereg_registration_responses,
prereg_registration_metadata_built,
veer_registration_responses,
veer_condensed
)
from osf.utils.workflows import (
RegistrationModerationStates,
RegistrationModerationTriggers,
ApprovalStates
)
and context from other files:
# Path: osf_tests/factories.py
# def get_default_metaschema():
# """This needs to be a method so it gets called after the test database is set up"""
# return models.RegistrationSchema.objects.first()
#
# class DraftRegistrationFactory(DjangoModelFactory):
# class Meta:
# model = models.DraftRegistration
#
# @classmethod
# def _create(cls, *args, **kwargs):
# title = kwargs.pop('title', None)
# initiator = kwargs.get('initiator', None)
# description = kwargs.pop('description', None)
# branched_from = kwargs.get('branched_from', None)
# registration_schema = kwargs.get('registration_schema')
# registration_metadata = kwargs.get('registration_metadata')
# provider = kwargs.get('provider')
# branched_from_creator = branched_from.creator if branched_from else None
# initiator = initiator or branched_from_creator or kwargs.get('user', None) or kwargs.get('creator', None) or UserFactory()
# registration_schema = registration_schema or get_default_metaschema()
# registration_metadata = registration_metadata or {}
# provider = provider or models.RegistrationProvider.get_default()
# provider.schemas.add(registration_schema)
# draft = models.DraftRegistration.create_from_node(
# node=branched_from,
# user=initiator,
# schema=registration_schema,
# data=registration_metadata,
# provider=provider,
# )
# if title:
# draft.title = title
# if description:
# draft.description = description
# draft.registration_responses = draft.flatten_registration_metadata()
# draft.save()
# return draft
, which may contain function names, class names, or code. Output only the next line. | registration = embargo_termination.target_registration |
Predict the next line for this snippet: <|code_start|> registration.registration_approval.save()
sub_reg = registration._nodes.first()._nodes.first()
assert sub_reg.is_registration_approved is True
def test_is_retracted(self):
retraction = factories.RetractionFactory(state=Sanction.APPROVED, approve=True)
registration = Registration.objects.get(retraction=retraction)
assert registration.is_retracted
@mock.patch('osf.models.node.AbstractNode.update_search')
def test_is_retracted_searches_parents(self, mock_update_search):
user = factories.UserFactory()
node = factories.ProjectFactory(creator=user)
child = factories.NodeFactory(creator=user, parent=node)
factories.NodeFactory(creator=user, parent=child)
with mock_archive(node, autoapprove=True, retraction=True, autoapprove_retraction=True) as registration:
sub_reg = registration._nodes.first()._nodes.first()
assert sub_reg.is_retracted is True
def test_is_pending_retraction(self):
retraction = factories.RetractionFactory()
registration = Registration.objects.get(retraction=retraction)
assert retraction.is_pending_approval is True
assert registration.is_pending_retraction is True
@mock.patch('osf.models.node.AbstractNode.update_search')
def test_is_pending_retraction_searches_parents(self, mock_update_search):
user = factories.UserFactory()
node = factories.ProjectFactory(creator=user)
child = factories.NodeFactory(creator=user, parent=node)
<|code_end|>
with the help of current file imports:
import mock
import pytest
from addons.wiki.models import WikiVersion
from django.core.exceptions import ValidationError
from django.utils import timezone
from framework.auth.core import Auth
from framework.exceptions import PermissionsError
from nose.tools import assert_raises
from osf.models import Node, Registration, Sanction, RegistrationSchema, NodeLog
from addons.wiki.models import WikiPage
from osf.utils.permissions import ADMIN
from osf.registrations.utils import get_registration_provider_submissions_url
from website import settings
from . import factories
from .utils import assert_datetime_equal, mock_archive
from osf_tests.factories import get_default_metaschema, DraftRegistrationFactory
from addons.wiki.tests.factories import WikiFactory, WikiVersionFactory
from api.providers.workflows import Workflows
from osf.migrations import update_provider_auth_groups
from osf.models.action import RegistrationAction
from osf_tests.management_commands.test_migration_registration_responses import (
prereg_registration_responses,
prereg_registration_metadata_built,
veer_registration_responses,
veer_condensed
)
from osf.utils.workflows import (
RegistrationModerationStates,
RegistrationModerationTriggers,
ApprovalStates
)
and context from other files:
# Path: osf_tests/factories.py
# def get_default_metaschema():
# """This needs to be a method so it gets called after the test database is set up"""
# return models.RegistrationSchema.objects.first()
#
# class DraftRegistrationFactory(DjangoModelFactory):
# class Meta:
# model = models.DraftRegistration
#
# @classmethod
# def _create(cls, *args, **kwargs):
# title = kwargs.pop('title', None)
# initiator = kwargs.get('initiator', None)
# description = kwargs.pop('description', None)
# branched_from = kwargs.get('branched_from', None)
# registration_schema = kwargs.get('registration_schema')
# registration_metadata = kwargs.get('registration_metadata')
# provider = kwargs.get('provider')
# branched_from_creator = branched_from.creator if branched_from else None
# initiator = initiator or branched_from_creator or kwargs.get('user', None) or kwargs.get('creator', None) or UserFactory()
# registration_schema = registration_schema or get_default_metaschema()
# registration_metadata = registration_metadata or {}
# provider = provider or models.RegistrationProvider.get_default()
# provider.schemas.add(registration_schema)
# draft = models.DraftRegistration.create_from_node(
# node=branched_from,
# user=initiator,
# schema=registration_schema,
# data=registration_metadata,
# provider=provider,
# )
# if title:
# draft.title = title
# if description:
# draft.description = description
# draft.registration_responses = draft.flatten_registration_metadata()
# draft.save()
# return draft
, which may contain function names, class names, or code. Output only the next line. | factories.NodeFactory(creator=user, parent=child) |
Given snippet: <|code_start|> context = {}
context['login_url'] = web_url_for('dashboard', _absolute=True)
return context
@collect_auth
def redirect_unsupported_institution(auth):
"""
Sends user back to the "Unsupported Institution" page on CAS. Logs user out if they are
already logged in.
HTTP Method: GET
:param auth: the authentication context
:return
"""
cas_unsupp_inst_url = cas.get_login_url('', campaign='unsupportedinstitution')
# if users are logged in, log them out and redirect back to this page
if auth.logged_in:
return auth_logout(redirect_url=cas_unsupp_inst_url)
return redirect(cas_unsupp_inst_url)
def forgot_password_post():
"""Dispatches to ``_forgot_password_post`` passing non-institutional user mail template
and reset action."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import furl
import markupsafe
from rest_framework import status as http_status
from future.moves.urllib.parse import urlencode
from django.core.exceptions import ValidationError
from django.utils import timezone
from flask import request
from addons.osfstorage.models import Region
from framework import forms, sentry, status
from framework import auth as framework_auth
from framework.auth import exceptions
from framework.auth import cas, campaigns
from framework.auth import logout as osf_logout
from framework.auth import get_user
from framework.auth.exceptions import DuplicateEmailError, ExpiredTokenError, InvalidTokenError
from framework.auth.core import generate_verification_key
from framework.auth.decorators import block_bing_preview, collect_auth, must_be_logged_in
from framework.auth.forms import ResendConfirmationForm, ForgotPasswordForm, ResetPasswordForm
from framework.auth.utils import ensure_external_identity_uniqueness, validate_recaptcha
from framework.exceptions import HTTPError
from framework.flask import redirect # VOL-aware redirect
from framework.sessions.utils import remove_sessions_for_user, remove_session
from framework.sessions import get_session
from framework.utils import throttle_period_expired
from osf.models import OSFUser
from osf.utils.sanitize import strip_html
from website import settings, mails, language
from website.ember_osf_web.decorators import ember_flag_is_active
from api.waffle.utils import storage_i18n_flag_active
from website.util import web_url_for
from osf.exceptions import ValidationValueError, BlockedEmailError
from osf.models.provider import PreprintProvider
from osf.models.tag import Tag
from osf.utils.requests import check_select_for_update
from osf import features
from website.util.metrics import CampaignClaimedTags, CampaignSourceTags
and context:
# Path: osf/models/provider.py
# class PreprintProvider(AbstractProvider):
#
# def __init__(self, *args, **kwargs):
# self._meta.get_field('share_publish_type').default = 'Preprint'
# super().__init__(*args, **kwargs)
#
# PUSH_SHARE_TYPE_HELP = 'This SHARE type will be used when pushing publications to SHARE'
#
# REVIEWABLE_RELATION_NAME = 'preprints'
#
# additional_providers = fields.ArrayField(models.CharField(max_length=200), default=list, blank=True)
# in_sloan_study = models.NullBooleanField(default=True)
#
# PREPRINT_WORD_CHOICES = (
# ('preprint', 'Preprint'),
# ('paper', 'Paper'),
# ('thesis', 'Thesis'),
# ('work', 'Work'),
# ('none', 'None')
# )
# preprint_word = models.CharField(max_length=10, choices=PREPRINT_WORD_CHOICES, default='preprint')
# subjects_acceptable = DateTimeAwareJSONField(blank=True, default=list)
#
# class Meta:
# permissions = (
# # custom permissions for use in the OSF Admin App
# ('view_preprintprovider', 'Can view preprint provider details'),
# )
#
# @property
# def readable_type(self):
# return 'preprint'
#
# @property
# def all_subjects(self):
# if self.subjects.exists():
# return self.subjects.all()
# else:
# # TODO: Delet this when all PreprintProviders have a mapping
# return rules_to_subjects(self.subjects_acceptable)
#
# @property
# def has_highlighted_subjects(self):
# return self.subjects.filter(highlighted=True).exists()
#
# @property
# def highlighted_subjects(self):
# if self.has_highlighted_subjects:
# return self.subjects.filter(highlighted=True).order_by('text')[:10]
# else:
# return sorted(self.top_level_subjects, key=lambda s: s.text)[:10]
#
# @property
# def top_level_subjects(self):
# if self.subjects.exists():
# return optimize_subject_query(self.subjects.filter(parent__isnull=True))
# else:
# # TODO: Delet this when all PreprintProviders have a mapping
# if len(self.subjects_acceptable) == 0:
# return optimize_subject_query(Subject.objects.filter(parent__isnull=True, provider___id='osf'))
# tops = set([sub[0][0] for sub in self.subjects_acceptable])
# return [Subject.load(sub) for sub in tops]
#
# @property
# def landing_url(self):
# return self.domain if self.domain else '{}preprints/{}'.format(settings.DOMAIN, self._id)
#
# def get_absolute_url(self):
# return '{}preprint_providers/{}'.format(self.absolute_api_v2_url, self._id)
#
# @property
# def absolute_api_v2_url(self):
# path = '/providers/preprints/{}/'.format(self._id)
# return api_v2_url(path)
which might include code, classes, or functions. Output only the next line. | return _forgot_password_post(mail_template=mails.FORGOT_PASSWORD, |
Given snippet: <|code_start|> if not dry_run:
row.save()
try:
handle_registration_row(row, initiator, provider, schema, auto_approval=auto_approval, dry_run=dry_run)
successful_row_count += 1
except RegistrationBulkCreationRowError as e:
logger.error(e.long_message)
logger.error(e.error)
sentry.log_exception()
if auto_approval and e.approval_failure:
approval_error_list.append(e.short_message)
else:
draft_error_list.append(e.short_message)
if not dry_run:
if row.draft_registration:
row.draft_registration.delete()
elif e.draft_id:
DraftRegistration.objects.get(id=e.draft_id).delete()
row.delete()
else:
row.delete()
except Exception as e:
error = f'Bulk upload registration creation encountered ' \
f'an unexpected exception: [row="{row.id}", error="{repr(e)}"]'
logger.error(error)
sentry.log_message(error)
sentry.log_exception()
draft_error_list.append(f'Title: N/A, External ID: N/A, Row Hash: {row.row_hash}, Error: Unexpected')
if not dry_run:
if row.draft_registration:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from django.utils import timezone
from framework import sentry
from framework.auth import Auth
from framework.celery_tasks import app as celery_app
from osf.exceptions import (
NodeStateError,
RegistrationBulkCreationContributorError,
RegistrationBulkCreationRowError,
UserNotAffiliatedError,
UserStateError,
ValidationValueError,
)
from osf.models import (
AbstractNode,
Contributor,
DraftRegistration,
Institution,
OSFUser,
RegistrationBulkUploadJob,
RegistrationBulkUploadRow,
RegistrationProvider,
RegistrationSchema,
Subject,
)
from osf.models.licenses import NodeLicense
from osf.models.registration_bulk_upload_job import JobState
from osf.models.registration_bulk_upload_row import RegistrationBulkUploadContributors
from osf.registrations.utils import get_registration_provider_submissions_url
from osf.utils.permissions import ADMIN
from website import mails, settings
and context:
# Path: osf/models/registration_bulk_upload_job.py
# class JobState(IntEnum):
# """Defines the six states of registration bulk upload jobs.
# """
#
# PENDING = 0 # Database preparation is in progress
# INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up
# PICKED_UP = 2 # Registration creation is in progress
# DONE_FULL = 3 # All (draft) registrations have been successfully created
# DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process
# DONE_ERROR = 5 # All (draft) registrations have failed
#
# Path: osf/models/registration_bulk_upload_row.py
# class RegistrationBulkUploadContributors:
# """A helper class of which an instance contains parsed data about contributors per registration row.
# """
#
# def __init__(self, admin_set, read_only_set, read_write_set, author_set, contributor_list):
# self.contributor_list = contributor_list
# self.admin_set = admin_set
# self.read_write_set = read_write_set
# self.read_only_set = read_only_set
# self.author_set = author_set
#
# def is_bibliographic(self, email):
# return email in self.author_set
#
# def get_permission(self, email):
# if email in self.admin_set:
# return ADMIN
# elif email in self.read_write_set:
# return WRITE
# elif email in self.read_only_set:
# return READ
# else:
# raise RegistrationBulkCreationContributorError(error=f'{email} does not have a permission')
which might include code, classes, or functions. Output only the next line. | row.draft_registration.delete() |
Given the code snippet: <|code_start|> if dry_run:
logger.info('Dry run: complete. Bulk creation started in dry-run mode and the job state was not updated')
logger.info(f'Done. [{number_of_jobs}] jobs have been picked up and kicked off.')
@celery_app.task()
def bulk_create_registrations(upload_id, dry_run=True):
try:
upload = RegistrationBulkUploadJob.objects.get(id=upload_id)
except RegistrationBulkUploadJob.DoesNotExist:
# This error should not happen since this task is only called by `monitor_registration_bulk_upload_jobs`
sentry.log_exception()
message = f'Registration bulk upload job not found: [id={upload_id}]'
return handle_internal_error(initiator=None, provider=None, message=message, dry_run=dry_run)
# Retrieve bulk upload job
provider = upload.provider
auto_approval = upload.provider.bulk_upload_auto_approval
schema = upload.schema
initiator = upload.initiator
logger.info(
f'Bulk creating draft registrations: [provider={provider._id}, '
f'schema={schema._id}, initiator={initiator._id}, auto_approval={auto_approval}]',
)
# Check registration rows and pick up them one by one to create draft registrations
registration_rows = RegistrationBulkUploadRow.objects.filter(
upload__id=upload_id,
is_picked_up=False,
<|code_end|>
, generate the next line using the imports in this file:
import logging
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from django.utils import timezone
from framework import sentry
from framework.auth import Auth
from framework.celery_tasks import app as celery_app
from osf.exceptions import (
NodeStateError,
RegistrationBulkCreationContributorError,
RegistrationBulkCreationRowError,
UserNotAffiliatedError,
UserStateError,
ValidationValueError,
)
from osf.models import (
AbstractNode,
Contributor,
DraftRegistration,
Institution,
OSFUser,
RegistrationBulkUploadJob,
RegistrationBulkUploadRow,
RegistrationProvider,
RegistrationSchema,
Subject,
)
from osf.models.licenses import NodeLicense
from osf.models.registration_bulk_upload_job import JobState
from osf.models.registration_bulk_upload_row import RegistrationBulkUploadContributors
from osf.registrations.utils import get_registration_provider_submissions_url
from osf.utils.permissions import ADMIN
from website import mails, settings
and context (functions, classes, or occasionally code) from other files:
# Path: osf/models/registration_bulk_upload_job.py
# class JobState(IntEnum):
# """Defines the six states of registration bulk upload jobs.
# """
#
# PENDING = 0 # Database preparation is in progress
# INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up
# PICKED_UP = 2 # Registration creation is in progress
# DONE_FULL = 3 # All (draft) registrations have been successfully created
# DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process
# DONE_ERROR = 5 # All (draft) registrations have failed
#
# Path: osf/models/registration_bulk_upload_row.py
# class RegistrationBulkUploadContributors:
# """A helper class of which an instance contains parsed data about contributors per registration row.
# """
#
# def __init__(self, admin_set, read_only_set, read_write_set, author_set, contributor_list):
# self.contributor_list = contributor_list
# self.admin_set = admin_set
# self.read_write_set = read_write_set
# self.read_only_set = read_only_set
# self.author_set = author_set
#
# def is_bibliographic(self, email):
# return email in self.author_set
#
# def get_permission(self, email):
# if email in self.admin_set:
# return ADMIN
# elif email in self.read_write_set:
# return WRITE
# elif email in self.read_only_set:
# return READ
# else:
# raise RegistrationBulkCreationContributorError(error=f'{email} does not have a permission')
. Output only the next line. | is_completed=False, |
Next line prediction: <|code_start|># SPDX-License-Identifier: MIT
from __future__ import absolute_import, division, print_function
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
<|code_end|>
. Use current file imports:
(import functools
from ._compat import new_class
from ._make import _make_ne)
and context including class names, function names, or small code snippets from other files:
# Path: src/attr/_compat.py
# def new_class(name, bases, kwds, exec_body):
# """
# A minimal stub of types.new_class that we need for make_class.
# """
# ns = {}
# exec_body(ns)
#
# return type(name, bases, ns)
#
# Path: src/attr/_make.py
# def _make_ne():
# """
# Create __ne__ method.
# """
#
# def __ne__(self, other):
# """
# Check equality and either forward a NotImplemented or
# return the result negated.
# """
# result = self.__eq__(other)
# if result is NotImplemented:
# return NotImplemented
#
# return not result
#
# return __ne__
. Output only the next line. | require_same_type=True, |
Based on the snippet: <|code_start|># SPDX-License-Identifier: MIT
from __future__ import absolute_import, division, print_function
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
from ._compat import new_class
from ._make import _make_ne
and context (classes, functions, sometimes code) from other files:
# Path: src/attr/_compat.py
# def new_class(name, bases, kwds, exec_body):
# """
# A minimal stub of types.new_class that we need for make_class.
# """
# ns = {}
# exec_body(ns)
#
# return type(name, bases, ns)
#
# Path: src/attr/_make.py
# def _make_ne():
# """
# Create __ne__ method.
# """
#
# def __ne__(self, other):
# """
# Check equality and either forward a NotImplemented or
# return the result negated.
# """
# result = self.__eq__(other)
# if result is NotImplemented:
# return NotImplemented
#
# return not result
#
# return __ne__
. Output only the next line. | le=None, |
Here is a snippet: <|code_start|># -*-encoding:utf-8-*-
class Test(object):
pass
handlers = {
"/test": Test,
"/path/{test}": Test
}
def test():
router = Router(handles=handlers, url="/test")
handler = router.get_handler()
if Test != handler[0] and (not isinstance(handler[1], PathParam)):
print(Test)
print(handler)
<|code_end|>
. Write the next line using the current file imports:
from karlooper.router.router import Router, PathParam
and context from other files:
# Path: karlooper/router/router.py
# class Router(object):
# def __init__(self, handles, url):
# self.__handlers = handles
# self.__url = url
# self.__is_static_enable = get_cli_data().get("static")
# self.__is_debug = get_cli_data().get("debug")
#
# def get_handler(self):
# """
# I will add url regex parse in the future
# :return: return a handler object
# """
# path_param = PathParam()
# handler = self.__handlers.get(self.__url, None)
# if handler is None:
# url_list = self.__handlers.keys()
# for url in url_list:
# path_param = self.get_path_param(url)
# if path_param.status:
# handler = self.__handlers.get(url, None)
# return handler, path_param
# if handler is None \
# and self.__is_debug \
# and self.__is_static_enable \
# and (str(self.__is_debug).lower() == "true") \
# and (not handler) \
# and ("/static/" in self.__url):
# handler = StaticHandler
# return handler, path_param
#
# def get_path_param(self, path):
# """ parse param in url
#
# :param path: url rule
# :return: a PathParam object
#
# """
#
# path_attr_list = path.split("/")
# url_attr_list = self.__url.split("/")
# path_param = PathParam()
# if len(path_attr_list) != len(url_attr_list):
# path_param.status = False
# return path_param
# for index in xrange(len(path_attr_list)):
# path_attr = path_attr_list[index]
# url_attr = url_attr_list[index]
# if ("{" not in path_attr or "}" not in path_attr) and path_attr != url_attr:
# path_param.status = False
# return path_param
# if "{" in path_attr and "}" in path_attr:
# path_value_key = path_attr.replace("{", "").replace("}", "")
# path_param.status = True
# path_param.value[path_value_key] = url_attr
# return path_param
#
# class PathParam(object):
# status = False
# value = {}
, which may include functions, classes, or code. Output only the next line. | assert "Router get handler error" |
Based on the snippet: <|code_start|># -*-encoding:utf-8-*-
class Test(object):
pass
handlers = {
"/test": Test,
"/path/{test}": Test
}
def test():
router = Router(handles=handlers, url="/test")
handler = router.get_handler()
if Test != handler[0] and (not isinstance(handler[1], PathParam)):
print(Test)
<|code_end|>
, predict the immediate next line with the help of imports:
from karlooper.router.router import Router, PathParam
and context (classes, functions, sometimes code) from other files:
# Path: karlooper/router/router.py
# class Router(object):
# def __init__(self, handles, url):
# self.__handlers = handles
# self.__url = url
# self.__is_static_enable = get_cli_data().get("static")
# self.__is_debug = get_cli_data().get("debug")
#
# def get_handler(self):
# """
# I will add url regex parse in the future
# :return: return a handler object
# """
# path_param = PathParam()
# handler = self.__handlers.get(self.__url, None)
# if handler is None:
# url_list = self.__handlers.keys()
# for url in url_list:
# path_param = self.get_path_param(url)
# if path_param.status:
# handler = self.__handlers.get(url, None)
# return handler, path_param
# if handler is None \
# and self.__is_debug \
# and self.__is_static_enable \
# and (str(self.__is_debug).lower() == "true") \
# and (not handler) \
# and ("/static/" in self.__url):
# handler = StaticHandler
# return handler, path_param
#
# def get_path_param(self, path):
# """ parse param in url
#
# :param path: url rule
# :return: a PathParam object
#
# """
#
# path_attr_list = path.split("/")
# url_attr_list = self.__url.split("/")
# path_param = PathParam()
# if len(path_attr_list) != len(url_attr_list):
# path_param.status = False
# return path_param
# for index in xrange(len(path_attr_list)):
# path_attr = path_attr_list[index]
# url_attr = url_attr_list[index]
# if ("{" not in path_attr or "}" not in path_attr) and path_attr != url_attr:
# path_param.status = False
# return path_param
# if "{" in path_attr and "}" in path_attr:
# path_value_key = path_attr.replace("{", "").replace("}", "")
# path_param.status = True
# path_param.value[path_value_key] = url_attr
# return path_param
#
# class PathParam(object):
# status = False
# value = {}
. Output only the next line. | print(handler) |
Next line prediction: <|code_start|>
class JSONReportObject(EmbeddedDocument):
name = StringField(required=True)
_json_data = FileField()
def get_as_dict(self):
return json.loads(self._json_data.read())
class RawReportObject(EmbeddedDocument):
name = StringField(required=True)
_raw_data = FileField()
def get_raw_data(self):
return self._raw_data.read()
class Report(db.Document):
REPORT_STATUS_CODE_OK = 0
<|code_end|>
. Use current file imports:
(from flask import json
from mass_flask_config.app import db
from mongoengine import StringField, DateTimeField, ReferenceField, IntField, ListField, EmbeddedDocument, FileField, EmbeddedDocumentListField, DictField, MapField, GridFSProxy
from .analysis_system import AnalysisSystem
from .sample import Sample
from mass_flask_core.utils import TimeFunctions)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | REPORT_STATUS_CODE_FAILURE = 1 |
Given snippet: <|code_start|>
class JSONReportObject(EmbeddedDocument):
name = StringField(required=True)
_json_data = FileField()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import json
from mass_flask_config.app import db
from mongoengine import StringField, DateTimeField, ReferenceField, IntField, ListField, EmbeddedDocument, FileField, EmbeddedDocumentListField, DictField, MapField, GridFSProxy
from .analysis_system import AnalysisSystem
from .sample import Sample
from mass_flask_core.utils import TimeFunctions
and context:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
which might include code, classes, or functions. Output only the next line. | def get_as_dict(self): |
Based on the snippet: <|code_start|> (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
)
analysis_system = ReferenceField(AnalysisSystem, required=True)
sample = ReferenceField(Sample, required=True)
analysis_date = DateTimeField()
upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
error_message = StringField(null=True, required=False)
tags = ListField(StringField())
additional_metadata = DictField()
json_report_objects = MapField(field=FileField())
raw_report_objects = MapField(field=FileField())
meta = {
'ordering': ['-upload_date'],
'indexes': ['upload_date']
}
def __repr__(self):
return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
def __str__(self):
return self.__repr__()
def _add_report_object(self, file, target):
proxy = GridFSProxy()
proxy.put(file)
target[file.name] = proxy
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import json
from mass_flask_config.app import db
from mongoengine import StringField, DateTimeField, ReferenceField, IntField, ListField, EmbeddedDocument, FileField, EmbeddedDocumentListField, DictField, MapField, GridFSProxy
from .analysis_system import AnalysisSystem
from .sample import Sample
from mass_flask_core.utils import TimeFunctions
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | def add_json_report_object(self, file): |
Given the code snippet: <|code_start|> def get_as_dict(self):
return json.loads(self._json_data.read())
class RawReportObject(EmbeddedDocument):
name = StringField(required=True)
_raw_data = FileField()
def get_raw_data(self):
return self._raw_data.read()
class Report(db.Document):
REPORT_STATUS_CODE_OK = 0
REPORT_STATUS_CODE_FAILURE = 1
REPORT_STATUS_CODES = (
(REPORT_STATUS_CODE_OK, 'OK'),
(REPORT_STATUS_CODE_FAILURE, 'FAIL'),
)
analysis_system = ReferenceField(AnalysisSystem, required=True)
sample = ReferenceField(Sample, required=True)
analysis_date = DateTimeField()
upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
error_message = StringField(null=True, required=False)
tags = ListField(StringField())
additional_metadata = DictField()
<|code_end|>
, generate the next line using the imports in this file:
from flask import json
from mass_flask_config.app import db
from mongoengine import StringField, DateTimeField, ReferenceField, IntField, ListField, EmbeddedDocument, FileField, EmbeddedDocumentListField, DictField, MapField, GridFSProxy
from .analysis_system import AnalysisSystem
from .sample import Sample
from mass_flask_core.utils import TimeFunctions
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | json_report_objects = MapField(field=FileField()) |
Here is a snippet: <|code_start|> 'view_sample',
'submit_sample',
]
class APIKey(db.Document):
expiry_date = DateTimeField()
scopes = ListField(StringField(choices=API_SCOPES))
meta = {
'allow_inheritance': True,
}
def is_expired(self):
if self.expiry_date is not None and TimeFunctions.get_timestamp() >= self.expiry_date:
return True
else:
return False
def generate_auth_token(self):
if self.id:
s = Serializer(app.secret_key)
return s.dumps(str(self.id))
else:
raise ValueError('APIKey must be saved before requesting an auth token.')
@property
def referenced_entity(self):
return None
<|code_end|>
. Write the next line using the current file imports:
from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance
and context from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
, which may include functions, classes, or code. Output only the next line. | @staticmethod |
Given the code snippet: <|code_start|>
class UserAPIKey(APIKey):
user = ReferenceField(User, required=True)
@staticmethod
def get_or_create(user):
api_key = UserAPIKey.objects(user=user.id).first()
if not api_key:
api_key = UserAPIKey(user=user.id)
api_key.save()
return api_key
@property
def referenced_entity(self):
return self.user
class InstanceAPIKey(APIKey):
instance = ReferenceField(AnalysisSystemInstance, required=True)
@staticmethod
def get_or_create(instance):
api_key = InstanceAPIKey.objects(instance=instance.id).first()
if not api_key:
api_key = InstanceAPIKey(instance=instance.id)
api_key.save()
return api_key
@property
def referenced_entity(self):
<|code_end|>
, generate the next line using the imports in this file:
from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
. Output only the next line. | return self.instance |
Given the code snippet: <|code_start|> return None
@staticmethod
def api_key_loader(key):
s = Serializer(app.secret_key)
try:
data = s.loads(key)
api_key = APIKey.objects(id=data).first()
if api_key.is_expired():
api_key.delete()
return None
else:
return api_key.referenced_entity
except BadSignature:
return None # invalid token
class UserAPIKey(APIKey):
user = ReferenceField(User, required=True)
@staticmethod
def get_or_create(user):
api_key = UserAPIKey.objects(user=user.id).first()
if not api_key:
api_key = UserAPIKey(user=user.id)
api_key.save()
return api_key
@property
def referenced_entity(self):
<|code_end|>
, generate the next line using the imports in this file:
from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
. Output only the next line. | return self.user |
Given the code snippet: <|code_start|>
API_SCOPES = [
'view_sample',
'submit_sample',
]
class APIKey(db.Document):
expiry_date = DateTimeField()
scopes = ListField(StringField(choices=API_SCOPES))
<|code_end|>
, generate the next line using the imports in this file:
from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
. Output only the next line. | meta = { |
Next line prediction: <|code_start|>
API_SCOPES = [
'view_sample',
'submit_sample',
]
class APIKey(db.Document):
expiry_date = DateTimeField()
scopes = ListField(StringField(choices=API_SCOPES))
meta = {
'allow_inheritance': True,
}
def is_expired(self):
if self.expiry_date is not None and TimeFunctions.get_timestamp() >= self.expiry_date:
return True
else:
<|code_end|>
. Use current file imports:
(from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
. Output only the next line. | return False |
Here is a snippet: <|code_start|> def referenced_entity(self):
return None
@staticmethod
def api_key_loader(key):
s = Serializer(app.secret_key)
try:
data = s.loads(key)
api_key = APIKey.objects(id=data).first()
if api_key.is_expired():
api_key.delete()
return None
else:
return api_key.referenced_entity
except BadSignature:
return None # invalid token
class UserAPIKey(APIKey):
user = ReferenceField(User, required=True)
@staticmethod
def get_or_create(user):
api_key = UserAPIKey.objects(user=user.id).first()
if not api_key:
api_key = UserAPIKey(user=user.id)
api_key.save()
return api_key
@property
<|code_end|>
. Write the next line using the current file imports:
from mongoengine import DateTimeField, ListField, StringField, ReferenceField
from itsdangerous import URLSafeSerializer as Serializer, BadSignature
from mass_flask_core.utils.time_functions import TimeFunctions
from mass_flask_config.app import db, app, setup_key_based_auth
from mass_flask_core.models import User, AnalysisSystemInstance
and context from other files:
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
, which may include functions, classes, or code. Output only the next line. | def referenced_entity(self): |
Given the code snippet: <|code_start|>
class AnalysisSystemTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
obj = mixer.blend(AnalysisSystem, identifier_name='Test')
self.assertEqual(obj.__repr__(), '[AnalysisSystem] Test')
self.assertEqual(obj.__str__(), '[AnalysisSystem] Test')
def test_is_system_name_unique(self):
with self.assertRaises(NotUniqueError):
a1 = mixer.blend(AnalysisSystem, identifier_name='duplicate')
a1.save()
a2 = mixer.blend(AnalysisSystem, identifier_name='duplicate')
a2.save()
def test_is_null_name_forbidden(self):
with self.assertRaises(ValidationError):
mixer.blend(AnalysisSystem, identifier_name=None)
def test_is_empty_name_forbidden(self):
with self.assertRaises(ValidationError):
mixer.blend(AnalysisSystem, identifier_name='')
<|code_end|>
, generate the next line using the imports in this file:
from mass_flask_core.models import AnalysisSystem
from mongoengine.errors import ValidationError, NotUniqueError
from mass_flask_core.tests import FlaskTestCase
from mixer.backend.mongoengine import mixer
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | def test_is_short_name_forbidden(self): |
Here is a snippet: <|code_start|>
class AnalysisSystemTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
obj = mixer.blend(AnalysisSystem, identifier_name='Test')
self.assertEqual(obj.__repr__(), '[AnalysisSystem] Test')
self.assertEqual(obj.__str__(), '[AnalysisSystem] Test')
def test_is_system_name_unique(self):
with self.assertRaises(NotUniqueError):
a1 = mixer.blend(AnalysisSystem, identifier_name='duplicate')
a1.save()
a2 = mixer.blend(AnalysisSystem, identifier_name='duplicate')
a2.save()
def test_is_null_name_forbidden(self):
with self.assertRaises(ValidationError):
mixer.blend(AnalysisSystem, identifier_name=None)
def test_is_empty_name_forbidden(self):
<|code_end|>
. Write the next line using the current file imports:
from mass_flask_core.models import AnalysisSystem
from mongoengine.errors import ValidationError, NotUniqueError
from mass_flask_core.tests import FlaskTestCase
from mixer.backend.mongoengine import mixer
and context from other files:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
, which may include functions, classes, or code. Output only the next line. | with self.assertRaises(ValidationError): |
Here is a snippet: <|code_start|>
def get_pagination_compatible_schema(schema_class):
class PaginationCompatibleSchema(Schema):
results = Nested(schema_class, many=True)
next = Int()
previous = Int()
return PaginationCompatibleSchema()
def register_api_endpoint(endpoint_name, resource):
endpoint_path = '/{}/'.format(endpoint_name)
endpoint_detail_path = endpoint_path + '<{}>/'.format(resource.query_key_field)
endpoint_detail_path_spec = endpoint_path + '{{{}}}/'.format(resource.query_key_field)
<|code_end|>
. Write the next line using the current file imports:
from mass_flask_api.config import api_blueprint
from marshmallow import Schema
from marshmallow.fields import Nested, Int
and context from other files:
# Path: mass_flask_api/config.py
# class BasePathAPISpec(APISpec):
# def to_dict(self):
# def api_root():
# def swagger():
# def api_unauthorized_callback():
# def before_request_set_unauthorized_callback():
, which may include functions, classes, or code. Output only the next line. | resource_view = resource.as_view(endpoint_name) |
Based on the snippet: <|code_start|>
def _get_sample_statistics():
result = []
now = TimeFunctions.get_timestamp().replace(hour=0, minute=0, second=0, microsecond=0)
for i in range(0,14):
start = now - datetime.timedelta(days=i)
end = now - datetime.timedelta(days=i-1)
number = Sample.objects(delivery_date__gte=start, delivery_date__lt=end).count()
result.append((start, number))
return result
@webui_blueprint.route('/')
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from flask import render_template
from mass_flask_core.models import Sample
from mass_flask_core.utils import TimeFunctions
from mass_flask_webui.config import webui_blueprint
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_webui/config.py
. Output only the next line. | def index(): |
Next line prediction: <|code_start|>
def _get_sample_statistics():
result = []
now = TimeFunctions.get_timestamp().replace(hour=0, minute=0, second=0, microsecond=0)
for i in range(0,14):
start = now - datetime.timedelta(days=i)
<|code_end|>
. Use current file imports:
(import datetime
from flask import render_template
from mass_flask_core.models import Sample
from mass_flask_core.utils import TimeFunctions
from mass_flask_webui.config import webui_blueprint)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_webui/config.py
. Output only the next line. | end = now - datetime.timedelta(days=i-1) |
Continue the code snippet: <|code_start|>
def _get_sample_statistics():
result = []
now = TimeFunctions.get_timestamp().replace(hour=0, minute=0, second=0, microsecond=0)
for i in range(0,14):
start = now - datetime.timedelta(days=i)
end = now - datetime.timedelta(days=i-1)
number = Sample.objects(delivery_date__gte=start, delivery_date__lt=end).count()
result.append((start, number))
<|code_end|>
. Use current file imports:
import datetime
from flask import render_template
from mass_flask_core.models import Sample
from mass_flask_core.utils import TimeFunctions
from mass_flask_webui.config import webui_blueprint
and context (classes, functions, or code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
#
# Path: mass_flask_webui/config.py
. Output only the next line. | return result |
Predict the next line for this snippet: <|code_start|>
class AnalysisSystemSchema(BaseSchema):
url = URLFor('.analysis_system_detail', identifier_name='<identifier_name>', _external=True)
class Meta(BaseSchema.Meta):
model = AnalysisSystem
dump_only = [
'id',
<|code_end|>
with the help of current file imports:
from flask_marshmallow.fields import URLFor
from mass_flask_api.config import api_blueprint
from mass_flask_api.schemas.base import BaseSchema
from mass_flask_core.models import AnalysisSystem
and context from other files:
# Path: mass_flask_api/config.py
# class BasePathAPISpec(APISpec):
# def to_dict(self):
# def api_root():
# def swagger():
# def api_unauthorized_callback():
# def before_request_set_unauthorized_callback():
#
# Path: mass_flask_api/schemas/base.py
# class BaseSchema(ModelSchema):
# class Meta:
# model_skip_values = []
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
, which may contain function names, class names, or code. Output only the next line. | '_cls', |
Continue the code snippet: <|code_start|>
class AnalysisSystemSchema(BaseSchema):
url = URLFor('.analysis_system_detail', identifier_name='<identifier_name>', _external=True)
class Meta(BaseSchema.Meta):
model = AnalysisSystem
dump_only = [
<|code_end|>
. Use current file imports:
from flask_marshmallow.fields import URLFor
from mass_flask_api.config import api_blueprint
from mass_flask_api.schemas.base import BaseSchema
from mass_flask_core.models import AnalysisSystem
and context (classes, functions, or code) from other files:
# Path: mass_flask_api/config.py
# class BasePathAPISpec(APISpec):
# def to_dict(self):
# def api_root():
# def swagger():
# def api_unauthorized_callback():
# def before_request_set_unauthorized_callback():
#
# Path: mass_flask_api/schemas/base.py
# class BaseSchema(ModelSchema):
# class Meta:
# model_skip_values = []
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
. Output only the next line. | 'id', |
Here is a snippet: <|code_start|>
class LoginForm(Form):
username = StringField(validators=[DataRequired()])
password = PasswordField(validators=[DataRequired()])
submit = SubmitField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
def validate(self, extra_validators=None):
if not super(LoginForm, self).validate():
return False
user = User.user_loader(username=self.data['username'], password=self.data['password'])
if not user:
flash('Username/password incorrect.', 'warning')
<|code_end|>
. Write the next line using the current file imports:
from flask_wtf import Form
from flask import flash
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired
from mass_flask_core.models import User
and context from other files:
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
, which may include functions, classes, or code. Output only the next line. | return False |
Continue the code snippet: <|code_start|>
@webui_blueprint.route('/report/<report_id>/')
def report_detail(report_id):
report = Report.objects(id=report_id).first()
<|code_end|>
. Use current file imports:
from flask import render_template
from mass_flask_core.models import Report
from mass_flask_webui.config import webui_blueprint
and context (classes, functions, or code) from other files:
# Path: mass_flask_core/models/report.py
# class Report(db.Document):
#
# REPORT_STATUS_CODE_OK = 0
# REPORT_STATUS_CODE_FAILURE = 1
#
# REPORT_STATUS_CODES = (
# (REPORT_STATUS_CODE_OK, 'OK'),
# (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
# )
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_date = DateTimeField()
# upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
# error_message = StringField(null=True, required=False)
# tags = ListField(StringField())
# additional_metadata = DictField()
# json_report_objects = MapField(field=FileField())
# raw_report_objects = MapField(field=FileField())
#
# meta = {
# 'ordering': ['-upload_date'],
# 'indexes': ['upload_date']
# }
#
# def __repr__(self):
# return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# def _add_report_object(self, file, target):
# proxy = GridFSProxy()
# proxy.put(file)
# target[file.name] = proxy
#
# def add_json_report_object(self, file):
# self._add_report_object(file, self.json_report_objects)
#
# def add_raw_report_object(self, file):
# self._add_report_object(file, self.raw_report_objects)
#
# Path: mass_flask_webui/config.py
. Output only the next line. | return render_template('report_generic.html', report=report) |
Predict the next line for this snippet: <|code_start|>
class RequestDispatchTestCase(FlaskTestCase):
def test_are_requests_correct_after_sample_creation(self):
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
self._are_requests_correct(ipsample, urisample, system)
<|code_end|>
with the help of current file imports:
from mixer.backend.mongoengine import mixer
from mongoengine import DoesNotExist
from mass_flask_core.models import AnalysisSystem, AnalysisRequest, IPSample, URISample
from mass_flask_core.tests import FlaskTestCase
and context from other files:
# Path: mass_flask_core/models/sample.py
# class IPSample(Sample):
# ip_address = StringField(required=True)
#
# @property
# def title(self):
# return self.ip_address
#
# def _initialize(self, **kwargs):
# self.ip_address = kwargs['ip_address']
# self.tags.append('sample-type:ipsample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'ip_address' not in kwargs:
# raise ValidationError('Parameter ip_address is missing')
# else:
# try:
# sample = cls.objects.get(ip_address=kwargs['ip_address'])
# except DoesNotExist:
# sample = IPSample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# class URISample(Sample):
# uri = StringField(required=True)
#
# @property
# def title(self):
# return self.uri
#
# def _initialize(self, **kwargs):
# self.uri = kwargs['uri']
# self.tags.append('sample-type:urisample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'uri' not in kwargs:
# raise ValidationError('Parameter uri is missing')
# else:
# try:
# sample = cls.objects.get(uri=kwargs['uri'])
# except DoesNotExist:
# sample = URISample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
, which may contain function names, class names, or code. Output only the next line. | def test_are_requests_correct_after_analysis_system_creation(self): |
Here is a snippet: <|code_start|>
class RequestDispatchTestCase(FlaskTestCase):
def test_are_requests_correct_after_sample_creation(self):
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
self._are_requests_correct(ipsample, urisample, system)
def test_are_requests_correct_after_analysis_system_creation(self):
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
# Refresh samples from DB, to reload the dispatched_to field
ipsample = IPSample.objects.get(id=ipsample.id)
urisample = URISample.objects.get(id=urisample.id)
self._are_requests_correct(ipsample, urisample, system)
def _are_requests_correct(self, ipsample, urisample, system):
<|code_end|>
. Write the next line using the current file imports:
from mixer.backend.mongoengine import mixer
from mongoengine import DoesNotExist
from mass_flask_core.models import AnalysisSystem, AnalysisRequest, IPSample, URISample
from mass_flask_core.tests import FlaskTestCase
and context from other files:
# Path: mass_flask_core/models/sample.py
# class IPSample(Sample):
# ip_address = StringField(required=True)
#
# @property
# def title(self):
# return self.ip_address
#
# def _initialize(self, **kwargs):
# self.ip_address = kwargs['ip_address']
# self.tags.append('sample-type:ipsample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'ip_address' not in kwargs:
# raise ValidationError('Parameter ip_address is missing')
# else:
# try:
# sample = cls.objects.get(ip_address=kwargs['ip_address'])
# except DoesNotExist:
# sample = IPSample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# class URISample(Sample):
# uri = StringField(required=True)
#
# @property
# def title(self):
# return self.uri
#
# def _initialize(self, **kwargs):
# self.uri = kwargs['uri']
# self.tags.append('sample-type:urisample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'uri' not in kwargs:
# raise ValidationError('Parameter uri is missing')
# else:
# try:
# sample = cls.objects.get(uri=kwargs['uri'])
# except DoesNotExist:
# sample = URISample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(ipsample.dispatched_to, [system]) |
Using the snippet: <|code_start|>
class RequestDispatchTestCase(FlaskTestCase):
def test_are_requests_correct_after_sample_creation(self):
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
self._are_requests_correct(ipsample, urisample, system)
def test_are_requests_correct_after_analysis_system_creation(self):
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
# Refresh samples from DB, to reload the dispatched_to field
ipsample = IPSample.objects.get(id=ipsample.id)
urisample = URISample.objects.get(id=urisample.id)
self._are_requests_correct(ipsample, urisample, system)
def _are_requests_correct(self, ipsample, urisample, system):
self.assertEqual(ipsample.dispatched_to, [system])
self.assertEqual(urisample.dispatched_to, [])
AnalysisRequest.objects.get(sample=ipsample, analysis_system=system)
<|code_end|>
, determine the next line of code. You have imports:
from mixer.backend.mongoengine import mixer
from mongoengine import DoesNotExist
from mass_flask_core.models import AnalysisSystem, AnalysisRequest, IPSample, URISample
from mass_flask_core.tests import FlaskTestCase
and context (class names, function names, or code) available:
# Path: mass_flask_core/models/sample.py
# class IPSample(Sample):
# ip_address = StringField(required=True)
#
# @property
# def title(self):
# return self.ip_address
#
# def _initialize(self, **kwargs):
# self.ip_address = kwargs['ip_address']
# self.tags.append('sample-type:ipsample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'ip_address' not in kwargs:
# raise ValidationError('Parameter ip_address is missing')
# else:
# try:
# sample = cls.objects.get(ip_address=kwargs['ip_address'])
# except DoesNotExist:
# sample = IPSample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# class URISample(Sample):
# uri = StringField(required=True)
#
# @property
# def title(self):
# return self.uri
#
# def _initialize(self, **kwargs):
# self.uri = kwargs['uri']
# self.tags.append('sample-type:urisample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'uri' not in kwargs:
# raise ValidationError('Parameter uri is missing')
# else:
# try:
# sample = cls.objects.get(uri=kwargs['uri'])
# except DoesNotExist:
# sample = URISample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | with self.assertRaises(DoesNotExist): |
Next line prediction: <|code_start|>
class RequestDispatchTestCase(FlaskTestCase):
def test_are_requests_correct_after_sample_creation(self):
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
self._are_requests_correct(ipsample, urisample, system)
def test_are_requests_correct_after_analysis_system_creation(self):
ipsample = mixer.blend(IPSample, tags=['sample-type:ipsample'])
urisample = mixer.blend(URISample, tags=['sample-type:urisample'])
system = mixer.blend(AnalysisSystem, tag_filter_expression='sample-type:ipsample')
# Refresh samples from DB, to reload the dispatched_to field
ipsample = IPSample.objects.get(id=ipsample.id)
urisample = URISample.objects.get(id=urisample.id)
<|code_end|>
. Use current file imports:
(from mixer.backend.mongoengine import mixer
from mongoengine import DoesNotExist
from mass_flask_core.models import AnalysisSystem, AnalysisRequest, IPSample, URISample
from mass_flask_core.tests import FlaskTestCase)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_core/models/sample.py
# class IPSample(Sample):
# ip_address = StringField(required=True)
#
# @property
# def title(self):
# return self.ip_address
#
# def _initialize(self, **kwargs):
# self.ip_address = kwargs['ip_address']
# self.tags.append('sample-type:ipsample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'ip_address' not in kwargs:
# raise ValidationError('Parameter ip_address is missing')
# else:
# try:
# sample = cls.objects.get(ip_address=kwargs['ip_address'])
# except DoesNotExist:
# sample = IPSample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# class URISample(Sample):
# uri = StringField(required=True)
#
# @property
# def title(self):
# return self.uri
#
# def _initialize(self, **kwargs):
# self.uri = kwargs['uri']
# self.tags.append('sample-type:urisample')
#
# @classmethod
# def create_or_update(cls, **kwargs):
# if 'uri' not in kwargs:
# raise ValidationError('Parameter uri is missing')
# else:
# try:
# sample = cls.objects.get(uri=kwargs['uri'])
# except DoesNotExist:
# sample = URISample()
# sample._initialize(**kwargs)
#
# sample._update(**kwargs)
# sample.save()
# return sample
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | self._are_requests_correct(ipsample, urisample, system) |
Given the following code snippet before the placeholder: <|code_start|>
class DevelopmentConfig(BaseConfig):
DEBUG = True
MONGODB_SETTINGS = {
'host': 'mongodb://localhost:27017/mass-flask-development',
<|code_end|>
, predict the next line using imports from the current file:
from mass_flask_config.config_base import BaseConfig
and context including class names, function names, and sometimes code from other files:
# Path: mass_flask_config/config_base.py
# class BaseConfig(object):
# DEBUG = False
# TESTING = False
# LOGGER_NAME = 'mass_server_flask'
# BOOTSTRAP_SERVE_LOCAL = True
# BOOTSTRAP_USE_MINIFIED = True
# SCHEDULER_VIEWS_ENABLED = False
# OBJECTS_PER_PAGE = 100
# SCHEDULE_ANALYSES_INTERVAL = 30
# MAX_SCHEDULE_THRESHOLD = 100
. Output only the next line. | 'tz_aware': True |
Using the snippet: <|code_start|>
class RelationGraphTestCase(FlaskTestCase):
def assertGraphEqual(self, sample, result_set, depth=None):
if depth is None:
self.assertEqual(GraphFunctions.get_relation_graph(sample), result_set)
<|code_end|>
, determine the next line of code. You have imports:
from mixer.backend.mongoengine import mixer
from mass_flask_core.models import Sample, SampleRelation
from mass_flask_core.tests import FlaskTestCase
from mass_flask_core.utils import GraphFunctions
and context (class names, function names, or code) available:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/sample_relation.py
# class SampleRelation(db.Document):
# sample = ReferenceField(Sample, required=True)
# other = ReferenceField(Sample, required=True)
# meta = {
# 'allow_inheritance': True,
# }
#
# def __repr__(self):
# repr_string = '[{}] {} -- {}'
# return repr_string.format(self.__class__.__name__, self.sample, self.other)
#
# def __str__(self):
# return self.__repr__()
#
# def _initialize(self, **kwargs):
# self.sample = Sample.objects(id=kwargs['sample']).first()
# self.other = Sample.objects(id=kwargs['other']).first()
#
# @property
# def title(self):
# return self.id
#
# @classmethod
# def create(cls, **kwargs):
# if 'sample' not in kwargs or 'other' not in kwargs:
# raise ValidationError('Parameter "sample" or "other" missing')
# else:
# sample_relation = cls()
# sample_relation._initialize(**kwargs)
# sample_relation.save()
# return sample_relation
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
#
# Path: mass_flask_core/utils/graph_functions.py
# class GraphFunctions:
# @staticmethod
# def get_relation_graph(sample, depth=3):
# current_depth = 0
# samples_at_current_depth = [sample.id]
# all_queried_samples = []
# found_relations = set()
#
# while current_depth < depth:
# from mass_flask_core.models import SampleRelation
# relations_at_current_depth = SampleRelation.objects(Q(sample__in=samples_at_current_depth) | Q(other__in=samples_at_current_depth)).no_dereference()
# all_queried_samples.extend(samples_at_current_depth)
# samples_at_next_depth = []
# for relation in relations_at_current_depth:
# found_relations.add(relation)
# if relation.sample.id not in all_queried_samples:
# samples_at_next_depth.append(relation.sample.id)
# if relation.other.id not in all_queried_samples:
# samples_at_next_depth.append(relation.other.id)
# samples_at_current_depth = samples_at_next_depth
# current_depth += 1
# return found_relations
. Output only the next line. | else: |
Based on the snippet: <|code_start|> return datetime.strptime(string, '%Y-%m-%dT%H:%M:%S+00:00')
@staticmethod
def _create_list_from_string(string):
return string.split(',')
@property
def schema(self):
return Ref('schema').resolve(self)
@property
def pagination_schema(self):
return Ref('pagination_schema').resolve(self)
@property
def queryset(self):
return Ref('queryset').resolve(self)
@property
def query_key_field(self):
return Ref('query_key_field').resolve(self)
@property
def filter_parameters(self):
return Ref('filter_parameters').resolve(self)
@PaginationFunctions.paginate
def _get_list(self):
filter_condition = {}
for parameter, parameter_type in self.filter_parameters:
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import jsonify, request
from flask.views import MethodView
from mongoengine import DoesNotExist
from datetime import datetime
from mass_flask_core.utils import PaginationFunctions
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_core/utils/pagination_functions.py
# class PaginationFunctions:
# @staticmethod
# def paginate(view_function):
# @wraps(view_function)
# def paginate_function(*args, **kwargs):
# if 'page' in request.args:
# page = int(request.args['page'])
# else:
# page = 1
# per_page = current_app.config['OBJECTS_PER_PAGE']
# queryset = view_function(*args, **kwargs)
# page_count = ceil(queryset.count()/per_page)
# paginated_queryset = queryset.paginate(page=page, per_page=per_page)
# result = {
# 'results': paginated_queryset.items,
# 'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
# 'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
# 'page': page,
# 'page_count': page_count
# }
# return result
# return paginate_function
. Output only the next line. | if parameter in request.args: |
Using the snippet: <|code_start|> 'shannon_entropy__lte',
'shannon_entropy__gte'
]
return _exact_fields_to_dict(file_form_data, exact_fields)
def _get_ip_filters(ip_form_data):
exact_fields = [
'ip_address'
]
return _exact_fields_to_dict(ip_form_data, exact_fields)
def _get_domain_filters(domain_form_data):
exact_fields = [
'domain',
'domain__contains',
'domain__startswith',
'domain__endswith'
]
return _exact_fields_to_dict(domain_form_data, exact_fields)
def _get_uri_filters(uri_form_data):
exact_fields = [
'uri',
'uri__contains',
'uri__startswith',
'uri__endswith'
]
<|code_end|>
, determine the next line of code. You have imports:
from flask import render_template, request
from mass_flask_core.models import Sample
from mass_flask_core.utils import PaginationFunctions
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.sample_search import SampleSearchForm
and context (class names, function names, or code) available:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/pagination_functions.py
# class PaginationFunctions:
# @staticmethod
# def paginate(view_function):
# @wraps(view_function)
# def paginate_function(*args, **kwargs):
# if 'page' in request.args:
# page = int(request.args['page'])
# else:
# page = 1
# per_page = current_app.config['OBJECTS_PER_PAGE']
# queryset = view_function(*args, **kwargs)
# page_count = ceil(queryset.count()/per_page)
# paginated_queryset = queryset.paginate(page=page, per_page=per_page)
# result = {
# 'results': paginated_queryset.items,
# 'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
# 'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
# 'page': page,
# 'page_count': page_count
# }
# return result
# return paginate_function
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/sample_search.py
# class SampleSearchForm(NoCSRFForm):
# common = FormField(CommonSearchForm, label='Common search filters')
# file = FormField(FileSampleSearchForm, label='Search filters related to file samples')
# ip = FormField(IPSampleSearchForm, label='Search filters related to IP samples')
# domain = FormField(DomainSampleSearchForm, label='Search filters related to domain samples')
# uri = FormField(URISampleSearchForm, label='Search filters related to URI samples')
# submit = SubmitField()
. Output only the next line. | return _exact_fields_to_dict(uri_form_data, exact_fields) |
Predict the next line for this snippet: <|code_start|>
def _is_present_and_not_empty(form_data, variable):
return variable in form_data and form_data[variable]
def _exact_fields_to_dict(form_data, exact_fields):
result_dict = {}
<|code_end|>
with the help of current file imports:
from flask import render_template, request
from mass_flask_core.models import Sample
from mass_flask_core.utils import PaginationFunctions
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.sample_search import SampleSearchForm
and context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/pagination_functions.py
# class PaginationFunctions:
# @staticmethod
# def paginate(view_function):
# @wraps(view_function)
# def paginate_function(*args, **kwargs):
# if 'page' in request.args:
# page = int(request.args['page'])
# else:
# page = 1
# per_page = current_app.config['OBJECTS_PER_PAGE']
# queryset = view_function(*args, **kwargs)
# page_count = ceil(queryset.count()/per_page)
# paginated_queryset = queryset.paginate(page=page, per_page=per_page)
# result = {
# 'results': paginated_queryset.items,
# 'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
# 'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
# 'page': page,
# 'page_count': page_count
# }
# return result
# return paginate_function
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/sample_search.py
# class SampleSearchForm(NoCSRFForm):
# common = FormField(CommonSearchForm, label='Common search filters')
# file = FormField(FileSampleSearchForm, label='Search filters related to file samples')
# ip = FormField(IPSampleSearchForm, label='Search filters related to IP samples')
# domain = FormField(DomainSampleSearchForm, label='Search filters related to domain samples')
# uri = FormField(URISampleSearchForm, label='Search filters related to URI samples')
# submit = SubmitField()
, which may contain function names, class names, or code. Output only the next line. | for field in exact_fields: |
Here is a snippet: <|code_start|> 'file_size__gte',
'shannon_entropy__lte',
'shannon_entropy__gte'
]
return _exact_fields_to_dict(file_form_data, exact_fields)
def _get_ip_filters(ip_form_data):
exact_fields = [
'ip_address'
]
return _exact_fields_to_dict(ip_form_data, exact_fields)
def _get_domain_filters(domain_form_data):
exact_fields = [
'domain',
'domain__contains',
'domain__startswith',
'domain__endswith'
]
return _exact_fields_to_dict(domain_form_data, exact_fields)
def _get_uri_filters(uri_form_data):
exact_fields = [
'uri',
'uri__contains',
'uri__startswith',
'uri__endswith'
<|code_end|>
. Write the next line using the current file imports:
from flask import render_template, request
from mass_flask_core.models import Sample
from mass_flask_core.utils import PaginationFunctions
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.sample_search import SampleSearchForm
and context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/pagination_functions.py
# class PaginationFunctions:
# @staticmethod
# def paginate(view_function):
# @wraps(view_function)
# def paginate_function(*args, **kwargs):
# if 'page' in request.args:
# page = int(request.args['page'])
# else:
# page = 1
# per_page = current_app.config['OBJECTS_PER_PAGE']
# queryset = view_function(*args, **kwargs)
# page_count = ceil(queryset.count()/per_page)
# paginated_queryset = queryset.paginate(page=page, per_page=per_page)
# result = {
# 'results': paginated_queryset.items,
# 'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
# 'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
# 'page': page,
# 'page_count': page_count
# }
# return result
# return paginate_function
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/sample_search.py
# class SampleSearchForm(NoCSRFForm):
# common = FormField(CommonSearchForm, label='Common search filters')
# file = FormField(FileSampleSearchForm, label='Search filters related to file samples')
# ip = FormField(IPSampleSearchForm, label='Search filters related to IP samples')
# domain = FormField(DomainSampleSearchForm, label='Search filters related to domain samples')
# uri = FormField(URISampleSearchForm, label='Search filters related to URI samples')
# submit = SubmitField()
, which may include functions, classes, or code. Output only the next line. | ] |
Continue the code snippet: <|code_start|>
def _get_file_filters(file_form_data):
exact_fields = [
'mime_type',
'file_names',
'md5sum',
'sha1sum',
'sha256sum',
'sha512sum',
'file_size__lte',
'file_size__gte',
'shannon_entropy__lte',
'shannon_entropy__gte'
]
return _exact_fields_to_dict(file_form_data, exact_fields)
def _get_ip_filters(ip_form_data):
exact_fields = [
'ip_address'
]
return _exact_fields_to_dict(ip_form_data, exact_fields)
def _get_domain_filters(domain_form_data):
exact_fields = [
'domain',
'domain__contains',
'domain__startswith',
'domain__endswith'
<|code_end|>
. Use current file imports:
from flask import render_template, request
from mass_flask_core.models import Sample
from mass_flask_core.utils import PaginationFunctions
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.sample_search import SampleSearchForm
and context (classes, functions, or code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/pagination_functions.py
# class PaginationFunctions:
# @staticmethod
# def paginate(view_function):
# @wraps(view_function)
# def paginate_function(*args, **kwargs):
# if 'page' in request.args:
# page = int(request.args['page'])
# else:
# page = 1
# per_page = current_app.config['OBJECTS_PER_PAGE']
# queryset = view_function(*args, **kwargs)
# page_count = ceil(queryset.count()/per_page)
# paginated_queryset = queryset.paginate(page=page, per_page=per_page)
# result = {
# 'results': paginated_queryset.items,
# 'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
# 'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
# 'page': page,
# 'page_count': page_count
# }
# return result
# return paginate_function
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/sample_search.py
# class SampleSearchForm(NoCSRFForm):
# common = FormField(CommonSearchForm, label='Common search filters')
# file = FormField(FileSampleSearchForm, label='Search filters related to file samples')
# ip = FormField(IPSampleSearchForm, label='Search filters related to IP samples')
# domain = FormField(DomainSampleSearchForm, label='Search filters related to domain samples')
# uri = FormField(URISampleSearchForm, label='Search filters related to URI samples')
# submit = SubmitField()
. Output only the next line. | ] |
Given snippet: <|code_start|>
class AnalysisSystemInstanceTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='InstanceTestSystem')
instance = mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
self.assertEqual(instance.__repr__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319')
self.assertEqual(instance.__str__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319')
def test_is_uuid_unique(self):
system = mixer.blend(AnalysisSystem, identifier_name='InstanceTestSystem')
mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
# Create another system with the same name, expect that it fails
with self.assertRaises(NotUniqueError):
mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
def test_is_null_name_forbidden(self):
with self.assertRaises(ValidationError):
AnalysisSystemInstance.objects.create(uuid=None)
def test_is_online_interval_working(self):
obj = AnalysisSystemInstance()
obj.last_seen = TimeFunctions.get_timestamp()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
from mixer.backend.mongoengine import mixer
from mongoengine import NotUniqueError, ValidationError
from mass_flask_core.models import AnalysisSystem, AnalysisSystemInstance
from mass_flask_core.tests import FlaskTestCase
from mass_flask_core.utils import TimeFunctions
and context:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
which might include code, classes, or functions. Output only the next line. | self.assertTrue(obj.is_online) |
Based on the snippet: <|code_start|>
class AnalysisSystemInstanceTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='InstanceTestSystem')
instance = mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
self.assertEqual(instance.__repr__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319')
self.assertEqual(instance.__str__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319')
def test_is_uuid_unique(self):
system = mixer.blend(AnalysisSystem, identifier_name='InstanceTestSystem')
mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
# Create another system with the same name, expect that it fails
with self.assertRaises(NotUniqueError):
mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
def test_is_null_name_forbidden(self):
with self.assertRaises(ValidationError):
AnalysisSystemInstance.objects.create(uuid=None)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from mixer.backend.mongoengine import mixer
from mongoengine import NotUniqueError, ValidationError
from mass_flask_core.models import AnalysisSystem, AnalysisSystemInstance
from mass_flask_core.tests import FlaskTestCase
from mass_flask_core.utils import TimeFunctions
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | def test_is_online_interval_working(self): |
Next line prediction: <|code_start|>
class AnalysisSystemInstanceTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='InstanceTestSystem')
instance = mixer.blend(AnalysisSystemInstance, uuid='e25b2339-23d4-4544-8c99-f2968a935319', analysis_system=system)
self.assertEqual(instance.__repr__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319')
<|code_end|>
. Use current file imports:
(import datetime
from mixer.backend.mongoengine import mixer
from mongoengine import NotUniqueError, ValidationError
from mass_flask_core.models import AnalysisSystem, AnalysisSystemInstance
from mass_flask_core.tests import FlaskTestCase
from mass_flask_core.utils import TimeFunctions)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | self.assertEqual(instance.__str__(), '[AnalysisSystemInstance] InstanceTestSystem e25b2339-23d4-4544-8c99-f2968a935319') |
Here is a snippet: <|code_start|>
class FileSampleSubmitForm(Form):
file = FileField('File', validators=[FileRequired()])
tlp_level = SelectField('Sample privacy (TLP level)', coerce=int, choices=[
(TLPLevelField.TLP_LEVEL_WHITE, 'WHITE (unlimited)'),
(TLPLevelField.TLP_LEVEL_GREEN, 'GREEN (community)'),
(TLPLevelField.TLP_LEVEL_AMBER, 'AMBER (limited distribution)'),
(TLPLevelField.TLP_LEVEL_RED, 'RED (personal for named recipients)'),
])
submit = SubmitField()
class IPSampleSubmitForm(Form):
ip_address = StringField('IPv4/IPv6 address', validators=[InputRequired(), IPAddress()])
tlp_level = SelectField('Sample privacy (TLP level)', coerce=int, choices=[
(TLPLevelField.TLP_LEVEL_WHITE, 'WHITE (unlimited)'),
(TLPLevelField.TLP_LEVEL_GREEN, 'GREEN (community)'),
(TLPLevelField.TLP_LEVEL_AMBER, 'AMBER (limited distribution)'),
(TLPLevelField.TLP_LEVEL_RED, 'RED (personal for named recipients)'),
<|code_end|>
. Write the next line using the current file imports:
from flask_wtf import Form
from flask_wtf.file import FileField, FileRequired
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import InputRequired, IPAddress, URL
from mass_flask_core.models import TLPLevelField
and context from other files:
# Path: mass_flask_core/models/tlp_level.py
# class TLPLevelField(IntField):
# TLP_LEVEL_WHITE = 0 # Access without login
# TLP_LEVEL_GREEN = 1 # Access with login
# TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group
# TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups
#
# def __init__(self, *args, **kwargs):
# kwargs['choices'] = [
# TLPLevelField.TLP_LEVEL_WHITE,
# TLPLevelField.TLP_LEVEL_GREEN,
# TLPLevelField.TLP_LEVEL_AMBER,
# TLPLevelField.TLP_LEVEL_RED
# ]
# super(TLPLevelField, self).__init__(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | ]) |
Here is a snippet: <|code_start|>
class AnalysisRequestTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='RequestTestSystem')
sample = mixer.blend(Sample, id='55c863b79b65210a5625411a')
obj = mixer.blend(AnalysisRequest, sample=sample, analysis_system=system)
<|code_end|>
. Write the next line using the current file imports:
from mixer.backend.mongoengine import mixer
from mass_flask_core.models import AnalysisSystem, Sample, AnalysisRequest
from mass_flask_core.tests import FlaskTestCase
and context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
, which may include functions, classes, or code. Output only the next line. | obj.save() |
Given snippet: <|code_start|>
class AnalysisRequestTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='RequestTestSystem')
sample = mixer.blend(Sample, id='55c863b79b65210a5625411a')
obj = mixer.blend(AnalysisRequest, sample=sample, analysis_system=system)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mixer.backend.mongoengine import mixer
from mass_flask_core.models import AnalysisSystem, Sample, AnalysisRequest
from mass_flask_core.tests import FlaskTestCase
and context:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
which might include code, classes, or functions. Output only the next line. | obj.save() |
Given snippet: <|code_start|>
class AnalysisRequestTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='RequestTestSystem')
sample = mixer.blend(Sample, id='55c863b79b65210a5625411a')
obj = mixer.blend(AnalysisRequest, sample=sample, analysis_system=system)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mixer.backend.mongoengine import mixer
from mass_flask_core.models import AnalysisSystem, Sample, AnalysisRequest
from mass_flask_core.tests import FlaskTestCase
and context:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
which might include code, classes, or functions. Output only the next line. | obj.save() |
Continue the code snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
class SampleRelation(db.Document):
sample = ReferenceField(Sample, required=True)
other = ReferenceField(Sample, required=True)
meta = {
'allow_inheritance': True,
}
def __repr__(self):
repr_string = '[{}] {} -- {}'
return repr_string.format(self.__class__.__name__, self.sample, self.other)
<|code_end|>
. Use current file imports:
from mongoengine import FloatField
from mongoengine import ReferenceField
from mongoengine import ValidationError
from mass_flask_config.app import db
from .sample import Sample
import logging
and context (classes, functions, or code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
. Output only the next line. | def __str__(self): |
Given the following code snippet before the placeholder: <|code_start|>
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
class SampleRelation(db.Document):
sample = ReferenceField(Sample, required=True)
other = ReferenceField(Sample, required=True)
meta = {
'allow_inheritance': True,
}
def __repr__(self):
repr_string = '[{}] {} -- {}'
return repr_string.format(self.__class__.__name__, self.sample, self.other)
<|code_end|>
, predict the next line using imports from the current file:
from mongoengine import FloatField
from mongoengine import ReferenceField
from mongoengine import ValidationError
from mass_flask_config.app import db
from .sample import Sample
import logging
and context including class names, function names, and sometimes code from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
. Output only the next line. | def __str__(self): |
Given the code snippet: <|code_start|>
class ReportTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='ReportTestSystem')
sample = mixer.blend(Sample, id='55cdd8e89b65211708b7da46')
obj = mixer.blend(Report, sample=sample, analysis_system=system)
<|code_end|>
, generate the next line using the imports in this file:
from mass_flask_core.models import AnalysisSystem, Report, Sample
from mixer.backend.mongoengine import mixer
from mass_flask_core.tests import FlaskTestCase
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/report.py
# class Report(db.Document):
#
# REPORT_STATUS_CODE_OK = 0
# REPORT_STATUS_CODE_FAILURE = 1
#
# REPORT_STATUS_CODES = (
# (REPORT_STATUS_CODE_OK, 'OK'),
# (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
# )
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_date = DateTimeField()
# upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
# error_message = StringField(null=True, required=False)
# tags = ListField(StringField())
# additional_metadata = DictField()
# json_report_objects = MapField(field=FileField())
# raw_report_objects = MapField(field=FileField())
#
# meta = {
# 'ordering': ['-upload_date'],
# 'indexes': ['upload_date']
# }
#
# def __repr__(self):
# return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# def _add_report_object(self, file, target):
# proxy = GridFSProxy()
# proxy.put(file)
# target[file.name] = proxy
#
# def add_json_report_object(self, file):
# self._add_report_object(file, self.json_report_objects)
#
# def add_raw_report_object(self, file):
# self._add_report_object(file, self.raw_report_objects)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | self.assertEqual(obj.__repr__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem') |
Based on the snippet: <|code_start|>
class ReportTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='ReportTestSystem')
sample = mixer.blend(Sample, id='55cdd8e89b65211708b7da46')
obj = mixer.blend(Report, sample=sample, analysis_system=system)
<|code_end|>
, predict the immediate next line with the help of imports:
from mass_flask_core.models import AnalysisSystem, Report, Sample
from mixer.backend.mongoengine import mixer
from mass_flask_core.tests import FlaskTestCase
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/report.py
# class Report(db.Document):
#
# REPORT_STATUS_CODE_OK = 0
# REPORT_STATUS_CODE_FAILURE = 1
#
# REPORT_STATUS_CODES = (
# (REPORT_STATUS_CODE_OK, 'OK'),
# (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
# )
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_date = DateTimeField()
# upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
# error_message = StringField(null=True, required=False)
# tags = ListField(StringField())
# additional_metadata = DictField()
# json_report_objects = MapField(field=FileField())
# raw_report_objects = MapField(field=FileField())
#
# meta = {
# 'ordering': ['-upload_date'],
# 'indexes': ['upload_date']
# }
#
# def __repr__(self):
# return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# def _add_report_object(self, file, target):
# proxy = GridFSProxy()
# proxy.put(file)
# target[file.name] = proxy
#
# def add_json_report_object(self, file):
# self._add_report_object(file, self.json_report_objects)
#
# def add_raw_report_object(self, file):
# self._add_report_object(file, self.raw_report_objects)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | self.assertEqual(obj.__repr__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem') |
Continue the code snippet: <|code_start|>
class ReportTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='ReportTestSystem')
sample = mixer.blend(Sample, id='55cdd8e89b65211708b7da46')
obj = mixer.blend(Report, sample=sample, analysis_system=system)
self.assertEqual(obj.__repr__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem')
<|code_end|>
. Use current file imports:
from mass_flask_core.models import AnalysisSystem, Report, Sample
from mixer.backend.mongoengine import mixer
from mass_flask_core.tests import FlaskTestCase
and context (classes, functions, or code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/report.py
# class Report(db.Document):
#
# REPORT_STATUS_CODE_OK = 0
# REPORT_STATUS_CODE_FAILURE = 1
#
# REPORT_STATUS_CODES = (
# (REPORT_STATUS_CODE_OK, 'OK'),
# (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
# )
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_date = DateTimeField()
# upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
# error_message = StringField(null=True, required=False)
# tags = ListField(StringField())
# additional_metadata = DictField()
# json_report_objects = MapField(field=FileField())
# raw_report_objects = MapField(field=FileField())
#
# meta = {
# 'ordering': ['-upload_date'],
# 'indexes': ['upload_date']
# }
#
# def __repr__(self):
# return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# def _add_report_object(self, file, target):
# proxy = GridFSProxy()
# proxy.put(file)
# target[file.name] = proxy
#
# def add_json_report_object(self, file):
# self._add_report_object(file, self.json_report_objects)
#
# def add_raw_report_object(self, file):
# self._add_report_object(file, self.raw_report_objects)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | self.assertEqual(obj.__str__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem') |
Based on the snippet: <|code_start|>
class ReportTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='ReportTestSystem')
sample = mixer.blend(Sample, id='55cdd8e89b65211708b7da46')
obj = mixer.blend(Report, sample=sample, analysis_system=system)
self.assertEqual(obj.__repr__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem')
<|code_end|>
, predict the immediate next line with the help of imports:
from mass_flask_core.models import AnalysisSystem, Report, Sample
from mixer.backend.mongoengine import mixer
from mass_flask_core.tests import FlaskTestCase
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/report.py
# class Report(db.Document):
#
# REPORT_STATUS_CODE_OK = 0
# REPORT_STATUS_CODE_FAILURE = 1
#
# REPORT_STATUS_CODES = (
# (REPORT_STATUS_CODE_OK, 'OK'),
# (REPORT_STATUS_CODE_FAILURE, 'FAIL'),
# )
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_date = DateTimeField()
# upload_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# status = IntField(choices=REPORT_STATUS_CODES, default=REPORT_STATUS_CODE_OK, required=True)
# error_message = StringField(null=True, required=False)
# tags = ListField(StringField())
# additional_metadata = DictField()
# json_report_objects = MapField(field=FileField())
# raw_report_objects = MapField(field=FileField())
#
# meta = {
# 'ordering': ['-upload_date'],
# 'indexes': ['upload_date']
# }
#
# def __repr__(self):
# return '[Report] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# def _add_report_object(self, file, target):
# proxy = GridFSProxy()
# proxy.put(file)
# target[file.name] = proxy
#
# def add_json_report_object(self, file):
# self._add_report_object(file, self.json_report_objects)
#
# def add_raw_report_object(self, file):
# self._add_report_object(file, self.raw_report_objects)
#
# Path: mass_flask_core/tests/flask_test_case.py
# class FlaskTestCase(TestCase):
# @staticmethod
# def _clean_test_database():
# conn = connection.get_connection()
# db = connection.get_db()
# conn.drop_database(db)
#
# def __call__(self, result=None):
# self._pre_setup()
# super(FlaskTestCase, self).__call__(result)
# self._post_tearDown()
#
# def _pre_setup(self):
# bootstrap_mass_flask()
# if not 'MASS_TESTING' in app.config or app.config['MASS_TESTING'] is False:
# raise RuntimeError('Running unit test without TESTING=True in configuration. Aborting.')
# self.app = app
# self.client = app.test_client()
# self._ctx = self.app.test_request_context()
# self._ctx.push()
#
# def _post_tearDown(self):
# self._ctx.pop()
# self._clean_test_database()
. Output only the next line. | self.assertEqual(obj.__str__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem') |
Predict the next line for this snippet: <|code_start|>
def _filter_matches_tags(tags, tag_filter):
return TagParser(tags).parse_string(tag_filter)
def _match_sample_and_system(sample, system):
if system in sample.dispatched_to:
return
if not _filter_matches_tags(sample.tags, system.tag_filter_expression):
return
analysis_request = AnalysisRequest(sample=sample, analysis_system=system)
analysis_request.save()
sample.dispatched_to.append(system)
sample.save()
def update_dispatch_request_for_new_sample(sender, document, **kwargs):
if not issubclass(sender, Sample):
return
if kwargs.get('created') is True:
for system in AnalysisSystem.objects():
<|code_end|>
with the help of current file imports:
from mass_flask_core.models import Sample, AnalysisSystem, AnalysisRequest
from mass_flask_core.utils.tag_parser import TagParser
and context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/utils/tag_parser.py
# class TagParser:
#
# MAX_TAG_LENGTH = 160
#
# def __init__(self, tag_list):
# self.tag_list = tag_list
# self._init_parser()
#
# def _bool_op(self, t):
# tag = t[0]
# if tag in self.tag_list:
# return True
# else:
# return False
#
# def _bool_and(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 & arg2
#
# def _bool_or(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 | arg2
#
# def _bool_not(self, t):
# arg = t[0][1]
# return not arg
#
# def _init_parser(self):
# TRUE = Keyword('True')
# FALSE = Keyword('False')
# boolOperand = TRUE | FALSE | Regex(r'[a-zA-Z0-9:\-\/]+')
# boolOperand.setParseAction(self._bool_op)
#
# self._parse_expr = infixNotation(
# boolOperand,
# [
# ('not', 1, opAssoc.RIGHT, self._bool_not),
# ('and', 2, opAssoc.LEFT, self._bool_and),
# ('or', 2, opAssoc.LEFT, self._bool_or),
# ])
#
# def parse_string(self, string):
# if string == '':
# return True
# try:
# return self._parse_expr.parseString(string)[0]
# except ParseException:
# return False
, which may contain function names, class names, or code. Output only the next line. | _match_sample_and_system(document, system) |
Predict the next line after this snippet: <|code_start|>
def _filter_matches_tags(tags, tag_filter):
return TagParser(tags).parse_string(tag_filter)
def _match_sample_and_system(sample, system):
if system in sample.dispatched_to:
return
if not _filter_matches_tags(sample.tags, system.tag_filter_expression):
return
analysis_request = AnalysisRequest(sample=sample, analysis_system=system)
analysis_request.save()
<|code_end|>
using the current file's imports:
from mass_flask_core.models import Sample, AnalysisSystem, AnalysisRequest
from mass_flask_core.utils.tag_parser import TagParser
and any relevant context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/utils/tag_parser.py
# class TagParser:
#
# MAX_TAG_LENGTH = 160
#
# def __init__(self, tag_list):
# self.tag_list = tag_list
# self._init_parser()
#
# def _bool_op(self, t):
# tag = t[0]
# if tag in self.tag_list:
# return True
# else:
# return False
#
# def _bool_and(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 & arg2
#
# def _bool_or(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 | arg2
#
# def _bool_not(self, t):
# arg = t[0][1]
# return not arg
#
# def _init_parser(self):
# TRUE = Keyword('True')
# FALSE = Keyword('False')
# boolOperand = TRUE | FALSE | Regex(r'[a-zA-Z0-9:\-\/]+')
# boolOperand.setParseAction(self._bool_op)
#
# self._parse_expr = infixNotation(
# boolOperand,
# [
# ('not', 1, opAssoc.RIGHT, self._bool_not),
# ('and', 2, opAssoc.LEFT, self._bool_and),
# ('or', 2, opAssoc.LEFT, self._bool_or),
# ])
#
# def parse_string(self, string):
# if string == '':
# return True
# try:
# return self._parse_expr.parseString(string)[0]
# except ParseException:
# return False
. Output only the next line. | sample.dispatched_to.append(system) |
Using the snippet: <|code_start|>
def _filter_matches_tags(tags, tag_filter):
return TagParser(tags).parse_string(tag_filter)
def _match_sample_and_system(sample, system):
if system in sample.dispatched_to:
return
if not _filter_matches_tags(sample.tags, system.tag_filter_expression):
return
analysis_request = AnalysisRequest(sample=sample, analysis_system=system)
analysis_request.save()
sample.dispatched_to.append(system)
sample.save()
def update_dispatch_request_for_new_sample(sender, document, **kwargs):
if not issubclass(sender, Sample):
return
if kwargs.get('created') is True:
for system in AnalysisSystem.objects():
<|code_end|>
, determine the next line of code. You have imports:
from mass_flask_core.models import Sample, AnalysisSystem, AnalysisRequest
from mass_flask_core.utils.tag_parser import TagParser
and context (class names, function names, or code) available:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/utils/tag_parser.py
# class TagParser:
#
# MAX_TAG_LENGTH = 160
#
# def __init__(self, tag_list):
# self.tag_list = tag_list
# self._init_parser()
#
# def _bool_op(self, t):
# tag = t[0]
# if tag in self.tag_list:
# return True
# else:
# return False
#
# def _bool_and(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 & arg2
#
# def _bool_or(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 | arg2
#
# def _bool_not(self, t):
# arg = t[0][1]
# return not arg
#
# def _init_parser(self):
# TRUE = Keyword('True')
# FALSE = Keyword('False')
# boolOperand = TRUE | FALSE | Regex(r'[a-zA-Z0-9:\-\/]+')
# boolOperand.setParseAction(self._bool_op)
#
# self._parse_expr = infixNotation(
# boolOperand,
# [
# ('not', 1, opAssoc.RIGHT, self._bool_not),
# ('and', 2, opAssoc.LEFT, self._bool_and),
# ('or', 2, opAssoc.LEFT, self._bool_or),
# ])
#
# def parse_string(self, string):
# if string == '':
# return True
# try:
# return self._parse_expr.parseString(string)[0]
# except ParseException:
# return False
. Output only the next line. | _match_sample_and_system(document, system) |
Predict the next line for this snippet: <|code_start|>
def _filter_matches_tags(tags, tag_filter):
return TagParser(tags).parse_string(tag_filter)
def _match_sample_and_system(sample, system):
if system in sample.dispatched_to:
return
if not _filter_matches_tags(sample.tags, system.tag_filter_expression):
return
analysis_request = AnalysisRequest(sample=sample, analysis_system=system)
analysis_request.save()
<|code_end|>
with the help of current file imports:
from mass_flask_core.models import Sample, AnalysisSystem, AnalysisRequest
from mass_flask_core.utils.tag_parser import TagParser
and context from other files:
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/utils/tag_parser.py
# class TagParser:
#
# MAX_TAG_LENGTH = 160
#
# def __init__(self, tag_list):
# self.tag_list = tag_list
# self._init_parser()
#
# def _bool_op(self, t):
# tag = t[0]
# if tag in self.tag_list:
# return True
# else:
# return False
#
# def _bool_and(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 & arg2
#
# def _bool_or(self, t):
# arg1 = t[0][0]
# arg2 = t[0][2]
# return arg1 | arg2
#
# def _bool_not(self, t):
# arg = t[0][1]
# return not arg
#
# def _init_parser(self):
# TRUE = Keyword('True')
# FALSE = Keyword('False')
# boolOperand = TRUE | FALSE | Regex(r'[a-zA-Z0-9:\-\/]+')
# boolOperand.setParseAction(self._bool_op)
#
# self._parse_expr = infixNotation(
# boolOperand,
# [
# ('not', 1, opAssoc.RIGHT, self._bool_not),
# ('and', 2, opAssoc.LEFT, self._bool_and),
# ('or', 2, opAssoc.LEFT, self._bool_or),
# ])
#
# def parse_string(self, string):
# if string == '':
# return True
# try:
# return self._parse_expr.parseString(string)[0]
# except ParseException:
# return False
, which may contain function names, class names, or code. Output only the next line. | sample.dispatched_to.append(system) |
Given the code snippet: <|code_start|>
class AnalysisSystem(db.Document):
identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
verbose_name = StringField(max_length=200, required=True)
<|code_end|>
, generate the next line using the imports in this file:
from mongoengine import StringField
from mass_flask_config.app import db
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
. Output only the next line. | information_text = StringField() |
Given snippet: <|code_start|>
class FlaskTestCase(TestCase):
@staticmethod
def _clean_test_database():
conn = connection.get_connection()
db = connection.get_db()
conn.drop_database(db)
def __call__(self, result=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from mongoengine import connection
from mass_flask_config.app import app
from mass_flask_config.bootstrap import bootstrap_mass_flask
and context:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_config/bootstrap.py
# def bootstrap_mass_flask():
# connect_signals()
# app.register_blueprint(api_blueprint, url_prefix='/api')
# app.register_blueprint(webui_blueprint, url_prefix='/webui')
# app.register_blueprint(scheduling_blueprint, url_prefix='/scheduling')
which might include code, classes, or functions. Output only the next line. | self._pre_setup() |
Predict the next line after this snippet: <|code_start|>
class FlaskTestCase(TestCase):
@staticmethod
def _clean_test_database():
<|code_end|>
using the current file's imports:
from unittest import TestCase
from mongoengine import connection
from mass_flask_config.app import app
from mass_flask_config.bootstrap import bootstrap_mass_flask
and any relevant context from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_config/bootstrap.py
# def bootstrap_mass_flask():
# connect_signals()
# app.register_blueprint(api_blueprint, url_prefix='/api')
# app.register_blueprint(webui_blueprint, url_prefix='/webui')
# app.register_blueprint(scheduling_blueprint, url_prefix='/scheduling')
. Output only the next line. | conn = connection.get_connection() |
Predict the next line for this snippet: <|code_start|>
def _get_instance_with_minimum_count(instance_list):
min_count = sys.maxsize
min_instance = None
for instance in instance_list:
if instance.analyses_count < min_count:
min_count = instance.analyses_count
min_instance = instance
return min_instance
def _schedule_analysis(request, instance):
s = ScheduledAnalysis(analysis_system_instance=instance, sample=request.sample)
s.save()
instance.analyses_count += 1
def _schedule_analysis_request(request, instance_dict):
if request.analysis_system.id not in instance_dict:
return False
instances = instance_dict[request.analysis_system.id]
if len(instances) == 0:
return False
min_instance = _get_instance_with_minimum_count(instances)
_schedule_analysis(request, min_instance)
if min_instance.analyses_count > current_app.config['MAX_SCHEDULE_THRESHOLD']:
instances.remove(min_instance)
<|code_end|>
with the help of current file imports:
import sys
from flask import current_app
from mass_flask_core.models import AnalysisSystemInstance, ScheduledAnalysis, AnalysisRequest
from mass_flask_config.app import app
and context from other files:
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/scheduled_analysis.py
# class ScheduledAnalysis(db.Document):
# analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_scheduled'],
# 'indexes': ['analysis_scheduled']
# }
#
# # @staticmethod
# # def get_count_for_instance(instance):
# # analyses_count = ScheduledAnalysis.objects(analysis_system_instance=instance).count()
# # return analyses_count
#
# # @staticmethod
# # def get_count_for_all_instances():
# # instance_counts = dict()
# # for item in AnalysisSystemInstance.objects:
# # instance_counts[item] = 0
# # for item in ScheduledAnalysis.objects:
# # instance_counts[item.analysis_system_instance] += 1
# # return instance_counts
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
, which may contain function names, class names, or code. Output only the next line. | return True |
Predict the next line for this snippet: <|code_start|>
def _prepare_instance_dict():
instance_dict = {}
instances = AnalysisSystemInstance.objects().no_dereference()
for instance in instances:
if instance.analysis_system.id not in instance_dict.keys():
instance_dict[instance.analysis_system.id] = list()
if not instance.is_online:
<|code_end|>
with the help of current file imports:
import sys
from flask import current_app
from mass_flask_core.models import AnalysisSystemInstance, ScheduledAnalysis, AnalysisRequest
from mass_flask_config.app import app
and context from other files:
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/scheduled_analysis.py
# class ScheduledAnalysis(db.Document):
# analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_scheduled'],
# 'indexes': ['analysis_scheduled']
# }
#
# # @staticmethod
# # def get_count_for_instance(instance):
# # analyses_count = ScheduledAnalysis.objects(analysis_system_instance=instance).count()
# # return analyses_count
#
# # @staticmethod
# # def get_count_for_all_instances():
# # instance_counts = dict()
# # for item in AnalysisSystemInstance.objects:
# # instance_counts[item] = 0
# # for item in ScheduledAnalysis.objects:
# # instance_counts[item.analysis_system_instance] += 1
# # return instance_counts
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
, which may contain function names, class names, or code. Output only the next line. | continue |
Given the following code snippet before the placeholder: <|code_start|> s = ScheduledAnalysis(analysis_system_instance=instance, sample=request.sample)
s.save()
instance.analyses_count += 1
def _schedule_analysis_request(request, instance_dict):
if request.analysis_system.id not in instance_dict:
return False
instances = instance_dict[request.analysis_system.id]
if len(instances) == 0:
return False
min_instance = _get_instance_with_minimum_count(instances)
_schedule_analysis(request, min_instance)
if min_instance.analyses_count > current_app.config['MAX_SCHEDULE_THRESHOLD']:
instances.remove(min_instance)
return True
def schedule_analyses():
with app.app_context():
instance_dict = _prepare_instance_dict()
analysis_requests = AnalysisRequest.objects().no_dereference()
requests_scheduled = 0
requests_not_scheduled = 0
for request in analysis_requests:
if _schedule_analysis_request(request, instance_dict):
request.delete()
<|code_end|>
, predict the next line using imports from the current file:
import sys
from flask import current_app
from mass_flask_core.models import AnalysisSystemInstance, ScheduledAnalysis, AnalysisRequest
from mass_flask_config.app import app
and context including class names, function names, and sometimes code from other files:
# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
# @property
# def is_authenticated(self):
# return True
#
# def get_roles(self):
# return ['analysis_system_instance']
#
# @property
# def max_tlp_level(self):
# return TLPLevelField.TLP_LEVEL_WHITE
#
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
# last_seen = DateTimeField()
#
# meta = {
# 'ordering': ['analysis_system', 'uuid'],
# 'indexes': [('analysis_system', 'uuid')]
# }
#
# def __repr__(self):
# return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
#
# def __str__(self):
# return self.__repr__()
#
# def update_last_seen(self):
# self.last_seen = TimeFunctions.get_timestamp()
# self.save()
#
# @property
# def is_online(self):
# if self.last_seen is None:
# return False
#
# difference = TimeFunctions.get_timestamp() - self.last_seen
# return difference < datetime.timedelta(minutes=10)
#
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
# analysis_system = ReferenceField(AnalysisSystem, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_requested'],
# 'indexes': ['analysis_requested']
# }
#
# def __repr__(self):
# return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/scheduled_analysis.py
# class ScheduledAnalysis(db.Document):
# analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True)
# sample = ReferenceField(Sample, required=True)
# analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# priority = IntField(default=0, required=True)
#
# meta = {
# 'ordering': ['-analysis_scheduled'],
# 'indexes': ['analysis_scheduled']
# }
#
# # @staticmethod
# # def get_count_for_instance(instance):
# # analyses_count = ScheduledAnalysis.objects(analysis_system_instance=instance).count()
# # return analyses_count
#
# # @staticmethod
# # def get_count_for_all_instances():
# # instance_counts = dict()
# # for item in AnalysisSystemInstance.objects:
# # instance_counts[item] = 0
# # for item in ScheduledAnalysis.objects:
# # instance_counts[item.analysis_system_instance] += 1
# # return instance_counts
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
. Output only the next line. | requests_scheduled += 1 |
Predict the next line for this snippet: <|code_start|>
@webui_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
if current_authenticated_entity.is_authenticated:
return redirect(url_for('.profile'))
else:
form = LoginForm()
if form.validate_on_submit():
app.session_provider.login_entity(form.user)
flash('Logged in successfully!', 'success')
return redirect(url_for('.profile'))
return render_template('login.html', form=form)
@webui_blueprint.route('/logout/', methods=['GET'])
@privilege_required(RolePrivilege('user'))
def logout():
app.session_provider.logout_entity()
<|code_end|>
with the help of current file imports:
from flask import flash, render_template, redirect, url_for
from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege
from mass_flask_config.app import app
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.login import LoginForm
and context from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/login.py
# class LoginForm(Form):
# username = StringField(validators=[DataRequired()])
# password = PasswordField(validators=[DataRequired()])
# submit = SubmitField()
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.user = None
#
# def validate(self, extra_validators=None):
# if not super(LoginForm, self).validate():
# return False
# user = User.user_loader(username=self.data['username'], password=self.data['password'])
# if not user:
# flash('Username/password incorrect.', 'warning')
# return False
# else:
# self.user = user
# return True
, which may contain function names, class names, or code. Output only the next line. | flash('Logged out successfully!', 'success') |
Using the snippet: <|code_start|>
@webui_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
if current_authenticated_entity.is_authenticated:
return redirect(url_for('.profile'))
<|code_end|>
, determine the next line of code. You have imports:
from flask import flash, render_template, redirect, url_for
from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege
from mass_flask_config.app import app
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.login import LoginForm
and context (class names, function names, or code) available:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/login.py
# class LoginForm(Form):
# username = StringField(validators=[DataRequired()])
# password = PasswordField(validators=[DataRequired()])
# submit = SubmitField()
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.user = None
#
# def validate(self, extra_validators=None):
# if not super(LoginForm, self).validate():
# return False
# user = User.user_loader(username=self.data['username'], password=self.data['password'])
# if not user:
# flash('Username/password incorrect.', 'warning')
# return False
# else:
# self.user = user
# return True
. Output only the next line. | else: |
Using the snippet: <|code_start|>
@webui_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
if current_authenticated_entity.is_authenticated:
return redirect(url_for('.profile'))
else:
form = LoginForm()
if form.validate_on_submit():
app.session_provider.login_entity(form.user)
flash('Logged in successfully!', 'success')
return redirect(url_for('.profile'))
<|code_end|>
, determine the next line of code. You have imports:
from flask import flash, render_template, redirect, url_for
from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege
from mass_flask_config.app import app
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.login import LoginForm
and context (class names, function names, or code) available:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_webui/config.py
#
# Path: mass_flask_webui/forms/login.py
# class LoginForm(Form):
# username = StringField(validators=[DataRequired()])
# password = PasswordField(validators=[DataRequired()])
# submit = SubmitField()
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.user = None
#
# def validate(self, extra_validators=None):
# if not super(LoginForm, self).validate():
# return False
# user = User.user_loader(username=self.data['username'], password=self.data['password'])
# if not user:
# flash('Username/password incorrect.', 'warning')
# return False
# else:
# self.user = user
# return True
. Output only the next line. | return render_template('login.html', form=form) |
Given the code snippet: <|code_start|>
if __name__ == '__main__':
print('mass-server-flask version' + app.version)
username = input('Please enter username to create: ')
password = getpass(prompt='Please enter the password for the new user: ')
password_verify = getpass(prompt='Enter password again to verify: ')
<|code_end|>
, generate the next line using the imports in this file:
from getpass import getpass
from mass_flask_core.models import User, UserLevel
from mass_flask_config.app import app
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
#
# class UserLevel:
# USER_LEVEL_ANONYMOUS = 0
# USER_LEVEL_USER = 1
# USER_LEVEL_PRIVILEGED = 2
# USER_LEVEL_MANAGER = 3
# USER_LEVEL_ADMIN = 4
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
. Output only the next line. | if password != password_verify: |
Predict the next line after this snippet: <|code_start|>
if __name__ == '__main__':
print('mass-server-flask version' + app.version)
username = input('Please enter username to create: ')
password = getpass(prompt='Please enter the password for the new user: ')
password_verify = getpass(prompt='Enter password again to verify: ')
if password != password_verify:
print('Passwords do not match. Exiting.')
exit(1)
make_admin = False
while True:
input_admin = input('Should the new user have admin privileges? [y/n] ')
if input_admin == 'y':
make_admin = True
break
elif input_admin == 'n':
make_admin = False
break
user = User()
<|code_end|>
using the current file's imports:
from getpass import getpass
from mass_flask_core.models import User, UserLevel
from mass_flask_config.app import app
and any relevant context from other files:
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
#
# class UserLevel:
# USER_LEVEL_ANONYMOUS = 0
# USER_LEVEL_USER = 1
# USER_LEVEL_PRIVILEGED = 2
# USER_LEVEL_MANAGER = 3
# USER_LEVEL_ADMIN = 4
#
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
. Output only the next line. | user.username = username |
Given the code snippet: <|code_start|>
@webui_blueprint.route('/apidocs/')
def apidocs():
return render_template('apidocs.html')
@webui_blueprint.route('/cli_scripts/')
<|code_end|>
, generate the next line using the imports in this file:
from flask import render_template
from mass_flask_webui.config import webui_blueprint
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_webui/config.py
. Output only the next line. | def cli_scripts(): |
Here is a snippet: <|code_start|>
class Comment(db.EmbeddedDocument):
comment = StringField(max_length=1000, verbose_name='Comment', help_text='Leave a comment', required=True)
post_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
user = ReferenceField(User, required=True)
class CommentsMixin:
<|code_end|>
. Write the next line using the current file imports:
from mongoengine import StringField, DateTimeField, ReferenceField, EmbeddedDocumentField, ListField
from mass_flask_config.app import db
from .user import User
from mass_flask_core.utils import TimeFunctions
and context from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
, which may include functions, classes, or code. Output only the next line. | comments = ListField(EmbeddedDocumentField(Comment)) |
Based on the snippet: <|code_start|>
class Comment(db.EmbeddedDocument):
comment = StringField(max_length=1000, verbose_name='Comment', help_text='Leave a comment', required=True)
post_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
user = ReferenceField(User, required=True)
class CommentsMixin:
comments = ListField(EmbeddedDocumentField(Comment))
<|code_end|>
, predict the immediate next line with the help of imports:
from mongoengine import StringField, DateTimeField, ReferenceField, EmbeddedDocumentField, ListField
from mass_flask_config.app import db
from .user import User
from mass_flask_core.utils import TimeFunctions
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/user.py
# class User(db.Document, UserMixin):
# def is_authenticated(self):
# return True
#
# username = StringField(min_length=3, max_length=50, unique=True, required=True)
# password_hash = StringField(min_length=5, max_length=200)
# user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True)
#
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
#
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
#
# def get_id(self):
# return str(self.id)
#
# @staticmethod
# def user_loader(**kwargs):
# if 'username' in kwargs and 'password' in kwargs:
# user = User.objects(username=kwargs['username']).first()
# if user and user.check_password(kwargs['password']):
# return user
# else:
# return None
# elif 'id' in kwargs and kwargs['id']:
# return User.objects(id=ObjectId(kwargs['id'])).first()
# else:
# raise RuntimeError('This access method is not supported by the user loader.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | def add_comment(self, comment, post_date, user): |
Given the code snippet: <|code_start|>
class RequestAnalysisForm(Form):
analysis_system = SelectField('Analysis system', choices=[], validators=[InputRequired()])
priority = IntegerField('Priority', validators=[InputRequired()], default=0)
submit = SubmitField('Request')
def __init__(self):
super(RequestAnalysisForm, self).__init__()
self._query_analysis_system_choices()
<|code_end|>
, generate the next line using the imports in this file:
from flask_wtf import Form
from wtforms import SelectField, IntegerField, SubmitField
from wtforms.validators import InputRequired
from mass_flask_core.models import AnalysisSystem
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
. Output only the next line. | def _query_analysis_system_choices(self): |
Given the code snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
<|code_end|>
, generate the next line using the imports in this file:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | return model_conversion[model_class_name] |
Next line prediction: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
return model_conversion[model_class_name]
else:
<|code_end|>
. Use current file imports:
(from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | raise ValueError('Unsupported model type: {}'.format(model_class_name)) |
Predict the next line for this snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
return model_conversion[model_class_name]
<|code_end|>
with the help of current file imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
, which may contain function names, class names, or code. Output only the next line. | else: |
Continue the code snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
return model_conversion[model_class_name]
<|code_end|>
. Use current file imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context (classes, functions, or code) from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | else: |
Continue the code snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
return model_conversion[model_class_name]
else:
<|code_end|>
. Use current file imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context (classes, functions, or code) from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | raise ValueError('Unsupported model type: {}'.format(model_class_name)) |
Given the following code snippet before the placeholder: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
if model_class_name in model_conversion:
<|code_end|>
, predict the next line using imports from the current file:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context including class names, function names, and sometimes code from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | return model_conversion[model_class_name] |
Here is a snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
<|code_end|>
. Write the next line using the current file imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
, which may include functions, classes, or code. Output only the next line. | if model_class_name in model_conversion: |
Based on the snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
<|code_end|>
, predict the immediate next line with the help of imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | if model_class_name in model_conversion: |
Given the following code snippet before the placeholder: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
<|code_end|>
, predict the next line using imports from the current file:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context including class names, function names, and sometimes code from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
<|code_end|>
using the current file's imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and any relevant context from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | } |
Given the code snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
<|code_end|>
, generate the next line using the imports in this file:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context (functions, classes, or occasionally code) from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
. Output only the next line. | model_conversion = { |
Predict the next line for this snippet: <|code_start|>
class SchemaMapping:
@staticmethod
def get_schema_for_model_class(model_class_name):
model_conversion = {
'Sample': SampleSchema,
'FileSample': FileSampleSchema,
'ExecutableBinarySample': ExecutableBinarySampleSchema,
'IPSample': IPSampleSchema,
'DomainSample': DomainSampleSchema,
'URISample': URISampleSchema,
'SampleRelation': SampleRelationSchema,
'DroppedBySampleRelation': DroppedBySampleRelationSchema,
'ResolvedBySampleRelation': ResolvedBySampleRelationSchema,
'ContactedBySampleRelation': ContactedBySampleRelationSchema,
'RetrievedBySampleRelation': RetrievedBySampleRelationSchema,
'SsdeepSampleRelation': SsdeepSampleRelationSchema,
}
<|code_end|>
with the help of current file imports:
from mass_flask_api.schemas import SampleSchema, FileSampleSchema, ExecutableBinarySampleSchema, ReportSchema, IPSampleSchema, DomainSampleSchema, URISampleSchema
from mass_flask_api.schemas import SampleRelationSchema, DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, ContactedBySampleRelationSchema, RetrievedBySampleRelationSchema, SsdeepSampleRelationSchema
and context from other files:
# Path: mass_flask_api/schemas/report.py
# class ReportSchema(BaseSchema):
# url = URLFor('.report_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name')
# json_report_objects = FileMapField(endpoint='.json_report_object', file_url_key='object_name')
# raw_report_objects = FileMapField(endpoint='.raw_report_object', file_url_key='object_name')
#
# class Meta(BaseSchema.Meta):
# model = Report
# dump_only = [
# 'id',
# '_cls',
# 'upload_date',
# 'status'
# ]
#
# @pre_dump
# def _clean_analysis_date(self, data):
# if data.analysis_date:
# data.analysis_date = data.analysis_date.replace(microsecond=0)
# return data
#
# Path: mass_flask_api/schemas/sample.py
# class SampleSchema(BaseSchema):
# url = URLFor('.sample_detail', id='<id>', _external=True)
# dispatched_to = List(ForeignReferenceField(endpoint='.analysis_system_detail', queryset=AnalysisSystem.objects(), query_parameter='identifier_name'))
#
# class Meta(BaseSchema.Meta):
# model = Sample
# exclude = ['created_by', 'comments']
# dump_only = [
# 'id',
# 'dispatched_to',
# '_cls',
# 'delivery_date'
# ]
#
# class FileSampleSchema(SampleSchema):
# file = URLFor('.sample_download', id='<id>', _external=True)
#
# class Meta(BaseSchema.Meta):
# model = FileSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only + [
# 'file_size',
# 'file_names',
# 'magic_string',
# 'md5sum',
# 'sha1sum',
# 'sha256sum',
# 'sha512sum',
# 'shannon_entropy',
# 'ssdeep_hash'
# ]
#
# class ExecutableBinarySampleSchema(FileSampleSchema):
# class Meta(BaseSchema.Meta):
# model = ExecutableBinarySample
# exclude = ['created_by', 'comments']
# dump_only = FileSampleSchema.Meta.dump_only + [
# 'filesystem_events',
# 'registry_events',
# 'sections',
# 'resources',
# 'imports',
# 'strings'
# ]
#
# class IPSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = IPSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class DomainSampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = DomainSample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# class URISampleSchema(SampleSchema):
# class Meta(BaseSchema.Meta):
# model = URISample
# exclude = ['created_by', 'comments']
# dump_only = SampleSchema.Meta.dump_only
#
# Path: mass_flask_api/schemas/sample_relation.py
# class SampleRelationSchema(BaseSchema):
# url = URLFor('.sample_relation_detail', id='<id>', _external=True)
# sample = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
# other = ForeignReferenceField(endpoint='.sample_detail', queryset=Sample.objects(), query_parameter='id')
#
# class Meta(BaseSchema.Meta):
# model = SampleRelation
# dump_only = [
# 'id',
# '_cls'
# ]
#
# class DroppedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = DroppedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ResolvedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ResolvedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class ContactedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = ContactedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class RetrievedBySampleRelationSchema(SampleRelationSchema):
# class Meta(BaseSchema.Meta):
# model = RetrievedBySampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
#
# class SsdeepSampleRelationSchema(SampleRelationSchema):
# match = Float()
#
# class Meta(BaseSchema.Meta):
# model = SsdeepSampleRelation
# dump_only = SampleRelationSchema.Meta.dump_only
, which may contain function names, class names, or code. Output only the next line. | if model_class_name in model_conversion: |
Based on the snippet: <|code_start|>
class AnalysisRequest(db.Document):
analysis_system = ReferenceField(AnalysisSystem, required=True)
sample = ReferenceField(Sample, required=True)
analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
priority = IntField(default=0, required=True)
meta = {
'ordering': ['-analysis_requested'],
<|code_end|>
, predict the immediate next line with the help of imports:
from mass_flask_config.app import db
from .analysis_system import AnalysisSystem
from .sample import Sample
from mongoengine import DateTimeField, ReferenceField, IntField
from mass_flask_core.utils import TimeFunctions
and context (classes, functions, sometimes code) from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | 'indexes': ['analysis_requested'] |
Here is a snippet: <|code_start|>
class AnalysisRequest(db.Document):
analysis_system = ReferenceField(AnalysisSystem, required=True)
sample = ReferenceField(Sample, required=True)
analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
priority = IntField(default=0, required=True)
meta = {
'ordering': ['-analysis_requested'],
<|code_end|>
. Write the next line using the current file imports:
from mass_flask_config.app import db
from .analysis_system import AnalysisSystem
from .sample import Sample
from mongoengine import DateTimeField, ReferenceField, IntField
from mass_flask_core.utils import TimeFunctions
and context from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
, which may include functions, classes, or code. Output only the next line. | 'indexes': ['analysis_requested'] |
Next line prediction: <|code_start|>
class AnalysisRequest(db.Document):
analysis_system = ReferenceField(AnalysisSystem, required=True)
sample = ReferenceField(Sample, required=True)
analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
priority = IntField(default=0, required=True)
<|code_end|>
. Use current file imports:
(from mass_flask_config.app import db
from .analysis_system import AnalysisSystem
from .sample import Sample
from mongoengine import DateTimeField, ReferenceField, IntField
from mass_flask_core.utils import TimeFunctions)
and context including class names, function names, or small code snippets from other files:
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():
#
# Path: mass_flask_core/models/analysis_system.py
# class AnalysisSystem(db.Document):
# identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True)
# verbose_name = StringField(max_length=200, required=True)
# information_text = StringField()
# tag_filter_expression = StringField(max_length=400, required=True, default='')
#
# meta = {
# 'ordering': ['identifier_name'],
# 'indexes': ['identifier_name']
# }
#
# def __repr__(self):
# return '[AnalysisSystem] {}'.format(self.identifier_name)
#
# def __str__(self):
# return self.__repr__()
#
# Path: mass_flask_core/models/sample.py
# class Sample(db.Document, CommentsMixin):
# delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
# tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$'))
# dispatched_to = ListField(ReferenceField(AnalysisSystem))
# created_by = GenericReferenceField()
# tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True)
#
# meta = {
# 'allow_inheritance': True,
# 'ordering': ['-delivery_date'],
# 'indexes': ['delivery_date'],
# 'queryset_class': SampleQuerySet
# }
#
# def __repr__(self):
# return '[{}] {}'.format(str(self.__class__.__name__), str(self.id))
#
# def __str__(self):
# return self.__repr__()
#
# @property
# def title(self):
# return self.id
#
# def add_tags(self, tags):
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
# self.save()
#
# def _update(self, **kwargs):
# if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen:
# self.first_seen = kwargs['first_seen']
# if 'tlp_level' in kwargs and not self.tlp_level:
# self.tlp_level = kwargs['tlp_level']
# if current_authenticated_entity.is_authenticated and not self.created_by:
# self.created_by = current_authenticated_entity._get_current_object()
# if 'tags' in kwargs:
# tags = kwargs['tags']
# else:
# tags = []
# self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags)
#
# @classmethod
# def create_or_update(cls, **kwargs):
# raise ValidationError('Samples of the base type Sample should not be instantiated directly.')
#
# Path: mass_flask_core/utils/time_functions.py
# class TimeFunctions:
# @staticmethod
# def get_timestamp():
# # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision
# return datetime.now(utc).replace(microsecond=0)
. Output only the next line. | meta = { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.