Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_c... | ) |
Using the snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_create... | ) |
Given snippet: <|code_start|>
class OverviewJSONView(AngularAppMixin, ChartsUtilityMixin, JSONResponseMixin, View):
@allowed_action
def get_data(self, in_data):
return {'views': self.view_count_today(),
'visitors': self.visitor_count_today(),
'unique_visitors': self.un... | def visitor_count_today(self): |
Predict the next line after this snippet: <|code_start|>
class OverviewJSONView(AngularAppMixin, ChartsUtilityMixin, JSONResponseMixin, View):
@allowed_action
def get_data(self, in_data):
return {'views': self.view_count_today(),
'visitors': self.visitor_count_today(),
<|code_end|>
u... | 'unique_visitors': self.unique_visitor_count_today(), |
Using the snippet: <|code_start|> self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts:register'), {
'email': 'testemail@gmail.com',
'password1': 'passwd',
... | }) |
Using the snippet: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts... | def test_website_create(self): |
Next line prediction: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('acco... | request = self.factory.post(reverse('accounts:login'), { |
Predict the next line after this snippet: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory... | def test_website_create(self): |
Continue the code snippet: <|code_start|>
class MonthlyChartView(AngularAppMixin, JSONResponseMixin, ChartsUtilityMixin, View):
num_days = 30
SERIES = (
('page_views', 'Page views'),
('visits', 'Visitors'),
('unique_visitors', 'Unique visitors'),
<|code_end|>
. Use current file import... | ('avg_duration', 'Average view duration'), |
Based on the snippet: <|code_start|>
class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
return self.request.GET['next']
<|code_end|>
, predict the immediate next line with the help... | return reverse_lazy('accounts:website_list') |
Given the following code snippet before the placeholder: <|code_start|>
class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
<|code_end|>
, predict the next line using imports from the current f... | return self.request.GET['next'] |
Given the code snippet: <|code_start|>class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
return self.request.GET['next']
return reverse_lazy('accounts:website_list')
def ... | return super(RegisterView, self).form_valid(form) |
Given snippet: <|code_start|>class RegisterView(FormView):
template_name = 'accounts/register.html'
form_class = EmailUserCreationForm
success_url = reverse_lazy('accounts:login')
def form_valid(self, form):
form.save()
messages.success(self.request, 'Registration successful, you can no... | return self.request.user.website_set.order_by('pk') |
Predict the next line after this snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='website/home.html'), name='home'),
url(r'^learnmore$', TemplateView.as_view(template_name='website/learnmore.html'), name='learnmore'),
url(r'^report/$', ReportView.as_view(), na... | url(r'api/', include('core.apiurls', namespace='api')), |
Given the code snippet: <|code_start|> return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
class ChartsUtilityMixin(object):
num_days = None
@property
def pageviews(self):
return PageView.objects.filter(session__website=self.kwargs['website_id'])
@property
... | timestamp__gt=self.today_midnight() - timezone.timedelta(days=1)) |
Predict the next line for this snippet: <|code_start|> def get_website(self):
try:
website = Website.objects.get(pk=self.kwargs['website_id'])
except Website.DoesNotExist:
raise Http404('No such website.')
if website.user != self.request.user:
raise Permiss... | def sessions(self): |
Given snippet: <|code_start|>class ChartsUtilityMixin(object):
num_days = None
@property
def pageviews(self):
return PageView.objects.filter(session__website=self.kwargs['website_id'])
@property
def pageviews_today(self):
return self.pageviews.filter(view_timestamp__gt=self.today_m... | return timezone.now().astimezone(self.get_website().timezone) - timezone.timedelta(**kwargs) |
Given the following code snippet before the placeholder: <|code_start|>
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class AngularAppMixin(LoginRequiredMixin):
def get_web... | raise Http404('No such website.') |
Based on the snippet: <|code_start|>
class Website(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=255)
url = models.URLField()
timezone = TimeZoneField()
def __unicode__(self):
return self.name
def view_count_today(self):
... | uuid = models.CharField(max_length=50) |
Based on the snippet: <|code_start|> """Request to cancel an activity task failed"""
def __init__(self, event_id, activity_id, cause, decision_task_completed_event_id):
super(RequestCancelActivityTaskFailedError, self).__init__(
event_id, activity_id, decision_task_completed_event_id)
... | self.workflow_execution) |
Using the snippet: <|code_start|> def task_func():
task_raises_recursive()
@task_func.do_except
def except_func(err):
self.tb_str = format_exc()
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue... | main() |
Given the code snippet: <|code_start|> self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_format(self):
@task
def task_func():
raise RuntimeError("Test")
@task_func... | strfile = six.StringIO() |
Using the snippet: <|code_start|> raise RuntimeError("Test")
count -= 1
task_raises_recursive(count)
@task
def task_func():
task_raises_recursive()
@task_func.do_except
def except_func(err):
self.tb_str = format_exc()
... | except RuntimeError: |
Continue the code snippet: <|code_start|>
def setUp(self):
self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_format(self):
@task
def task_func():
raise RuntimeError("T... | @task_func.do_except |
Predict the next line for this snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures('core_debug')
class TestTraceback(unittest.TestCase):
def setUp(self):
self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifi... | def test_print(self): |
Here is a snippet: <|code_start|> @task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
strfile = six.StringIO()
print_exc(file=strfile)
self.tb_str = strfile.getvalue()
ev = AsyncEventLoop()
... | @task_func.do_except |
Given the following code snippet before the placeholder: <|code_start|>
class TestDecisionList(unittest.TestCase):
def test_delete_decision(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
self.assertTrue(dlist)
dlist.delete_decision(decisions.Ca... | swf_list = dlist.to_swf() |
Next line prediction: <|code_start|>
class TestDecisionList(unittest.TestCase):
def test_delete_decision(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
self.assertTrue(dlist)
dlist.delete_decision(decisions.CancelTimer, 999)
self.assert... | unittest.main() |
Using the snippet: <|code_start|> 'startToCloseTimeout': '6', 'taskPriority': '100', 'input': 'input'}
decision = decisions.ScheduleActivityTask(
activity_id="activity_id", activity_type_name="name", activity_type_version="1.0").decision
assert 'taskList' not in decision['scheduleActivityTaskDec... | tag_list=['tag', 'list'], task_list="task_list", task_start_to_close_timeout="3", task_priority='100').decision |
Predict the next line after this snippet: <|code_start|>
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
<|code_end|>
using the current ... | self._context = None |
Given snippet: <|code_start|>
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
self._context = None
self.set_context(s... | def __exit__(self, exc_type, exc_val, exc_tb): |
Next line prediction: <|code_start|> ('TypeAlreadyExistsFault', swf_exceptions.TypeAlreadyExistsError),
('OperationNotPermittedFault', swf_exceptions.OperationNotPermittedError),
('UnknownResourceFault', swf_exceptions.UnknownResourceError),
('SWFResponseError', swf_exceptions.SWFResponseError),
('Th... | exception = RuntimeError("Not handled by swf_exception_wrapper") |
Given the following code snippet before the placeholder: <|code_start|> with self:
task = AsyncTask(self.finally_func, context=self,
name=self.finally_func.__name__)
task.daemon = self.daemon
task.cancellable = False
... | args.append("except_func=%r" % self.except_func.__name__) |
Continue the code snippet: <|code_start|> @abc.abstractmethod
def handle_exception(self, error):
raise NotImplementedError()
class AsyncTaskContext(AbstractAsyncTaskContext):
def __init__(self, daemon=False, parent=None, name=None):
self._setup()
self.daemon = daemon
self.... | if child.daemon: |
Based on the snippet: <|code_start|> else:
self.update_parent()
def __enter__(self):
self._parent_context = get_async_context()
set_async_context(self)
return self
def __exit__(self, exc_type, err, tb):
set_async_context(self._parent_context)
self._pa... | args.insert(0, "") |
Continue the code snippet: <|code_start|> def handle_exception(self, exception, tb_list=None):
if DEBUG:
log.debug("Handling exception %r %r", self, exception)
if self.exception is None \
or not isinstance(exception, CancellationError):
self.exception = exception
... | def schedule_task(self, task, now=False): |
Based on the snippet: <|code_start|> else:
self.update_parent()
def __enter__(self):
self._parent_context = get_async_context()
set_async_context(self)
return self
def __exit__(self, exc_type, err, tb):
set_async_context(self._parent_context)
self._pa... | args.insert(0, "") |
Based on the snippet: <|code_start|>
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
pass
@signal()
def signal1(self):
pass
class SubSpamWorkflow(SpamWorkflow):
@execute('1.1', ... | assert set(SubSpamWorkflow._workflow_types.values()) == {'execute0', 'execute1'} |
Predict the next line for this snippet: <|code_start|>
class SpamWorkflow(wodef.WorkflowDefinition):
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
pass
@signal()
def signal1(self):
... | class SubSpamWorkflow(SpamWorkflow): |
Given snippet: <|code_start|>
class SpamWorkflow(wodef.WorkflowDefinition):
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports... | pass |
Predict the next line after this snippet: <|code_start|>
class TestUtils(unittest.TestCase):
def test_camel_keys_to_snake_case(self):
d = {
'workflowType': 'A',
'taskList': 'B',
'childPolicy': 'C',
'executionStartToCloseTimeout': 'D',
'taskStart... | }) |
Based on the snippet: <|code_start|>
class TestUtils(unittest.TestCase):
def test_camel_keys_to_snake_case(self):
d = {
'workflowType': 'A',
'taskList': 'B',
'childPolicy': 'C',
'executionStartToCloseTimeout': 'D',
'taskStartToCloseTimeout': 'E',... | 'workflow_type': 'A', |
Here is a snippet: <|code_start|># Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
#... | DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" |
Based on the snippet: <|code_start|># pragma: no cover
warnings.warn("This module is deprecated. Please use the new API", DeprecationWarning)
SESSION_KEY = "__esteid_session"
class EsteidSessionError(Exception):
pass
def get_esteid_session(request):
return request.session.get(SESSION_KEY, {})
def st... | session[SESSION_KEY] = data # Django session object requires setting keys explicitly |
Next line prediction: <|code_start|>
ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
<|code_end|>
. Use current file imports:
(import re
from esteid.constants import Countries
from esteid.excep... | def id_code_ee_is_valid(id_code: str) -> bool: |
Based on the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
... | ] |
Predict the next line after this snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
url... | url(r"^flowtest/", include(esteid.flowtest.urls)), |
Here is a snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
u... | ] |
Using the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
u... | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Predict the next line after this snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
url... | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Using the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
u... | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_alg... | [ |
Using the snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_algo_fai... | pytest.param("60001019906", True, id="test MobileID code"), |
Predict the next line for this snippet: <|code_start|> [
pytest.param("", False, id="empty string"),
pytest.param(None, False, id="None"),
pytest.param(["30303039914"], False, id="list"),
pytest.param("ABCDEFGHQWE", False, id="not digits"),
pytest.param("10101010", False, id="... | pytest.param("010101-10006", True, id="test MobileID code"), |
Next line prediction: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
<|code_end|>
. Use current file imports:
(import hashlib
import pytest
from esteid.co... | assert hash_value == hash_method(b"FOOBAR").digest() |
Given snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_algo_fails()... | pytest.param("123456789O123456", False, id="too many digits"), |
Using the snippet: <|code_start|>
def esteid_services(*_, **__):
return {
"ESTEID_DEMO": settings.ESTEID_DEMO,
"ID_CARD_ENABLED": settings.ID_CARD_ENABLED,
"MOBILE_ID_ENABLED": settings.MOBILE_ID_ENABLED,
"MOBILE_ID_TEST_MODE": settings.MOBILE_ID_TEST_MODE,
"SMART_ID_ENABLED... | } |
Given the code snippet: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
<|code_end|>
, generate the next line using the imports in this file:
import json
import logging
from htt... | if TYPE_CHECKING: |
Next line prediction: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
if TYPE_CHECKING:
# Make type checkers aware of request.session attribute which is missing on the HttpRe... | class RequestType(HttpRequest): |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
if TYPE_CHECKING:
# Make type checkers aware of request.session attribute which is mis... | session: base_session.AbstractBaseSession |
Given snippet: <|code_start|>
@pytest.mark.parametrize(
"hash_value,expected_verification_code",
[
(b"\x00\x00", "0000"),
(b"00", "1584"),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
import pytest
from ..utils import get_verification_cod... | (hashlib.sha256(b"test").digest(), "5000"), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize(
"common_name,expected_name",
[
("TESTNUMBER,SEITSMES,51001091072", "Seitsmes Testnumber"),
("TESTNUMBER\\,SEITSMES\\,51001091072", "Seitsmes Testnumber"),
("TEST-NUMBER,SEITSMES MEES,51001091072", "S... | "common_name,expected_id", |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"lang_code, result",
[
*[(code.upper(), code) for code in Languages.ALL],
*[(code.lower(), code) for code in Languages.ALL],
*[(alpha2.upper(), code) for alpha2, code in Languages._MAP_ISO_639_1_TO_MID.items()],
... | ("EST", "EST"), |
Based on the snippet: <|code_start|>
@pytest.fixture()
def idcardsigner():
signer = IdCardSigner({}, initial=True)
mock_container = Mock(name="mock_container")
with patch.object(signer, "open_container", return_value=mock_container), patch.object(signer, "save_session_data"):
mock_container.prepa... | "digest_b64": "MTIz", |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture()
def idcardsigner():
signer = IdCardSigner({}, initial=True)
mock_container = Mock(name="mock_container")
with patch.object(signer, "open_container", return_value=mock_container), patch.object(signer, "save_session_data"):
mo... | "timestamp": int(time()), |
Predict the next line after this snippet: <|code_start|> with pytest.raises(InvalidParameter, match="Failed to decode"):
signer.setup({"certificate": b"something not hex-encoded"})
with pytest.raises(InvalidParameter, match="supported certificate format"):
signer.setup({"certificate": binascii.b... | def test_idcardsigner_finalize(pyasice_mock, idcard_session_data): |
Predict the next line for this snippet: <|code_start|>
validity = cert_asn1["tbs_certificate"]["validity"].native
valid_from: datetime = validity["not_before"]
valid_to: datetime = validity["not_after"]
return cls(
issuer=issuer.human_friendly,
issuer_serial=str(... | @staticmethod |
Given snippet: <|code_start|> @classmethod
def from_dict(cls, the_dict):
return cls(**camel_2_py(the_dict))
@attr.s
class CertificatePolicy(FromDictMixin):
oid = attr.ib()
url = attr.ib(default=None)
description = attr.ib(default=None)
@attr.s
class Certificate(FromDictMixin):
issuer ... | def from_certificate(cls, cert: "Union[bytes, Asn1CryptoCertificate, OsCryptoCertificate]"): |
Predict the next line after this snippet: <|code_start|> def from_dict(cls, the_dict):
return cls(**camel_2_py(the_dict))
@attr.s
class CertificatePolicy(FromDictMixin):
oid = attr.ib()
url = attr.ib(default=None)
description = attr.ib(default=None)
@attr.s
class Certificate(FromDictMixin):
... | if isinstance(cert, bytes): |
Next line prediction: <|code_start|>
if TYPE_CHECKING:
class FromDictMixin(object):
@classmethod
<|code_end|>
. Use current file imports:
(from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certifica... | def from_dict(cls, the_dict): |
Given the code snippet: <|code_start|> )
@classmethod
def from_certificate(cls, cert: "Union[bytes, Asn1CryptoCertificate, OsCryptoCertificate]"):
if isinstance(cert, bytes):
cert = load_certificate(cert)
cert_asn1: "Asn1CryptoCertificate" = getattr(cert, "asn1", cert)
pe... | class Signer(FromDictMixin): |
Here is a snippet: <|code_start|>
validity = cert_asn1["tbs_certificate"]["validity"].native
valid_from: datetime = validity["not_before"]
valid_to: datetime = validity["not_after"]
return cls(
issuer=issuer.human_friendly,
issuer_serial=str(serial),
... | @staticmethod |
Continue the code snippet: <|code_start|>
sign_session = service.sign(...)
mobileidsigner.save_session_data.assert_called_once_with(
digest=sign_session.digest,
container=container,
xml_sig=xml_sig,
session_id=sign_session.session_id,
)
assert result["verification_code"... | mobileid_session_data["session_id"], |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"data,error",
[
pytest.param(
None,
InvalidParameters,
id="No data",
),
pytest.param(
{},
InvalidParameters,
id="Empty data",
),
pytes... | pytest.param( |
Given the following code snippet before the placeholder: <|code_start|> InvalidParameters,
id="No data",
),
pytest.param(
{},
InvalidParameters,
id="Empty data",
),
pytest.param(
{"id_code": "asdf", "phone_number": "a... | def test_mobileidsigner_setup(data, error): |
Continue the code snippet: <|code_start|> id="Empty data",
),
pytest.param(
{"id_code": "asdf", "phone_number": "asdf"},
InvalidParameter,
id="Invalid Phone",
),
pytest.param(
{"id_code": "asdf", "phone_number": "+37200000766"},
... | signer.setup(data) |
Next line prediction: <|code_start|>def test_mobileidsigner_prepare(mobileidsigner, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice):
mobileidsigner.setup({"id_code": MID_DEMO_PIN_EE_OK, "phone_number": MID_DEMO_PHONE_EE_OK})
result = mobileidsigner.prepare(None, [])
mobileidsigner.open_containe... | session_id=sign_session.session_id, |
Predict the next line for this snippet: <|code_start|> session_id=sign_session.session_id,
)
assert result["verification_code"] == sign_session.verification_code
@patch.object(signer_module, "Container")
@patch.object(signer_module, "XmlSignature")
def test_mobileidsigner_finalize(
XmlSignatureMoc... | ContainerMock.open.assert_called_once_with(mobileid_session_data["temp_container_file"]) |
Based on the snippet: <|code_start|>
TEST_TXT = "test.txt"
TEST_TXT_CONTENT = b"Hello"
@pytest.fixture()
def test_txt(tmp_path):
# Can't pass fixtures to parametrize() so we need a well-known file name for a parameterized test.
# tmp_path is pytest's builtin fixture with a temporary path as a pathlib.Path... | f.write(TEST_TXT_CONTENT) |
Predict the next line for this snippet: <|code_start|>
TEST_TXT = "test.txt"
TEST_TXT_CONTENT = b"Hello"
@pytest.fixture()
def test_txt(tmp_path):
# Can't pass fixtures to parametrize() so we need a well-known file name for a parameterized test.
# tmp_path is pytest's builtin fixture with a temporary path... | TypeError(""), |
Based on the snippet: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
"hash_type",
"hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
"... | "certificate_level", |
Predict the next line after this snippet: <|code_start|> "hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
"document_number",
"certificate", # DER-encoded certificate
"certificate_b6... | "signature_algorithm", |
Given the code snippet: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
"hash_type",
"hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
... | [ |
Given the following code snippet before the placeholder: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from typing import Optional
from esteid.constants... | "hash_type", |
Predict the next line for this snippet: <|code_start|>
def test_context_processors_esteid_services(override_esteid_settings):
test_settings = {
"ESTEID_DEMO": 1,
"ID_CARD_ENABLED": 2,
"MOBILE_ID_ENABLED": 3,
"MOBILE_ID_TEST_MODE": 4,
"SMART_ID_ENABLED": 5,
<|code_end|>
with... | "SMART_ID_TEST_MODE": 6, |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize(
"expected_verification_code,hash_raw",
[
("7712", b"Hello World!"),
("3404", b"You broke it, didn't you."),
("0914", b"Weeeeeeeeeeeeeeeeeeeeee[bzzt]"),
],
)
<|code_end|>
, predict the ... | def test_verification_code_generator(expected_verification_code, hash_raw): |
Next line prediction: <|code_start|>
@pytest.mark.parametrize(
"expected_verification_code,hash_raw",
[
("7712", b"Hello World!"),
("3404", b"You broke it, didn't you."),
("0914", b"Weeeeeeeeeeeeeeeeeeeeee[bzzt]"),
<|code_end|>
. Use current file imports:
(import pytest
from esteid.co... | ], |
Predict the next line after this snippet: <|code_start|>
# 3rd Party
# Local Apps
class WelcomeEmail(generics.EmailSendable, GrapevineModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="welcome_emails")
try:
# In Django 1.7, this is finally addressed!
objects = WelcomeEm... | return {"to": [self.user.email], "bcc": ["top@secret.com"]} |
Continue the code snippet: <|code_start|>from __future__ import unicode_literals
# Django
# 3rd Party
# Local Apps
class WelcomeEmail(generics.EmailSendable, GrapevineModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="welcome_emails")
try:
# In Django 1.7, this is finally add... | class Meta: |
Given snippet: <|code_start|>
@property
def admin_view_info(self):
return '%s_%s' % self.model_meta_info
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
if obj:
context['additional_object_tools'] = self.additional_object_tools(obj)... | pass |
Here is a snippet: <|code_start|> return (self.model._meta.app_label, self.model._meta.model_name,)
@property
def admin_view_info(self):
return '%s_%s' % self.model_meta_info
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
if obj:
... | except NoReverseMatch: |
Predict the next line after this snippet: <|code_start|># 3rd Party
# from celery import shared_task
try:
# This library isn't absolutely required until you
# want to use the SendGrid backend
except ImportError:
pass
# Local Apps
class EmailBackend(GrapevineEmailBackend):
DISPLAY_NAME = "sendgrid"
... | "spamreport": "Spam Report" |
Given snippet: <|code_start|>from __future__ import unicode_literals
# Django
# 3rd Party
class UserFactory(factory.django.DjangoModelFactory):
username = factory.fuzzy.FuzzyText(length=10)
first_name = factory.fuzzy.FuzzyText(length=10)
last_name = factory.fuzzy.FuzzyText(length=10)
email = factory... | class EmailFactory(factory.django.DjangoModelFactory): |
Predict the next line for this snippet: <|code_start|># Sys
try:
except ImportError:
try:
except:
# Django
# Local
<|code_end|>
with the help of current file imports:
import json
import requests
from cStringIO import StringIO
from StringIO import StringIO
from io import StringIO
from... | class MailgunAPIError(Exception): |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class GrapevineEmailBackend(BaseEmailBackend):
# Used to register a callback url for the 3rd party
DISPLAY_NAME = None
# Used to process catalog events
IMPORT_PATH = None
LISTENS_FOR_EVENTS = True
... | return urls |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class GrapevineEmailBackend(BaseEmailBackend):
# Used to register a callback url for the 3rd party
DISPLAY_NAME = None
# Used to process catalog events
IMPORT_PATH = ... | LISTENS_FOR_EVENTS = True |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class EmailSendable(mixins.Emailable, mixins.SendableMixin):
class Meta(mixins.SendableMixin.Meta):
abstract = True
if 'tablets' in settings.INSTALLED_APPS:
class EmailTemplateSendable(mixins.Emaila... | abstract = True |
Given the following code snippet before the placeholder: <|code_start|> select_related = ['article__site_owner', 'contributor__user']
def get_queryset(self):
queryset = super(UserDetailView, self).get_queryset()
return queryset.select_related(*self.select_related)
class UserRedirectView(LoginR... | class UserListView(LoginRequiredMixin, ListView): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Import the reverse lookup function
# view imports
class UserDetailView(LoginRequiredMixin, SelectRelatedMixin, DetailView):
model = User
select_related = ['article__site_owner', 'contributor__user']
def get_queryset(self):
quer... | permanent = False |
Continue the code snippet: <|code_start|>
def tearDown(self):
if os.path.isdir(self.db):
shutil.rmtree(self.db)
def create_db(self, files):
self.db = tempfile.mkdtemp()
for filename, content in files.items():
open(os.path.join(self.db, filename), 'w+').write(cont... | key: value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.