Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
TNX_ID_RE = re.compile(ur'^\w{1,30}$')
class RequestPaymentForm(forms.Form):
txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
to = forms.IntegerField(
label=_('10 digits phone number'),
max_value=9999999999,
widget=forms.TextInput(attrs={'maxlength':'10'})
)
summ = forms.DecimalField(
max_digits=MAX_MONEY_DIGITS,
decimal_places=MAX_MONEY_PLACES,
<|code_end|>
with the help of current file imports:
import re
from django import forms
from django.utils.translation import ugettext_lazy as _
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES
from payway.qiwi.conf.settings import QIWI_PERCENT
and context from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# Path: payway/qiwi/conf/settings.py
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
, which may contain function names, class names, or code. Output only the next line. | label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')), |
Using the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
url(r'^add-money/(?P<account_uid>\d+)/(?P<invoice_uid>\d+)$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/(?P<account_uid>\d+)/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from payway.accounts.views.add_account import AddAccountView
from payway.accounts.views.add_money import AddMoneyView
from payway.accounts.views.invoices_list import InvoicesListListView
from payway.accounts.views.list import AccountsListView
from payway.accounts.views.statement import AccountStatementView
and context (class names, function names, or code) available:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/accounts/views/add_money.py
# class AddMoneyView(TemplateView):
# template_name = 'accounts/add_money.html'
#
# def get(self, request, *args, **kwargs):
#
# account_uid = int(kwargs.get('account_uid', -1))
# invoice_uid = int(kwargs.get('invoice_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoice, created = Invoice.objects.get_or_create(
# uid=invoice_uid,
# account=account,
# defaults={
# 'account': account,
# 'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
# }
# )
#
# context = super(AddMoneyView, self).get_context_data(**kwargs)
# context['add_money_form'] = AddMoneyForm({
# 'money_amount': invoice.money_amount_without_percent.amount,
# 'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
# 'invoice_uid': invoice.uid
# })
#
# return self.render_to_response(context)
#
# def post(self, request):
# form = AddMoneyForm(request.POST or None)
# if form.is_valid():
# invoice = get_object_or_404(Invoice, uid=form.cleaned_data.get('invoice_uid'))
# new_money_amount = form.cleaned_data.get('money_amount')
# invoice.money_amount = Money(new_money_amount, invoice.money_amount.currency)
# invoice.save()
# return redirect(form.cleaned_data['payment_system'], invoice_uid=invoice.uid)
#
# return self.render_to_response({'add_money_form': form})
#
# Path: payway/accounts/views/invoices_list.py
# class InvoicesListListView(TemplateView):
# template_name = 'accounts/invoices_list.html'
#
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoices_page = create_paginated_page(
# query_set=account.invoices.all().order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=INVOICES_PER_PAGE
# )
# return self.render_to_response({'invoices_page': invoices_page})
#
# Path: payway/accounts/views/list.py
# class AccountsListView(TemplateView):
# template_name = 'accounts/list.html'
#
# def get(self, request):
# accounts_page = create_paginated_page(
# query_set=Account.objects.filter(user=request.user).order_by('-id'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ACCOUNTS_PER_PAGE
# )
# return self.render_to_response({'accounts_page': accounts_page })
#
# Path: payway/accounts/views/statement.py
# class AccountStatementView(TemplateView):
# template_name = 'accounts/statement.html'
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# transactions_page = create_paginated_page(
# query_set=Transaction.objects.filter(account=account).order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=TRANSACTIONS_PER_PAGE
# )
# return self.render_to_response({'transactions_page': transactions_page})
. Output only the next line. | url(r'^add-account/currency/(?P<currency>\w{3})$', login_required(AddAccountView.as_view()), name='accounts_add_account'), |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from payway.accounts.views.add_account import AddAccountView
from payway.accounts.views.add_money import AddMoneyView
from payway.accounts.views.invoices_list import InvoicesListListView
from payway.accounts.views.list import AccountsListView
from payway.accounts.views.statement import AccountStatementView
and context including class names, function names, and sometimes code from other files:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/accounts/views/add_money.py
# class AddMoneyView(TemplateView):
# template_name = 'accounts/add_money.html'
#
# def get(self, request, *args, **kwargs):
#
# account_uid = int(kwargs.get('account_uid', -1))
# invoice_uid = int(kwargs.get('invoice_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoice, created = Invoice.objects.get_or_create(
# uid=invoice_uid,
# account=account,
# defaults={
# 'account': account,
# 'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
# }
# )
#
# context = super(AddMoneyView, self).get_context_data(**kwargs)
# context['add_money_form'] = AddMoneyForm({
# 'money_amount': invoice.money_amount_without_percent.amount,
# 'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
# 'invoice_uid': invoice.uid
# })
#
# return self.render_to_response(context)
#
# def post(self, request):
# form = AddMoneyForm(request.POST or None)
# if form.is_valid():
# invoice = get_object_or_404(Invoice, uid=form.cleaned_data.get('invoice_uid'))
# new_money_amount = form.cleaned_data.get('money_amount')
# invoice.money_amount = Money(new_money_amount, invoice.money_amount.currency)
# invoice.save()
# return redirect(form.cleaned_data['payment_system'], invoice_uid=invoice.uid)
#
# return self.render_to_response({'add_money_form': form})
#
# Path: payway/accounts/views/invoices_list.py
# class InvoicesListListView(TemplateView):
# template_name = 'accounts/invoices_list.html'
#
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoices_page = create_paginated_page(
# query_set=account.invoices.all().order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=INVOICES_PER_PAGE
# )
# return self.render_to_response({'invoices_page': invoices_page})
#
# Path: payway/accounts/views/list.py
# class AccountsListView(TemplateView):
# template_name = 'accounts/list.html'
#
# def get(self, request):
# accounts_page = create_paginated_page(
# query_set=Account.objects.filter(user=request.user).order_by('-id'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ACCOUNTS_PER_PAGE
# )
# return self.render_to_response({'accounts_page': accounts_page })
#
# Path: payway/accounts/views/statement.py
# class AccountStatementView(TemplateView):
# template_name = 'accounts/statement.html'
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# transactions_page = create_paginated_page(
# query_set=Transaction.objects.filter(account=account).order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=TRANSACTIONS_PER_PAGE
# )
# return self.render_to_response({'transactions_page': transactions_page})
. Output only the next line. | url(r'^add-money/(?P<account_uid>\d+)/(?P<invoice_uid>\d+)$', login_required(AddMoneyView.as_view()), name='accounts_add_money'), |
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
url(r'^add-money/(?P<account_uid>\d+)/(?P<invoice_uid>\d+)$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/(?P<account_uid>\d+)/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-account/currency/(?P<currency>\w{3})$', login_required(AddAccountView.as_view()), name='accounts_add_account'),
url(r'^list/$', login_required(AccountsListView.as_view()), name='accounts_list'),
url(r'^statement/(?P<account_uid>\d+)/$', login_required(AccountStatementView.as_view()), name='accounts_statement'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from payway.accounts.views.add_account import AddAccountView
from payway.accounts.views.add_money import AddMoneyView
from payway.accounts.views.invoices_list import InvoicesListListView
from payway.accounts.views.list import AccountsListView
from payway.accounts.views.statement import AccountStatementView
and context from other files:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/accounts/views/add_money.py
# class AddMoneyView(TemplateView):
# template_name = 'accounts/add_money.html'
#
# def get(self, request, *args, **kwargs):
#
# account_uid = int(kwargs.get('account_uid', -1))
# invoice_uid = int(kwargs.get('invoice_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoice, created = Invoice.objects.get_or_create(
# uid=invoice_uid,
# account=account,
# defaults={
# 'account': account,
# 'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
# }
# )
#
# context = super(AddMoneyView, self).get_context_data(**kwargs)
# context['add_money_form'] = AddMoneyForm({
# 'money_amount': invoice.money_amount_without_percent.amount,
# 'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
# 'invoice_uid': invoice.uid
# })
#
# return self.render_to_response(context)
#
# def post(self, request):
# form = AddMoneyForm(request.POST or None)
# if form.is_valid():
# invoice = get_object_or_404(Invoice, uid=form.cleaned_data.get('invoice_uid'))
# new_money_amount = form.cleaned_data.get('money_amount')
# invoice.money_amount = Money(new_money_amount, invoice.money_amount.currency)
# invoice.save()
# return redirect(form.cleaned_data['payment_system'], invoice_uid=invoice.uid)
#
# return self.render_to_response({'add_money_form': form})
#
# Path: payway/accounts/views/invoices_list.py
# class InvoicesListListView(TemplateView):
# template_name = 'accounts/invoices_list.html'
#
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoices_page = create_paginated_page(
# query_set=account.invoices.all().order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=INVOICES_PER_PAGE
# )
# return self.render_to_response({'invoices_page': invoices_page})
#
# Path: payway/accounts/views/list.py
# class AccountsListView(TemplateView):
# template_name = 'accounts/list.html'
#
# def get(self, request):
# accounts_page = create_paginated_page(
# query_set=Account.objects.filter(user=request.user).order_by('-id'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ACCOUNTS_PER_PAGE
# )
# return self.render_to_response({'accounts_page': accounts_page })
#
# Path: payway/accounts/views/statement.py
# class AccountStatementView(TemplateView):
# template_name = 'accounts/statement.html'
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# transactions_page = create_paginated_page(
# query_set=Transaction.objects.filter(account=account).order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=TRANSACTIONS_PER_PAGE
# )
# return self.render_to_response({'transactions_page': transactions_page})
, which may include functions, classes, or code. Output only the next line. | url(r'^invoices/(?P<account_uid>\d+)/$', login_required(InvoicesListListView.as_view()), name='accounts_invoices'), |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
url(r'^add-money/(?P<account_uid>\d+)/(?P<invoice_uid>\d+)$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/(?P<account_uid>\d+)/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-account/currency/(?P<currency>\w{3})$', login_required(AddAccountView.as_view()), name='accounts_add_account'),
<|code_end|>
with the help of current file imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from payway.accounts.views.add_account import AddAccountView
from payway.accounts.views.add_money import AddMoneyView
from payway.accounts.views.invoices_list import InvoicesListListView
from payway.accounts.views.list import AccountsListView
from payway.accounts.views.statement import AccountStatementView
and context from other files:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/accounts/views/add_money.py
# class AddMoneyView(TemplateView):
# template_name = 'accounts/add_money.html'
#
# def get(self, request, *args, **kwargs):
#
# account_uid = int(kwargs.get('account_uid', -1))
# invoice_uid = int(kwargs.get('invoice_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoice, created = Invoice.objects.get_or_create(
# uid=invoice_uid,
# account=account,
# defaults={
# 'account': account,
# 'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
# }
# )
#
# context = super(AddMoneyView, self).get_context_data(**kwargs)
# context['add_money_form'] = AddMoneyForm({
# 'money_amount': invoice.money_amount_without_percent.amount,
# 'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
# 'invoice_uid': invoice.uid
# })
#
# return self.render_to_response(context)
#
# def post(self, request):
# form = AddMoneyForm(request.POST or None)
# if form.is_valid():
# invoice = get_object_or_404(Invoice, uid=form.cleaned_data.get('invoice_uid'))
# new_money_amount = form.cleaned_data.get('money_amount')
# invoice.money_amount = Money(new_money_amount, invoice.money_amount.currency)
# invoice.save()
# return redirect(form.cleaned_data['payment_system'], invoice_uid=invoice.uid)
#
# return self.render_to_response({'add_money_form': form})
#
# Path: payway/accounts/views/invoices_list.py
# class InvoicesListListView(TemplateView):
# template_name = 'accounts/invoices_list.html'
#
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoices_page = create_paginated_page(
# query_set=account.invoices.all().order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=INVOICES_PER_PAGE
# )
# return self.render_to_response({'invoices_page': invoices_page})
#
# Path: payway/accounts/views/list.py
# class AccountsListView(TemplateView):
# template_name = 'accounts/list.html'
#
# def get(self, request):
# accounts_page = create_paginated_page(
# query_set=Account.objects.filter(user=request.user).order_by('-id'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ACCOUNTS_PER_PAGE
# )
# return self.render_to_response({'accounts_page': accounts_page })
#
# Path: payway/accounts/views/statement.py
# class AccountStatementView(TemplateView):
# template_name = 'accounts/statement.html'
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# transactions_page = create_paginated_page(
# query_set=Transaction.objects.filter(account=account).order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=TRANSACTIONS_PER_PAGE
# )
# return self.render_to_response({'transactions_page': transactions_page})
, which may contain function names, class names, or code. Output only the next line. | url(r'^list/$', login_required(AccountsListView.as_view()), name='accounts_list'), |
Given the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
url(r'^add-money/(?P<account_uid>\d+)/(?P<invoice_uid>\d+)$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/(?P<account_uid>\d+)/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-money/$', login_required(AddMoneyView.as_view()), name='accounts_add_money'),
url(r'^add-account/currency/(?P<currency>\w{3})$', login_required(AddAccountView.as_view()), name='accounts_add_account'),
url(r'^list/$', login_required(AccountsListView.as_view()), name='accounts_list'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from payway.accounts.views.add_account import AddAccountView
from payway.accounts.views.add_money import AddMoneyView
from payway.accounts.views.invoices_list import InvoicesListListView
from payway.accounts.views.list import AccountsListView
from payway.accounts.views.statement import AccountStatementView
and context (functions, classes, or occasionally code) from other files:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/accounts/views/add_money.py
# class AddMoneyView(TemplateView):
# template_name = 'accounts/add_money.html'
#
# def get(self, request, *args, **kwargs):
#
# account_uid = int(kwargs.get('account_uid', -1))
# invoice_uid = int(kwargs.get('invoice_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoice, created = Invoice.objects.get_or_create(
# uid=invoice_uid,
# account=account,
# defaults={
# 'account': account,
# 'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
# }
# )
#
# context = super(AddMoneyView, self).get_context_data(**kwargs)
# context['add_money_form'] = AddMoneyForm({
# 'money_amount': invoice.money_amount_without_percent.amount,
# 'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
# 'invoice_uid': invoice.uid
# })
#
# return self.render_to_response(context)
#
# def post(self, request):
# form = AddMoneyForm(request.POST or None)
# if form.is_valid():
# invoice = get_object_or_404(Invoice, uid=form.cleaned_data.get('invoice_uid'))
# new_money_amount = form.cleaned_data.get('money_amount')
# invoice.money_amount = Money(new_money_amount, invoice.money_amount.currency)
# invoice.save()
# return redirect(form.cleaned_data['payment_system'], invoice_uid=invoice.uid)
#
# return self.render_to_response({'add_money_form': form})
#
# Path: payway/accounts/views/invoices_list.py
# class InvoicesListListView(TemplateView):
# template_name = 'accounts/invoices_list.html'
#
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# invoices_page = create_paginated_page(
# query_set=account.invoices.all().order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=INVOICES_PER_PAGE
# )
# return self.render_to_response({'invoices_page': invoices_page})
#
# Path: payway/accounts/views/list.py
# class AccountsListView(TemplateView):
# template_name = 'accounts/list.html'
#
# def get(self, request):
# accounts_page = create_paginated_page(
# query_set=Account.objects.filter(user=request.user).order_by('-id'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ACCOUNTS_PER_PAGE
# )
# return self.render_to_response({'accounts_page': accounts_page })
#
# Path: payway/accounts/views/statement.py
# class AccountStatementView(TemplateView):
# template_name = 'accounts/statement.html'
#
# def get(self, request, *args, **kwargs):
# account_uid = int(kwargs.get('account_uid', -1))
# account = get_object_or_404(Account, uid=account_uid)
#
# transactions_page = create_paginated_page(
# query_set=Transaction.objects.filter(account=account).order_by('-created'),
# page_number=request.GET.get('page') or 1,
# objects_per_page=TRANSACTIONS_PER_PAGE
# )
# return self.render_to_response({'transactions_page': transactions_page})
. Output only the next line. | url(r'^statement/(?P<account_uid>\d+)/$', login_required(AccountStatementView.as_view()), name='accounts_statement'), |
Using the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from payway.qiwi.views import QiwiView
and context (class names, function names, or code) available:
# Path: payway/qiwi/views.py
# class QiwiView(TemplateView):
# template_name = 'qiwi/add_money_request.html'
#
# def get(self, request, *args, **kwargs):
# context = super(QiwiView, self).get_context_data(**kwargs)
# invoice_uid = int(kwargs.get('invoice_uid', 0))
# invoice = get_object_or_404(Invoice, uid=invoice_uid)
# invoice.update_money_amount_with_percent(QIWI_PERCENT)
#
# context['request_form'] = RequestPaymentForm(initial={
# 'txn_id': invoice.uid,
# 'from': QIWI_LOGIN,
# 'summ': invoice.money_amount.amount,
# 'com': render_to_string(
# 'qiwi/payment_description.txt', {
# 'invoice_uid': invoice.uid,
# 'user': request.user
# }).strip()[:255],
# 'lifetime': QIWI_BILL_LIFETIME,
# 'check_agt': QIWI_CHECK_AGT
# })
#
# return self.render_to_response(context)
. Output only the next line. | url(r'add-money/(?P<invoice_uid>\d+)/$', login_required(QiwiView.as_view()), name='qiwi_add_money'), |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class PaymentRequestFormTests(TestCase):
def setUp(self):
self.valid_data = {
'LMI_PAYEE_PURSE': 'Z123412341234',
'LMI_PAYMENT_AMOUNT': '999999.99',
'LMI_PAYMENT_DESC': 'test payment',
'LMI_PAYMENT_NO': '2147483647',
'LMI_SIM_MODE': '0',
}
def test_valid_payment_request_form(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from payway.webmoney.forms import RequestPaymentForm
and context including class names, function names, and sometimes code from other files:
# Path: payway/webmoney/forms.py
# class RequestPaymentForm(BasePaymentForm):
#
# LMI_PAYMENT_AMOUNT = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), WEBMONEY_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# required=True
# )
# LMI_SIM_MODE = forms.IntegerField(initial="0", widget=forms.HiddenInput())
. Output only the next line. | form = RequestPaymentForm(data=self.valid_data) |
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class BaseTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
'user',
'user@example.com',
'abc123',
)
<|code_end|>
. Write the next line using the current file imports:
import random
import moneyed
from django.contrib.auth.models import User
from django.test import TestCase
from moneyed.classes import Money
from nose.tools import eq_, raises
from payway.accounts.models import Account, Transaction, Overdraft, Invoice, ResponsePayment
from simptools.money import round_down
and context from other files:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
#
# class Overdraft(Exception):
# pass
#
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# class ResponsePayment(InheritanceCastModel, AbstractPayment):
# """
# Parent response model
# """
# OK_STATUS = Choices((True, 'SUCCESS', _('success')), (False, 'FAIL', _('fail')))
#
# is_OK = models.BooleanField(choices=OK_STATUS, default=OK_STATUS.FAIL)
#
# class Meta:
# db_table = 'payway_response_payments'
#
# def __unicode__(self):
# return u'id:{0} is_ok:{2}'.format(self.id, self.money_amount, self.is_OK)
, which may include functions, classes, or code. Output only the next line. | self.account = Account.objects.create(user=self.user) |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AddAccountView(TemplateView):
template_name = 'accounts/list.html'
MESSAGES = {
'WRONG_CURRENCY': _('Currency not allowed!'),
}
def get(self, request, *args, **kwargs):
currency = kwargs.get('currency')
<|code_end|>
with the help of current file imports:
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from payway.accounts.models import CURRENCY_CHOICES
and context from other files:
# Path: payway/accounts/models.py
# CURRENCY_CHOICES = (
# (CURRENCIES['RUB'].code, CURRENCIES['RUB'].name),
# (CURRENCIES['USD'].code, CURRENCIES['USD'].name)
# )
, which may contain function names, class names, or code. Output only the next line. | if currency not in dict(CURRENCY_CHOICES).keys(): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountsListView(TemplateView):
template_name = 'accounts/list.html'
def get(self, request):
accounts_page = create_paginated_page(
query_set=Account.objects.filter(user=request.user).order_by('-id'),
page_number=request.GET.get('page') or 1,
<|code_end|>
, predict the next line using imports from the current file:
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import ACCOUNTS_PER_PAGE
from payway.accounts.models import Account
and context including class names, function names, and sometimes code from other files:
# Path: payway/accounts/conf/settings.py
# ACCOUNTS_PER_PAGE = getattr(settings, 'ACCOUNTS_PER_PAGE', 5)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
. Output only the next line. | objects_per_page=ACCOUNTS_PER_PAGE |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountsListView(TemplateView):
template_name = 'accounts/list.html'
def get(self, request):
accounts_page = create_paginated_page(
<|code_end|>
with the help of current file imports:
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import ACCOUNTS_PER_PAGE
from payway.accounts.models import Account
and context from other files:
# Path: payway/accounts/conf/settings.py
# ACCOUNTS_PER_PAGE = getattr(settings, 'ACCOUNTS_PER_PAGE', 5)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
, which may contain function names, class names, or code. Output only the next line. | query_set=Account.objects.filter(user=request.user).order_by('-id'), |
Predict the next line for this snippet: <|code_start|> self.assert_correct_currency(money)
if money < Money(0, self.currency):
raise ValueError("You can't add a negative money amount")
return Transaction.objects.create(
account=self,
money_amount=money,
)
def transfer(self, money, to_account):
self.assert_correct_currency(money)
if money < Money(0, self.currency):
raise ValueError("You can't transfer a negative money amount")
self.withdraw(money)
return Transaction.objects.create(
account=to_account,
money_amount=money,
)
def assert_correct_currency(self, money):
if money.currency != self.currency:
raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
class Transaction(TimeStampedModel):
account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
<|code_end|>
with the help of current file imports:
from model_utils import Choices
from model_utils.models import TimeStampedModel, InheritanceCastModel
from moneyed import CURRENCIES
from django.db import models
from django.contrib.auth.models import User
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.money.models import fields
from django_simptools.models import RandomUIDAbstractModel
from django.utils.translation import ugettext_lazy as _
from moneyed.classes import Money, get_currency
from payway.accounts.querysets import TransactionQuerySet, InvoiceQuerySet
from simptools.money import round_down
import moneyed
and context from other files:
# Path: payway/accounts/querysets.py
# class TransactionQuerySet(ExtendedQuerySet):
#
# def sum_values(self):
# return self.aggregate(Sum('money_amount'))['money_amount__sum'] or 0.0
#
# class InvoiceQuerySet(ExtendedQuerySet):
#
# def get_or_create_invoice_with_other_money_amount(self, txn, money_amount):
# invoice = self.get(uid=txn)
# if invoice:
# money_amount = Money(money_amount, invoice.money_amount.currency)
# if invoice.money_amount != money_amount:
# self.__log_different_amount(invoice, invoice.money_amount, money_amount)
# invoice = self.create(
# account=invoice.account,
# money_amount=money_amount,
# money_amount_without_percent=invoice.money_amount_without_percent
# )
# return invoice
#
# def __log_different_amount(self, invoice, should_be, given):
# if should_be != given:
# logging.warning(u"Got different money amount for {0} invoice. Amount should be {1} but was {2}".format(
# invoice,
# should_be,
# given
# ))
, which may contain function names, class names, or code. Output only the next line. | objects = ChainableQuerySetManager(TransactionQuerySet) |
Based on the snippet: <|code_start|> account=to_account,
money_amount=money,
)
def assert_correct_currency(self, money):
if money.currency != self.currency:
raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
class Transaction(TimeStampedModel):
account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
objects = ChainableQuerySetManager(TransactionQuerySet)
class Meta:
verbose_name = _('transaction')
verbose_name_plural = _('transactions')
db_table = 'payway_transactions'
def __unicode__(self):
return 'Transaction #%d (%s)' % (self.id, self.money_amount)
def save(self, *args, **kwargs):
self.money_amount = round_down(self.money_amount)
super(Transaction, self).save(*args, **kwargs)
class Invoice(RandomUIDAbstractModel, TimeStampedModel):
account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
<|code_end|>
, predict the immediate next line with the help of imports:
from model_utils import Choices
from model_utils.models import TimeStampedModel, InheritanceCastModel
from moneyed import CURRENCIES
from django.db import models
from django.contrib.auth.models import User
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.money.models import fields
from django_simptools.models import RandomUIDAbstractModel
from django.utils.translation import ugettext_lazy as _
from moneyed.classes import Money, get_currency
from payway.accounts.querysets import TransactionQuerySet, InvoiceQuerySet
from simptools.money import round_down
import moneyed
and context (classes, functions, sometimes code) from other files:
# Path: payway/accounts/querysets.py
# class TransactionQuerySet(ExtendedQuerySet):
#
# def sum_values(self):
# return self.aggregate(Sum('money_amount'))['money_amount__sum'] or 0.0
#
# class InvoiceQuerySet(ExtendedQuerySet):
#
# def get_or_create_invoice_with_other_money_amount(self, txn, money_amount):
# invoice = self.get(uid=txn)
# if invoice:
# money_amount = Money(money_amount, invoice.money_amount.currency)
# if invoice.money_amount != money_amount:
# self.__log_different_amount(invoice, invoice.money_amount, money_amount)
# invoice = self.create(
# account=invoice.account,
# money_amount=money_amount,
# money_amount_without_percent=invoice.money_amount_without_percent
# )
# return invoice
#
# def __log_different_amount(self, invoice, should_be, given):
# if should_be != given:
# logging.warning(u"Got different money amount for {0} invoice. Amount should be {1} but was {2}".format(
# invoice,
# should_be,
# given
# ))
. Output only the next line. | objects = ChainableQuerySetManager(InvoiceQuerySet) |
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
<|code_end|>
using the current file's imports:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and any relevant context from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
. Output only the next line. | invoice = get_object_or_404(Invoice, uid=invoice_uid) |
Given the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
invoice = get_object_or_404(Invoice, uid=invoice_uid)
invoice.update_money_amount_with_percent(QIWI_PERCENT)
context['request_form'] = RequestPaymentForm(initial={
'txn_id': invoice.uid,
'from': QIWI_LOGIN,
'summ': invoice.money_amount.amount,
'com': render_to_string(
'qiwi/payment_description.txt', {
'invoice_uid': invoice.uid,
'user': request.user
}).strip()[:255],
<|code_end|>
, generate the next line using the imports in this file:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and context (functions, classes, or occasionally code) from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
. Output only the next line. | 'lifetime': QIWI_BILL_LIFETIME, |
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
invoice = get_object_or_404(Invoice, uid=invoice_uid)
invoice.update_money_amount_with_percent(QIWI_PERCENT)
context['request_form'] = RequestPaymentForm(initial={
'txn_id': invoice.uid,
'from': QIWI_LOGIN,
'summ': invoice.money_amount.amount,
'com': render_to_string(
'qiwi/payment_description.txt', {
'invoice_uid': invoice.uid,
'user': request.user
}).strip()[:255],
'lifetime': QIWI_BILL_LIFETIME,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and context (classes, functions, sometimes code) from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
. Output only the next line. | 'check_agt': QIWI_CHECK_AGT |
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
invoice = get_object_or_404(Invoice, uid=invoice_uid)
<|code_end|>
. Use current file imports:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and context (classes, functions, or code) from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
. Output only the next line. | invoice.update_money_amount_with_percent(QIWI_PERCENT) |
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
invoice = get_object_or_404(Invoice, uid=invoice_uid)
invoice.update_money_amount_with_percent(QIWI_PERCENT)
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and context from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
, which may include functions, classes, or code. Output only the next line. | context['request_form'] = RequestPaymentForm(initial={ |
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiView(TemplateView):
template_name = 'qiwi/add_money_request.html'
def get(self, request, *args, **kwargs):
context = super(QiwiView, self).get_context_data(**kwargs)
invoice_uid = int(kwargs.get('invoice_uid', 0))
invoice = get_object_or_404(Invoice, uid=invoice_uid)
invoice.update_money_amount_with_percent(QIWI_PERCENT)
context['request_form'] = RequestPaymentForm(initial={
'txn_id': invoice.uid,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic.base import TemplateView
from payway.accounts.models import Invoice
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME, QIWI_CHECK_AGT, QIWI_PERCENT
from payway.qiwi.forms import RequestPaymentForm
from payway.qiwi.conf.settings import QIWI_LOGIN
and context (classes, functions, sometimes code) from other files:
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
#
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_CHECK_AGT = getattr(settings, 'QIWI_CHECK_AGT', False)
#
# QIWI_PERCENT = getattr(settings, 'QIWI_PERCENT', 4.0)
#
# Path: payway/qiwi/forms.py
# class RequestPaymentForm(forms.Form):
#
# txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput())
# to = forms.IntegerField(
# label=_('10 digits phone number'),
# max_value=9999999999,
# widget=forms.TextInput(attrs={'maxlength':'10'})
# )
# summ = forms.DecimalField(
# max_digits=MAX_MONEY_DIGITS,
# decimal_places=MAX_MONEY_PLACES,
# label=u'{0} {1}% {2}'.format(_('sum with'), QIWI_PERCENT, _('percent')),
# widget=forms.TextInput(attrs={'readonly':'readonly'}),
# )
# com = forms.CharField(label=_(u'description'), widget=forms.HiddenInput(), required=False)
# lifetime = forms.IntegerField(required=False, widget=forms.HiddenInput())
# check_agt = forms.BooleanField(required=False, widget=forms.HiddenInput())
#
#
# def __init__(self, *args, **kwargs):
# super(RequestPaymentForm, self).__init__(*args, **kwargs)
# # because 'from' is keyword
# self.fields['from'] = forms.IntegerField(label=_('from'), widget=forms.HiddenInput())
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
. Output only the next line. | 'from': QIWI_LOGIN, |
Given the following code snippet before the placeholder: <|code_start|> return response
class checkBill(complextypes.ComplexType):
login = str
password = str
txn = str
class checkBillResponse(complextypes.ComplexType):
user = str
amount = str
date = str
lifetime = str
status = int
class MockCheckBillService(soaphandler.SoapHandler):
@webservice(_params=checkBill, _returns=checkBillResponse)
def checkBill(self, request):
login = request.login
password = request.password
if not all([login==QIWI_LOGIN, password==QIWI_PASSWORD]):
raise Exception("incorrect login or password")
response = checkBillResponse()
response.user = RECEIVED_DATA['createBill']['user']
response.amount = RECEIVED_DATA['createBill']['amount']
response.date = BILLING_DATE
response.lifetime = RECEIVED_DATA['createBill']['lifetime']
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import tornado
import sys
from threading import Thread
from tornadows import soaphandler, webservices, complextypes
from tornadows.soaphandler import webservice
from django.core.management import setup_environ
from payway_demo import settings
from payway.qiwi.models import Bill
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD
and context including class names, function names, and sometimes code from other files:
# Path: payway/qiwi/models.py
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
. Output only the next line. | response.status = Bill.STATUS.MADE |
Here is a snippet: <|code_start|> amount = str
comment = str
txn = str
lifetime = str
alarm = int
create = bool
class createBillResponse(complextypes.ComplexType):
createBillResult = int
RECEIVED_DATA = {}
BILLING_DATE = '10.01.2012 13:00:00'
class MockCreateBillService(soaphandler.SoapHandler):
@webservice(_params=createBill, _returns=createBillResponse)
def createBill(self, request):
login = request.login
password = request.password
user = request.user
amount = request.amount
comment = request.comment
txn = request.txn
lifetime = request.lifetime
alarm = request.alarm
create = request.create
response = createBillResponse()
response.createBillResult = 0
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import tornado
import sys
from threading import Thread
from tornadows import soaphandler, webservices, complextypes
from tornadows.soaphandler import webservice
from django.core.management import setup_environ
from payway_demo import settings
from payway.qiwi.models import Bill
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD
and context from other files:
# Path: payway/qiwi/models.py
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
, which may include functions, classes, or code. Output only the next line. | if not all([login==QIWI_LOGIN, password==QIWI_PASSWORD]): |
Based on the snippet: <|code_start|> amount = str
comment = str
txn = str
lifetime = str
alarm = int
create = bool
class createBillResponse(complextypes.ComplexType):
createBillResult = int
RECEIVED_DATA = {}
BILLING_DATE = '10.01.2012 13:00:00'
class MockCreateBillService(soaphandler.SoapHandler):
@webservice(_params=createBill, _returns=createBillResponse)
def createBill(self, request):
login = request.login
password = request.password
user = request.user
amount = request.amount
comment = request.comment
txn = request.txn
lifetime = request.lifetime
alarm = request.alarm
create = request.create
response = createBillResponse()
response.createBillResult = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import tornado
import sys
from threading import Thread
from tornadows import soaphandler, webservices, complextypes
from tornadows.soaphandler import webservice
from django.core.management import setup_environ
from payway_demo import settings
from payway.qiwi.models import Bill
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD
and context (classes, functions, sometimes code) from other files:
# Path: payway/qiwi/models.py
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
. Output only the next line. | if not all([login==QIWI_LOGIN, password==QIWI_PASSWORD]): |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
MIN_MONEY_VALUE = 1.0
PAYMENT_SYSTEM_CHOICES = (
('webmoney_add_money', 'Webmoney WMR'),
('qiwi_add_money', 'Qiwi RUB'),
)
class AddMoneyForm(forms.Form):
money_amount = forms.DecimalField(
label=_('money amount'),
min_value=MIN_MONEY_VALUE,
max_digits=MAX_MONEY_DIGITS,
<|code_end|>
. Use current file imports:
(from django import forms
from django.forms.fields import ChoiceField
from django.forms.widgets import RadioSelect
from django.utils.translation import ugettext_lazy as _
from django_simptools.models import RandomUIDAbstractModel
from payway.accounts.models import MAX_MONEY_PLACES, MAX_MONEY_DIGITS)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_PLACES = 2
#
# MAX_MONEY_DIGITS = 20
. Output only the next line. | decimal_places=MAX_MONEY_PLACES, |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
MIN_MONEY_VALUE = 1.0
PAYMENT_SYSTEM_CHOICES = (
('webmoney_add_money', 'Webmoney WMR'),
('qiwi_add_money', 'Qiwi RUB'),
)
class AddMoneyForm(forms.Form):
money_amount = forms.DecimalField(
label=_('money amount'),
min_value=MIN_MONEY_VALUE,
<|code_end|>
with the help of current file imports:
from django import forms
from django.forms.fields import ChoiceField
from django.forms.widgets import RadioSelect
from django.utils.translation import ugettext_lazy as _
from django_simptools.models import RandomUIDAbstractModel
from payway.accounts.models import MAX_MONEY_PLACES, MAX_MONEY_DIGITS
and context from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_PLACES = 2
#
# MAX_MONEY_DIGITS = 20
, which may contain function names, class names, or code. Output only the next line. | max_digits=MAX_MONEY_DIGITS, |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class Order(TimeStampedModel):
PAYMENT_STATUS = Choices(
(False, 'NOT_PAID', _('not paid')),
(True, 'PAID', _('paid')),
)
user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant'))
uid = models.PositiveIntegerField(unique=False, editable=False)
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_simptools.money.models import fields
from model_utils import Choices
from model_utils.models import TimeStampedModel
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.querysets import ExtendedQuerySet
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES, Account
from payway.merchants.models import Merchant)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
#
# URL_METHODS = Choices(
# ('POST', 'POST'),
# ('GET', 'GET'),
# )
#
# user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
# name = models.CharField('Имя', max_length=255)
# secret_key = models.CharField(_('secret key'), max_length=50)
#
# result_url = models.URLField(_('result url'))
# result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
#
# success_url = models.URLField(_('success url'))
# fail_url = models.URLField(_('fail url'))
#
# class Meta:
# verbose_name = 'продавец'
# verbose_name_plural = 'продавцы'
# db_table = 'payway_merchants'
. Output only the next line. | sum = fields.MoneyField(_('sum'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) |
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class Order(TimeStampedModel):
PAYMENT_STATUS = Choices(
(False, 'NOT_PAID', _('not paid')),
(True, 'PAID', _('paid')),
)
user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant'))
uid = models.PositiveIntegerField(unique=False, editable=False)
<|code_end|>
using the current file's imports:
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_simptools.money.models import fields
from model_utils import Choices
from model_utils.models import TimeStampedModel
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.querysets import ExtendedQuerySet
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES, Account
from payway.merchants.models import Merchant
and any relevant context from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
#
# URL_METHODS = Choices(
# ('POST', 'POST'),
# ('GET', 'GET'),
# )
#
# user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
# name = models.CharField('Имя', max_length=255)
# secret_key = models.CharField(_('secret key'), max_length=50)
#
# result_url = models.URLField(_('result url'))
# result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
#
# success_url = models.URLField(_('success url'))
# fail_url = models.URLField(_('fail url'))
#
# class Meta:
# verbose_name = 'продавец'
# verbose_name_plural = 'продавцы'
# db_table = 'payway_merchants'
. Output only the next line. | sum = fields.MoneyField(_('sum'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class Order(TimeStampedModel):
PAYMENT_STATUS = Choices(
(False, 'NOT_PAID', _('not paid')),
(True, 'PAID', _('paid')),
)
user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant'))
uid = models.PositiveIntegerField(unique=False, editable=False)
sum = fields.MoneyField(_('sum'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
<|code_end|>
with the help of current file imports:
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_simptools.money.models import fields
from model_utils import Choices
from model_utils.models import TimeStampedModel
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.querysets import ExtendedQuerySet
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES, Account
from payway.merchants.models import Merchant
and context from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
#
# URL_METHODS = Choices(
# ('POST', 'POST'),
# ('GET', 'GET'),
# )
#
# user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
# name = models.CharField('Имя', max_length=255)
# secret_key = models.CharField(_('secret key'), max_length=50)
#
# result_url = models.URLField(_('result url'))
# result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
#
# success_url = models.URLField(_('success url'))
# fail_url = models.URLField(_('fail url'))
#
# class Meta:
# verbose_name = 'продавец'
# verbose_name_plural = 'продавцы'
# db_table = 'payway_merchants'
, which may contain function names, class names, or code. Output only the next line. | account = models.ForeignKey(Account, related_name='orders', verbose_name=_('account')) |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class Order(TimeStampedModel):
PAYMENT_STATUS = Choices(
(False, 'NOT_PAID', _('not paid')),
(True, 'PAID', _('paid')),
)
user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_simptools.money.models import fields
from model_utils import Choices
from model_utils.models import TimeStampedModel
from django_simptools.managers import ChainableQuerySetManager
from django_simptools.querysets import ExtendedQuerySet
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES, Account
from payway.merchants.models import Merchant)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
#
# URL_METHODS = Choices(
# ('POST', 'POST'),
# ('GET', 'GET'),
# )
#
# user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
# name = models.CharField('Имя', max_length=255)
# secret_key = models.CharField(_('secret key'), max_length=50)
#
# result_url = models.URLField(_('result url'))
# result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
#
# success_url = models.URLField(_('success url'))
# fail_url = models.URLField(_('fail url'))
#
# class Meta:
# verbose_name = 'продавец'
# verbose_name_plural = 'продавцы'
# db_table = 'payway_merchants'
. Output only the next line. | merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant')) |
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context (classes, functions, sometimes code) from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE): |
Using the snippet: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context (class names, function names, or code) available:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE): |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
<|code_end|>
. Use current file imports:
(import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH)
and context including class names, function names, or small code snippets from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | url = QIWI_SOAP_CLIENT_URL |
Given the code snippet: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context (functions, classes, or occasionally code) from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE): |
Given snippet: <|code_start|>sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE):
if len(user) > 10: raise QiwiSoapClientException("User phone number should be less than 10")
client = Client(cls.url)
response = client.service.createBill(
login=login,
password=password,
user=user,
amount=amount,
comment=comment,
txn=txn,
lifetime=cls.hours_to_lifetime(lifetime),
alarm=alarm,
create=create)
return response
@classmethod
def hours_to_lifetime(cls, days):
now = datetime.datetime.now()
now += datetime.timedelta(days=days)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
which might include code, classes, or functions. Output only the next line. | return now.strftime(QIWI_DATETIME_FORMAT) |
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
<|code_end|>
. Use current file imports:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context (classes, functions, or code) from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE): |
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds
class QiwiSoapClientException(Exception):
pass
class QiwiSoapClient(object):
url = QIWI_SOAP_CLIENT_URL
@classmethod
<|code_end|>
. Write the next line using the current file imports:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
, which may include functions, classes, or code. Output only the next line. | def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
logger = logging.getLogger(__name__)
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import logging
from suds.xsd import sxbasic
from suds.client import Client
from payway.qiwi.conf.settings import QIWI_ALARM, QIWI_CREATE, QIWI_SOAP_CLIENT_URL, QIWI_BILL_LIFETIME, QIWI_DATETIME_FORMAT
from payway.qiwi.conf.settings import QIWI_LOGIN, QIWI_PASSWORD, XML_SCHEMA_PATH
and context including class names, function names, and sometimes code from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_ALARM = getattr(settings, 'QIWI_ALARM', 0)
#
# QIWI_CREATE = getattr(settings, 'QIWI_CREATE', False)
#
# QIWI_SOAP_CLIENT_URL = getattr(settings, 'QIWI_SOAP_CLIENT_URL', 'https://ishop.qiwi.ru/services/ishop?wsdl')
#
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# QIWI_DATETIME_FORMAT = getattr(settings, 'QIWI_DATETIME_FORMAT', '%d.%m.%Y %H:%M:%S')
#
# Path: payway/qiwi/conf/settings.py
# QIWI_LOGIN = getattr(settings, 'QIWI_LOGIN')
#
# QIWI_PASSWORD = getattr(settings, 'QIWI_PASSWORD')
#
# XML_SCHEMA_PATH = 'file://' + os.path.join(QIWI_MODULE_PATH, 'templates', 'suds', 'XMLSchema.xml')
. Output only the next line. | sxbasic.Import.bind('http://www.w3.org/2001/XMLSchema', XML_SCHEMA_PATH) # for suds |
Given snippet: <|code_start|> u'LMI_SYS_TRANS_NO': u'315',
u'LMI_TELEPAT_PHONENUMBER': u'',
u'LMI_PAYMER_NUMBER': u'',
u'LMI_CAPITALLER_WMID': u'',
u'LMI_PAYMER_EMAIL': u'',
u'LMI_TELEPAT_ORDERID': u'',
}
def test_prerequest(self):
prerequest_data = {
u'LMI_PREREQUEST': u'1',
u'LMI_PAYMENT_DESC': u'admin payment for 1961380063 invoice',
u'LMI_MODE': u'1',
u'LMI_PAYMENT_AMOUNT': u'1.00',
u'LMI_LANG': u'ru-RU',
u'LMI_PAYMENT_NO': u'1961380063',
u'LMI_PAYER_PURSE': u'R172474141621',
u'LMI_PAYER_WM': u'326319216579',
u'LMI_PAYEE_PURSE': u'R834617269654',
u'LMI_DBLCHK': u'SMS'
}
url = reverse('webmoney_result')
response = self.client.post(url, prerequest_data)
self.failUnlessEqual(response.status_code, 200)
self.assertContains(response, "YES")
def test_result_response(self):
success_payments_count = ResultResponsePayment.objects.count()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.models import User
from django.test import TestCase
from django.core.urlresolvers import reverse
from moneyed.classes import Money, RUB
from django_simptools.tests import AuthorizedViewTestCase
from payway.accounts.models import Account
from payway.webmoney.models import ResultResponsePayment
from django.core.mail import outbox
and context:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/webmoney/models.py
# class ResultResponsePayment(ResponsePayment):
#
# class Meta:
# db_table = 'payway_webmoney_resultresponsepayment'
#
# payment_system = _('Webmoney')
#
# PAYMENT_MODE = Choices((0, _('real')), (1, _('test')))
#
# LMI_MODE = models.PositiveSmallIntegerField(choices=PAYMENT_MODE)
# payee_purse = models.ForeignKey(Purse, related_name='success_payments')
#
# LMI_SYS_INVS_NO = models.PositiveIntegerField()
# LMI_SYS_TRANS_NO = models.PositiveIntegerField()
# LMI_SYS_TRANS_DATE = models.DateTimeField()
# LMI_PAYMENT_NO = models.PositiveIntegerField()
#
# LMI_PAYER_PURSE = models.CharField(max_length=13)
# LMI_PAYER_WM = models.CharField(max_length=12)
# LMI_HASH = models.CharField(max_length=255)
#
# LMI_CAPITALLER_WMID = models.CharField(max_length=12, blank=True)
# LMI_WMCHECK_NUMBER = models.CharField(max_length=20, blank=True)
# LMI_PAYMER_NUMBER = models.CharField(max_length=30, blank=True)
# LMI_PAYMER_EMAIL = models.EmailField(blank=True)
# LMI_TELEPAT_PHONENUMBER = models.CharField(max_length=30, blank=True)
# LMI_TELEPAT_ORDERID = models.CharField(max_length=30, blank=True)
# LMI_PAYMENT_DESC = models.CharField(max_length=255, blank=True)
# LMI_LANG = models.CharField(max_length=10, blank=True)
which might include code, classes, or functions. Output only the next line. | account = Account.objects.filter(user=self.user)[0] |
Given the following code snippet before the placeholder: <|code_start|> u'LMI_DBLCHK': u'SMS',
u'LMI_SYS_TRANS_NO': u'315',
u'LMI_TELEPAT_PHONENUMBER': u'',
u'LMI_PAYMER_NUMBER': u'',
u'LMI_CAPITALLER_WMID': u'',
u'LMI_PAYMER_EMAIL': u'',
u'LMI_TELEPAT_ORDERID': u'',
}
def test_prerequest(self):
prerequest_data = {
u'LMI_PREREQUEST': u'1',
u'LMI_PAYMENT_DESC': u'admin payment for 1961380063 invoice',
u'LMI_MODE': u'1',
u'LMI_PAYMENT_AMOUNT': u'1.00',
u'LMI_LANG': u'ru-RU',
u'LMI_PAYMENT_NO': u'1961380063',
u'LMI_PAYER_PURSE': u'R172474141621',
u'LMI_PAYER_WM': u'326319216579',
u'LMI_PAYEE_PURSE': u'R834617269654',
u'LMI_DBLCHK': u'SMS'
}
url = reverse('webmoney_result')
response = self.client.post(url, prerequest_data)
self.failUnlessEqual(response.status_code, 200)
self.assertContains(response, "YES")
def test_result_response(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.auth.models import User
from django.test import TestCase
from django.core.urlresolvers import reverse
from moneyed.classes import Money, RUB
from django_simptools.tests import AuthorizedViewTestCase
from payway.accounts.models import Account
from payway.webmoney.models import ResultResponsePayment
from django.core.mail import outbox
and context including class names, function names, and sometimes code from other files:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# Path: payway/webmoney/models.py
# class ResultResponsePayment(ResponsePayment):
#
# class Meta:
# db_table = 'payway_webmoney_resultresponsepayment'
#
# payment_system = _('Webmoney')
#
# PAYMENT_MODE = Choices((0, _('real')), (1, _('test')))
#
# LMI_MODE = models.PositiveSmallIntegerField(choices=PAYMENT_MODE)
# payee_purse = models.ForeignKey(Purse, related_name='success_payments')
#
# LMI_SYS_INVS_NO = models.PositiveIntegerField()
# LMI_SYS_TRANS_NO = models.PositiveIntegerField()
# LMI_SYS_TRANS_DATE = models.DateTimeField()
# LMI_PAYMENT_NO = models.PositiveIntegerField()
#
# LMI_PAYER_PURSE = models.CharField(max_length=13)
# LMI_PAYER_WM = models.CharField(max_length=12)
# LMI_HASH = models.CharField(max_length=255)
#
# LMI_CAPITALLER_WMID = models.CharField(max_length=12, blank=True)
# LMI_WMCHECK_NUMBER = models.CharField(max_length=20, blank=True)
# LMI_PAYMER_NUMBER = models.CharField(max_length=30, blank=True)
# LMI_PAYMER_EMAIL = models.EmailField(blank=True)
# LMI_TELEPAT_PHONENUMBER = models.CharField(max_length=30, blank=True)
# LMI_TELEPAT_ORDERID = models.CharField(max_length=30, blank=True)
# LMI_PAYMENT_DESC = models.CharField(max_length=255, blank=True)
# LMI_LANG = models.CharField(max_length=10, blank=True)
. Output only the next line. | success_payments_count = ResultResponsePayment.objects.count() |
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
def mock_MerchantHttpClient_success_execute():
class ResponseMock(object):
text = RESPONSE_STATUS.OK
<|code_end|>
. Use current file imports:
from mock import Mock
from requests.exceptions import ConnectionError
from simptools.wrappers.http import HttpClient
from payway.merchants.http import MerchantHttpClient, RESPONSE_STATUS
and context (classes, functions, or code) from other files:
# Path: payway/merchants/http.py
# class MerchantHttpClient(HttpClient):
#
# @classmethod
# def notify(cls, merchant, order):
# result = ''
# try:
# request = MerchantHttpRequest(merchant, order)
# response = cls.execute(request)
# result = response.text
# except ConnectionError:
# logging.warn('Problems when connecting to merchant {0}'.format(merchant.result_url))
# return result
#
# RESPONSE_STATUS = Choices(
# ('OK', 'OK'),
# )
. Output only the next line. | MerchantHttpClient.execute = Mock(return_value=ResponseMock()) |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
def mock_MerchantHttpClient_success_execute():
class ResponseMock(object):
<|code_end|>
. Use current file imports:
(from mock import Mock
from requests.exceptions import ConnectionError
from simptools.wrappers.http import HttpClient
from payway.merchants.http import MerchantHttpClient, RESPONSE_STATUS)
and context including class names, function names, or small code snippets from other files:
# Path: payway/merchants/http.py
# class MerchantHttpClient(HttpClient):
#
# @classmethod
# def notify(cls, merchant, order):
# result = ''
# try:
# request = MerchantHttpRequest(merchant, order)
# response = cls.execute(request)
# result = response.text
# except ConnectionError:
# logging.warn('Problems when connecting to merchant {0}'.format(merchant.result_url))
# return result
#
# RESPONSE_STATUS = Choices(
# ('OK', 'OK'),
# )
. Output only the next line. | text = RESPONSE_STATUS.OK |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountAdmin(admin.ModelAdmin):
list_display = (
'uid',
'currency_code',
'user',
)
class InvoiceAdmin(admin.ModelAdmin):
list_display = (
'uid',
)
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from payway.accounts.models import Account, Transaction, Invoice
and context including class names, function names, and sometimes code from other files:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
#
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
. Output only the next line. | admin.site.register(Account, AccountAdmin) |
Using the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountAdmin(admin.ModelAdmin):
list_display = (
'uid',
'currency_code',
'user',
)
class InvoiceAdmin(admin.ModelAdmin):
list_display = (
'uid',
)
admin.site.register(Account, AccountAdmin)
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from payway.accounts.models import Account, Transaction, Invoice
and context (class names, function names, or code) available:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
#
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
. Output only the next line. | admin.site.register(Transaction) |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountAdmin(admin.ModelAdmin):
list_display = (
'uid',
'currency_code',
'user',
)
class InvoiceAdmin(admin.ModelAdmin):
list_display = (
'uid',
)
admin.site.register(Account, AccountAdmin)
admin.site.register(Transaction)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from payway.accounts.models import Account, Transaction, Invoice
and context:
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
#
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
#
# account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
# money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
# objects = ChainableQuerySetManager(InvoiceQuerySet)
#
# class Meta:
# verbose_name = _('invoice')
# verbose_name_plural = _('invoices')
# db_table = 'payway_invoices'
#
# def __init__(self, *args, **kwargs):
# money_amount = kwargs.get('money_amount') or None
# if money_amount:
# kwargs.setdefault('money_amount_without_percent', money_amount)
# super(Invoice, self).__init__(*args, **kwargs)
#
# def get_success_response_payments(self):
# return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
#
# def __unicode__(self):
# return u'{0}'.format(self.uid)
#
# def update_money_amount_with_percent(self, percent=0.0):
# self.money_amount_without_percent = self.money_amount
# self.money_amount += round_down(percent % self.money_amount)
# self.save()
which might include code, classes, or functions. Output only the next line. | admin.site.register(Invoice, InvoiceAdmin) |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiSoapClientTestCase(TestCase):
mock_qiwi_provider = None
@classmethod
def setUpClass(cls):
cls.mock_qiwi_provider = MockQiwiProviderRunner()
cls.mock_qiwi_provider.start()
sleep(0.5)
@property
def bill_data(self):
return {
'user': '1111111111',
'amount': 200.00,
'comment': 'comment',
'txn': '1234'
}
def test_createBill(self):
<|code_end|>
with the help of current file imports:
from time import sleep
from django.test import TestCase
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME
from payway.qiwi.models import TERMINATION_CODES, Bill
from payway.qiwi.soap.client import QiwiSoapClient
from payway.qiwi.tests.mock_provider import MockQiwiProviderRunner, RECEIVED_DATA, BILLING_DATE
and context from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# Path: payway/qiwi/models.py
# TERMINATION_CODES = Choices(
# (0, 'SUCCESS',_('0 Success')),
# (13, 'SERVER_IS_BUSY', _('13 Server is busy, please repeat your request later')),
# (150, 'AUTHORIZATION_ERROR', _('150 Authorization error (wrong login/password) ')),
# (210, 'BILL_NOT_FOUND', _('210 Bill not found')),
# (215, 'BILL_TXNID_EXISTS', _('215 Bill with this txn-id already exists')),
# (241, 'BILL_VERY_SMALL_SUM', _('241 Very small bill sum')),
# (242, 'BILL_MAXIMUM_SUM_EXCEEDED', _('242 Bill maximum sum exceeded')),
# (278, 'BILL_LIST_MAX_TIME_RANGE_EXCEEDED', _('278 Bill list maximum time range exceeded')),
# (298, 'NO_SUCH_AGENT', _('298 No such agent in the system')),
# (300, 'UNKNOWN_ERROR', _('300 Unknown error')),
# (330, 'ENCRYPTION_ERROR', _('330 Encryption error')),
# (370, 'MAXIMUM_REQUEST_OVERLIMIT', _('370 Maximum allowed concurrent requests overlimit'))
# )
#
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/soap/client.py
# class QiwiSoapClient(object):
# url = QIWI_SOAP_CLIENT_URL
#
# @classmethod
# def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE):
# if len(user) > 10: raise QiwiSoapClientException("User phone number should be less than 10")
# client = Client(cls.url)
#
# response = client.service.createBill(
# login=login,
# password=password,
# user=user,
# amount=amount,
# comment=comment,
# txn=txn,
# lifetime=cls.hours_to_lifetime(lifetime),
# alarm=alarm,
# create=create)
# return response
#
# @classmethod
# def hours_to_lifetime(cls, days):
# now = datetime.datetime.now()
# now += datetime.timedelta(days=days)
# return now.strftime(QIWI_DATETIME_FORMAT)
#
# @classmethod
# def cancelBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.cancelBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# @classmethod
# def checkBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.checkBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# Path: payway/qiwi/tests/mock_provider.py
# class MockQiwiProviderRunner(Thread):
# PORT = 18888
#
# def __init__(self):
# Thread.__init__(self)
# self.setDaemon(True)
# self.services = [
# ('createBill', MockCreateBillService),
# ('cancelBill', MockCancelBillService),
# ('checkBill', MockCheckBillService),
# ]
#
# def run(self):
# app = webservices.WebService(self.services)
# app.listen(self.PORT)
# tornado.ioloop.IOLoop.instance().start()
#
# def stop(self):
# tornado.ioloop.IOLoop.instance().stop()
# self.join()
#
# RECEIVED_DATA = {}
#
# BILLING_DATE = '10.01.2012 13:00:00'
, which may contain function names, class names, or code. Output only the next line. | self.assertEquals(TERMINATION_CODES.SUCCESS, self.createBill()) |
Continue the code snippet: <|code_start|>
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiSoapClientTestCase(TestCase):
mock_qiwi_provider = None
@classmethod
def setUpClass(cls):
cls.mock_qiwi_provider = MockQiwiProviderRunner()
cls.mock_qiwi_provider.start()
sleep(0.5)
@property
def bill_data(self):
return {
'user': '1111111111',
'amount': 200.00,
'comment': 'comment',
'txn': '1234'
}
def test_createBill(self):
self.assertEquals(TERMINATION_CODES.SUCCESS, self.createBill())
self.assertDictContainsSubset(self.bill_data, RECEIVED_DATA['createBill'])
def createBill(self):
<|code_end|>
. Use current file imports:
from time import sleep
from django.test import TestCase
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME
from payway.qiwi.models import TERMINATION_CODES, Bill
from payway.qiwi.soap.client import QiwiSoapClient
from payway.qiwi.tests.mock_provider import MockQiwiProviderRunner, RECEIVED_DATA, BILLING_DATE
and context (classes, functions, or code) from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# Path: payway/qiwi/models.py
# TERMINATION_CODES = Choices(
# (0, 'SUCCESS',_('0 Success')),
# (13, 'SERVER_IS_BUSY', _('13 Server is busy, please repeat your request later')),
# (150, 'AUTHORIZATION_ERROR', _('150 Authorization error (wrong login/password) ')),
# (210, 'BILL_NOT_FOUND', _('210 Bill not found')),
# (215, 'BILL_TXNID_EXISTS', _('215 Bill with this txn-id already exists')),
# (241, 'BILL_VERY_SMALL_SUM', _('241 Very small bill sum')),
# (242, 'BILL_MAXIMUM_SUM_EXCEEDED', _('242 Bill maximum sum exceeded')),
# (278, 'BILL_LIST_MAX_TIME_RANGE_EXCEEDED', _('278 Bill list maximum time range exceeded')),
# (298, 'NO_SUCH_AGENT', _('298 No such agent in the system')),
# (300, 'UNKNOWN_ERROR', _('300 Unknown error')),
# (330, 'ENCRYPTION_ERROR', _('330 Encryption error')),
# (370, 'MAXIMUM_REQUEST_OVERLIMIT', _('370 Maximum allowed concurrent requests overlimit'))
# )
#
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/soap/client.py
# class QiwiSoapClient(object):
# url = QIWI_SOAP_CLIENT_URL
#
# @classmethod
# def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE):
# if len(user) > 10: raise QiwiSoapClientException("User phone number should be less than 10")
# client = Client(cls.url)
#
# response = client.service.createBill(
# login=login,
# password=password,
# user=user,
# amount=amount,
# comment=comment,
# txn=txn,
# lifetime=cls.hours_to_lifetime(lifetime),
# alarm=alarm,
# create=create)
# return response
#
# @classmethod
# def hours_to_lifetime(cls, days):
# now = datetime.datetime.now()
# now += datetime.timedelta(days=days)
# return now.strftime(QIWI_DATETIME_FORMAT)
#
# @classmethod
# def cancelBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.cancelBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# @classmethod
# def checkBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.checkBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# Path: payway/qiwi/tests/mock_provider.py
# class MockQiwiProviderRunner(Thread):
# PORT = 18888
#
# def __init__(self):
# Thread.__init__(self)
# self.setDaemon(True)
# self.services = [
# ('createBill', MockCreateBillService),
# ('cancelBill', MockCancelBillService),
# ('checkBill', MockCheckBillService),
# ]
#
# def run(self):
# app = webservices.WebService(self.services)
# app.listen(self.PORT)
# tornado.ioloop.IOLoop.instance().start()
#
# def stop(self):
# tornado.ioloop.IOLoop.instance().stop()
# self.join()
#
# RECEIVED_DATA = {}
#
# BILLING_DATE = '10.01.2012 13:00:00'
. Output only the next line. | QiwiSoapClient.url = 'http://127.0.0.1:{0}/createBill?wsdl'.format(MockQiwiProviderRunner.PORT) |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiSoapClientTestCase(TestCase):
mock_qiwi_provider = None
@classmethod
def setUpClass(cls):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from time import sleep
from django.test import TestCase
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME
from payway.qiwi.models import TERMINATION_CODES, Bill
from payway.qiwi.soap.client import QiwiSoapClient
from payway.qiwi.tests.mock_provider import MockQiwiProviderRunner, RECEIVED_DATA, BILLING_DATE
and context:
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# Path: payway/qiwi/models.py
# TERMINATION_CODES = Choices(
# (0, 'SUCCESS',_('0 Success')),
# (13, 'SERVER_IS_BUSY', _('13 Server is busy, please repeat your request later')),
# (150, 'AUTHORIZATION_ERROR', _('150 Authorization error (wrong login/password) ')),
# (210, 'BILL_NOT_FOUND', _('210 Bill not found')),
# (215, 'BILL_TXNID_EXISTS', _('215 Bill with this txn-id already exists')),
# (241, 'BILL_VERY_SMALL_SUM', _('241 Very small bill sum')),
# (242, 'BILL_MAXIMUM_SUM_EXCEEDED', _('242 Bill maximum sum exceeded')),
# (278, 'BILL_LIST_MAX_TIME_RANGE_EXCEEDED', _('278 Bill list maximum time range exceeded')),
# (298, 'NO_SUCH_AGENT', _('298 No such agent in the system')),
# (300, 'UNKNOWN_ERROR', _('300 Unknown error')),
# (330, 'ENCRYPTION_ERROR', _('330 Encryption error')),
# (370, 'MAXIMUM_REQUEST_OVERLIMIT', _('370 Maximum allowed concurrent requests overlimit'))
# )
#
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/soap/client.py
# class QiwiSoapClient(object):
# url = QIWI_SOAP_CLIENT_URL
#
# @classmethod
# def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE):
# if len(user) > 10: raise QiwiSoapClientException("User phone number should be less than 10")
# client = Client(cls.url)
#
# response = client.service.createBill(
# login=login,
# password=password,
# user=user,
# amount=amount,
# comment=comment,
# txn=txn,
# lifetime=cls.hours_to_lifetime(lifetime),
# alarm=alarm,
# create=create)
# return response
#
# @classmethod
# def hours_to_lifetime(cls, days):
# now = datetime.datetime.now()
# now += datetime.timedelta(days=days)
# return now.strftime(QIWI_DATETIME_FORMAT)
#
# @classmethod
# def cancelBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.cancelBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# @classmethod
# def checkBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.checkBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# Path: payway/qiwi/tests/mock_provider.py
# class MockQiwiProviderRunner(Thread):
# PORT = 18888
#
# def __init__(self):
# Thread.__init__(self)
# self.setDaemon(True)
# self.services = [
# ('createBill', MockCreateBillService),
# ('cancelBill', MockCancelBillService),
# ('checkBill', MockCheckBillService),
# ]
#
# def run(self):
# app = webservices.WebService(self.services)
# app.listen(self.PORT)
# tornado.ioloop.IOLoop.instance().start()
#
# def stop(self):
# tornado.ioloop.IOLoop.instance().stop()
# self.join()
#
# RECEIVED_DATA = {}
#
# BILLING_DATE = '10.01.2012 13:00:00'
which might include code, classes, or functions. Output only the next line. | cls.mock_qiwi_provider = MockQiwiProviderRunner() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class QiwiSoapClientTestCase(TestCase):
mock_qiwi_provider = None
@classmethod
def setUpClass(cls):
cls.mock_qiwi_provider = MockQiwiProviderRunner()
cls.mock_qiwi_provider.start()
sleep(0.5)
@property
def bill_data(self):
return {
'user': '1111111111',
'amount': 200.00,
'comment': 'comment',
'txn': '1234'
}
def test_createBill(self):
self.assertEquals(TERMINATION_CODES.SUCCESS, self.createBill())
<|code_end|>
, predict the next line using imports from the current file:
from time import sleep
from django.test import TestCase
from payway.qiwi.conf.settings import QIWI_BILL_LIFETIME
from payway.qiwi.models import TERMINATION_CODES, Bill
from payway.qiwi.soap.client import QiwiSoapClient
from payway.qiwi.tests.mock_provider import MockQiwiProviderRunner, RECEIVED_DATA, BILLING_DATE
and context including class names, function names, and sometimes code from other files:
# Path: payway/qiwi/conf/settings.py
# QIWI_BILL_LIFETIME = getattr(settings, 'QIWI_BILL_LIFETIME', 24) # hours
#
# Path: payway/qiwi/models.py
# TERMINATION_CODES = Choices(
# (0, 'SUCCESS',_('0 Success')),
# (13, 'SERVER_IS_BUSY', _('13 Server is busy, please repeat your request later')),
# (150, 'AUTHORIZATION_ERROR', _('150 Authorization error (wrong login/password) ')),
# (210, 'BILL_NOT_FOUND', _('210 Bill not found')),
# (215, 'BILL_TXNID_EXISTS', _('215 Bill with this txn-id already exists')),
# (241, 'BILL_VERY_SMALL_SUM', _('241 Very small bill sum')),
# (242, 'BILL_MAXIMUM_SUM_EXCEEDED', _('242 Bill maximum sum exceeded')),
# (278, 'BILL_LIST_MAX_TIME_RANGE_EXCEEDED', _('278 Bill list maximum time range exceeded')),
# (298, 'NO_SUCH_AGENT', _('298 No such agent in the system')),
# (300, 'UNKNOWN_ERROR', _('300 Unknown error')),
# (330, 'ENCRYPTION_ERROR', _('330 Encryption error')),
# (370, 'MAXIMUM_REQUEST_OVERLIMIT', _('370 Maximum allowed concurrent requests overlimit'))
# )
#
# class Bill(ResponsePayment):
#
#
# STATUS = Choices(
# (50, 'MADE', _('50 Made')),
# (52, 'PROCESSING', _('52 Processing')),
# (60, 'PAYED', _('60 Paid')),
# (150, 'TERMINAL_ERROR', _('150 Cancelled (Terminal error)')),
# (151, 'MACHINE_ERROR', _('151 Cancelled (authorization error, declined, not enough money on account or something else)')),
# (160, 'CANCELLED', _('160 Cancelled')),
# (161, 'TIMEOUT', _('161 Cancelled (Timeout)')),
# )
# payment_system = _('Qiwi Wallet')
# status = models.PositiveSmallIntegerField(_('Status'), choices=STATUS)
# user = models.CharField(_('User phone number'), max_length=10)
# date = models.CharField(_('Billing date'), max_length=20)
# lifetime = models.CharField(_('Bill lifetime'), max_length=20)
#
# class Meta:
# verbose_name = _('bill')
# verbose_name_plural = _('bills')
# db_table = 'payway_qiwi_bill'
#
# Path: payway/qiwi/soap/client.py
# class QiwiSoapClient(object):
# url = QIWI_SOAP_CLIENT_URL
#
# @classmethod
# def createBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, user='', amount='', comment='', txn='', lifetime=QIWI_BILL_LIFETIME, alarm=QIWI_ALARM, create=QIWI_CREATE):
# if len(user) > 10: raise QiwiSoapClientException("User phone number should be less than 10")
# client = Client(cls.url)
#
# response = client.service.createBill(
# login=login,
# password=password,
# user=user,
# amount=amount,
# comment=comment,
# txn=txn,
# lifetime=cls.hours_to_lifetime(lifetime),
# alarm=alarm,
# create=create)
# return response
#
# @classmethod
# def hours_to_lifetime(cls, days):
# now = datetime.datetime.now()
# now += datetime.timedelta(days=days)
# return now.strftime(QIWI_DATETIME_FORMAT)
#
# @classmethod
# def cancelBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.cancelBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# @classmethod
# def checkBill(cls, login=QIWI_LOGIN, password=QIWI_PASSWORD, txn=''):
# client = Client(cls.url)
# response = client.service.checkBill(
# login=login,
# password=password,
# txn=txn,
# )
# return response
#
# Path: payway/qiwi/tests/mock_provider.py
# class MockQiwiProviderRunner(Thread):
# PORT = 18888
#
# def __init__(self):
# Thread.__init__(self)
# self.setDaemon(True)
# self.services = [
# ('createBill', MockCreateBillService),
# ('cancelBill', MockCancelBillService),
# ('checkBill', MockCheckBillService),
# ]
#
# def run(self):
# app = webservices.WebService(self.services)
# app.listen(self.PORT)
# tornado.ioloop.IOLoop.instance().start()
#
# def stop(self):
# tornado.ioloop.IOLoop.instance().stop()
# self.join()
#
# RECEIVED_DATA = {}
#
# BILLING_DATE = '10.01.2012 13:00:00'
. Output only the next line. | self.assertDictContainsSubset(self.bill_data, RECEIVED_DATA['createBill']) |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
url(r'^payment/$', login_required(csrf_exempt(OrderPaymentView.as_view())), name='orders_payment'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView
from payway.orders.views.list import OrderListView
from payway.orders.views.payment import OrderPaymentView
and context:
# Path: payway/orders/views/list.py
# class OrderListView(TemplateView):
# template_name = 'orders/list.html'
#
# def get(self, request, *args, **kwargs):
# orders_page = create_paginated_page(
# query_set=Order.objects.filter(user=request.user).order_by("-id"),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ORDERS_PER_PAGE
# )
# return self.render_to_response({'orders_page': orders_page})
#
# Path: payway/orders/views/payment.py
# class OrderPaymentView(TemplateView):
# template_name = 'orders/payment.html'
#
# def get(self, request, *args, **kwargs):
# merchant = get_object_or_404(Merchant, uid=request.GET.get('merchant_uid'))
# order = Order.objects.get_or_None(
# merchant=merchant,
# uid=request.GET.get('uid') or -1
# )
# order_form = OrderForm(data=request.GET, accounts=self.get_accounts_list(request))
# return self.render_to_response({
# 'order_form': order_form,
# 'is_paid': order.is_paid if order else False,
# 'success_url': merchant.success_url,
# 'fail_url': merchant.fail_url,
# })
#
# @transaction.commit_on_success
# def post(self, request):
# accounts = self.get_accounts_list(request)
# order_form = OrderForm(data=request.POST, accounts=accounts)
#
# if order_form.is_valid():
# account = get_object_or_404(Account, user=request.user, uid=order_form.cleaned_data['account'])
# merchant = get_object_or_404(Merchant, uid=order_form.cleaned_data['merchant_uid'])
# merchant_account = get_object_or_404(Account, user=merchant.user, uid=order_form.cleaned_data['merchant_account'])
#
# order_sum = Money(order_form.cleaned_data['sum'], account.currency)
# order_uid = order_form.cleaned_data['uid']
#
# if order_sum <= account.get_balance():
# order, created = Order.objects.get_or_create(
# uid=order_uid,
# account=account,
# merchant=merchant,
# defaults={
# 'uid': order_uid,
# 'account': account,
# 'sum': order_sum,
# 'merchant': merchant,
# 'description': order_form.cleaned_data['description']
# }
# )
# if not created:
# order.sum = order_sum
#
# if not order.is_paid:
# response = MerchantHttpClient.notify(merchant, order)
# if RESPONSE_STATUS.OK not in response:
# order.set_paid(False)
# messages.error(request, _("Connection error. Merchant couldn't process order! Merchant response ") + response)
# else:
# account.transfer(order_sum, merchant_account)
# order.set_paid(True)
# messages.info(request, _("Order paid successfully"))
#
# order.save()
# order_form.set_account_field_choices(self.get_accounts_list(request))
#
# return self.render_to_response({
# 'order_form': order_form,
# 'is_paid': order.is_paid,
# 'success_url': merchant.success_url,
# 'fail_url': merchant.fail_url,
# })
#
# order_form.set_not_enough_money_error()
#
# return self.render_to_response({
# 'order_form': order_form,
# })
#
# def get_accounts_list(self, request):
# return get_list_or_404(Account, user=request.user)
which might include code, classes, or functions. Output only the next line. | url(r'^list/$', login_required(OrderListView.as_view()), name='orders_list'), |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
urlpatterns = patterns('',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView
from payway.orders.views.list import OrderListView
from payway.orders.views.payment import OrderPaymentView
and context:
# Path: payway/orders/views/list.py
# class OrderListView(TemplateView):
# template_name = 'orders/list.html'
#
# def get(self, request, *args, **kwargs):
# orders_page = create_paginated_page(
# query_set=Order.objects.filter(user=request.user).order_by("-id"),
# page_number=request.GET.get('page') or 1,
# objects_per_page=ORDERS_PER_PAGE
# )
# return self.render_to_response({'orders_page': orders_page})
#
# Path: payway/orders/views/payment.py
# class OrderPaymentView(TemplateView):
# template_name = 'orders/payment.html'
#
# def get(self, request, *args, **kwargs):
# merchant = get_object_or_404(Merchant, uid=request.GET.get('merchant_uid'))
# order = Order.objects.get_or_None(
# merchant=merchant,
# uid=request.GET.get('uid') or -1
# )
# order_form = OrderForm(data=request.GET, accounts=self.get_accounts_list(request))
# return self.render_to_response({
# 'order_form': order_form,
# 'is_paid': order.is_paid if order else False,
# 'success_url': merchant.success_url,
# 'fail_url': merchant.fail_url,
# })
#
# @transaction.commit_on_success
# def post(self, request):
# accounts = self.get_accounts_list(request)
# order_form = OrderForm(data=request.POST, accounts=accounts)
#
# if order_form.is_valid():
# account = get_object_or_404(Account, user=request.user, uid=order_form.cleaned_data['account'])
# merchant = get_object_or_404(Merchant, uid=order_form.cleaned_data['merchant_uid'])
# merchant_account = get_object_or_404(Account, user=merchant.user, uid=order_form.cleaned_data['merchant_account'])
#
# order_sum = Money(order_form.cleaned_data['sum'], account.currency)
# order_uid = order_form.cleaned_data['uid']
#
# if order_sum <= account.get_balance():
# order, created = Order.objects.get_or_create(
# uid=order_uid,
# account=account,
# merchant=merchant,
# defaults={
# 'uid': order_uid,
# 'account': account,
# 'sum': order_sum,
# 'merchant': merchant,
# 'description': order_form.cleaned_data['description']
# }
# )
# if not created:
# order.sum = order_sum
#
# if not order.is_paid:
# response = MerchantHttpClient.notify(merchant, order)
# if RESPONSE_STATUS.OK not in response:
# order.set_paid(False)
# messages.error(request, _("Connection error. Merchant couldn't process order! Merchant response ") + response)
# else:
# account.transfer(order_sum, merchant_account)
# order.set_paid(True)
# messages.info(request, _("Order paid successfully"))
#
# order.save()
# order_form.set_account_field_choices(self.get_accounts_list(request))
#
# return self.render_to_response({
# 'order_form': order_form,
# 'is_paid': order.is_paid,
# 'success_url': merchant.success_url,
# 'fail_url': merchant.fail_url,
# })
#
# order_form.set_not_enough_money_error()
#
# return self.render_to_response({
# 'order_form': order_form,
# })
#
# def get_accounts_list(self, request):
# return get_list_or_404(Account, user=request.user)
which might include code, classes, or functions. Output only the next line. | url(r'^payment/$', login_required(csrf_exempt(OrderPaymentView.as_view())), name='orders_payment'), |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class InvoicesListListView(TemplateView):
template_name = 'accounts/invoices_list.html'
def get(self, request, *args, **kwargs):
account_uid = int(kwargs.get('account_uid', -1))
account = get_object_or_404(Account, uid=account_uid)
invoices_page = create_paginated_page(
query_set=account.invoices.all().order_by('-created'),
page_number=request.GET.get('page') or 1,
<|code_end|>
. Use current file imports:
(from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import INVOICES_PER_PAGE
from payway.accounts.models import Account)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/conf/settings.py
# INVOICES_PER_PAGE = getattr(settings, 'INVOICES_PER_PAGE', 5)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
. Output only the next line. | objects_per_page=INVOICES_PER_PAGE |
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class InvoicesListListView(TemplateView):
template_name = 'accounts/invoices_list.html'
def get(self, request, *args, **kwargs):
account_uid = int(kwargs.get('account_uid', -1))
<|code_end|>
. Use current file imports:
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import INVOICES_PER_PAGE
from payway.accounts.models import Account
and context (classes, functions, or code) from other files:
# Path: payway/accounts/conf/settings.py
# INVOICES_PER_PAGE = getattr(settings, 'INVOICES_PER_PAGE', 5)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
. Output only the next line. | account = get_object_or_404(Account, uid=account_uid) |
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class MerchantHttpClientTestCase(TestCase):
fixtures = [
"payway_merchants_merchants.json",
"payway_orders_orders.json",
]
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from simptools.wrappers.http import HttpClient
from payway.merchants.models import Merchant
from payway.merchants.tests.http.mocks import *
and context from other files:
# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
#
# URL_METHODS = Choices(
# ('POST', 'POST'),
# ('GET', 'GET'),
# )
#
# user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
# name = models.CharField('Имя', max_length=255)
# secret_key = models.CharField(_('secret key'), max_length=50)
#
# result_url = models.URLField(_('result url'))
# result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
#
# success_url = models.URLField(_('success url'))
# fail_url = models.URLField(_('fail url'))
#
# class Meta:
# verbose_name = 'продавец'
# verbose_name_plural = 'продавцы'
# db_table = 'payway_merchants'
, which may include functions, classes, or code. Output only the next line. | self.merchant = Merchant.objects.get(uid=972855239) |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class OrderForm(forms.Form):
uid = forms.IntegerField(
label=_('order number'),
min_value=0,
max_value=RandomUIDAbstractModel.MAX_UID,
widget=forms.TextInput(attrs={'readonly':'readonly'}),
)
sum = forms.DecimalField(
label=_('order sum'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.forms.util import ErrorList
from django.utils.translation import ugettext_lazy as _
from django_simptools.models import RandomUIDAbstractModel
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES
from payway.orders.conf.settings import ORDER_MIN_SUM
and context:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# Path: payway/orders/conf/settings.py
# ORDER_MIN_SUM = getattr(settings, 'ORDERS_ORDER_MIN_SUM', 5)
which might include code, classes, or functions. Output only the next line. | max_digits=MAX_MONEY_DIGITS, |
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class OrderForm(forms.Form):
uid = forms.IntegerField(
label=_('order number'),
min_value=0,
max_value=RandomUIDAbstractModel.MAX_UID,
widget=forms.TextInput(attrs={'readonly':'readonly'}),
)
sum = forms.DecimalField(
label=_('order sum'),
max_digits=MAX_MONEY_DIGITS,
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.forms.util import ErrorList
from django.utils.translation import ugettext_lazy as _
from django_simptools.models import RandomUIDAbstractModel
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES
from payway.orders.conf.settings import ORDER_MIN_SUM
and context (classes, functions, sometimes code) from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# Path: payway/orders/conf/settings.py
# ORDER_MIN_SUM = getattr(settings, 'ORDERS_ORDER_MIN_SUM', 5)
. Output only the next line. | decimal_places=MAX_MONEY_PLACES, |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class OrderForm(forms.Form):
uid = forms.IntegerField(
label=_('order number'),
min_value=0,
max_value=RandomUIDAbstractModel.MAX_UID,
widget=forms.TextInput(attrs={'readonly':'readonly'}),
)
sum = forms.DecimalField(
label=_('order sum'),
max_digits=MAX_MONEY_DIGITS,
decimal_places=MAX_MONEY_PLACES,
<|code_end|>
. Use current file imports:
(from django import forms
from django.forms.util import ErrorList
from django.utils.translation import ugettext_lazy as _
from django_simptools.models import RandomUIDAbstractModel
from payway.accounts.models import MAX_MONEY_DIGITS, MAX_MONEY_PLACES
from payway.orders.conf.settings import ORDER_MIN_SUM)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/models.py
# MAX_MONEY_DIGITS = 20
#
# MAX_MONEY_PLACES = 2
#
# Path: payway/orders/conf/settings.py
# ORDER_MIN_SUM = getattr(settings, 'ORDERS_ORDER_MIN_SUM', 5)
. Output only the next line. | min_value=ORDER_MIN_SUM, |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountStatementView(TemplateView):
template_name = 'accounts/statement.html'
def get(self, request, *args, **kwargs):
account_uid = int(kwargs.get('account_uid', -1))
account = get_object_or_404(Account, uid=account_uid)
transactions_page = create_paginated_page(
query_set=Transaction.objects.filter(account=account).order_by('-created'),
page_number=request.GET.get('page') or 1,
<|code_end|>
. Use current file imports:
(from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import TRANSACTIONS_PER_PAGE
from payway.accounts.models import Account, Transaction)
and context including class names, function names, or small code snippets from other files:
# Path: payway/accounts/conf/settings.py
# TRANSACTIONS_PER_PAGE = getattr(settings, 'TRANSACTIONS_PER_PAGE', 10)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
. Output only the next line. | objects_per_page=TRANSACTIONS_PER_PAGE |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountStatementView(TemplateView):
template_name = 'accounts/statement.html'
def get(self, request, *args, **kwargs):
account_uid = int(kwargs.get('account_uid', -1))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import TRANSACTIONS_PER_PAGE
from payway.accounts.models import Account, Transaction
and context:
# Path: payway/accounts/conf/settings.py
# TRANSACTIONS_PER_PAGE = getattr(settings, 'TRANSACTIONS_PER_PAGE', 10)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | account = get_object_or_404(Account, uid=account_uid) |
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AccountStatementView(TemplateView):
template_name = 'accounts/statement.html'
def get(self, request, *args, **kwargs):
account_uid = int(kwargs.get('account_uid', -1))
account = get_object_or_404(Account, uid=account_uid)
transactions_page = create_paginated_page(
<|code_end|>
with the help of current file imports:
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django_simptools.shortcuts import create_paginated_page
from payway.accounts.conf.settings import TRANSACTIONS_PER_PAGE
from payway.accounts.models import Account, Transaction
and context from other files:
# Path: payway/accounts/conf/settings.py
# TRANSACTIONS_PER_PAGE = getattr(settings, 'TRANSACTIONS_PER_PAGE', 10)
#
# Path: payway/accounts/models.py
# class Account(RandomUIDAbstractModel):
# user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
# currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
# permissions = (('can_view_account_report', 'Can view account report'),)
# db_table = 'payway_accounts'
#
# @property
# def currency(self):
# currency = None
# if self.currency_code:
# currency = get_currency(self.currency_code)
# return currency
#
# def __unicode__(self):
# return u"{0} {1}".format(self.uid, self.currency)
#
# def get_balance(self):
# sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
# return round_down(Money(sum, self.currency))
#
# def withdraw(self, money, allow_overdraft=False):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't withdraw a negative amount")
#
# if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
# raise Overdraft
#
# return Transaction.objects.create(
# account=self,
# money_amount=money * '-1.0',
# )
#
# def add(self, money):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't add a negative money amount")
#
# return Transaction.objects.create(
# account=self,
# money_amount=money,
# )
#
# def transfer(self, money, to_account):
# self.assert_correct_currency(money)
#
# if money < Money(0, self.currency):
# raise ValueError("You can't transfer a negative money amount")
#
# self.withdraw(money)
#
# return Transaction.objects.create(
# account=to_account,
# money_amount=money,
# )
#
# def assert_correct_currency(self, money):
# if money.currency != self.currency:
# raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))
#
# class Transaction(TimeStampedModel):
# account = models.ForeignKey(Account, related_name='transactions', verbose_name=_('account'))
# money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
# objects = ChainableQuerySetManager(TransactionQuerySet)
#
# class Meta:
# verbose_name = _('transaction')
# verbose_name_plural = _('transactions')
# db_table = 'payway_transactions'
#
# def __unicode__(self):
# return 'Transaction #%d (%s)' % (self.id, self.money_amount)
#
# def save(self, *args, **kwargs):
# self.money_amount = round_down(self.money_amount)
# super(Transaction, self).save(*args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | query_set=Transaction.objects.filter(account=account).order_by('-created'), |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class Command(NoArgsCommand):
def handle_noargs(self, **options):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import NoArgsCommand
from payway.qiwi.soap.server import run_qiwi_soap_server
and context:
# Path: payway/qiwi/soap/server.py
# def run_qiwi_soap_server():
# tornado.options.parse_command_line()
# tornado.options.parse_config_file(QIWI_SOAP_SERVER_CONF)
#
# service = [('UpdateBillService', UpdateBillSoapHandler)]
# app = webservices.WebService(service)
# app.listen(QIWI_SOAP_SERVER_PORT)
# logging.info("Starting torando web server on port {0}".format(QIWI_SOAP_SERVER_PORT))
# tornado.ioloop.IOLoop.instance().start()
which might include code, classes, or functions. Output only the next line. | run_qiwi_soap_server() |
Given snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class AddAccountViewTests(BaseViewTestCase):
def setUp(self):
self.create_new_user_with_account()
self._url = reverse("accounts_add_account", args=['RUB'])
def test_get(self):
accounts_count = self.user.accounts.count()
self.assert_redirects(reverse('accounts_list'))
self.assertEquals(accounts_count+1, self.user.accounts.count())
def test_get_with_wrong_currency(self):
url = reverse("accounts_add_account", args=['XXX'])
response = self.client.get(url)
self.assertRedirects(response, reverse('accounts_list'))
self.assert_has_message(
response,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.messages import constants
from django.core.urlresolvers import reverse
from payway.accounts.views.add_account import AddAccountView
from payway.utils.tests.base import BaseViewTestCase
and context:
# Path: payway/accounts/views/add_account.py
# class AddAccountView(TemplateView):
# template_name = 'accounts/list.html'
#
# MESSAGES = {
# 'WRONG_CURRENCY': _('Currency not allowed!'),
# }
#
# def get(self, request, *args, **kwargs):
# currency = kwargs.get('currency')
# if currency not in dict(CURRENCY_CHOICES).keys():
# messages.warning(request, self.MESSAGES['WRONG_CURRENCY'])
# else:
# request.user.accounts.create(user=request.user, currency=currency)
# return redirect('accounts_list')
#
# Path: payway/utils/tests/base.py
# class BaseViewTestCase(AuthorizedViewTestCase):
#
# _url = ''
#
# def create_new_user_with_account(self):
# password = 'abc123'
# self.user = User.objects.create_user(
# 'user',
# 'user@example.com',
# password,
# )
# self.account = self.user.accounts.create(user=self.user, currency='RUB')
# self.account.add(Money(20, self.account.currency))
# self.client_login(username=self.user.username, password=password)
#
# def assert_url_available(self):
# response = self.client.get(self._url)
# self.failUnlessEqual(response.status_code, 200)
#
# def assert_redirects(self, expected_url):
# response = self.client.get(self._url)
# self.assertRedirects(response, expected_url)
#
# def assert_has_message(self, response, message, level):
# messages_list = CookieStorage(response)._decode(response.cookies['messages'].value)
# self.assertIn(Message(level, message), messages_list)
which might include code, classes, or functions. Output only the next line. | message=AddAccountView.MESSAGES['WRONG_CURRENCY'], |
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*-
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
TERMINATION_CODES = Choices(
(0, 'SUCCESS',_('0 Success')),
(13, 'SERVER_IS_BUSY', _('13 Server is busy, please repeat your request later')),
(150, 'AUTHORIZATION_ERROR', _('150 Authorization error (wrong login/password) ')),
(210, 'BILL_NOT_FOUND', _('210 Bill not found')),
(215, 'BILL_TXNID_EXISTS', _('215 Bill with this txn-id already exists')),
(241, 'BILL_VERY_SMALL_SUM', _('241 Very small bill sum')),
(242, 'BILL_MAXIMUM_SUM_EXCEEDED', _('242 Bill maximum sum exceeded')),
(278, 'BILL_LIST_MAX_TIME_RANGE_EXCEEDED', _('278 Bill list maximum time range exceeded')),
(298, 'NO_SUCH_AGENT', _('298 No such agent in the system')),
(300, 'UNKNOWN_ERROR', _('300 Unknown error')),
(330, 'ENCRYPTION_ERROR', _('330 Encryption error')),
(370, 'MAXIMUM_REQUEST_OVERLIMIT', _('370 Maximum allowed concurrent requests overlimit'))
)
<|code_end|>
. Use current file imports:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
from payway.accounts.models import ResponsePayment
and context (classes, functions, or code) from other files:
# Path: payway/accounts/models.py
# class ResponsePayment(InheritanceCastModel, AbstractPayment):
# """
# Parent response model
# """
# OK_STATUS = Choices((True, 'SUCCESS', _('success')), (False, 'FAIL', _('fail')))
#
# is_OK = models.BooleanField(choices=OK_STATUS, default=OK_STATUS.FAIL)
#
# class Meta:
# db_table = 'payway_response_payments'
#
# def __unicode__(self):
# return u'id:{0} is_ok:{2}'.format(self.id, self.money_amount, self.is_OK)
. Output only the next line. | class Bill(ResponsePayment): |
Predict the next line for this snippet: <|code_start|>
code = "```py\n{0}\n```"
class Moderation(Cog):
def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.discord_path = bot.path.discord
self.files_path = bot.path.files
self.nick_massing = []
self.nick_unmassing = []
@commands.command(pass_context=True)
@commands.cooldown(2, 5, commands.BucketType.server)
<|code_end|>
with the help of current file imports:
import asyncio, discord, aiohttp
import re, io, random, datetime
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
, which may contain function names, class names, or code. Output only the next line. | @checks.mod_or_perm(manage_messages=True) |
Predict the next line for this snippet: <|code_start|>
chatbot = ChatBot("NotSoBot",
trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
output_adapter="chatterbot.output.OutputFormatAdapter",
output_format='text',
database='chatterbot-database',
database_uri='mongodb://localhost:27017/')
cb = Cleverbot()
<|code_end|>
with the help of current file imports:
import discord
import asyncio
import re
from cleverbot import Cleverbot
from discord.ext import commands
from chatterbot import ChatBot
from mods.cog import Cog
from utils import checks
and context from other files:
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
#
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
, which may contain function names, class names, or code. Output only the next line. | class AI(Cog): |
Here is a snippet: <|code_start|> output_format='text',
database='chatterbot-database',
database_uri='mongodb://localhost:27017/')
cb = Cleverbot()
class AI(Cog):
def __init__(self, bot):
super().__init__(bot)
self.ai_target = {}
@commands.command(aliases=['cb'])
async def cleverbot(self, *, question:str):
await self.bot.say(':speech_balloon: '+cb.ask(question)[:2000])
@commands.group(pass_context=True, aliases=['artificialinteligence', 'talk'], invoke_without_command=True)
async def ai(self, ctx, *, msg:str=None):
"""Toggle AI Targeted Responses"""
if msg != None:
await self.bot.send_typing(ctx.message.channel)
ask_msg = ctx.message.content[:899]
await self.bot.say("**{0}**\n".format(ctx.message.author.name)+str(chatbot.get_response(ask_msg)))
return
if any([ctx.message.author.id == x for x in self.ai_target]) == False:
await self.bot.say("ok, AI targetting user `{0}`\n".format(ctx.message.author.name))
self.ai_target.update({ctx.message.author.id:ctx.message.channel.id})
else:
await self.bot.say("ok, removed AI target `{0}`".format(ctx.message.author.name))
del self.ai_target[ctx.message.author.id]
@ai.command(name='remove', aliases=['forceremove'], pass_context=True)
<|code_end|>
. Write the next line using the current file imports:
import discord
import asyncio
import re
from cleverbot import Cleverbot
from discord.ext import commands
from chatterbot import ChatBot
from mods.cog import Cog
from utils import checks
and context from other files:
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
#
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
, which may include functions, classes, or code. Output only the next line. | @checks.mod_or_perm(manage_server=True) |
Continue the code snippet: <|code_start|> def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.escape = bot.escape
self.bytes_download = bot.bytes_download
self.get_json = bot.get_json
async def banned_tags(self, ctx, search):
if ctx.message.channel.is_private:
return False
sql = 'SELECT * FROM banned_nsfw_tags WHERE server={0}'
sql = sql.format(ctx.message.server.id)
result = self.cursor.execute(sql).fetchall()
tags = []
for x in result:
tags.append(x['tag'])
found = []
for tag in tags:
for s in [x for x in search]:
try:
index = tags.index(str(s))
found.append(tags[index])
except (IndexError, ValueError):
continue
if len(found) != 0:
await self.bot.send_message(ctx.message.channel, ':no_entry: Your search included banned tag(s): `{0}`'.format(', '.join(found)))
return True
return False
@commands.group(pass_context=True, aliases=['bannsfwtag', 'bannsfwsearch', 'nsfwban'], invoke_without_command=True, no_pm=True)
<|code_end|>
. Use current file imports:
import discord
import random
import json
import xml.etree.ElementTree
import aiohttp
import bs4
import sys
from io import BytesIO
from discord.ext import commands
from utils import checks
from mods.cog import Cog
from urllib.parse import quote
and context (classes, functions, or code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.mod_or_perm(manage_server=True) |
Predict the next line for this snippet: <|code_start|>
class Commands(Cog):
def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.escape = bot.escape
@commands.group(pass_context=True, aliases=['setprefix', 'changeprefix'], invoke_without_command=True, no_pm=True)
<|code_end|>
with the help of current file imports:
import asyncio
import discord
import sys
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
, which may contain function names, class names, or code. Output only the next line. | @checks.admin_or_perm(manage_server=True) |
Predict the next line after this snippet: <|code_start|>
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
#hard coded color roles cause I don't want to rewrite this and deal with discord roles, lul
class Utils(Cog):
def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.discord_path = bot.path.discord
self.files_path = bot.path.files
self.download = bot.download
self.bytes_download = bot.bytes_download
self.get_json = bot.get_json
self.truncate = bot.truncate
self.ping_responses = ['redacted']
self.ping_count = random.randint(0, len(self.ping_responses)-1)
self.color_roles = ['red', 'green', 'blue', 'purple', 'orange', 'black', 'white', 'cyan', 'lime', 'pink', 'yellow', 'lightred', 'lavender', 'salmon', 'darkblue', 'darkpurple']
@commands.command(pass_context=True)
@commands.cooldown(1, 10)
async def status(self, ctx, *, status:str):
"""changes bots status"""
await self.bot.change_presence(game=discord.Game(name=status))
await self.bot.say("ok, status changed to ``" + status + "``")
@commands.command(pass_context=True)
<|code_end|>
using the current file's imports:
import asyncio, discord, aiohttp
import os, sys, traceback
import re, json, io, copy, random, hashlib
import time, pytz
import textblob, tabulate
from discord.ext import commands
from sys import argv, path
from io import BytesIO
from utils import checks
from mods.cog import Cog
from mods.Fun import google_api
and any relevant context from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.is_owner() |
Given the code snippet: <|code_start|>
#mainly from https://github.com/Rapptz/RoboDanny/blob/master/cogs/repl.py
class Repl(Cog):
def __init__(self, bot):
super().__init__(bot)
self.sessions = set()
self.cursor = bot.mysql.cursor
async def cleanup_code(self, content):
"""Automatically removes code blocks from the code."""
if content.startswith('```') and content.endswith('```'):
clean = '\n'.join(content.split('\n')[1:-1])
else:
clean = content.strip('` \n')
if clean.startswith('http'):
with aiohttp.ClientSession() as session:
async with session.get(clean) as r:
code = await r.text()
clean = code
return clean
def get_syntax_error(self, e):
return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)
@commands.command(pass_context=True, hidden=True)
<|code_end|>
, generate the next line using the imports in this file:
from discord.ext import commands
from utils import checks
from contextlib import redirect_stdout
from mods.cog import Cog
import asyncio
import traceback
import discord
import inspect
import aiohttp
import io
and context (functions, classes, or occasionally code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.is_owner() |
Using the snippet: <|code_start|> except KeyError:
content = ''
else:
content = fromstring(content)
content = format(content)
parsed_posts.append({
'content': content,
'url': url,
})
return parsed_posts
def get_discord_posts(board):
'''All posts that are in discords chat limits'''
posts = get_posts(board)
posts = filter(lambda x: x['content'], posts)
posts = filter(lambda x: len(x['content']) >= 20, posts)
return posts
def r_f_discord_post(board):
'''Random formatted post that is within discord limits'''
posts = get_discord_posts(board)
posts = tuple(post['content'] for post in posts)
post = random.choice(posts)
return post
<|code_end|>
, determine the next line of code. You have imports:
import requests
import random
import re
from discord.ext import commands
from lxml.html import fromstring
from mods.cog import Cog
and context (class names, function names, or code) available:
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | class Chan(Cog): |
Given the following code snippet before the placeholder: <|code_start|> results = ""
for s in result:
owner_id = s['user']
tag = s['tag']
tag = self.tag_formatter(tag)
if owner_id == ctx.message.author.id:
results += "Tag: `{0}` | Owner: <@{1}>\n".format(tag, owner_id)
else:
user = await self.bot.get_user_info(str(owner_id))
results += "Tag: `{0}` | Owner: **{1}**\n".format(tag, user)
await self.truncate(ctx.message.channel, ":white_check_mark: Results:\n{1}".format(txt, results))
@tag_search.command(name='content', pass_context=True, no_pm=True)
async def tag_search_content(self, ctx, *, txt:str):
txt = self.tag_formatter(txt)
sql = "SELECT * FROM `tags` WHERE content LIKE {0} AND server IS NOT NULL"
sql = sql.format("%"+self.escape(txt)+"%")
result = self.cursor.execute(sql).fetchall()
if len(result) == 0:
await self.bot.say(":exclamation: No results found for tags with content like `{0}`".format(txt))
return
results = ""
for s in result:
owner_id = s['user']
tag = s['tag']
tag = self.tag_formatter(tag)
results += "Tag Name: {0} | Owner: <@{1}>\n".format(tag, owner_id)
await self.bot.say("**Results For Tags With Content Like `{0}`**\n{1}".format(txt, results))
@tag.group(name='forceremove', pass_context=True, no_pm=True)
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import discord
import os
import re
import random
import math
import io
import sys, traceback
import linecache
from io import StringIO
from itertools import islice, cycle
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context including class names, function names, and sometimes code from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.is_owner()
|
Given the code snippet: <|code_start|>
#old code (hence the sql mess), y fix
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
def check_int(k):
if k[0] in ('-', '+'):
return k[1:].isdigit()
return k.isdigit()
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import discord
import os
import re
import random
import math
import io
import sys, traceback
import linecache
from io import StringIO
from itertools import islice, cycle
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context (functions, classes, or occasionally code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | class Tags(Cog):
|
Based on the snippet: <|code_start|>
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
class Logs(Cog):
def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.escape = bot.escape
self.discord_path = bot.path.discord
self.files_path = bot.path.files
self.download = bot.download
self.bytes_download = bot.bytes_download
self.truncate = bot.truncate
self.banned_users = {}
self.attachment_cache = {}
def remove_server(self, server):
remove_sql = "DELETE FROM `logs` WHERE server={0}"
remove_sql = remove_sql.format(server.id)
self.cursor.execute(remove_sql)
self.cursor.commit()
def remove_server_tracking(self, server):
remove_sql = "DELETE FROM `tracking` WHERE server={0}"
remove_sql = remove_sql.format(server.id)
self.cursor.execute(remove_sql)
self.cursor.commit()
@commands.group(pass_context=True, aliases=['slogs', 'adminlogs'], no_pm=True, invoke_without_command=True)
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import discord
import sys
import re
import time
import numpy as np
import PIL
import datetime
from discord.ext import commands
from utils import checks
from io import BytesIO
from mods.cog import Cog
and context (classes, functions, sometimes code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.admin_or_perm(manage_server=True)
|
Given snippet: <|code_start|>
def edge(pixels, image, angle):
img = Image.open(image)
img = img.rotate(angle, expand=True)
edges = img.filter(ImageFilter.FIND_EDGES)
edges = edges.convert('RGBA')
edge_data = edges.load()
filter_pixels = []
edge_pixels = []
intervals = []
for y in range(img.size[1]):
filter_pixels.append([])
for x in range(img.size[0]):
filter_pixels[y].append(edge_data[x, y])
for y in range(len(pixels)):
edge_pixels.append([])
for x in range(len(pixels[0])):
if util.lightness(filter_pixels[y][x]) < 0.25:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PIL import Image, ImageFilter
from pixelsort import constants
from pixelsort import util
import random as rand
and context:
# Path: pixelsort/constants.py
which might include code, classes, or functions. Output only the next line. | edge_pixels[y].append(constants.white_pixel) |
Here is a snippet: <|code_start|>
parser = mods.Tags.Tags.parser
default_join = 'Welcome to **{server}** - {mention}! You are the {servercount} member to join.'
default_leave = '**{user}#{discrim}** has left the server.'
#http://stackoverflow.com/a/16671271
def number_formating(n):
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
class Object():
pass
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
class JoinLeave(Cog):
def __init__(self, bot):
super().__init__(bot)
self.cursor = bot.mysql.cursor
self.escape = bot.escape
@commands.group(pass_context=True, aliases=['welcomemessage', 'join'], invoke_without_command=True, no_pm=True)
<|code_end|>
. Write the next line using the current file imports:
import discord
import asyncio
import mods.Tags
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
, which may include functions, classes, or code. Output only the next line. | @checks.admin_or_perm(manage_server=True) |
Continue the code snippet: <|code_start|>
parser = mods.Tags.Tags.parser
default_join = 'Welcome to **{server}** - {mention}! You are the {servercount} member to join.'
default_leave = '**{user}#{discrim}** has left the server.'
#http://stackoverflow.com/a/16671271
def number_formating(n):
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
class Object():
pass
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
<|code_end|>
. Use current file imports:
import discord
import asyncio
import mods.Tags
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context (classes, functions, or code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | class JoinLeave(Cog): |
Based on the snippet: <|code_start|>
class SteamId(object):
def __init__(self):
super(SteamId, self).__init__()
self._universe = None
self._accountType = None
self._instance = None
self._accountId = None
@property
def universe(self):
return self._universe
@property
def accountType(self):
return self._accountType
@property
def instance(self):
return self._instance
@property
def accountId(self):
return self._accountId
@property
def steamId(self):
x = "0"
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from .steamaccountuniverse import SteamAccountUniverse
from .steamaccounttype import SteamAccountType
and context (classes, functions, sometimes code) from other files:
# Path: steam/steamaccountuniverse.py
# class SteamAccountUniverse(object):
# Invalid = 0
# Public = 1
# Beta = 2
# Internal = 3
# Dev = 4
#
# Path: steam/steamaccounttype.py
# class SteamAccountType(object):
# Invalid = 0
# Individual = 1
# Multiseat = 2
# GameServer = 3
# AnonymousGameServer = 4
# Pending = 5
# ContentServer = 6
# Clan = 7
# Chat = 8
# ClanChat = 8
# LobbyChat = 8
# P2PSuperSeeder = 9
# AnonymousUser = 10
#
# DefaultInstanceIds = {}
# DefaultInstanceIds[Invalid] = 0
# DefaultInstanceIds[Individual] = 1
# DefaultInstanceIds[Multiseat] = 0
# DefaultInstanceIds[GameServer] = 1
# DefaultInstanceIds[AnonymousGameServer] = 0
# DefaultInstanceIds[Pending] = 0
# DefaultInstanceIds[ContentServer] = 0
# DefaultInstanceIds[Clan] = 0
# DefaultInstanceIds[Chat] = 0
# DefaultInstanceIds[ClanChat] = 0x00080000
# DefaultInstanceIds[LobbyChat] = 0x00040000
# DefaultInstanceIds[P2PSuperSeeder] = 0
# DefaultInstanceIds[AnonymousUser] = 0
# DefaultInstanceIds["c"] = 0x00080000
# DefaultInstanceIds["L"] = 0x00040000
#
# Characters = {}
# Characters[Invalid] = "I"
# Characters[Individual] = "U"
# Characters[Multiseat] = "M"
# Characters[GameServer] = "G"
# Characters[AnonymousGameServer] = "A"
# Characters[Pending] = "P"
# Characters[ContentServer] = "C"
# Characters[Clan] = "g"
# Characters[Chat] = "T"
# Characters[ClanChat] = "c"
# Characters[LobbyChat] = "L"
# Characters[AnonymousUser] = "a"
#
# CharacterAccountTypes = {}
# CharacterAccountTypes["I"] = Invalid
# CharacterAccountTypes["U"] = Individual
# CharacterAccountTypes["M"] = Multiseat
# CharacterAccountTypes["G"] = GameServer
# CharacterAccountTypes["A"] = AnonymousGameServer
# CharacterAccountTypes["P"] = Pending
# CharacterAccountTypes["C"] = ContentServer
# CharacterAccountTypes["g"] = Clan
# CharacterAccountTypes["T"] = Chat
# CharacterAccountTypes["c"] = ClanChat
# CharacterAccountTypes["L"] = LobbyChat
# CharacterAccountTypes["a"] = AnonymousUser
#
# @classmethod
# def defaultInstanceId(cls, x):
# if x in cls.DefaultInstanceIds: return cls.DefaultInstanceIds[x]
# return cls.DefaultInstanceIds.get(cls.CharacterAccountTypes.get(x))
#
# @classmethod
# def fromCharacter(cls, c):
# return cls.CharacterAccountTypes.get(c)
#
# @classmethod
# def toCharacter(cls, accountType):
# return cls.Characters.get(accountType)
. Output only the next line. | if self.universe != SteamAccountUniverse.Public: x = "?"
|
Given snippet: <|code_start|> self._instance = None
self._accountId = None
@property
def universe(self):
return self._universe
@property
def accountType(self):
return self._accountType
@property
def instance(self):
return self._instance
@property
def accountId(self):
return self._accountId
@property
def steamId(self):
x = "0"
if self.universe != SteamAccountUniverse.Public: x = "?"
y = self.accountId & 1
z = self.accountId >> 1
return "STEAM_%s:%d:%d" % (x, y, z)
@property
def steamId3(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from .steamaccountuniverse import SteamAccountUniverse
from .steamaccounttype import SteamAccountType
and context:
# Path: steam/steamaccountuniverse.py
# class SteamAccountUniverse(object):
# Invalid = 0
# Public = 1
# Beta = 2
# Internal = 3
# Dev = 4
#
# Path: steam/steamaccounttype.py
# class SteamAccountType(object):
# Invalid = 0
# Individual = 1
# Multiseat = 2
# GameServer = 3
# AnonymousGameServer = 4
# Pending = 5
# ContentServer = 6
# Clan = 7
# Chat = 8
# ClanChat = 8
# LobbyChat = 8
# P2PSuperSeeder = 9
# AnonymousUser = 10
#
# DefaultInstanceIds = {}
# DefaultInstanceIds[Invalid] = 0
# DefaultInstanceIds[Individual] = 1
# DefaultInstanceIds[Multiseat] = 0
# DefaultInstanceIds[GameServer] = 1
# DefaultInstanceIds[AnonymousGameServer] = 0
# DefaultInstanceIds[Pending] = 0
# DefaultInstanceIds[ContentServer] = 0
# DefaultInstanceIds[Clan] = 0
# DefaultInstanceIds[Chat] = 0
# DefaultInstanceIds[ClanChat] = 0x00080000
# DefaultInstanceIds[LobbyChat] = 0x00040000
# DefaultInstanceIds[P2PSuperSeeder] = 0
# DefaultInstanceIds[AnonymousUser] = 0
# DefaultInstanceIds["c"] = 0x00080000
# DefaultInstanceIds["L"] = 0x00040000
#
# Characters = {}
# Characters[Invalid] = "I"
# Characters[Individual] = "U"
# Characters[Multiseat] = "M"
# Characters[GameServer] = "G"
# Characters[AnonymousGameServer] = "A"
# Characters[Pending] = "P"
# Characters[ContentServer] = "C"
# Characters[Clan] = "g"
# Characters[Chat] = "T"
# Characters[ClanChat] = "c"
# Characters[LobbyChat] = "L"
# Characters[AnonymousUser] = "a"
#
# CharacterAccountTypes = {}
# CharacterAccountTypes["I"] = Invalid
# CharacterAccountTypes["U"] = Individual
# CharacterAccountTypes["M"] = Multiseat
# CharacterAccountTypes["G"] = GameServer
# CharacterAccountTypes["A"] = AnonymousGameServer
# CharacterAccountTypes["P"] = Pending
# CharacterAccountTypes["C"] = ContentServer
# CharacterAccountTypes["g"] = Clan
# CharacterAccountTypes["T"] = Chat
# CharacterAccountTypes["c"] = ClanChat
# CharacterAccountTypes["L"] = LobbyChat
# CharacterAccountTypes["a"] = AnonymousUser
#
# @classmethod
# def defaultInstanceId(cls, x):
# if x in cls.DefaultInstanceIds: return cls.DefaultInstanceIds[x]
# return cls.DefaultInstanceIds.get(cls.CharacterAccountTypes.get(x))
#
# @classmethod
# def fromCharacter(cls, c):
# return cls.CharacterAccountTypes.get(c)
#
# @classmethod
# def toCharacter(cls, accountType):
# return cls.Characters.get(accountType)
which might include code, classes, or functions. Output only the next line. | character = SteamAccountType.toCharacter(self.accountType)
|
Based on the snippet: <|code_start|> path = self.files_path('markov/{0}/'.format(message.server.id))
await self.add_markov(path, message.content)
if message.author.id in self.users.keys() and self.users[message.author.id] == message.server.id:
path = self.files_path('markov/{0}_{1}/'.format(message.author.id, message.server.id))
await self.add_markov(path, message.content)
@commands.group(pass_context=True, aliases=['mark', 'm'], no_pm=True, invoke_without_command=True)
async def markov(self, ctx, *, text:str=None):
for m in ctx.message.mentions:
user = m
text = text.replace(user.mention, '')
break
else:
user = False
if user:
if user.id not in self.users.keys():
return
elif self.users[user.id] != ctx.message.server.id:
return
if ctx.message.server.id not in self.servers:
return
path = self.files_path('markov/{0}/'.format('{0}_{1}'.format(ctx.message.author.id, ctx.message.server.id) if user else ctx.message.server.id))
code = "var markov_ultra = require('markov-ultra');var markov = new markov_ultra['default']('{0}', 6000000000);console.log(markov.generate(2, 2000{1}))".format(path, ', `{0}`'.format(text) if text else '')
result = await self.bot.run_process(['node', '-e', code], True)
if result and result != '' and result != '\n':
await self.bot.say(str(result).replace('http//', 'http://').replace('https//', 'https://').replace('\\\\', '\\'))
else:
await self.bot.say(':warning: **Markov Failed**.')
@markov.command(name='generate', pass_context=True)
<|code_end|>
, predict the immediate next line with the help of imports:
import discord
import asyncio
import random
import re
import sys, linecache
from discord.ext import commands
from mods.cog import Cog
from utils import checks
and context (classes, functions, sometimes code) from other files:
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
#
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
. Output only the next line. | @checks.is_owner() |
Continue the code snippet: <|code_start|> thing = '{0}\n{1}'.format(max_server.name, max_)
return max_server.name, max_
async def get_channels(self):
text_channels = 0
voice_channels = 0
for server in self.bot.servers:
for channel in server.channels:
if channel.type == discord.ChannelType.text:
text_channels += 1
if channel.type == discord.ChannelType.voice:
voice_channels += 1
return text_channels, voice_channels
async def update_stats(self):
sql = 'REPLACE INTO `stats` (`shard`, `servers`, `largest_member_server`, `largest_member_server_name`, `users`, `unique_users`, `text_channels`, `voice_channels`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)'
servers = len(self.bot.servers)
largest = await self.get_largest_server()
largest_member_server = largest[1]
largest_member_server_name = largest[0]
users_array = [x for x in self.bot.get_all_members()]
users = len(users_array)
unique_users = len(set(users_array))
channels = await self.get_channels()
text_channels = channels[0]
voice_channels = channels[1]
self.cursor.execute(sql, (self.bot.shard_id, servers, largest_member_server, largest_member_server_name, users, unique_users, text_channels, voice_channels))
self.cursor.commit()
@commands.command()
<|code_end|>
. Use current file imports:
import discord
import time
import requests
import io
from discord.ext import commands
from utils import checks
from mods.cog import Cog
and context (classes, functions, or code) from other files:
# Path: utils/checks.py
# class No_Owner(commands.CommandError): pass
# class No_Perms(commands.CommandError): pass
# class No_Role(commands.CommandError): pass
# class No_Admin(commands.CommandError): pass
# class No_Mod(commands.CommandError): pass
# class No_Sup(commands.CommandError): pass
# class No_ServerandPerm(commands.CommandError): pass
# class Nsfw(commands.CommandError): pass
# def is_owner_check(message):
# def is_owner():
# def check_permissions(ctx, perms):
# def role_or_perm(t, ctx, check, **perms):
# def mod_or_perm(**perms):
# def predicate(ctx):
# def admin_or_perm(**perms):
# def predicate(ctx):
# def is_in_servers(*server_ids):
# def predicate(ctx):
# def server_and_perm(ctx, *server_ids, **perms):
# def sup(ctx):
# def nsfw():
# def predicate(ctx):
#
# Path: mods/cog.py
# class Cog(metaclass=CogMeta):
# def __init__(self, bot:NotSoBot):
# self._bot = bot
#
# @property
# def bot(self):
# return self._bot
#
# @classmethod
# def setup(cls, bot:NotSoBot):
# bot.add_cog(cls(bot))
. Output only the next line. | @checks.is_owner() |
Based on the snippet: <|code_start|> PYTHON,
"%s/plans/k8s_2t.py" % APP_PATH,
]
print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
with open(ec.plan_pid_file, "w") as f:
f.write("%d" % os.getpid())
os.execve(cmd[0], cmd, os.environ)
def validate():
cmd = [
PYTHON,
"%s/validate.py" % PROJECT_PATH,
]
print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
os.execve(cmd[0], cmd, os.environ)
def show_configs(ec):
for k, v in ec.__dict__.items():
print("%s=%s" % (k, v))
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='Enjoliver')
parser.add_argument('task', type=str, choices=["gunicorn", "plan", "matchbox", "show-configs", "validate"],
help="Choose the task to run")
parser.add_argument('--configs', type=str, default="%s/configs.yaml" % APP_PATH,
help="Choose the yaml config file")
task = parser.parse_args().task
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import multiprocessing
import os
import signal
import sys
import time
from app import (
configs,
smartdb,
ops,
gunicorn_conf
)
and context (classes, functions, sometimes code) from other files:
# Path: app/configs.py
# APP_PATH = os.path.dirname(os.path.abspath(__file__))
# PROJECT_PATH = os.path.dirname(APP_PATH)
# EC = EnjoliverConfig("%s/configs.yaml" % os.path.dirname(__file__))
# class EnjoliverConfig:
# def config_override(self, key: str, default):
# def __init__(self, yaml_full_path=os.getenv("ENJOLIVER_CONFIGS_YAML",
# "%s/configs.yaml" % APP_PATH), importer=""):
. Output only the next line. | f = parser.parse_args().configs |
Continue the code snippet: <|code_start|>
class TestConfigSyncSchedules(TestCase):
unit_path = "%s" % os.path.dirname(__file__)
tests_path = "%s" % os.path.split(unit_path)[0]
test_matchbox_path = "%s/test_matchbox" % tests_path
api_uri = "http://127.0.0.1:5000"
def test_00(self):
<|code_end|>
. Use current file imports:
import json
import os
from unittest import TestCase
from app import sync
and context (classes, functions, or code) from other files:
# Path: app/sync.py
# EC = EnjoliverConfig(importer=__file__)
# class ConfigSyncSchedules(object):
# def __init__(self, api_uri: str, matchbox_path: str, ignition_dict: dict, extra_selector_dict=None):
# def _reporting_ignitions(self):
# def get_dns_attr(fqdn: str):
# def cni_ipam(host_cidrv4: str, host_gateway: str):
# def get_first_ip_address(ip_range: str):
# def get_extra_selectors(extra_selectors: dict):
# def etcd_member_ip_list(self):
# def kubernetes_control_plane_ip_list(self):
# def kubernetes_nodes_ip_list(self):
# def order_http_uri(ips: list, ec_value: int, secure=False):
# def order_etcd_named(ips: list, ec_value: int, secure=False):
# def kubernetes_etcd_initial_cluster(self):
# def vault_etcd_initial_cluster(self):
# def fleet_etcd_initial_cluster(self):
# def kubernetes_etcd_member_client_uri_list(self):
# def vault_etcd_member_client_uri_list(self):
# def fleet_etcd_member_client_uri_list(self):
# def kubernetes_etcd_member_peer_uri_list(self):
# def vault_etcd_member_peer_uri_list(self):
# def fleet_etcd_member_peer_uri_list(self):
# def kubernetes_control_plane(self):
# def compute_disks_size(disks: list):
# def produce_matchbox_data(self, marker: str, i: int, m: dict, automatic_name: str, update_extra_metadata=None):
# def etcd_member_kubernetes_control_plane(self):
# def kubernetes_nodes(self):
# def notify(self):
# def apply(self, nb_try=2, seconds_sleep=0):
# def _query_roles(self, *roles):
# def _query_ip_list(self, role):
. Output only the next line. | s = sync.ConfigSyncSchedules( |
Given the code snippet: <|code_start|>
class TestTools(TestCase):
unit_path = "%s" % os.path.dirname(__file__)
tests_path = "%s" % os.path.split(unit_path)[0]
def test_00(self):
<|code_end|>
, generate the next line using the imports in this file:
import os
from unittest import TestCase
from app import tools
and context (functions, classes, or occasionally code) from other files:
# Path: app/tools.py
# EC = EnjoliverConfig()
# def get_mac_from_raw_query(request_raw_query: str):
# def get_verified_dns_query(interface: dict):
. Output only the next line. | self.assertIsNone(tools.get_verified_dns_query({ |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
RUNTIME_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_PATH = os.path.dirname(RUNTIME_PATH)
sys.path.append(PROJECT_PATH)
sys.path.append(RUNTIME_PATH)
for p in os.listdir(os.path.join(PROJECT_PATH, "env/lib/")):
PYTHON_LIB = os.path.join(PROJECT_PATH, "env/lib/%s/site-packages" % p)
sys.path.append(PYTHON_LIB)
def start_acserver():
cmd = ["%s/acserver/acserver" % RUNTIME_PATH, "%s/ac-config.yml" % RUNTIME_PATH]
os.execve(cmd[0], cmd, os.environ)
class AcserverError(Exception):
pass
if __name__ == '__main__':
if os.geteuid() != 0:
raise PermissionError("start as root")
with open("/dev/null", 'w') as null:
code = subprocess.call(["ip", "addr", "show", "rack0"], stdout=null)
if code != 0:
<|code_end|>
using the current file's imports:
import multiprocessing
import os.path
import signal
import subprocess
import sys
import requests
from runtime import (
config,
)
and any relevant context from other files:
# Path: runtime/config.py
# def rkt_path_d(path):
# def rkt_stage1_d(path):
# def dgr_config(path):
# def acserver_config(path):
. Output only the next line. | config.rkt_path_d(RUNTIME_PATH) |
Continue the code snippet: <|code_start|> matchbox = os.getenv("CHECK_MATCHBOX_PATH", "%s/matchbox" % cwd)
assets = "%s/assets" % matchbox
def test_discoveryC(self):
rule = "%s/%s/serve" % (self.assets, self.test_discoveryC.__name__.replace("test_", ""))
list_dir = os.listdir(rule)
self.assertIn("discoveryC", list_dir)
def test_enjoliver_agent(self):
rule = "%s/%s/serve" % (self.assets, self.test_enjoliver_agent.__name__.replace("test_", "").replace("_", "-"))
list_dir = os.listdir(rule)
self.assertIn("enjoliver-agent", list_dir)
def test_coreos(self):
rule = "%s/%s/serve" % (self.assets, self.test_coreos.__name__.replace("test_", ""))
list_dir = os.listdir(rule)
self.assertIn("coreos_production_image.bin.bz2", list_dir)
self.assertIn("coreos_production_image.bin.bz2.sig", list_dir)
self.assertIn("coreos_production_image_verity.txt", list_dir)
self.assertIn("coreos_production_pxe.vmlinuz", list_dir)
self.assertIn("coreos_production_pxe.vmlinuz.sig", list_dir)
self.assertIn("coreos_production_pxe_image.cpio.gz", list_dir)
self.assertIn("coreos_production_pxe_image.cpio.gz.sig", list_dir)
self.assertIn("version.txt", list_dir)
@unittest.skipIf(os.getenv("SKIP_ACSERVER"), "skip acserver storage")
class TestValidateAcserverStorage(unittest.TestCase):
cwd = os.path.dirname(os.path.abspath(__file__))
acserver_d = os.path.join(cwd, "runtime/acserver.d/enjoliver.local")
<|code_end|>
. Use current file imports:
import os
import unittest
import sys
from app import (
configs,
)
and context (classes, functions, or code) from other files:
# Path: app/configs.py
# APP_PATH = os.path.dirname(os.path.abspath(__file__))
# PROJECT_PATH = os.path.dirname(APP_PATH)
# EC = EnjoliverConfig("%s/configs.yaml" % os.path.dirname(__file__))
# class EnjoliverConfig:
# def config_override(self, key: str, default):
# def __init__(self, yaml_full_path=os.getenv("ENJOLIVER_CONFIGS_YAML",
# "%s/configs.yaml" % APP_PATH), importer=""):
. Output only the next line. | ec = configs.EnjoliverConfig(importer=__file__) |
Given snippet: <|code_start|>Partial Least Squares using SVD
moduleauthor:: Derek Tucker <dtucker@stat.fsu.edu>
"""
def pls_svd(time, qf, qg, no, alpha=0.0):
"""
This function computes the partial least squares using SVD
:param time: vector describing time samples
:param qf: numpy ndarray of shape (M,N) of N functions with M samples
:param qg: numpy ndarray of shape (M,N) of N functions with M samples
:param no: number of components
:param alpha: amount of smoothing (Default = 0.0 i.e., none)
:rtype: numpy ndarray
:return wqf: f weight function
:return wqg: g weight function
:return alpha: smoothing value
:return values: singular values
"""
binsize = np.diff(time)
binsize = binsize.mean()
Kfg = np.cov(qf, qg)
Kfg = Kfg[0:qf.shape[0], qf.shape[0]:Kfg.shape[0]]
nx = Kfg.shape[0]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from fdasrsf.utility_functions import diffop, geigen, innerprod_q
and context:
# Path: fdasrsf/utility_functions.py
# def diffop(n, binsize=1):
# """
# Creates a second order differential operator
#
# :param n: dimension
# :param binsize: dx (default = 1)
#
# :rtype: numpy ndarray
# :return m: matrix describing differential operator
#
# """
# m = diagflat(ones(n - 1), k=1) + diagflat(ones(n - 1), k=-1) + diagflat(2 * ones(n))
# m = inner(m.transpose(), m)
# m[0, 0] = 6
# m[-1, -1] = 6
# m /= (binsize ** 4.)
#
# return m
#
# def geigen(Amat, Bmat, Cmat):
# """
# generalized eigenvalue problem of the form
#
# max tr L'AM / sqrt(tr L'BL tr M'CM) w.r.t. L and M
#
# :param Amat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
#
# :rtype: numpy ndarray
# :return values: eigenvalues
# :return Lmat: left eigenvectors
# :return Mmat: right eigenvectors
#
# """
# if Bmat.shape[0] != Bmat.shape[1]:
# print("BMAT is not square.\n")
# sys.exit(1)
#
# if Cmat.shape[0] != Cmat.shape[1]:
# print("CMAT is not square.\n")
# sys.exit(1)
#
# p = Bmat.shape[0]
# q = Cmat.shape[0]
#
# s = min(p, q)
# tmp = fabs(Bmat - Bmat.transpose())
# tmp1 = fabs(Bmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("BMAT not symmetric..\n")
# sys.exit(1)
#
# tmp = fabs(Cmat - Cmat.transpose())
# tmp1 = fabs(Cmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("CMAT not symmetric..\n")
# sys.exit(1)
#
# Bmat = (Bmat + Bmat.transpose()) / 2.
# Cmat = (Cmat + Cmat.transpose()) / 2.
# Bfac = cholesky(Bmat)
# Cfac = cholesky(Cmat)
# Bfacinv = inv(Bfac)
# Bfacinvt = Bfacinv.transpose()
# Cfacinv = inv(Cfac)
# Dmat = Bfacinvt.dot(Amat).dot(Cfacinv)
# if p >= q:
# u, d, v = svd(Dmat)
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
# else:
# u, d, v = svd(Dmat.transpose())
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
#
# return values, Lmat, Mmat
#
# def innerprod_q(time, q1, q2):
# """
# calculates the innerproduct between two srsfs
#
# :param time vector descrbing time samples
# :param q1 vector of srsf 1
# :param q2 vector of srsf 2
#
# :rtype: scalar
# :return val: inner product value
#
# """
# val = trapz(q1 * q2, time)
# return val
which might include code, classes, or functions. Output only the next line. | D4x = diffop(nx, binsize) |
Predict the next line for this snippet: <|code_start|>
moduleauthor:: Derek Tucker <dtucker@stat.fsu.edu>
"""
def pls_svd(time, qf, qg, no, alpha=0.0):
"""
This function computes the partial least squares using SVD
:param time: vector describing time samples
:param qf: numpy ndarray of shape (M,N) of N functions with M samples
:param qg: numpy ndarray of shape (M,N) of N functions with M samples
:param no: number of components
:param alpha: amount of smoothing (Default = 0.0 i.e., none)
:rtype: numpy ndarray
:return wqf: f weight function
:return wqg: g weight function
:return alpha: smoothing value
:return values: singular values
"""
binsize = np.diff(time)
binsize = binsize.mean()
Kfg = np.cov(qf, qg)
Kfg = Kfg[0:qf.shape[0], qf.shape[0]:Kfg.shape[0]]
nx = Kfg.shape[0]
D4x = diffop(nx, binsize)
<|code_end|>
with the help of current file imports:
import numpy as np
from fdasrsf.utility_functions import diffop, geigen, innerprod_q
and context from other files:
# Path: fdasrsf/utility_functions.py
# def diffop(n, binsize=1):
# """
# Creates a second order differential operator
#
# :param n: dimension
# :param binsize: dx (default = 1)
#
# :rtype: numpy ndarray
# :return m: matrix describing differential operator
#
# """
# m = diagflat(ones(n - 1), k=1) + diagflat(ones(n - 1), k=-1) + diagflat(2 * ones(n))
# m = inner(m.transpose(), m)
# m[0, 0] = 6
# m[-1, -1] = 6
# m /= (binsize ** 4.)
#
# return m
#
# def geigen(Amat, Bmat, Cmat):
# """
# generalized eigenvalue problem of the form
#
# max tr L'AM / sqrt(tr L'BL tr M'CM) w.r.t. L and M
#
# :param Amat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
#
# :rtype: numpy ndarray
# :return values: eigenvalues
# :return Lmat: left eigenvectors
# :return Mmat: right eigenvectors
#
# """
# if Bmat.shape[0] != Bmat.shape[1]:
# print("BMAT is not square.\n")
# sys.exit(1)
#
# if Cmat.shape[0] != Cmat.shape[1]:
# print("CMAT is not square.\n")
# sys.exit(1)
#
# p = Bmat.shape[0]
# q = Cmat.shape[0]
#
# s = min(p, q)
# tmp = fabs(Bmat - Bmat.transpose())
# tmp1 = fabs(Bmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("BMAT not symmetric..\n")
# sys.exit(1)
#
# tmp = fabs(Cmat - Cmat.transpose())
# tmp1 = fabs(Cmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("CMAT not symmetric..\n")
# sys.exit(1)
#
# Bmat = (Bmat + Bmat.transpose()) / 2.
# Cmat = (Cmat + Cmat.transpose()) / 2.
# Bfac = cholesky(Bmat)
# Cfac = cholesky(Cmat)
# Bfacinv = inv(Bfac)
# Bfacinvt = Bfacinv.transpose()
# Cfacinv = inv(Cfac)
# Dmat = Bfacinvt.dot(Amat).dot(Cfacinv)
# if p >= q:
# u, d, v = svd(Dmat)
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
# else:
# u, d, v = svd(Dmat.transpose())
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
#
# return values, Lmat, Mmat
#
# def innerprod_q(time, q1, q2):
# """
# calculates the innerproduct between two srsfs
#
# :param time vector descrbing time samples
# :param q1 vector of srsf 1
# :param q2 vector of srsf 2
#
# :rtype: scalar
# :return val: inner product value
#
# """
# val = trapz(q1 * q2, time)
# return val
, which may contain function names, class names, or code. Output only the next line. | values, Lmat, Mmat = geigen(Kfg, np.eye(nx) + alpha * D4x, np.eye(nx) + alpha * D4x) |
Given snippet: <|code_start|>
def pls_svd(time, qf, qg, no, alpha=0.0):
"""
This function computes the partial least squares using SVD
:param time: vector describing time samples
:param qf: numpy ndarray of shape (M,N) of N functions with M samples
:param qg: numpy ndarray of shape (M,N) of N functions with M samples
:param no: number of components
:param alpha: amount of smoothing (Default = 0.0 i.e., none)
:rtype: numpy ndarray
:return wqf: f weight function
:return wqg: g weight function
:return alpha: smoothing value
:return values: singular values
"""
binsize = np.diff(time)
binsize = binsize.mean()
Kfg = np.cov(qf, qg)
Kfg = Kfg[0:qf.shape[0], qf.shape[0]:Kfg.shape[0]]
nx = Kfg.shape[0]
D4x = diffop(nx, binsize)
values, Lmat, Mmat = geigen(Kfg, np.eye(nx) + alpha * D4x, np.eye(nx) + alpha * D4x)
wf = Lmat[:, 0:no]
wg = Mmat[:, 0:no]
for ii in range(0, no):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from fdasrsf.utility_functions import diffop, geigen, innerprod_q
and context:
# Path: fdasrsf/utility_functions.py
# def diffop(n, binsize=1):
# """
# Creates a second order differential operator
#
# :param n: dimension
# :param binsize: dx (default = 1)
#
# :rtype: numpy ndarray
# :return m: matrix describing differential operator
#
# """
# m = diagflat(ones(n - 1), k=1) + diagflat(ones(n - 1), k=-1) + diagflat(2 * ones(n))
# m = inner(m.transpose(), m)
# m[0, 0] = 6
# m[-1, -1] = 6
# m /= (binsize ** 4.)
#
# return m
#
# def geigen(Amat, Bmat, Cmat):
# """
# generalized eigenvalue problem of the form
#
# max tr L'AM / sqrt(tr L'BL tr M'CM) w.r.t. L and M
#
# :param Amat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
# :param Bmat numpy ndarray of shape (M,N)
#
# :rtype: numpy ndarray
# :return values: eigenvalues
# :return Lmat: left eigenvectors
# :return Mmat: right eigenvectors
#
# """
# if Bmat.shape[0] != Bmat.shape[1]:
# print("BMAT is not square.\n")
# sys.exit(1)
#
# if Cmat.shape[0] != Cmat.shape[1]:
# print("CMAT is not square.\n")
# sys.exit(1)
#
# p = Bmat.shape[0]
# q = Cmat.shape[0]
#
# s = min(p, q)
# tmp = fabs(Bmat - Bmat.transpose())
# tmp1 = fabs(Bmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("BMAT not symmetric..\n")
# sys.exit(1)
#
# tmp = fabs(Cmat - Cmat.transpose())
# tmp1 = fabs(Cmat)
# if tmp.max() / tmp1.max() > 1e-10:
# print("CMAT not symmetric..\n")
# sys.exit(1)
#
# Bmat = (Bmat + Bmat.transpose()) / 2.
# Cmat = (Cmat + Cmat.transpose()) / 2.
# Bfac = cholesky(Bmat)
# Cfac = cholesky(Cmat)
# Bfacinv = inv(Bfac)
# Bfacinvt = Bfacinv.transpose()
# Cfacinv = inv(Cfac)
# Dmat = Bfacinvt.dot(Amat).dot(Cfacinv)
# if p >= q:
# u, d, v = svd(Dmat)
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
# else:
# u, d, v = svd(Dmat.transpose())
# values = d
# Lmat = Bfacinv.dot(u)
# Mmat = Cfacinv.dot(v.transpose())
#
# return values, Lmat, Mmat
#
# def innerprod_q(time, q1, q2):
# """
# calculates the innerproduct between two srsfs
#
# :param time vector descrbing time samples
# :param q1 vector of srsf 1
# :param q2 vector of srsf 2
#
# :rtype: scalar
# :return val: inner product value
#
# """
# val = trapz(q1 * q2, time)
# return val
which might include code, classes, or functions. Output only the next line. | wf[:, ii] = wf[:, ii] / np.sqrt(innerprod_q(time, wf[:, ii], wf[:, ii])) |
Continue the code snippet: <|code_start|> """
print ("Initializing...")
binsize = np.diff(time)
binsize = binsize.mean()
eps = np.finfo(np.double).eps
M = f.shape[0]
N = f.shape[1]
f0 = f
g0 = g
if showplot:
plot.f_plot(time, f, title="f Original Data")
plot.f_plot(time, g, title="g Original Data")
# Compute q-function of f and g
f, g1, g2 = uf.gradient_spline(time, f, smoothdata)
qf = g1 / np.sqrt(abs(g1) + eps)
g, g1, g2 = uf.gradient_spline(time, g, smoothdata)
qg = g1 / np.sqrt(abs(g1) + eps)
print("Calculating fPLS weight functions for %d Warped Functions..." % N)
itr = 0
fi = np.zeros((M, N, max_itr + 1))
fi[:, :, itr] = f
gi = np.zeros((M, N, max_itr + 1))
gi[:, :, itr] = g
qfi = np.zeros((M, N, max_itr + 1))
qfi[:, :, itr] = qf
qgi = np.zeros((M, N, max_itr + 1))
qgi[:, :, itr] = qg
<|code_end|>
. Use current file imports:
import numpy as np
import matplotlib.pyplot as plt
import fdasrsf.utility_functions as uf
import fdasrsf.plot_style as plot
import fpls_warp as fpls
import collections
from scipy.integrate import trapz, cumtrapz
from scipy.linalg import svd
from numpy.linalg import norm
from joblib import Parallel, delayed
from fdasrsf.fPLS import pls_svd
and context (classes, functions, or code) from other files:
# Path: fdasrsf/fPLS.py
# def pls_svd(time, qf, qg, no, alpha=0.0):
# """
# This function computes the partial least squares using SVD
#
# :param time: vector describing time samples
# :param qf: numpy ndarray of shape (M,N) of N functions with M samples
# :param qg: numpy ndarray of shape (M,N) of N functions with M samples
# :param no: number of components
# :param alpha: amount of smoothing (Default = 0.0 i.e., none)
#
# :rtype: numpy ndarray
# :return wqf: f weight function
# :return wqg: g weight function
# :return alpha: smoothing value
# :return values: singular values
#
# """
# binsize = np.diff(time)
# binsize = binsize.mean()
#
# Kfg = np.cov(qf, qg)
# Kfg = Kfg[0:qf.shape[0], qf.shape[0]:Kfg.shape[0]]
# nx = Kfg.shape[0]
# D4x = diffop(nx, binsize)
# values, Lmat, Mmat = geigen(Kfg, np.eye(nx) + alpha * D4x, np.eye(nx) + alpha * D4x)
# wf = Lmat[:, 0:no]
# wg = Mmat[:, 0:no]
#
# for ii in range(0, no):
# wf[:, ii] = wf[:, ii] / np.sqrt(innerprod_q(time, wf[:, ii], wf[:, ii]))
# wg[:, ii] = wg[:, ii] / np.sqrt(innerprod_q(time, wg[:, ii], wg[:, ii]))
#
# wqf = wf
# wqg = wg
#
# N = qf.shape[1]
# rfi = np.zeros(N)
# rgi = np.zeros(N)
#
# for l in range(0, N):
# rfi[l] = innerprod_q(time, qf[:, l], wqf[:, 0])
# rgi[l] = innerprod_q(time, qg[:, l], wqg[:, 0])
#
# cost = np.cov(rfi, rgi)[1, 0]
#
# return wqf, wqg, alpha, values, cost
. Output only the next line. | wqf1, wqg1, alpha, values, costmp = pls_svd(time, qfi[:, :, itr], |
Predict the next line after this snippet: <|code_start|> f.write(str(i) + '\t')
f.write(str(len(b)) + '\t')
f.write(str(len(c)) + '\t')
f.write(str(ed) + '\t')
f.write(str(wer))
f.write('\n')
f.write(' '.join(a))
f.write('\n')
f.write(' '.join(str(x[0]) for x in e))
f.write('\n')
f.write(' '.join(b))
f.write('\n')
f.write(' '.join(c))
f.write('\n\n')
visualization(i, a, b, c, d, e, directory)
def process(args):
# prepare data
dg = get_data_generator(args.data_name, args)
train_X, train_Y = dg.get_train_data()
test_X, test_Y = dg.get_test_data()
if args.use_start_symbol:
train_X = [['S'] + x for x in train_X]
test_X = [['S'] + x for x in test_X]
ori_test_X, ori_test_Y = test_X, test_Y
# Tokenize
<|code_end|>
using the current file's imports:
import argparse
import random
import editdistance
import os
import numpy as np
from data_generator import Tokenizer
from data_generator import get_data_generator
from model import get_model
and any relevant context from other files:
# Path: data_generator.py
# class Tokenizer(object):
# def __init__(self, args):
# self.args = args
#
# def get_dict(self, seqs):
# s = set()
# for seq in seqs:
# for elem in seq:
# s.add(elem)
# return {e: i + 1 for i, e in enumerate(s)}
#
# def convert_sequence(self, seqs, dic):
# result = []
# for seq in seqs:
# a = []
# for elem in seq:
# if elem not in dic:
# unk = '<unk>'
# if unk not in dic:
# dic[unk] = len(dic) + 1
# a.append(dic[unk])
# else:
# a.append(dic[elem])
# result.append(a)
# return result
#
# def padding(self, seqs, el, pad=0):
# lengths = []
# for seq in seqs:
# lengths.append(len(seq) + 1)
# for _ in range(el - len(seq)):
# seq.append(pad)
# return seqs, lengths
#
# def initialize_basic(self, X, Y, X_test, Y_test):
# voc = self.get_dict(X)
# act = self.get_dict(Y)
#
# x_out = self.convert_sequence(X, voc)
# y_out = self.convert_sequence(Y, act)
# x_test_out = self.convert_sequence(X_test, voc)
# y_test_out = self.convert_sequence(Y_test, act)
# return x_out, y_out, x_test_out, y_test_out, voc, act
#
# def get_maximum_length(self, train, test):
# train_max = max([len(x) for x in train])
# test_max = max([len(x) for x in test])
# return max(train_max, test_max) + 1
#
# def initialize(self, X, Y, X_test, Y_test):
# X, Y, X_test, Y_test, voc, act = self.initialize_basic(
# X, Y, X_test, Y_test)
# max_input = self.get_maximum_length(X, X_test)
# max_output = self.get_maximum_length(Y, Y_test)
# X, X_len = self.padding(X, max_input)
# Y, Y_len = self.padding(Y, max_output)
# X_test, X_test_len = self.padding(X_test, max_input)
# Y_test, Y_test_len = self.padding(Y_test, max_output)
# samples = X, Y, X_test, Y_test
# dicts = voc, act
# lengths = X_len, Y_len, X_test_len, Y_test_len
# maxs = max_input, max_output
# return samples, dicts, lengths, maxs
#
# Path: data_generator.py
# def get_data_generator(name, args):
# if name == 'fewshot':
# return FewShotDataGenerator(args)
# elif name == 'scan':
# return SCANGenerator(args)
# elif name == 'toy':
# return ToyDataGenerator(args)
# else:
# raise ValueError("Data generator name is not defined: " + name)
#
# Path: model.py
# def get_model(name, args):
# if name == 'simple':
# return SimpleModel(args)
# elif name == 'lstm':
# return LSTMModel(args)
# elif name == 's2s':
# return S2SModel(args)
# elif name == 's2s_att':
# return S2SAttentionModel(args)
# elif name == 'rand_reg':
# return RandRegModel(args)
# elif name == 'normal':
# return NormalModel(args)
# else:
# raise ValueError("Model name is not defined: " + name)
. Output only the next line. | tokenizer = Tokenizer(args) |
Given the code snippet: <|code_start|> acts.append(id2act[id])
actions.append(acts)
directory = fn + "/attention"
if not os.path.exists(directory):
os.makedirs(directory)
with open(fn + '/output.txt', 'w') as f:
for i, (a, b, c, d, e) in enumerate(zip(test_X, test_Y, actions, attention, switch)):
ed = editdistance.eval(b, c)
wer = ed / float(len(b))
f.write(str(i) + '\t')
f.write(str(len(b)) + '\t')
f.write(str(len(c)) + '\t')
f.write(str(ed) + '\t')
f.write(str(wer))
f.write('\n')
f.write(' '.join(a))
f.write('\n')
f.write(' '.join(str(x[0]) for x in e))
f.write('\n')
f.write(' '.join(b))
f.write('\n')
f.write(' '.join(c))
f.write('\n\n')
visualization(i, a, b, c, d, e, directory)
def process(args):
# prepare data
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import random
import editdistance
import os
import numpy as np
from data_generator import Tokenizer
from data_generator import get_data_generator
from model import get_model
and context (functions, classes, or occasionally code) from other files:
# Path: data_generator.py
# class Tokenizer(object):
# def __init__(self, args):
# self.args = args
#
# def get_dict(self, seqs):
# s = set()
# for seq in seqs:
# for elem in seq:
# s.add(elem)
# return {e: i + 1 for i, e in enumerate(s)}
#
# def convert_sequence(self, seqs, dic):
# result = []
# for seq in seqs:
# a = []
# for elem in seq:
# if elem not in dic:
# unk = '<unk>'
# if unk not in dic:
# dic[unk] = len(dic) + 1
# a.append(dic[unk])
# else:
# a.append(dic[elem])
# result.append(a)
# return result
#
# def padding(self, seqs, el, pad=0):
# lengths = []
# for seq in seqs:
# lengths.append(len(seq) + 1)
# for _ in range(el - len(seq)):
# seq.append(pad)
# return seqs, lengths
#
# def initialize_basic(self, X, Y, X_test, Y_test):
# voc = self.get_dict(X)
# act = self.get_dict(Y)
#
# x_out = self.convert_sequence(X, voc)
# y_out = self.convert_sequence(Y, act)
# x_test_out = self.convert_sequence(X_test, voc)
# y_test_out = self.convert_sequence(Y_test, act)
# return x_out, y_out, x_test_out, y_test_out, voc, act
#
# def get_maximum_length(self, train, test):
# train_max = max([len(x) for x in train])
# test_max = max([len(x) for x in test])
# return max(train_max, test_max) + 1
#
# def initialize(self, X, Y, X_test, Y_test):
# X, Y, X_test, Y_test, voc, act = self.initialize_basic(
# X, Y, X_test, Y_test)
# max_input = self.get_maximum_length(X, X_test)
# max_output = self.get_maximum_length(Y, Y_test)
# X, X_len = self.padding(X, max_input)
# Y, Y_len = self.padding(Y, max_output)
# X_test, X_test_len = self.padding(X_test, max_input)
# Y_test, Y_test_len = self.padding(Y_test, max_output)
# samples = X, Y, X_test, Y_test
# dicts = voc, act
# lengths = X_len, Y_len, X_test_len, Y_test_len
# maxs = max_input, max_output
# return samples, dicts, lengths, maxs
#
# Path: data_generator.py
# def get_data_generator(name, args):
# if name == 'fewshot':
# return FewShotDataGenerator(args)
# elif name == 'scan':
# return SCANGenerator(args)
# elif name == 'toy':
# return ToyDataGenerator(args)
# else:
# raise ValueError("Data generator name is not defined: " + name)
#
# Path: model.py
# def get_model(name, args):
# if name == 'simple':
# return SimpleModel(args)
# elif name == 'lstm':
# return LSTMModel(args)
# elif name == 's2s':
# return S2SModel(args)
# elif name == 's2s_att':
# return S2SAttentionModel(args)
# elif name == 'rand_reg':
# return RandRegModel(args)
# elif name == 'normal':
# return NormalModel(args)
# else:
# raise ValueError("Model name is not defined: " + name)
. Output only the next line. | dg = get_data_generator(args.data_name, args) |
Based on the snippet: <|code_start|>def process(args):
# prepare data
dg = get_data_generator(args.data_name, args)
train_X, train_Y = dg.get_train_data()
test_X, test_Y = dg.get_test_data()
if args.use_start_symbol:
train_X = [['S'] + x for x in train_X]
test_X = [['S'] + x for x in test_X]
ori_test_X, ori_test_Y = test_X, test_Y
# Tokenize
tokenizer = Tokenizer(args)
samples, dicts, lengths, maxs = tokenizer.initialize(
train_X, train_Y, test_X, test_Y)
train_X, train_Y, test_X, test_Y = samples
voc, act = dicts
train_X_len, train_Y_len, test_X_len, test_Y_len = lengths
if args.remove_x_eos:
train_X_len = [x - 1 for x in train_X_len]
test_X_len = [x - 1 for x in test_X_len]
max_input, max_output = maxs
args.input_length = max_input
args.output_length = max_output
# prepare model
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import random
import editdistance
import os
import numpy as np
from data_generator import Tokenizer
from data_generator import get_data_generator
from model import get_model
and context (classes, functions, sometimes code) from other files:
# Path: data_generator.py
# class Tokenizer(object):
# def __init__(self, args):
# self.args = args
#
# def get_dict(self, seqs):
# s = set()
# for seq in seqs:
# for elem in seq:
# s.add(elem)
# return {e: i + 1 for i, e in enumerate(s)}
#
# def convert_sequence(self, seqs, dic):
# result = []
# for seq in seqs:
# a = []
# for elem in seq:
# if elem not in dic:
# unk = '<unk>'
# if unk not in dic:
# dic[unk] = len(dic) + 1
# a.append(dic[unk])
# else:
# a.append(dic[elem])
# result.append(a)
# return result
#
# def padding(self, seqs, el, pad=0):
# lengths = []
# for seq in seqs:
# lengths.append(len(seq) + 1)
# for _ in range(el - len(seq)):
# seq.append(pad)
# return seqs, lengths
#
# def initialize_basic(self, X, Y, X_test, Y_test):
# voc = self.get_dict(X)
# act = self.get_dict(Y)
#
# x_out = self.convert_sequence(X, voc)
# y_out = self.convert_sequence(Y, act)
# x_test_out = self.convert_sequence(X_test, voc)
# y_test_out = self.convert_sequence(Y_test, act)
# return x_out, y_out, x_test_out, y_test_out, voc, act
#
# def get_maximum_length(self, train, test):
# train_max = max([len(x) for x in train])
# test_max = max([len(x) for x in test])
# return max(train_max, test_max) + 1
#
# def initialize(self, X, Y, X_test, Y_test):
# X, Y, X_test, Y_test, voc, act = self.initialize_basic(
# X, Y, X_test, Y_test)
# max_input = self.get_maximum_length(X, X_test)
# max_output = self.get_maximum_length(Y, Y_test)
# X, X_len = self.padding(X, max_input)
# Y, Y_len = self.padding(Y, max_output)
# X_test, X_test_len = self.padding(X_test, max_input)
# Y_test, Y_test_len = self.padding(Y_test, max_output)
# samples = X, Y, X_test, Y_test
# dicts = voc, act
# lengths = X_len, Y_len, X_test_len, Y_test_len
# maxs = max_input, max_output
# return samples, dicts, lengths, maxs
#
# Path: data_generator.py
# def get_data_generator(name, args):
# if name == 'fewshot':
# return FewShotDataGenerator(args)
# elif name == 'scan':
# return SCANGenerator(args)
# elif name == 'toy':
# return ToyDataGenerator(args)
# else:
# raise ValueError("Data generator name is not defined: " + name)
#
# Path: model.py
# def get_model(name, args):
# if name == 'simple':
# return SimpleModel(args)
# elif name == 'lstm':
# return LSTMModel(args)
# elif name == 's2s':
# return S2SModel(args)
# elif name == 's2s_att':
# return S2SAttentionModel(args)
# elif name == 'rand_reg':
# return RandRegModel(args)
# elif name == 'normal':
# return NormalModel(args)
# else:
# raise ValueError("Model name is not defined: " + name)
. Output only the next line. | model = get_model(args.model_name, args) |
Here is a snippet: <|code_start|> name=name,
import_name=import_name,
static_folder=static_folder,
static_url_path=static_url_path,
template_folder=template_folder,
url_prefix=url_prefix,
subdomain=subdomain,
url_defaults=url_defaults,
root_path=root_path,
)
flask.Blueprint.__init__(self, **bp_kwargs)
login_url = login_url or "/{bp.name}"
authorized_url = authorized_url or "/{bp.name}/authorized"
rule_kwargs = rule_kwargs or {}
self.add_url_rule(
rule=login_url.format(bp=self),
endpoint="login",
view_func=self.login,
**rule_kwargs,
)
self.add_url_rule(
rule=authorized_url.format(bp=self),
endpoint="authorized",
view_func=self.authorized,
**rule_kwargs,
)
if storage is None:
<|code_end|>
. Write the next line using the current file imports:
import warnings
import flask
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
from flask.signals import Namespace
from flask_dance.consumer.storage.session import SessionStorage
from flask_dance.utils import (
getattrd,
timestamp_from_datetime,
invalidate_cached_property,
)
and context from other files:
# Path: flask_dance/consumer/storage/session.py
# class SessionStorage(BaseStorage):
# """
# The default storage backend. Stores and retrieves OAuth tokens using
# the :ref:`Flask session <flask:sessions>`.
# """
#
# def __init__(self, key="{bp.name}_oauth_token"):
# """
# Args:
# key (str): The name to use as a key for storing the OAuth token in the
# Flask session. This string will have ``.format(bp=self.blueprint)``
# called on it before it is used. so you can refer to information
# on the blueprint as part of the key. For example, ``{bp.name}``
# will be replaced with the name of the blueprint.
# """
# self.key = key
#
# def get(self, blueprint):
# key = self.key.format(bp=blueprint)
# return flask.session.get(key)
#
# def set(self, blueprint, token):
# key = self.key.format(bp=blueprint)
# flask.session[key] = token
#
# def delete(self, blueprint):
# key = self.key.format(bp=blueprint)
# del flask.session[key]
#
# Path: flask_dance/utils.py
# def getattrd(obj, name, default=sentinel):
# """
# Same as getattr(), but allows dot notation lookup
# Source: http://stackoverflow.com/a/14324459
# """
# try:
# return functools.reduce(getattr, name.split("."), obj)
# except AttributeError as e:
# if default is not sentinel:
# return default
# raise
#
# def timestamp_from_datetime(dt):
# """
# Given a datetime, in UTC, return a float that represents the timestamp for
# that datetime.
#
# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548
# """
# dt = dt.replace(tzinfo=utc)
# if hasattr(dt, "timestamp") and callable(dt.timestamp):
# return dt.replace(tzinfo=utc).timestamp()
# return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
#
# def invalidate_cached_property(obj, name):
# obj.__dict__[name] = _missing
, which may include functions, classes, or code. Output only the next line. | self.storage = SessionStorage() |
Given the code snippet: <|code_start|> self.logged_in_funcs = []
self.from_config = {}
def invalidate_token(d):
try:
invalidate_cached_property(self.session, "token")
except KeyError:
pass
self.config = CallbackDict(on_update=invalidate_token)
self.before_app_request(self.load_config)
def load_config(self):
"""
Used to dynamically load variables from the Flask application config
into the blueprint. To tell this blueprint to pull configuration from
the app, just set key-value pairs in the ``from_config`` dict. Keys
are the name of the local variable to set on the blueprint object,
and values are the variable name in the Flask application config.
For example:
blueprint.from_config["session.client_id"] = "GITHUB_OAUTH_CLIENT_ID"
"""
for local_var, config_var in self.from_config.items():
value = flask.current_app.config.get(config_var)
if value:
if "." in local_var:
# this is a dotpath -- needs special handling
body, tail = local_var.rsplit(".", 1)
<|code_end|>
, generate the next line using the imports in this file:
import warnings
import flask
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
from flask.signals import Namespace
from flask_dance.consumer.storage.session import SessionStorage
from flask_dance.utils import (
getattrd,
timestamp_from_datetime,
invalidate_cached_property,
)
and context (functions, classes, or occasionally code) from other files:
# Path: flask_dance/consumer/storage/session.py
# class SessionStorage(BaseStorage):
# """
# The default storage backend. Stores and retrieves OAuth tokens using
# the :ref:`Flask session <flask:sessions>`.
# """
#
# def __init__(self, key="{bp.name}_oauth_token"):
# """
# Args:
# key (str): The name to use as a key for storing the OAuth token in the
# Flask session. This string will have ``.format(bp=self.blueprint)``
# called on it before it is used. so you can refer to information
# on the blueprint as part of the key. For example, ``{bp.name}``
# will be replaced with the name of the blueprint.
# """
# self.key = key
#
# def get(self, blueprint):
# key = self.key.format(bp=blueprint)
# return flask.session.get(key)
#
# def set(self, blueprint, token):
# key = self.key.format(bp=blueprint)
# flask.session[key] = token
#
# def delete(self, blueprint):
# key = self.key.format(bp=blueprint)
# del flask.session[key]
#
# Path: flask_dance/utils.py
# def getattrd(obj, name, default=sentinel):
# """
# Same as getattr(), but allows dot notation lookup
# Source: http://stackoverflow.com/a/14324459
# """
# try:
# return functools.reduce(getattr, name.split("."), obj)
# except AttributeError as e:
# if default is not sentinel:
# return default
# raise
#
# def timestamp_from_datetime(dt):
# """
# Given a datetime, in UTC, return a float that represents the timestamp for
# that datetime.
#
# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548
# """
# dt = dt.replace(tzinfo=utc)
# if hasattr(dt, "timestamp") and callable(dt.timestamp):
# return dt.replace(tzinfo=utc).timestamp()
# return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
#
# def invalidate_cached_property(obj, name):
# obj.__dict__[name] = _missing
. Output only the next line. | obj = getattrd(self, body) |
Given snippet: <|code_start|> @storage.deleter
def storage(self):
del self._storage
@property
def token(self):
"""
This property functions as pass-through to the token storage.
If you read from this property, you will receive the current
value from the token storage. If you assign a value to this
property, it will get set in the token storage.
"""
_token = self.storage.get(self)
if _token and _token.get("expires_in") and _token.get("expires_at"):
# Update the `expires_in` value, so that requests-oauthlib
# can handle automatic token refreshing. Assume that
# `expires_at` is a valid Unix timestamp.
expires_at = datetime.utcfromtimestamp(_token["expires_at"])
expires_in = expires_at - datetime.utcnow()
_token["expires_in"] = expires_in.total_seconds()
return _token
@token.setter
def token(self, value):
_token = value
if _token and _token.get("expires_in"):
# Set the `expires_at` value, overwriting any value
# that may already be there.
delta = timedelta(seconds=_token["expires_in"])
expires_at = datetime.utcnow() + delta
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import warnings
import flask
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
from flask.signals import Namespace
from flask_dance.consumer.storage.session import SessionStorage
from flask_dance.utils import (
getattrd,
timestamp_from_datetime,
invalidate_cached_property,
)
and context:
# Path: flask_dance/consumer/storage/session.py
# class SessionStorage(BaseStorage):
# """
# The default storage backend. Stores and retrieves OAuth tokens using
# the :ref:`Flask session <flask:sessions>`.
# """
#
# def __init__(self, key="{bp.name}_oauth_token"):
# """
# Args:
# key (str): The name to use as a key for storing the OAuth token in the
# Flask session. This string will have ``.format(bp=self.blueprint)``
# called on it before it is used. so you can refer to information
# on the blueprint as part of the key. For example, ``{bp.name}``
# will be replaced with the name of the blueprint.
# """
# self.key = key
#
# def get(self, blueprint):
# key = self.key.format(bp=blueprint)
# return flask.session.get(key)
#
# def set(self, blueprint, token):
# key = self.key.format(bp=blueprint)
# flask.session[key] = token
#
# def delete(self, blueprint):
# key = self.key.format(bp=blueprint)
# del flask.session[key]
#
# Path: flask_dance/utils.py
# def getattrd(obj, name, default=sentinel):
# """
# Same as getattr(), but allows dot notation lookup
# Source: http://stackoverflow.com/a/14324459
# """
# try:
# return functools.reduce(getattr, name.split("."), obj)
# except AttributeError as e:
# if default is not sentinel:
# return default
# raise
#
# def timestamp_from_datetime(dt):
# """
# Given a datetime, in UTC, return a float that represents the timestamp for
# that datetime.
#
# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548
# """
# dt = dt.replace(tzinfo=utc)
# if hasattr(dt, "timestamp") and callable(dt.timestamp):
# return dt.replace(tzinfo=utc).timestamp()
# return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
#
# def invalidate_cached_property(obj, name):
# obj.__dict__[name] = _missing
which might include code, classes, or functions. Output only the next line. | _token["expires_at"] = timestamp_from_datetime(expires_at) |
Based on the snippet: <|code_start|>
login_url = login_url or "/{bp.name}"
authorized_url = authorized_url or "/{bp.name}/authorized"
rule_kwargs = rule_kwargs or {}
self.add_url_rule(
rule=login_url.format(bp=self),
endpoint="login",
view_func=self.login,
**rule_kwargs,
)
self.add_url_rule(
rule=authorized_url.format(bp=self),
endpoint="authorized",
view_func=self.authorized,
**rule_kwargs,
)
if storage is None:
self.storage = SessionStorage()
elif callable(storage):
self.storage = storage()
else:
self.storage = storage
self.logged_in_funcs = []
self.from_config = {}
def invalidate_token(d):
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import warnings
import flask
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
from flask.signals import Namespace
from flask_dance.consumer.storage.session import SessionStorage
from flask_dance.utils import (
getattrd,
timestamp_from_datetime,
invalidate_cached_property,
)
and context (classes, functions, sometimes code) from other files:
# Path: flask_dance/consumer/storage/session.py
# class SessionStorage(BaseStorage):
# """
# The default storage backend. Stores and retrieves OAuth tokens using
# the :ref:`Flask session <flask:sessions>`.
# """
#
# def __init__(self, key="{bp.name}_oauth_token"):
# """
# Args:
# key (str): The name to use as a key for storing the OAuth token in the
# Flask session. This string will have ``.format(bp=self.blueprint)``
# called on it before it is used. so you can refer to information
# on the blueprint as part of the key. For example, ``{bp.name}``
# will be replaced with the name of the blueprint.
# """
# self.key = key
#
# def get(self, blueprint):
# key = self.key.format(bp=blueprint)
# return flask.session.get(key)
#
# def set(self, blueprint, token):
# key = self.key.format(bp=blueprint)
# flask.session[key] = token
#
# def delete(self, blueprint):
# key = self.key.format(bp=blueprint)
# del flask.session[key]
#
# Path: flask_dance/utils.py
# def getattrd(obj, name, default=sentinel):
# """
# Same as getattr(), but allows dot notation lookup
# Source: http://stackoverflow.com/a/14324459
# """
# try:
# return functools.reduce(getattr, name.split("."), obj)
# except AttributeError as e:
# if default is not sentinel:
# return default
# raise
#
# def timestamp_from_datetime(dt):
# """
# Given a datetime, in UTC, return a float that represents the timestamp for
# that datetime.
#
# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548
# """
# dt = dt.replace(tzinfo=utc)
# if hasattr(dt, "timestamp") and callable(dt.timestamp):
# return dt.replace(tzinfo=utc).timestamp()
# return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
#
# def invalidate_cached_property(obj, name):
# obj.__dict__[name] = _missing
. Output only the next line. | invalidate_cached_property(self.session, "token") |
Given snippet: <|code_start|>
def test_first():
assert first([1, 2, 3]) == 1
assert first([None, 2, 3]) == 2
assert first([None, 0, False, [], {}]) == None
assert first([None, 0, False, [], {}], default=42) == 42
first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) == 4
class C:
d = "foo"
class B:
C = C
class A:
B = B
def test_getattrd():
assert A.B.C.d == "foo"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from flask_dance.utils import FakeCache, first, getattrd
and context:
# Path: flask_dance/utils.py
# class FakeCache:
# """
# An object that mimics just enough of Flask-Caching's API to be compatible
# with our needs, but does nothing.
# """
#
# def get(self, key):
# return None
#
# def set(self, key, value):
# return None
#
# def delete(self, key):
# return None
#
# def first(iterable, default=None, key=None):
# """
# Return the first truthy value of an iterable.
# Shamelessly stolen from https://github.com/hynek/first
# """
# if key is None:
# for el in iterable:
# if el:
# return el
# else:
# for el in iterable:
# if key(el):
# return el
# return default
#
# def getattrd(obj, name, default=sentinel):
# """
# Same as getattr(), but allows dot notation lookup
# Source: http://stackoverflow.com/a/14324459
# """
# try:
# return functools.reduce(getattr, name.split("."), obj)
# except AttributeError as e:
# if default is not sentinel:
# return default
# raise
which might include code, classes, or functions. Output only the next line. | assert getattrd(A, "B.C.d") == "foo" |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Loops through all subscribers and marks each ticket appropriately.'
def handle_noargs(self, **options):
# Prepare our request.
headers = {
'Authorization': 'OAuth %s' % os.environ.get('TWITCH_OAUTH_TOKEN'),
'Accept': 'application/vnd.twitchtv.v3+json' }
url = 'https://api.twitch.tv/kraken/channels/avalonstar/subscriptions'
# Let's not invalidate anything unnecessarily. If we hit an exception
# with the first request, then bail.
try:
r = requests.get(url, headers=headers)
except requests.exceptions.RequestException as e:
logger.exception(e)
pass
# Rather than mark active tickets as inactive, mark all tickets as
# inactive. As we loop through the Twitch API, we'll mark
<|code_end|>
using the current file's imports:
import logging
import requests
import os
from django.core.management.base import NoArgsCommand
from apps.subscribers.models import Ticket
and any relevant context from other files:
# Path: apps/subscribers/models.py
# class Ticket(models.Model):
# twid = models.CharField(blank=True, max_length=40)
# name = models.CharField(max_length=200)
# display_name = models.CharField(blank=True, max_length=200)
# created = models.DateTimeField(default=timezone.now)
# updated = models.DateTimeField(default=timezone.now)
#
# # Store the months if there's a substreak (defaults to 1 month).
# streak = models.IntegerField(default=1)
#
# # Is this subscription active?
# is_active = models.BooleanField(default=True,
# help_text='Is this subscription active?')
# is_paid = models.BooleanField(default=True,
# help_text='Is this a paid subscription? (e.g., Not a bot.)')
#
# # Custom manager.
# objects = TicketManager()
#
# class Meta:
# ordering = ['updated']
# get_latest_by = 'updated'
#
# def __str__(self):
# return '{}'.format(self.name)
#
# def update(self, **kwargs):
# allowed_attributes = {'twid', 'display_name', 'updated', 'is_active'}
# for name, value in kwargs.items():
# assert name in allowed_attributes
# setattr(self, name, value)
# self.save()
. Output only the next line. | Ticket.objects.invalidate_tickets() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class QuoteAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('text', ('timestamp', 'subject'),)}),
('Metadata', {'fields': ('creator', 'broadcast', 'game')})
)
list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game']
raw_id_fields = ['broadcast', 'game']
autocomplete_lookup_fields = {'fk': ['game']}
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from .models import Quote
and context including class names, function names, and sometimes code from other files:
# Path: apps/quotes/models.py
# class Quote(models.Model):
# text = models.TextField()
# timestamp = models.DateField(default=timezone.now)
# subject = models.CharField(blank=True, max_length=200,
# help_text='The person that was quoted.')
# creator = models.CharField(blank=True, max_length=200,
# help_text='The person that created the quote.')
# broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='quotes')
# game = models.ForeignKey(Game, blank=True, null=True, related_name='quoted_on')
#
# class Meta:
# ordering = ['-timestamp']
#
# def __str__(self):
# return '{}'.format(self.text)
. Output only the next line. | admin.site.register(Quote, QuoteAdmin) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division
class BroadcastDetailView(DetailView):
model = Broadcast
slug_field = 'number'
class BroadcastListView(ListView):
model = Broadcast
def calculate_highlights_per_episode(self, **kwargs):
episodes = Broadcast.objects.count()
highlights = Highlight.objects.count()
return round((highlights / episodes), 2)
def calculate_raids_per_episode(self, **kwargs):
# Subtract 50 from the total number of episodes, since we only started
# recording raids at episode 51.
episodes = Broadcast.objects.count() - 50
raids = Raid.objects.count()
return round((raids / episodes), 2)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['first'] = Broadcast.objects.earliest()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, TemplateView
from apps.games.models import Game
from .models import Broadcast, Highlight, Raid
and context:
# Path: apps/games/models.py
# class Game(models.Model):
# # Metadata.
# name = models.CharField(max_length=200)
# platform = models.ForeignKey(Platform, null=True, related_name='games')
#
# # Imagery.
# image_art = models.ImageField('art', blank=True, upload_to='games',
# help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.')
# image_boxart = models.ImageField('boxart', blank=True, upload_to='games',
# help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.')
#
# # Statuses.
# is_abandoned = models.BooleanField('is abandoned?', default=False,
# help_text='Has this game been abandoned for good?')
# is_completed = models.BooleanField('is completed?', default=False,
# help_text='Has this game been completed (if applicable).' )
#
# def __str__(self):
# return '{}'.format(self.name)
#
# @staticmethod
# def autocomplete_search_fields():
# return ('name__exact', 'name__icontains')
#
# Path: apps/broadcasts/models.py
# class Broadcast(models.Model):
# # Metadata.
# number = models.IntegerField(blank=True, null=True)
# airdate = models.DateField(default=timezone.now)
# status = models.CharField(blank=True, max_length=200,
# help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.')
# notes = models.TextField(blank=True)
#
# # Connections.
# games = models.ManyToManyField(Game, related_name='appears_on')
# series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts',
# help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?')
#
# # Statuses.
# is_charity = models.BooleanField('is for charity?', default=False,
# help_text='Is a charity fundraiser involved in this episode?')
# is_marathon = models.BooleanField('is a marathon?', default=False,
# help_text='Is this a marathon episode (longer than 12 hours)?')
#
# class Meta:
# get_latest_by = 'airdate'
# ordering = ['-airdate']
#
# def __str__(self):
# return 'Episode {}'.format(self.number)
#
# def get_absolute_url(self):
# return reverse('broadcast-detail', kwargs={'slug': self.number})
#
# class Highlight(models.Model):
# broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights')
# twid = models.CharField('Twitch ID', max_length=200,
# help_text='The highlight\'s ID on Twitch; used for API calls, etc.')
#
# # Silly metadata (filled out by an API call).
# title = models.CharField(blank=True, max_length=200)
# description = models.TextField(blank=True)
# url = models.URLField('URL', blank=True)
# game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on')
#
# class Meta:
# ordering = ['-twid']
# order_with_respect_to = 'broadcast'
#
# def save(self, *args, **kwargs):
# # Grab our new highlight ID and run an API call.
# import requests
# endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid)
# json = requests.get(endpoint).json()
#
# # Take the response and save it to the instance.
# # But first, find the game, so we can save that.
# if json['game']:
# game = Game.objects.get(name=json['game'])
# self.game = game
# self.description = json['description']
# self.title = json['title']
# self.url = json['url']
# super().save(*args, **kwargs)
#
# def __str__(self):
# if not self.title:
# return 'Highlight for {}'.format(self.broadcast)
# return self.title
#
# class Raid(models.Model):
# broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids')
# timestamp = models.DateTimeField(default=timezone.now,
# help_text='When did it happen?')
# username = models.CharField(blank=True, max_length=200)
#
# # Silly metadata.
# game = models.CharField(blank=True, max_length=200,
# help_text='The game the raider was playing at the time of raiding.')
#
# class Meta:
# order_with_respect_to = 'broadcast'
# ordering = ['timestamp']
#
# def __str__(self):
# return '{}'.format(self.username)
which might include code, classes, or functions. Output only the next line. | context['games'] = Game.objects.all() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.