Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
class DashboardView(TemplateView):
template_name = "crumpet/pages/dashboard.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if not request.user.is_authenticated():
return redirect(reverse('account_login'))
polo = Poloniex()
print(polo.returnTicker()['BTC_ETH'])
user_account = models.UserAccount.objects.filter(
user=self.request.user
).first()
# if user_account.api_key and user_account.api_secret:
# polo = Poloniex(key=user_account.api_key, secret=user_account.api_secret)
# balance = polo.returnBalances()
# # balance = polo.returnCompleteBalances()
# ticker = polo.returnTicker()
#
# balance = {key: value for key, value in balance.items() if float(value) != 0}
# context['balance'] = balance
# # context['ticker'] = ticker
return self.render_to_response(context)
class AccountPageView(FormView):
<|code_end|>
, generate the next line using the imports in this file:
import json
from django.contrib import messages
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import TemplateView, FormView
from poloniex import Poloniex
from crumpet.profiles import forms, models, constants
from crumpet.models import Order
and context (functions, classes, or occasionally code) from other files:
# Path: crumpet/profiles/forms.py
# class UserAccountForm(forms.Form):
#
# Path: crumpet/profiles/models.py
# class UserAccount(models.Model):
# class Meta:
# def __str__(self):
#
# Path: crumpet/profiles/constants.py
# CRYPTO_EXCHANGES = (
# ("poloniex", _("Poloniex")),
# ("bittrex", _("Bittrex")),
# ("bitstamp", _("Bitstamp"))
# )
# EXCHANGE_PERIODS = (
# (300, "5-min"),
# (900, "15-min"),
# (1800, "30-min"),
# (7200, "2-hr"),
# (14400, "4-hr"),
# (86400, "1-day")
# )
# STRATEGIES = (
# ("To The Moon", "toTheMoon"),
# ("Strategy 2", "strategy 2"),
# )
# INSTRUMENTS = (
# ("ETH", _("Ethereum")),
# ("DGB", _("DigiByte")),
# ("XRP", _("Ripple")),
# ("XMR", _("Monero")),
# ("LTC", _("LiteCoin")),
# ("LSK", _("LISK")),
# ("STEEM", _("STEEM"))
# )
# MODES = (
# ("backtest", _("Backtest")),
# ("livetest", _("Live Backtest")),
# ("live", _("Live"))
# )
# BUY = 0
# SELL = 1
# ORDER_TYPES = (
# (OrderType.BUY, 'buy'),
# (OrderType.SELL, 'sell')
# )
# OPEN, CANCELLED, PROCESSED = 'open', 'cancelled', 'processed'
# ORDER_STATES = (
# (OPEN, _('open')),
# (CANCELLED, _('cancelled')),
# (PROCESSED, _('processed'))
# )
# SMA, EMA, RSI = 'sma', 'ema', 'rsi'
# INDICATORS = (
# (SMA, _('sma')),
# (EMA, _('ema')),
# (RSI, _('rsi'))
# )
# class OrderType(object):
#
# Path: crumpet/models.py
# class Order(models.Model):
# type = models.IntegerField(
# choices=constants.ORDER_TYPES,
# max_length=255,
# db_index=True
# )
# order_number = models.CharField(
# null=True,
# blank=True,
# max_length=50,
# verbose_name="Order Number"
# )
# amount = AmountField()
# price = AmountField()
# date = models.DateTimeField()
# created = models.DateTimeField(auto_now_add=True)
# updated = models.DateTimeField(auto_now=True)
# user_account = models.ForeignKey(UserAccount, related_name='orders')
# ticker = models.CharField(verbose_name='Ticker Symbol', max_length=30)
#
# status = models.CharField(
# default=None,
# choices=constants.ORDER_STATES,
# max_length=255,
# db_index=True
# )
#
# class Meta:
# ordering = ['-date']
# get_latest_by = 'date'
# db_table = 'bot_order'
#
# def __str__(self):
# return '{type} {amount} BTC at {price} US$'.format(
# type=self.get_type_display(),
# amount=self.amount,
# price=self.price
# )
. Output only the next line. | form_class = forms.UserAccountForm |
Predict the next line after this snippet: <|code_start|>
class DashboardView(TemplateView):
template_name = "crumpet/pages/dashboard.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if not request.user.is_authenticated():
return redirect(reverse('account_login'))
polo = Poloniex()
print(polo.returnTicker()['BTC_ETH'])
<|code_end|>
using the current file's imports:
import json
from django.contrib import messages
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import TemplateView, FormView
from poloniex import Poloniex
from crumpet.profiles import forms, models, constants
from crumpet.models import Order
and any relevant context from other files:
# Path: crumpet/profiles/forms.py
# class UserAccountForm(forms.Form):
#
# Path: crumpet/profiles/models.py
# class UserAccount(models.Model):
# class Meta:
# def __str__(self):
#
# Path: crumpet/profiles/constants.py
# CRYPTO_EXCHANGES = (
# ("poloniex", _("Poloniex")),
# ("bittrex", _("Bittrex")),
# ("bitstamp", _("Bitstamp"))
# )
# EXCHANGE_PERIODS = (
# (300, "5-min"),
# (900, "15-min"),
# (1800, "30-min"),
# (7200, "2-hr"),
# (14400, "4-hr"),
# (86400, "1-day")
# )
# STRATEGIES = (
# ("To The Moon", "toTheMoon"),
# ("Strategy 2", "strategy 2"),
# )
# INSTRUMENTS = (
# ("ETH", _("Ethereum")),
# ("DGB", _("DigiByte")),
# ("XRP", _("Ripple")),
# ("XMR", _("Monero")),
# ("LTC", _("LiteCoin")),
# ("LSK", _("LISK")),
# ("STEEM", _("STEEM"))
# )
# MODES = (
# ("backtest", _("Backtest")),
# ("livetest", _("Live Backtest")),
# ("live", _("Live"))
# )
# BUY = 0
# SELL = 1
# ORDER_TYPES = (
# (OrderType.BUY, 'buy'),
# (OrderType.SELL, 'sell')
# )
# OPEN, CANCELLED, PROCESSED = 'open', 'cancelled', 'processed'
# ORDER_STATES = (
# (OPEN, _('open')),
# (CANCELLED, _('cancelled')),
# (PROCESSED, _('processed'))
# )
# SMA, EMA, RSI = 'sma', 'ema', 'rsi'
# INDICATORS = (
# (SMA, _('sma')),
# (EMA, _('ema')),
# (RSI, _('rsi'))
# )
# class OrderType(object):
#
# Path: crumpet/models.py
# class Order(models.Model):
# type = models.IntegerField(
# choices=constants.ORDER_TYPES,
# max_length=255,
# db_index=True
# )
# order_number = models.CharField(
# null=True,
# blank=True,
# max_length=50,
# verbose_name="Order Number"
# )
# amount = AmountField()
# price = AmountField()
# date = models.DateTimeField()
# created = models.DateTimeField(auto_now_add=True)
# updated = models.DateTimeField(auto_now=True)
# user_account = models.ForeignKey(UserAccount, related_name='orders')
# ticker = models.CharField(verbose_name='Ticker Symbol', max_length=30)
#
# status = models.CharField(
# default=None,
# choices=constants.ORDER_STATES,
# max_length=255,
# db_index=True
# )
#
# class Meta:
# ordering = ['-date']
# get_latest_by = 'date'
# db_table = 'bot_order'
#
# def __str__(self):
# return '{type} {amount} BTC at {price} US$'.format(
# type=self.get_type_display(),
# amount=self.amount,
# price=self.price
# )
. Output only the next line. | user_account = models.UserAccount.objects.filter( |
Continue the code snippet: <|code_start|> ).first()
form.fields["api_key"].initial = user_account.api_key
form.fields["api_secret"].initial = user_account.api_secret
return context
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned_data["exchange"]
api_key = form.cleaned_data["api_key"]
api_secret = form.cleaned_data["api_secret"]
user_account = models.UserAccount.objects.filter(
user=self.request.user
).first()
if user_account:
user_account.exchange = exchange
user_account.api_key = api_key
user_account.api_secret = api_secret
user_account.save()
messages.success(self.request, 'Profile details updated.')
if user_account.api_key and user_account.api_secret:
polo = Poloniex(
key=user_account.api_key,
secret=user_account.api_secret)
trade_history = polo.returnTradeHistory()
<|code_end|>
. Use current file imports:
import json
from django.contrib import messages
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import TemplateView, FormView
from poloniex import Poloniex
from crumpet.profiles import forms, models, constants
from crumpet.models import Order
and context (classes, functions, or code) from other files:
# Path: crumpet/profiles/forms.py
# class UserAccountForm(forms.Form):
#
# Path: crumpet/profiles/models.py
# class UserAccount(models.Model):
# class Meta:
# def __str__(self):
#
# Path: crumpet/profiles/constants.py
# CRYPTO_EXCHANGES = (
# ("poloniex", _("Poloniex")),
# ("bittrex", _("Bittrex")),
# ("bitstamp", _("Bitstamp"))
# )
# EXCHANGE_PERIODS = (
# (300, "5-min"),
# (900, "15-min"),
# (1800, "30-min"),
# (7200, "2-hr"),
# (14400, "4-hr"),
# (86400, "1-day")
# )
# STRATEGIES = (
# ("To The Moon", "toTheMoon"),
# ("Strategy 2", "strategy 2"),
# )
# INSTRUMENTS = (
# ("ETH", _("Ethereum")),
# ("DGB", _("DigiByte")),
# ("XRP", _("Ripple")),
# ("XMR", _("Monero")),
# ("LTC", _("LiteCoin")),
# ("LSK", _("LISK")),
# ("STEEM", _("STEEM"))
# )
# MODES = (
# ("backtest", _("Backtest")),
# ("livetest", _("Live Backtest")),
# ("live", _("Live"))
# )
# BUY = 0
# SELL = 1
# ORDER_TYPES = (
# (OrderType.BUY, 'buy'),
# (OrderType.SELL, 'sell')
# )
# OPEN, CANCELLED, PROCESSED = 'open', 'cancelled', 'processed'
# ORDER_STATES = (
# (OPEN, _('open')),
# (CANCELLED, _('cancelled')),
# (PROCESSED, _('processed'))
# )
# SMA, EMA, RSI = 'sma', 'ema', 'rsi'
# INDICATORS = (
# (SMA, _('sma')),
# (EMA, _('ema')),
# (RSI, _('rsi'))
# )
# class OrderType(object):
#
# Path: crumpet/models.py
# class Order(models.Model):
# type = models.IntegerField(
# choices=constants.ORDER_TYPES,
# max_length=255,
# db_index=True
# )
# order_number = models.CharField(
# null=True,
# blank=True,
# max_length=50,
# verbose_name="Order Number"
# )
# amount = AmountField()
# price = AmountField()
# date = models.DateTimeField()
# created = models.DateTimeField(auto_now_add=True)
# updated = models.DateTimeField(auto_now=True)
# user_account = models.ForeignKey(UserAccount, related_name='orders')
# ticker = models.CharField(verbose_name='Ticker Symbol', max_length=30)
#
# status = models.CharField(
# default=None,
# choices=constants.ORDER_STATES,
# max_length=255,
# db_index=True
# )
#
# class Meta:
# ordering = ['-date']
# get_latest_by = 'date'
# db_table = 'bot_order'
#
# def __str__(self):
# return '{type} {amount} BTC at {price} US$'.format(
# type=self.get_type_display(),
# amount=self.amount,
# price=self.price
# )
. Output only the next line. | Order.objects.all().delete() |
Predict the next line after this snippet: <|code_start|>
@python_2_unicode_compatible
class UserAccount(models.Model):
"""User profile"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name="user_account"
)
exchange = models.CharField(
verbose_name="Crypto Exchanges",
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from crumpet.profiles import constants
and any relevant context from other files:
# Path: crumpet/profiles/constants.py
# CRYPTO_EXCHANGES = (
# ("poloniex", _("Poloniex")),
# ("bittrex", _("Bittrex")),
# ("bitstamp", _("Bitstamp"))
# )
# EXCHANGE_PERIODS = (
# (300, "5-min"),
# (900, "15-min"),
# (1800, "30-min"),
# (7200, "2-hr"),
# (14400, "4-hr"),
# (86400, "1-day")
# )
# STRATEGIES = (
# ("To The Moon", "toTheMoon"),
# ("Strategy 2", "strategy 2"),
# )
# INSTRUMENTS = (
# ("ETH", _("Ethereum")),
# ("DGB", _("DigiByte")),
# ("XRP", _("Ripple")),
# ("XMR", _("Monero")),
# ("LTC", _("LiteCoin")),
# ("LSK", _("LISK")),
# ("STEEM", _("STEEM"))
# )
# MODES = (
# ("backtest", _("Backtest")),
# ("livetest", _("Live Backtest")),
# ("live", _("Live"))
# )
# BUY = 0
# SELL = 1
# ORDER_TYPES = (
# (OrderType.BUY, 'buy'),
# (OrderType.SELL, 'sell')
# )
# OPEN, CANCELLED, PROCESSED = 'open', 'cancelled', 'processed'
# ORDER_STATES = (
# (OPEN, _('open')),
# (CANCELLED, _('cancelled')),
# (PROCESSED, _('processed'))
# )
# SMA, EMA, RSI = 'sma', 'ema', 'rsi'
# INDICATORS = (
# (SMA, _('sma')),
# (EMA, _('ema')),
# (RSI, _('rsi'))
# )
# class OrderType(object):
. Output only the next line. | choices=constants.CRYPTO_EXCHANGES, |
Predict the next line for this snippet: <|code_start|>"""crumpet URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r"^", include("crumpet.urls", namespace="crumpet")),
url(r"^backtests/", include("crumpet.backtests.urls", namespace="backtests")),
url(r'^accounts/', include('allauth.urls'))
]
<|code_end|>
with the help of current file imports:
from django.conf.urls import url, include
from django.contrib import admin
from project import settings
import debug_toolbar
and context from other files:
# Path: project/settings.py
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECRET_KEY = '=a&$4zs#n#u!r%(1o8w!rqee9^z+@l-pqnyld^h*74xs4#xl&+'
# DEBUG = True
# ALLOWED_HOSTS = ['*']
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# 'django.contrib.sites',
#
# # Project specific apps
# 'crumpet',
# 'crumpet.profiles',
# 'crumpet.backtests',
#
# # Django All Auth required modules
# 'allauth',
# 'allauth.account',
# 'allauth.socialaccount',
# 'webpack_loader'
# ]
# SITE_ID = 1
# MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# ]
# TEMPLATE_CONTEXT_PROCESSORS = [
# "django.contrib.auth.context_processors.auth",
# "django.core.context_processors.debug",
# "django.core.context_processors.i18n",
# "django.core.context_processors.media",
# "django.core.context_processors.static",
# "django.core.context_processors.tz",
# "django.core.context_processors.request",
# "django.contrib.messages.context_processors.messages",
# ]
# ROOT_URLCONF = 'project.urls'
# TEMPLATES = [
# {
# 'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
# 'APP_DIRS': True,
# 'OPTIONS': {
# 'context_processors': [
# 'django.template.context_processors.debug',
# 'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
# ],
# },
# },
# ]
# AUTHENTICATION_BACKENDS = (
# # Needed to login by username in Django admin, regardless of `allauth`
# "django.contrib.auth.backends.ModelBackend",
# # `allauth` specific authentication methods, such as login by e-mail
# "allauth.account.auth_backends.AuthenticationBackend"
# )
# TEMPLATE_CONTEXT_PROCESSORS = (
# "django.core.context_processors.request",
# "django.contrib.auth.context_processors.auth",
# "allauth.account.context_processors.account",
# "allauth.socialaccount.context_processors.socialaccount",
# )
# LOGIN_REDIRECT_URL = '/'
# LOGIN_URL = 'accounts/login'
# SOCIALACCOUNT_QUERY_EMAIL = True
# SOCIALACCOUNT_PROVIDERS = {
# 'facebook': {
# 'SCOPE': ['email', 'publish_stream'],
# 'METHOD': 'js_sdk' # instead of 'oauth2'
# }
# }
# ACCOUNT_AUTH_USER_MODEL = "allauth.account.models.EmailAddress"
# WSGI_APPLICATION = 'project.wsgi.application'
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# AUTH_PASSWORD_VALIDATORS = [
# {
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
# },
# ]
# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'UTC'
# USE_I18N = True
# USE_L10N = True
# USE_TZ = True
# STATIC_URL = '/static/'
, which may contain function names, class names, or code. Output only the next line. | if settings.DEBUG: |
Given the code snippet: <|code_start|>
class BacktestingView(FormView):
form_class = forms.ToTheMoonStrategyForm
template_name = "backtests/backtesting.html"
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned_data['exchange']
instrument = form.cleaned_data['instrument']
period = form.cleaned_data['exchange_period']
if form.cleaned_data['trading_fee']:
trading_fee = float(form.cleaned_data['trading_fee'])
wallet = Wallet(assets=100, currency=100, instrument=instrument, fee=trading_fee)
else:
wallet = Wallet(assets=100, currency=100, instrument=instrument)
strategy = form.cleaned_data['strategy']
mode = form.cleaned_data['mode']
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
sma_period = form.cleaned_data['sma_period']
ema_period = form.cleaned_data['ema_period']
<|code_end|>
, generate the next line using the imports in this file:
import simplejson
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import FormView
from crumpet.backtests import forms
from crumpet.tradebot import Tradebot, Wallet
and context (functions, classes, or occasionally code) from other files:
# Path: crumpet/backtests/forms.py
# class ToTheMoonStrategyForm(forms.Form):
#
# Path: crumpet/tradebot.py
# class Tradebot(object):
# def __init__(self, mode: str, wallet: Wallet, strategy: str, instrument: str, period: int, **kwargs) -> None:
# def __repr__(self):
# def restart(self):
# def increment_timer(self):
# def start_live_backtest(self):
# def init_live_bot_start(self) -> None:
# def init_bot_start(self) -> []:
# def get_time(self):
# def start(self):
# def stop(self):
# def buy_and_hold(price, wallet):
# def buy_and_hold_efficiency(tick):
# def display_stats(self, timer, tick):
. Output only the next line. | bot = Tradebot( |
Given the following code snippet before the placeholder: <|code_start|>
class BacktestingView(FormView):
form_class = forms.ToTheMoonStrategyForm
template_name = "backtests/backtesting.html"
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned_data['exchange']
instrument = form.cleaned_data['instrument']
period = form.cleaned_data['exchange_period']
if form.cleaned_data['trading_fee']:
trading_fee = float(form.cleaned_data['trading_fee'])
<|code_end|>
, predict the next line using imports from the current file:
import simplejson
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import FormView
from crumpet.backtests import forms
from crumpet.tradebot import Tradebot, Wallet
and context including class names, function names, and sometimes code from other files:
# Path: crumpet/backtests/forms.py
# class ToTheMoonStrategyForm(forms.Form):
#
# Path: crumpet/tradebot.py
# class Tradebot(object):
# def __init__(self, mode: str, wallet: Wallet, strategy: str, instrument: str, period: int, **kwargs) -> None:
# def __repr__(self):
# def restart(self):
# def increment_timer(self):
# def start_live_backtest(self):
# def init_live_bot_start(self) -> None:
# def init_bot_start(self) -> []:
# def get_time(self):
# def start(self):
# def stop(self):
# def buy_and_hold(price, wallet):
# def buy_and_hold_efficiency(tick):
# def display_stats(self, timer, tick):
. Output only the next line. | wallet = Wallet(assets=100, currency=100, instrument=instrument, fee=trading_fee) |
Next line prediction: <|code_start|> return False
return True
@property
def crosses_up(self):
if self.ema[-2] > self.sma[-2] and self.ema[-1] < self.sma[-1]:
return 'sma'
elif self.ema[-2] < self.sma[-2] and self.ema[-1] > self.sma[-1]:
return 'ema'
return ''
def decide(self, timer: str, tick, wallet: Wallet):
'''
The function the bot uses to decide whether to BUY or SELL.
:param tick:
:param timer: The timer used to keep track of the time.
:param wallet: The wallet used by the bot.
'''
n_close_data = numpy.array(tick.close, dtype=float)
self.sma = talib.SMA(n_close_data, self.sma_period)
self.ema = talib.EMA(n_close_data, self.ema_period)
max_buy_amount = wallet.max_buy_amount(tick.close[-1])
max_sell_amount = wallet.max_sell_amount()
price = tick.close[-1]
if self.guard:
if self.crosses_up == 'ema':
<|code_end|>
. Use current file imports:
(import datetime
import math
import numpy
import talib
from crumpet.constants import MINIMUM_AMOUNT
from crumpet.utils import bcolors
from crumpet.wallet import Wallet)
and context including class names, function names, or small code snippets from other files:
# Path: crumpet/constants.py
# MINIMUM_AMOUNT = 0.0001
#
# Path: crumpet/wallet.py
# class Wallet(object):
# '''
# This class keeps track of the current funds that a bot can utilize in trading.
# '''
#
# def __init__(self, assets: float, currency: float, instrument: str, fee: float = 0.25):
# '''
# This function initializes a Classification object.
# :param fee: The maximum percentage fee taken by the exchange per order.
# :param currency: The amount of currency (USD/ZAR) you have available to buy coins with.
# :param assets: The amount of the cypro-currency coins you have in your wallet ready to sell.
# :param instrument: The crypto-currency the bot will use to trade against BTC.
# '''
# self.instrument = instrument
# self.assets = assets
# self.currency = currency
# self.fee = fee
# self.starting_assets = assets
# self.starting_currency = currency
# self.initial_investment = 0
#
# def record_buy(self, buy_amount, price):
# '''
# Records the buy order transaction in the wallet.
# :param price: The current or closing price of the instrument.
# :param buy_amount: The amount to buy.
# '''
# self.assets += buy_amount
# self.currency -= (buy_amount * price)
#
# def record_sell(self, sell_amount, price):
# '''
# Records the sell order transaction in the wallet.
# :param price: The current or closing price of the instrument.
# :param sell_amount: The amount to sell.
# '''
# self.assets -= sell_amount
# self.currency += (sell_amount * price)
#
# def max_buy_amount(self, price):
# '''
# The maximum amount of a coin the bot can buy.
# :param price: The current or closing price of the instrument.
# '''
# return (self.currency / price) * (1 - (self.fee / 100))
#
# def max_sell_amount(self):
# '''
# The maximum amount of a coin the bot can sell.
# '''
# return self.assets * (1 - (self.fee / 100))
#
# def calculate_initial_investment(self, price: float):
# '''
# The initial investment made.
# :param price: The current or closing price of the instrument.
# '''
# self.initial_investment = (self.starting_assets * price) + self.starting_currency
#
# def percent_btc_profit(self, price):
# return ((((self.assets * price) + self.currency) - self.initial_investment) / self.initial_investment) * 100
#
# def total_btc(self, price):
# return (self.assets * price) + self.currency
. Output only the next line. | if max_buy_amount >= MINIMUM_AMOUNT: |
Predict the next line for this snippet: <|code_start|>
class BaseStrategy(object):
'''
The base strategy that all strategies inherit from.
'''
def __init__(self):
self.tick = []
@staticmethod
<|code_end|>
with the help of current file imports:
import datetime
import math
import numpy
import talib
from crumpet.constants import MINIMUM_AMOUNT
from crumpet.utils import bcolors
from crumpet.wallet import Wallet
and context from other files:
# Path: crumpet/constants.py
# MINIMUM_AMOUNT = 0.0001
#
# Path: crumpet/wallet.py
# class Wallet(object):
# '''
# This class keeps track of the current funds that a bot can utilize in trading.
# '''
#
# def __init__(self, assets: float, currency: float, instrument: str, fee: float = 0.25):
# '''
# This function initializes a Classification object.
# :param fee: The maximum percentage fee taken by the exchange per order.
# :param currency: The amount of currency (USD/ZAR) you have available to buy coins with.
# :param assets: The amount of the cypro-currency coins you have in your wallet ready to sell.
# :param instrument: The crypto-currency the bot will use to trade against BTC.
# '''
# self.instrument = instrument
# self.assets = assets
# self.currency = currency
# self.fee = fee
# self.starting_assets = assets
# self.starting_currency = currency
# self.initial_investment = 0
#
# def record_buy(self, buy_amount, price):
# '''
# Records the buy order transaction in the wallet.
# :param price: The current or closing price of the instrument.
# :param buy_amount: The amount to buy.
# '''
# self.assets += buy_amount
# self.currency -= (buy_amount * price)
#
# def record_sell(self, sell_amount, price):
# '''
# Records the sell order transaction in the wallet.
# :param price: The current or closing price of the instrument.
# :param sell_amount: The amount to sell.
# '''
# self.assets -= sell_amount
# self.currency += (sell_amount * price)
#
# def max_buy_amount(self, price):
# '''
# The maximum amount of a coin the bot can buy.
# :param price: The current or closing price of the instrument.
# '''
# return (self.currency / price) * (1 - (self.fee / 100))
#
# def max_sell_amount(self):
# '''
# The maximum amount of a coin the bot can sell.
# '''
# return self.assets * (1 - (self.fee / 100))
#
# def calculate_initial_investment(self, price: float):
# '''
# The initial investment made.
# :param price: The current or closing price of the instrument.
# '''
# self.initial_investment = (self.starting_assets * price) + self.starting_currency
#
# def percent_btc_profit(self, price):
# return ((((self.assets * price) + self.currency) - self.initial_investment) / self.initial_investment) * 100
#
# def total_btc(self, price):
# return (self.assets * price) + self.currency
, which may contain function names, class names, or code. Output only the next line. | def buy(timer: str, amount: float, price: float, wallet: Wallet): |
Based on the snippet: <|code_start|>Author: Derek Stegelman
"""
from __future__ import unicode_literals
@python_2_unicode_compatible
class Category(models.Model):
"""
Category model
"""
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editable=False)
user = models.ForeignKey(User, blank=True, null=True)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
"""
Updated Save to slug the name.
:param args:
:param kwargs:
:return:
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import feedparser
from time import mktime
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
from feedme.utils import unique_slugify
from .managers import FeedItemManager
from .tasks import update_feed
and context (classes, functions, sometimes code) from other files:
# Path: feedme/utils.py
# def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
# slug_separator='-'):
# """
# Calculates and stores a unique slug of ``value`` for an instance.
#
# ``slug_field_name`` should be a string matching the name of the field to
# store the slug in (and the field to check against for uniqueness).
#
# ``queryset`` usually doesn't need to be explicitly provided - it'll default
# to using the ``.all()`` queryset from the model's default manager.
# """
# slug_field = instance._meta.get_field(slug_field_name)
#
# slug = getattr(instance, slug_field.attname)
# slug_len = slug_field.max_length
#
# # Sort out the initial slug, limiting its length if necessary.
# slug = slugify(value)
# if slug_len:
# slug = slug[:slug_len]
# slug = _slug_strip(slug, slug_separator)
# original_slug = slug
#
# # Create the queryset if one wasn't explicitly provided and exclude the
# # current instance from the queryset.
# if queryset is None:
# queryset = instance.__class__._default_manager.all()
# if instance.pk:
# queryset = queryset.exclude(pk=instance.pk)
#
# # Find a unique slug. If one matches, at '-2' to the end and try again
# # (then '-3', etc).
# next = 2
# while not slug or queryset.filter(**{slug_field_name: slug}):
# slug = original_slug
# end = '%s%s' % (slug_separator, next)
# if slug_len and len(slug) + len(end) > slug_len:
# slug = slug[:slug_len-len(end)]
# slug = _slug_strip(slug, slug_separator)
# slug = '%s%s' % (slug, end)
# next += 1
#
# setattr(instance, slug_field.attname, slug)
#
# Path: feedme/managers.py
# class FeedItemManager(Manager):
# def get_queryset(self):
# return FeedItemQuerySet(self.model, using=self._db)
#
# def category(self, category_slug):
# return self.get_queryset().category(category_slug)
#
# def my_feed_items(self, user):
# return self.get_queryset().my_feed_items(user)
#
# def un_read(self):
# return self.get_queryset().un_read()
#
# def read(self):
# return self.get_queryset().read()
#
# def yesterday(self):
# return self.get_queryset().yesterday()
. Output only the next line. | unique_slugify(self, self.name) |
Given the code snippet: <|code_start|> and update the feeds.
"""
if force or not force and self.last_update < datetime.date.today():
self._update_processor()
return True
@models.permalink
def get_absolute_url(self):
"""
Feed permalink
:return:
"""
return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
@python_2_unicode_compatible
class FeedItem(models.Model):
"""
FeedItem Model
"""
title = models.CharField(max_length=350, blank=True)
link = models.URLField(blank=True)
content = models.TextField(blank=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
read = models.BooleanField(default=False)
guid = models.CharField(max_length=255)
date_fetched = models.DateField(auto_created=True, auto_now_add=True, editable=True)
pub_date = models.DateTimeField()
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import feedparser
from time import mktime
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
from feedme.utils import unique_slugify
from .managers import FeedItemManager
from .tasks import update_feed
and context (functions, classes, or occasionally code) from other files:
# Path: feedme/utils.py
# def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
# slug_separator='-'):
# """
# Calculates and stores a unique slug of ``value`` for an instance.
#
# ``slug_field_name`` should be a string matching the name of the field to
# store the slug in (and the field to check against for uniqueness).
#
# ``queryset`` usually doesn't need to be explicitly provided - it'll default
# to using the ``.all()`` queryset from the model's default manager.
# """
# slug_field = instance._meta.get_field(slug_field_name)
#
# slug = getattr(instance, slug_field.attname)
# slug_len = slug_field.max_length
#
# # Sort out the initial slug, limiting its length if necessary.
# slug = slugify(value)
# if slug_len:
# slug = slug[:slug_len]
# slug = _slug_strip(slug, slug_separator)
# original_slug = slug
#
# # Create the queryset if one wasn't explicitly provided and exclude the
# # current instance from the queryset.
# if queryset is None:
# queryset = instance.__class__._default_manager.all()
# if instance.pk:
# queryset = queryset.exclude(pk=instance.pk)
#
# # Find a unique slug. If one matches, at '-2' to the end and try again
# # (then '-3', etc).
# next = 2
# while not slug or queryset.filter(**{slug_field_name: slug}):
# slug = original_slug
# end = '%s%s' % (slug_separator, next)
# if slug_len and len(slug) + len(end) > slug_len:
# slug = slug[:slug_len-len(end)]
# slug = _slug_strip(slug, slug_separator)
# slug = '%s%s' % (slug, end)
# next += 1
#
# setattr(instance, slug_field.attname, slug)
#
# Path: feedme/managers.py
# class FeedItemManager(Manager):
# def get_queryset(self):
# return FeedItemQuerySet(self.model, using=self._db)
#
# def category(self, category_slug):
# return self.get_queryset().category(category_slug)
#
# def my_feed_items(self, user):
# return self.get_queryset().my_feed_items(user)
#
# def un_read(self):
# return self.get_queryset().un_read()
#
# def read(self):
# return self.get_queryset().read()
#
# def yesterday(self):
# return self.get_queryset().yesterday()
. Output only the next line. | objects = FeedItemManager() |
Predict the next line for this snippet: <|code_start|>"""
Django Feedme
Forms.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
class AddFeedForm(forms.ModelForm):
"""
Simple add feed form
"""
class Meta:
<|code_end|>
with the help of current file imports:
from django import forms
from .models import Feed, Category
and context from other files:
# Path: feedme/models.py
# class Feed(models.Model):
# """
# Feed Model
# """
# link = models.CharField(blank=True, max_length=450)
# url = models.CharField(blank=True, max_length=450)
# title = models.CharField(blank=True, null=True, max_length=250)
# category = models.ForeignKey(Category, blank=True, null=True)
# user = models.ForeignKey(User, blank=True, null=True)
# last_update = models.DateField(blank=True, null=True, editable=False)
#
# class Meta:
# unique_together = (
# ("url", "user"),
# )
#
# def __str__(self):
# return self.url
#
# def _get_title(self):
# """
# Fetch the title from the feed.
# :return:
# """
# parser = feedparser.parse(self.url)
# return parser.feed.title
#
# def save(self, *args, **kwargs):
# """
# Updated .save() method. Fetches the title
# from the feed, and updates the record timestamp.
# :param args:
# :param kwargs:
# :return:
# """
# if not self.title:
# self.title = self._get_title()
# super(Feed, self).save(*args, **kwargs)
# if self.last_update is None:
# self.update(force=True)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for all items in this feed.
# :return int count of un-read items:
# """
# return FeedItem.objects.filter(feed=self).un_read().count()
#
# def _update_feed(self):
# """
# Perform an update on this feed. This fetches the latest
# data from the feed and compares it to what we have stored currently.
# Then we go ahead and save that content and mark it as
# un-read.
# """
# # Update the last update field
# counter = 0
# feed = feedparser.parse(self.url)
# self.last_update = datetime.date.today()
# if "link" in feed.feed:
# self.link = feed.feed.link
# else:
# self.link = ""
# self.save()
# for item in feed.entries[:10]:
# # The RSS spec doesn't require the guid field so fall back on link
# if "id" in item:
# guid = item.id
# else:
# guid = item.link
#
# # Search for an existing item
# try:
# FeedItem.objects.get(guid=guid)
# except FeedItem.DoesNotExist:
# # Create it.
# counter += 1
# if "published_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))
# elif "updated_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))
# else:
# pub_date = datetime.datetime.now()
#
# pub_date = timezone.make_aware(pub_date, timezone.get_current_timezone())
#
# feed_item = FeedItem(title=item.title, link=item.link, content=item.description,
# guid=guid, pub_date=pub_date, feed=self)
# feed_item.save()
# return counter
#
# def _update_processor(self):
# """
# Kick off the prrocessing of the feeds. Either update with celery
# or in real time if we aren't using Celery.
# :return:
# """
# if getattr(settings, 'FEED_UPDATE_CELERY', False):
# from .tasks import update_feed
# update_feed.delay(self)
# return True
# self._update_feed()
# return True
#
# def update(self, force=False):
# """
# If we aren't forcing it
# and its not the same day, go ahead
# and update the feeds.
# """
#
# if force or not force and self.last_update < datetime.date.today():
# self._update_processor()
# return True
#
# @models.permalink
# def get_absolute_url(self):
# """
# Feed permalink
# :return:
# """
# return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
#
# class Category(models.Model):
# """
# Category model
# """
# name = models.CharField(max_length=250, blank=True)
# slug = models.SlugField(blank=True, null=True, editable=False)
# user = models.ForeignKey(User, blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# """
# Updated Save to slug the name.
# :param args:
# :param kwargs:
# :return:
# """
# unique_slugify(self, self.name)
# super(Category, self).save(*args, **kwargs)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for a given category.
# :return:
# """
# return FeedItem.objects.my_feed_items(self.user).category(self.slug).un_read().count()
, which may contain function names, class names, or code. Output only the next line. | model = Feed |
Given the code snippet: <|code_start|>"""
Django Feedme
Forms.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
class AddFeedForm(forms.ModelForm):
"""
Simple add feed form
"""
class Meta:
model = Feed
exclude = ('user', 'title')
class ImportFeedForm(forms.Form):
"""
Form for importing Google reader
"""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(ImportFeedForm, self).__init__(*args, **kwargs)
if user:
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from .models import Feed, Category
and context (functions, classes, or occasionally code) from other files:
# Path: feedme/models.py
# class Feed(models.Model):
# """
# Feed Model
# """
# link = models.CharField(blank=True, max_length=450)
# url = models.CharField(blank=True, max_length=450)
# title = models.CharField(blank=True, null=True, max_length=250)
# category = models.ForeignKey(Category, blank=True, null=True)
# user = models.ForeignKey(User, blank=True, null=True)
# last_update = models.DateField(blank=True, null=True, editable=False)
#
# class Meta:
# unique_together = (
# ("url", "user"),
# )
#
# def __str__(self):
# return self.url
#
# def _get_title(self):
# """
# Fetch the title from the feed.
# :return:
# """
# parser = feedparser.parse(self.url)
# return parser.feed.title
#
# def save(self, *args, **kwargs):
# """
# Updated .save() method. Fetches the title
# from the feed, and updates the record timestamp.
# :param args:
# :param kwargs:
# :return:
# """
# if not self.title:
# self.title = self._get_title()
# super(Feed, self).save(*args, **kwargs)
# if self.last_update is None:
# self.update(force=True)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for all items in this feed.
# :return int count of un-read items:
# """
# return FeedItem.objects.filter(feed=self).un_read().count()
#
# def _update_feed(self):
# """
# Perform an update on this feed. This fetches the latest
# data from the feed and compares it to what we have stored currently.
# Then we go ahead and save that content and mark it as
# un-read.
# """
# # Update the last update field
# counter = 0
# feed = feedparser.parse(self.url)
# self.last_update = datetime.date.today()
# if "link" in feed.feed:
# self.link = feed.feed.link
# else:
# self.link = ""
# self.save()
# for item in feed.entries[:10]:
# # The RSS spec doesn't require the guid field so fall back on link
# if "id" in item:
# guid = item.id
# else:
# guid = item.link
#
# # Search for an existing item
# try:
# FeedItem.objects.get(guid=guid)
# except FeedItem.DoesNotExist:
# # Create it.
# counter += 1
# if "published_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))
# elif "updated_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))
# else:
# pub_date = datetime.datetime.now()
#
# pub_date = timezone.make_aware(pub_date, timezone.get_current_timezone())
#
# feed_item = FeedItem(title=item.title, link=item.link, content=item.description,
# guid=guid, pub_date=pub_date, feed=self)
# feed_item.save()
# return counter
#
# def _update_processor(self):
# """
# Kick off the prrocessing of the feeds. Either update with celery
# or in real time if we aren't using Celery.
# :return:
# """
# if getattr(settings, 'FEED_UPDATE_CELERY', False):
# from .tasks import update_feed
# update_feed.delay(self)
# return True
# self._update_feed()
# return True
#
# def update(self, force=False):
# """
# If we aren't forcing it
# and its not the same day, go ahead
# and update the feeds.
# """
#
# if force or not force and self.last_update < datetime.date.today():
# self._update_processor()
# return True
#
# @models.permalink
# def get_absolute_url(self):
# """
# Feed permalink
# :return:
# """
# return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
#
# class Category(models.Model):
# """
# Category model
# """
# name = models.CharField(max_length=250, blank=True)
# slug = models.SlugField(blank=True, null=True, editable=False)
# user = models.ForeignKey(User, blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# """
# Updated Save to slug the name.
# :param args:
# :param kwargs:
# :return:
# """
# unique_slugify(self, self.name)
# super(Category, self).save(*args, **kwargs)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for a given category.
# :return:
# """
# return FeedItem.objects.my_feed_items(self.user).category(self.slug).un_read().count()
. Output only the next line. | self.fields['category'].queryset = Category.objects.filter(user=user) |
Continue the code snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and context (classes, functions, or code) from other files:
# Path: feedme/views.py
# class FeedList(LoginRequiredMixin, ListView):
# """
# Show the feed list for the logged in user.
# """
# template_name = 'feedme/feed_list.html'
# context_object_name = 'feed_items'
#
# def _update_feeds(self, user):
# """
# Update the feeds. We try to do this
# on page load in case we don't have the
# most updated feeds.
# """
# for feed in Feed.objects.filter(user=user):
# feed.update()
# return True
#
# def get_queryset(self):
# """
# Overwrite the query set method. Updates the feeds
# and then checks to see if the user is passing a feed id
# or category.
# """
# # Update the feed on page load..
# self._update_feeds(self.request.user)
# items = FeedItem.objects.my_feed_items(self.request.user).un_read()
#
# if self.kwargs.get('category', None):
# return items.category(self.kwargs.get('category'))
#
# if self.kwargs.get('feed_id', None):
# return items.filter(feed__id=self.kwargs.get('feed_id'))
#
# return items
#
# def get_context_data(self, **kwargs):
# """
# Update the context data. Add the categories and
# push the FeedForm to the template.
# """
# context = super(FeedList, self).get_context_data(**kwargs)
# context['categories'] = Category.objects.filter(user=self.request.user)
# context['add_form'] = AddFeedForm()
#
# return context
#
# class ImportView(LoginRequiredMixin, FormView):
# """
# Main view for importing feeds from Google Reader.
# """
# template_name = 'feedme/takeout_form.html'
# form_class = ImportFeedForm
# success_url = 'feedme-feed-list'
#
# def get_context_data(self, **kwargs):
# """
# Push extra context to the template.
# :param kwargs:
# :return:
# """
# context = super(ImportView, self).get_context_data(**kwargs)
# context['add_form'] = AddFeedForm()
# context['form'] = ImportFeedForm(user=self.request.user)
#
# return context
#
# def form_valid(self, form):
# """
# Process the form.
# """
# takeout = GoogleReaderTakeout(self.request.FILES['archive'])
# for data in takeout.subscriptions():
# if not data['xmlUrl']:
# logger.info("Found feed without url. Dumping %s." % data['title'])
# continue
# if data['category']:
# category, created = Category.objects.get_or_create(name=data['category'], user=self.request.user)
# else:
# category = form.cleaned_data['category']
# Feed.objects.get_or_create(
# url=data['xmlUrl'], title=data['title'],
# user=self.request.user, last_update=None,
# category=category
# )
#
# return redirect(reverse(self.get_success_url()))
#
# class AddView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
# """
# Simple class based create view
# """
# form_class = AddFeedForm
# model = Feed
#
# def mark_all_as_read(request):
# """
# Marks all items for a user as read.
# """
# items = FeedItem.objects.my_feed_items(request.user).un_read()
#
# for item in items:
# item.mark_as_read()
#
# return redirect('feedme-feed-list')
#
# @csrf_exempt
# def mark_as_read(request):
# """
# Ajax method to mark an item as being read.
# :param request:
# :return AJAX/HTTP Response of 200:
# """
# if request.method == "POST":
# feed_item = get_object_or_404(FeedItem, pk=request.POST.get('feed_item_id'))
# feed_item.read = True
# feed_item.save()
#
# return HttpResponse()
. Output only the next line. | url(r'^$', FeedList.as_view(), name="feedme-feed-list"), |
Given snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
url(r'^by_feed/(?P<feed_id>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-feed'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and context:
# Path: feedme/views.py
# class FeedList(LoginRequiredMixin, ListView):
# """
# Show the feed list for the logged in user.
# """
# template_name = 'feedme/feed_list.html'
# context_object_name = 'feed_items'
#
# def _update_feeds(self, user):
# """
# Update the feeds. We try to do this
# on page load in case we don't have the
# most updated feeds.
# """
# for feed in Feed.objects.filter(user=user):
# feed.update()
# return True
#
# def get_queryset(self):
# """
# Overwrite the query set method. Updates the feeds
# and then checks to see if the user is passing a feed id
# or category.
# """
# # Update the feed on page load..
# self._update_feeds(self.request.user)
# items = FeedItem.objects.my_feed_items(self.request.user).un_read()
#
# if self.kwargs.get('category', None):
# return items.category(self.kwargs.get('category'))
#
# if self.kwargs.get('feed_id', None):
# return items.filter(feed__id=self.kwargs.get('feed_id'))
#
# return items
#
# def get_context_data(self, **kwargs):
# """
# Update the context data. Add the categories and
# push the FeedForm to the template.
# """
# context = super(FeedList, self).get_context_data(**kwargs)
# context['categories'] = Category.objects.filter(user=self.request.user)
# context['add_form'] = AddFeedForm()
#
# return context
#
# class ImportView(LoginRequiredMixin, FormView):
# """
# Main view for importing feeds from Google Reader.
# """
# template_name = 'feedme/takeout_form.html'
# form_class = ImportFeedForm
# success_url = 'feedme-feed-list'
#
# def get_context_data(self, **kwargs):
# """
# Push extra context to the template.
# :param kwargs:
# :return:
# """
# context = super(ImportView, self).get_context_data(**kwargs)
# context['add_form'] = AddFeedForm()
# context['form'] = ImportFeedForm(user=self.request.user)
#
# return context
#
# def form_valid(self, form):
# """
# Process the form.
# """
# takeout = GoogleReaderTakeout(self.request.FILES['archive'])
# for data in takeout.subscriptions():
# if not data['xmlUrl']:
# logger.info("Found feed without url. Dumping %s." % data['title'])
# continue
# if data['category']:
# category, created = Category.objects.get_or_create(name=data['category'], user=self.request.user)
# else:
# category = form.cleaned_data['category']
# Feed.objects.get_or_create(
# url=data['xmlUrl'], title=data['title'],
# user=self.request.user, last_update=None,
# category=category
# )
#
# return redirect(reverse(self.get_success_url()))
#
# class AddView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
# """
# Simple class based create view
# """
# form_class = AddFeedForm
# model = Feed
#
# def mark_all_as_read(request):
# """
# Marks all items for a user as read.
# """
# items = FeedItem.objects.my_feed_items(request.user).un_read()
#
# for item in items:
# item.mark_as_read()
#
# return redirect('feedme-feed-list')
#
# @csrf_exempt
# def mark_as_read(request):
# """
# Ajax method to mark an item as being read.
# :param request:
# :return AJAX/HTTP Response of 200:
# """
# if request.method == "POST":
# feed_item = get_object_or_404(FeedItem, pk=request.POST.get('feed_item_id'))
# feed_item.read = True
# feed_item.save()
#
# return HttpResponse()
which might include code, classes, or functions. Output only the next line. | url(r'^import/$', ImportView.as_view(), name='feedme-import-google-takeout'), |
Given the following code snippet before the placeholder: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
url(r'^by_feed/(?P<feed_id>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-feed'),
url(r'^import/$', ImportView.as_view(), name='feedme-import-google-takeout'),
url(r'^mark_all_as_read/$', mark_all_as_read, name='feedme-mark-all-as-read'),
url(r'^ajax/mark_as_read/$', mark_as_read, name='feedme-mark-as-read-ajax'),
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and context including class names, function names, and sometimes code from other files:
# Path: feedme/views.py
# class FeedList(LoginRequiredMixin, ListView):
# """
# Show the feed list for the logged in user.
# """
# template_name = 'feedme/feed_list.html'
# context_object_name = 'feed_items'
#
# def _update_feeds(self, user):
# """
# Update the feeds. We try to do this
# on page load in case we don't have the
# most updated feeds.
# """
# for feed in Feed.objects.filter(user=user):
# feed.update()
# return True
#
# def get_queryset(self):
# """
# Overwrite the query set method. Updates the feeds
# and then checks to see if the user is passing a feed id
# or category.
# """
# # Update the feed on page load..
# self._update_feeds(self.request.user)
# items = FeedItem.objects.my_feed_items(self.request.user).un_read()
#
# if self.kwargs.get('category', None):
# return items.category(self.kwargs.get('category'))
#
# if self.kwargs.get('feed_id', None):
# return items.filter(feed__id=self.kwargs.get('feed_id'))
#
# return items
#
# def get_context_data(self, **kwargs):
# """
# Update the context data. Add the categories and
# push the FeedForm to the template.
# """
# context = super(FeedList, self).get_context_data(**kwargs)
# context['categories'] = Category.objects.filter(user=self.request.user)
# context['add_form'] = AddFeedForm()
#
# return context
#
# class ImportView(LoginRequiredMixin, FormView):
# """
# Main view for importing feeds from Google Reader.
# """
# template_name = 'feedme/takeout_form.html'
# form_class = ImportFeedForm
# success_url = 'feedme-feed-list'
#
# def get_context_data(self, **kwargs):
# """
# Push extra context to the template.
# :param kwargs:
# :return:
# """
# context = super(ImportView, self).get_context_data(**kwargs)
# context['add_form'] = AddFeedForm()
# context['form'] = ImportFeedForm(user=self.request.user)
#
# return context
#
# def form_valid(self, form):
# """
# Process the form.
# """
# takeout = GoogleReaderTakeout(self.request.FILES['archive'])
# for data in takeout.subscriptions():
# if not data['xmlUrl']:
# logger.info("Found feed without url. Dumping %s." % data['title'])
# continue
# if data['category']:
# category, created = Category.objects.get_or_create(name=data['category'], user=self.request.user)
# else:
# category = form.cleaned_data['category']
# Feed.objects.get_or_create(
# url=data['xmlUrl'], title=data['title'],
# user=self.request.user, last_update=None,
# category=category
# )
#
# return redirect(reverse(self.get_success_url()))
#
# class AddView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
# """
# Simple class based create view
# """
# form_class = AddFeedForm
# model = Feed
#
# def mark_all_as_read(request):
# """
# Marks all items for a user as read.
# """
# items = FeedItem.objects.my_feed_items(request.user).un_read()
#
# for item in items:
# item.mark_as_read()
#
# return redirect('feedme-feed-list')
#
# @csrf_exempt
# def mark_as_read(request):
# """
# Ajax method to mark an item as being read.
# :param request:
# :return AJAX/HTTP Response of 200:
# """
# if request.method == "POST":
# feed_item = get_object_or_404(FeedItem, pk=request.POST.get('feed_item_id'))
# feed_item.read = True
# feed_item.save()
#
# return HttpResponse()
. Output only the next line. | url(r'^ajax/add/$', AddView.as_view(), name='feedme-add-ajax'), |
Predict the next line for this snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
url(r'^by_feed/(?P<feed_id>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-feed'),
url(r'^import/$', ImportView.as_view(), name='feedme-import-google-takeout'),
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and context from other files:
# Path: feedme/views.py
# class FeedList(LoginRequiredMixin, ListView):
# """
# Show the feed list for the logged in user.
# """
# template_name = 'feedme/feed_list.html'
# context_object_name = 'feed_items'
#
# def _update_feeds(self, user):
# """
# Update the feeds. We try to do this
# on page load in case we don't have the
# most updated feeds.
# """
# for feed in Feed.objects.filter(user=user):
# feed.update()
# return True
#
# def get_queryset(self):
# """
# Overwrite the query set method. Updates the feeds
# and then checks to see if the user is passing a feed id
# or category.
# """
# # Update the feed on page load..
# self._update_feeds(self.request.user)
# items = FeedItem.objects.my_feed_items(self.request.user).un_read()
#
# if self.kwargs.get('category', None):
# return items.category(self.kwargs.get('category'))
#
# if self.kwargs.get('feed_id', None):
# return items.filter(feed__id=self.kwargs.get('feed_id'))
#
# return items
#
# def get_context_data(self, **kwargs):
# """
# Update the context data. Add the categories and
# push the FeedForm to the template.
# """
# context = super(FeedList, self).get_context_data(**kwargs)
# context['categories'] = Category.objects.filter(user=self.request.user)
# context['add_form'] = AddFeedForm()
#
# return context
#
# class ImportView(LoginRequiredMixin, FormView):
# """
# Main view for importing feeds from Google Reader.
# """
# template_name = 'feedme/takeout_form.html'
# form_class = ImportFeedForm
# success_url = 'feedme-feed-list'
#
# def get_context_data(self, **kwargs):
# """
# Push extra context to the template.
# :param kwargs:
# :return:
# """
# context = super(ImportView, self).get_context_data(**kwargs)
# context['add_form'] = AddFeedForm()
# context['form'] = ImportFeedForm(user=self.request.user)
#
# return context
#
# def form_valid(self, form):
# """
# Process the form.
# """
# takeout = GoogleReaderTakeout(self.request.FILES['archive'])
# for data in takeout.subscriptions():
# if not data['xmlUrl']:
# logger.info("Found feed without url. Dumping %s." % data['title'])
# continue
# if data['category']:
# category, created = Category.objects.get_or_create(name=data['category'], user=self.request.user)
# else:
# category = form.cleaned_data['category']
# Feed.objects.get_or_create(
# url=data['xmlUrl'], title=data['title'],
# user=self.request.user, last_update=None,
# category=category
# )
#
# return redirect(reverse(self.get_success_url()))
#
# class AddView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
# """
# Simple class based create view
# """
# form_class = AddFeedForm
# model = Feed
#
# def mark_all_as_read(request):
# """
# Marks all items for a user as read.
# """
# items = FeedItem.objects.my_feed_items(request.user).un_read()
#
# for item in items:
# item.mark_as_read()
#
# return redirect('feedme-feed-list')
#
# @csrf_exempt
# def mark_as_read(request):
# """
# Ajax method to mark an item as being read.
# :param request:
# :return AJAX/HTTP Response of 200:
# """
# if request.method == "POST":
# feed_item = get_object_or_404(FeedItem, pk=request.POST.get('feed_item_id'))
# feed_item.read = True
# feed_item.save()
#
# return HttpResponse()
, which may contain function names, class names, or code. Output only the next line. | url(r'^mark_all_as_read/$', mark_all_as_read, name='feedme-mark-all-as-read'), |
Here is a snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
url(r'^by_feed/(?P<feed_id>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-feed'),
url(r'^import/$', ImportView.as_view(), name='feedme-import-google-takeout'),
url(r'^mark_all_as_read/$', mark_all_as_read, name='feedme-mark-all-as-read'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and context from other files:
# Path: feedme/views.py
# class FeedList(LoginRequiredMixin, ListView):
# """
# Show the feed list for the logged in user.
# """
# template_name = 'feedme/feed_list.html'
# context_object_name = 'feed_items'
#
# def _update_feeds(self, user):
# """
# Update the feeds. We try to do this
# on page load in case we don't have the
# most updated feeds.
# """
# for feed in Feed.objects.filter(user=user):
# feed.update()
# return True
#
# def get_queryset(self):
# """
# Overwrite the query set method. Updates the feeds
# and then checks to see if the user is passing a feed id
# or category.
# """
# # Update the feed on page load..
# self._update_feeds(self.request.user)
# items = FeedItem.objects.my_feed_items(self.request.user).un_read()
#
# if self.kwargs.get('category', None):
# return items.category(self.kwargs.get('category'))
#
# if self.kwargs.get('feed_id', None):
# return items.filter(feed__id=self.kwargs.get('feed_id'))
#
# return items
#
# def get_context_data(self, **kwargs):
# """
# Update the context data. Add the categories and
# push the FeedForm to the template.
# """
# context = super(FeedList, self).get_context_data(**kwargs)
# context['categories'] = Category.objects.filter(user=self.request.user)
# context['add_form'] = AddFeedForm()
#
# return context
#
# class ImportView(LoginRequiredMixin, FormView):
# """
# Main view for importing feeds from Google Reader.
# """
# template_name = 'feedme/takeout_form.html'
# form_class = ImportFeedForm
# success_url = 'feedme-feed-list'
#
# def get_context_data(self, **kwargs):
# """
# Push extra context to the template.
# :param kwargs:
# :return:
# """
# context = super(ImportView, self).get_context_data(**kwargs)
# context['add_form'] = AddFeedForm()
# context['form'] = ImportFeedForm(user=self.request.user)
#
# return context
#
# def form_valid(self, form):
# """
# Process the form.
# """
# takeout = GoogleReaderTakeout(self.request.FILES['archive'])
# for data in takeout.subscriptions():
# if not data['xmlUrl']:
# logger.info("Found feed without url. Dumping %s." % data['title'])
# continue
# if data['category']:
# category, created = Category.objects.get_or_create(name=data['category'], user=self.request.user)
# else:
# category = form.cleaned_data['category']
# Feed.objects.get_or_create(
# url=data['xmlUrl'], title=data['title'],
# user=self.request.user, last_update=None,
# category=category
# )
#
# return redirect(reverse(self.get_success_url()))
#
# class AddView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
# """
# Simple class based create view
# """
# form_class = AddFeedForm
# model = Feed
#
# def mark_all_as_read(request):
# """
# Marks all items for a user as read.
# """
# items = FeedItem.objects.my_feed_items(request.user).un_read()
#
# for item in items:
# item.mark_as_read()
#
# return redirect('feedme-feed-list')
#
# @csrf_exempt
# def mark_as_read(request):
# """
# Ajax method to mark an item as being read.
# :param request:
# :return AJAX/HTTP Response of 200:
# """
# if request.method == "POST":
# feed_item = get_object_or_404(FeedItem, pk=request.POST.get('feed_item_id'))
# feed_item.read = True
# feed_item.save()
#
# return HttpResponse()
, which may include functions, classes, or code. Output only the next line. | url(r'^ajax/mark_as_read/$', mark_as_read, name='feedme-mark-as-read-ajax'), |
Using the snippet: <|code_start|>"""
Django Feedme
Digest.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
def send_digest():
"""
Send the daily digest for all users. This sends
both a .txt and .html version of the email.
:return:
"""
text_template = loader.get_template('feedme/mail/digest.txt')
html_template = loader.get_template('feedme/mail/digest.html')
subject = 'Daily FeedMe Digest'
for user in User.objects.all():
<|code_end|>
, determine the next line of code. You have imports:
from django.template import loader, Context
from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives
from .models import FeedItem
and context (class names, function names, or code) available:
# Path: feedme/models.py
# class FeedItem(models.Model):
# """
# FeedItem Model
# """
# title = models.CharField(max_length=350, blank=True)
# link = models.URLField(blank=True)
# content = models.TextField(blank=True)
# feed = models.ForeignKey(Feed, blank=True, null=True)
# read = models.BooleanField(default=False)
# guid = models.CharField(max_length=255)
# date_fetched = models.DateField(auto_created=True, auto_now_add=True, editable=True)
# pub_date = models.DateTimeField()
#
# objects = FeedItemManager()
#
# class Meta:
# ordering = ['id']
#
# def __str__(self):
# return self.title
#
# def mark_as_read(self):
# """
# Mark an item as read.
# """
# self.read = True
# self.save()
. Output only the next line. | items = FeedItem.objects.my_feed_items(user).yesterday() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
"""
Update all feed objects manually.
"""
help = 'Update all feeds'
def handle(self, *args, **options):
count = 0
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from feedme.models import Feed
and context (class names, function names, or code) available:
# Path: feedme/models.py
# class Feed(models.Model):
# """
# Feed Model
# """
# link = models.CharField(blank=True, max_length=450)
# url = models.CharField(blank=True, max_length=450)
# title = models.CharField(blank=True, null=True, max_length=250)
# category = models.ForeignKey(Category, blank=True, null=True)
# user = models.ForeignKey(User, blank=True, null=True)
# last_update = models.DateField(blank=True, null=True, editable=False)
#
# class Meta:
# unique_together = (
# ("url", "user"),
# )
#
# def __str__(self):
# return self.url
#
# def _get_title(self):
# """
# Fetch the title from the feed.
# :return:
# """
# parser = feedparser.parse(self.url)
# return parser.feed.title
#
# def save(self, *args, **kwargs):
# """
# Updated .save() method. Fetches the title
# from the feed, and updates the record timestamp.
# :param args:
# :param kwargs:
# :return:
# """
# if not self.title:
# self.title = self._get_title()
# super(Feed, self).save(*args, **kwargs)
# if self.last_update is None:
# self.update(force=True)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for all items in this feed.
# :return int count of un-read items:
# """
# return FeedItem.objects.filter(feed=self).un_read().count()
#
# def _update_feed(self):
# """
# Perform an update on this feed. This fetches the latest
# data from the feed and compares it to what we have stored currently.
# Then we go ahead and save that content and mark it as
# un-read.
# """
# # Update the last update field
# counter = 0
# feed = feedparser.parse(self.url)
# self.last_update = datetime.date.today()
# if "link" in feed.feed:
# self.link = feed.feed.link
# else:
# self.link = ""
# self.save()
# for item in feed.entries[:10]:
# # The RSS spec doesn't require the guid field so fall back on link
# if "id" in item:
# guid = item.id
# else:
# guid = item.link
#
# # Search for an existing item
# try:
# FeedItem.objects.get(guid=guid)
# except FeedItem.DoesNotExist:
# # Create it.
# counter += 1
# if "published_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))
# elif "updated_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))
# else:
# pub_date = datetime.datetime.now()
#
# pub_date = timezone.make_aware(pub_date, timezone.get_current_timezone())
#
# feed_item = FeedItem(title=item.title, link=item.link, content=item.description,
# guid=guid, pub_date=pub_date, feed=self)
# feed_item.save()
# return counter
#
# def _update_processor(self):
# """
# Kick off the prrocessing of the feeds. Either update with celery
# or in real time if we aren't using Celery.
# :return:
# """
# if getattr(settings, 'FEED_UPDATE_CELERY', False):
# from .tasks import update_feed
# update_feed.delay(self)
# return True
# self._update_feed()
# return True
#
# def update(self, force=False):
# """
# If we aren't forcing it
# and its not the same day, go ahead
# and update the feeds.
# """
#
# if force or not force and self.last_update < datetime.date.today():
# self._update_processor()
# return True
#
# @models.permalink
# def get_absolute_url(self):
# """
# Feed permalink
# :return:
# """
# return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
. Output only the next line. | for feed in Feed.objects.all(): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
"""
Management command to send the daily digest. Typically
called by Celery.
"""
help = 'Send Digest'
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from feedme import digest
and context (class names, function names, or code) available:
# Path: feedme/digest.py
# def send_digest():
. Output only the next line. | digest.send_digest() |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
class FeedMeTestCase(TestCase):
def test_update_feed(self):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from feedme.models import Feed, FeedItem
and context from other files:
# Path: feedme/models.py
# class Feed(models.Model):
# """
# Feed Model
# """
# link = models.CharField(blank=True, max_length=450)
# url = models.CharField(blank=True, max_length=450)
# title = models.CharField(blank=True, null=True, max_length=250)
# category = models.ForeignKey(Category, blank=True, null=True)
# user = models.ForeignKey(User, blank=True, null=True)
# last_update = models.DateField(blank=True, null=True, editable=False)
#
# class Meta:
# unique_together = (
# ("url", "user"),
# )
#
# def __str__(self):
# return self.url
#
# def _get_title(self):
# """
# Fetch the title from the feed.
# :return:
# """
# parser = feedparser.parse(self.url)
# return parser.feed.title
#
# def save(self, *args, **kwargs):
# """
# Updated .save() method. Fetches the title
# from the feed, and updates the record timestamp.
# :param args:
# :param kwargs:
# :return:
# """
# if not self.title:
# self.title = self._get_title()
# super(Feed, self).save(*args, **kwargs)
# if self.last_update is None:
# self.update(force=True)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for all items in this feed.
# :return int count of un-read items:
# """
# return FeedItem.objects.filter(feed=self).un_read().count()
#
# def _update_feed(self):
# """
# Perform an update on this feed. This fetches the latest
# data from the feed and compares it to what we have stored currently.
# Then we go ahead and save that content and mark it as
# un-read.
# """
# # Update the last update field
# counter = 0
# feed = feedparser.parse(self.url)
# self.last_update = datetime.date.today()
# if "link" in feed.feed:
# self.link = feed.feed.link
# else:
# self.link = ""
# self.save()
# for item in feed.entries[:10]:
# # The RSS spec doesn't require the guid field so fall back on link
# if "id" in item:
# guid = item.id
# else:
# guid = item.link
#
# # Search for an existing item
# try:
# FeedItem.objects.get(guid=guid)
# except FeedItem.DoesNotExist:
# # Create it.
# counter += 1
# if "published_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))
# elif "updated_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))
# else:
# pub_date = datetime.datetime.now()
#
# pub_date = timezone.make_aware(pub_date, timezone.get_current_timezone())
#
# feed_item = FeedItem(title=item.title, link=item.link, content=item.description,
# guid=guid, pub_date=pub_date, feed=self)
# feed_item.save()
# return counter
#
# def _update_processor(self):
# """
# Kick off the prrocessing of the feeds. Either update with celery
# or in real time if we aren't using Celery.
# :return:
# """
# if getattr(settings, 'FEED_UPDATE_CELERY', False):
# from .tasks import update_feed
# update_feed.delay(self)
# return True
# self._update_feed()
# return True
#
# def update(self, force=False):
# """
# If we aren't forcing it
# and its not the same day, go ahead
# and update the feeds.
# """
#
# if force or not force and self.last_update < datetime.date.today():
# self._update_processor()
# return True
#
# @models.permalink
# def get_absolute_url(self):
# """
# Feed permalink
# :return:
# """
# return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
#
# class FeedItem(models.Model):
# """
# FeedItem Model
# """
# title = models.CharField(max_length=350, blank=True)
# link = models.URLField(blank=True)
# content = models.TextField(blank=True)
# feed = models.ForeignKey(Feed, blank=True, null=True)
# read = models.BooleanField(default=False)
# guid = models.CharField(max_length=255)
# date_fetched = models.DateField(auto_created=True, auto_now_add=True, editable=True)
# pub_date = models.DateTimeField()
#
# objects = FeedItemManager()
#
# class Meta:
# ordering = ['id']
#
# def __str__(self):
# return self.title
#
# def mark_as_read(self):
# """
# Mark an item as read.
# """
# self.read = True
# self.save()
, which may include functions, classes, or code. Output only the next line. | feed = Feed(url='http://rss.cnn.com/rss/cnn_topstories.rss') |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
class FeedMeTestCase(TestCase):
def test_update_feed(self):
feed = Feed(url='http://rss.cnn.com/rss/cnn_topstories.rss')
feed.save()
feed.update(force=True)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from feedme.models import Feed, FeedItem
and context (classes, functions, sometimes code) from other files:
# Path: feedme/models.py
# class Feed(models.Model):
# """
# Feed Model
# """
# link = models.CharField(blank=True, max_length=450)
# url = models.CharField(blank=True, max_length=450)
# title = models.CharField(blank=True, null=True, max_length=250)
# category = models.ForeignKey(Category, blank=True, null=True)
# user = models.ForeignKey(User, blank=True, null=True)
# last_update = models.DateField(blank=True, null=True, editable=False)
#
# class Meta:
# unique_together = (
# ("url", "user"),
# )
#
# def __str__(self):
# return self.url
#
# def _get_title(self):
# """
# Fetch the title from the feed.
# :return:
# """
# parser = feedparser.parse(self.url)
# return parser.feed.title
#
# def save(self, *args, **kwargs):
# """
# Updated .save() method. Fetches the title
# from the feed, and updates the record timestamp.
# :param args:
# :param kwargs:
# :return:
# """
# if not self.title:
# self.title = self._get_title()
# super(Feed, self).save(*args, **kwargs)
# if self.last_update is None:
# self.update(force=True)
#
# @property
# def get_unread_count(self):
# """
# Fetch the unread count for all items in this feed.
# :return int count of un-read items:
# """
# return FeedItem.objects.filter(feed=self).un_read().count()
#
# def _update_feed(self):
# """
# Perform an update on this feed. This fetches the latest
# data from the feed and compares it to what we have stored currently.
# Then we go ahead and save that content and mark it as
# un-read.
# """
# # Update the last update field
# counter = 0
# feed = feedparser.parse(self.url)
# self.last_update = datetime.date.today()
# if "link" in feed.feed:
# self.link = feed.feed.link
# else:
# self.link = ""
# self.save()
# for item in feed.entries[:10]:
# # The RSS spec doesn't require the guid field so fall back on link
# if "id" in item:
# guid = item.id
# else:
# guid = item.link
#
# # Search for an existing item
# try:
# FeedItem.objects.get(guid=guid)
# except FeedItem.DoesNotExist:
# # Create it.
# counter += 1
# if "published_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))
# elif "updated_parsed" in item:
# pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))
# else:
# pub_date = datetime.datetime.now()
#
# pub_date = timezone.make_aware(pub_date, timezone.get_current_timezone())
#
# feed_item = FeedItem(title=item.title, link=item.link, content=item.description,
# guid=guid, pub_date=pub_date, feed=self)
# feed_item.save()
# return counter
#
# def _update_processor(self):
# """
# Kick off the prrocessing of the feeds. Either update with celery
# or in real time if we aren't using Celery.
# :return:
# """
# if getattr(settings, 'FEED_UPDATE_CELERY', False):
# from .tasks import update_feed
# update_feed.delay(self)
# return True
# self._update_feed()
# return True
#
# def update(self, force=False):
# """
# If we aren't forcing it
# and its not the same day, go ahead
# and update the feeds.
# """
#
# if force or not force and self.last_update < datetime.date.today():
# self._update_processor()
# return True
#
# @models.permalink
# def get_absolute_url(self):
# """
# Feed permalink
# :return:
# """
# return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})
#
# class FeedItem(models.Model):
# """
# FeedItem Model
# """
# title = models.CharField(max_length=350, blank=True)
# link = models.URLField(blank=True)
# content = models.TextField(blank=True)
# feed = models.ForeignKey(Feed, blank=True, null=True)
# read = models.BooleanField(default=False)
# guid = models.CharField(max_length=255)
# date_fetched = models.DateField(auto_created=True, auto_now_add=True, editable=True)
# pub_date = models.DateTimeField()
#
# objects = FeedItemManager()
#
# class Meta:
# ordering = ['id']
#
# def __str__(self):
# return self.title
#
# def mark_as_read(self):
# """
# Mark an item as read.
# """
# self.read = True
# self.save()
. Output only the next line. | self.assertEqual(FeedItem.objects.all().count(), 10) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# TODO: can be simplified into, after merging https://github.com/divio/django-cms/pull/5898
# from blogit.urls import get_urls
# def get_urls(self, page=None, language=None, **kwargs):
# return get_urls('module')
class BlogitApphook(CMSApp):
name = _('Blogit')
def get_urls(self, page=None, language=None, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
from blogit import settings as bs
and context including class names, function names, and sometimes code from other files:
# Path: blogit/settings.py
# ACTIVE_FIELD_HELP_TEXT = _('Is this object active?')
# TITLE = getattr(settings, 'BLOGIT_TITLE', _('Blogit'))
# DESCRIPTION = getattr(settings, 'BLOGIT_DESCRIPTION', _('This is a blog about everything'))
# FEED_LIMIT = getattr(settings, 'BLOGIT_FEED_LIMIT', 100)
# FEED_ITEM_AUTHOR_NAME = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_NAME', None)
# FEED_ITEM_AUTHOR_EMAIL = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_EMAIL', None)
# FEED_ITEM_DESCRIPTION_FULL = getattr(settings, 'BLOGIT_FEED_ITEM_DESCRIPTION_FULL', False)
# FEED_DEFAULT = getattr(settings, 'BLOGIT_FEED_DEFAULT', 'rss')
# SITEMAP_PRIORITY = getattr(settings, 'BLOGIT_SITEMAP_PRIORITY', 0.5)
# SITEMAP_CHANGEFREQ = getattr(settings, 'BLOGIT_SITEMAP_CHANGEFREQ', 'weekly')
# POSTS_PER_PAGE = getattr(settings, 'BLOGIT_POSTS_PER_PAGE', 10)
# POST_DETAIL_DATE_URL = getattr(settings, 'BLOGIT_POST_DETAIL_DATE_URL', False)
# SINGLE_APPHOOK = getattr(settings, 'BLOGIT_SINGLE_APPHOOK', False)
. Output only the next line. | if bs.SINGLE_APPHOOK: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError:
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
@python_2_unicode_compatible
class Category(MPTTModel, TranslatableModel):
"""
Category
"""
<|code_end|>
, predict the next line using imports from the current file:
from cms.models.fields import PlaceholderField
from cms.utils.i18n import get_current_language
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.models import MPTTModel, TreeForeignKey
from parler.managers import TranslatableManager
from parler.models import TranslatableModel, TranslatedFields
from parler.utils.context import switch_language
from blogit import settings as bs
from blogit.managers import PostManager
from blogit.utils import get_text_from_placeholder
from django.utils.encoding import force_unicode
from django.utils.encoding import force_text as force_unicode
and context including class names, function names, and sometimes code from other files:
# Path: blogit/settings.py
# ACTIVE_FIELD_HELP_TEXT = _('Is this object active?')
# TITLE = getattr(settings, 'BLOGIT_TITLE', _('Blogit'))
# DESCRIPTION = getattr(settings, 'BLOGIT_DESCRIPTION', _('This is a blog about everything'))
# FEED_LIMIT = getattr(settings, 'BLOGIT_FEED_LIMIT', 100)
# FEED_ITEM_AUTHOR_NAME = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_NAME', None)
# FEED_ITEM_AUTHOR_EMAIL = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_EMAIL', None)
# FEED_ITEM_DESCRIPTION_FULL = getattr(settings, 'BLOGIT_FEED_ITEM_DESCRIPTION_FULL', False)
# FEED_DEFAULT = getattr(settings, 'BLOGIT_FEED_DEFAULT', 'rss')
# SITEMAP_PRIORITY = getattr(settings, 'BLOGIT_SITEMAP_PRIORITY', 0.5)
# SITEMAP_CHANGEFREQ = getattr(settings, 'BLOGIT_SITEMAP_CHANGEFREQ', 'weekly')
# POSTS_PER_PAGE = getattr(settings, 'BLOGIT_POSTS_PER_PAGE', 10)
# POST_DETAIL_DATE_URL = getattr(settings, 'BLOGIT_POST_DETAIL_DATE_URL', False)
# SINGLE_APPHOOK = getattr(settings, 'BLOGIT_SINGLE_APPHOOK', False)
#
# Path: blogit/managers.py
# class PostManager(TranslatableManager):
# queryset_class = PostQuerySet
#
# def published(self, request, **kwargs):
# queryset = self.public(**kwargs).published()
# if hasattr(request, 'user') and request.user.is_authenticated:
# if request.user.is_staff:
# queryset = queryset | self.draft(**kwargs)
# queryset = queryset | self.private(request.user, **kwargs)
# return queryset
#
# def draft(self, **kwargs):
# return self.get_queryset().filter(status=0, **kwargs)
#
# def private(self, user, **kwargs):
# return self.get_queryset().filter(status=1, author=user, **kwargs)
#
# def public(self, **kwargs):
# return self.get_queryset().filter(status=2, **kwargs)
#
# def hidden(self, **kwargs):
# return self.get_queryset().filter(status=3, **kwargs)
#
# Path: blogit/utils.py
# def get_text_from_placeholder(placeholder, language=None, request=None):
# """
# Returns rendered and strippet text from given placeholder
# """
# if not placeholder:
# return ''
# if not language:
# language = get_current_language()
# if not request:
# request = get_request(language)
#
# bits = []
# plugins = placeholder.cmsplugin_set.filter(language=language)
# for base_plugin in plugins:
# instance, plugin_type = base_plugin.get_plugin_instance()
# if instance is None:
# continue
# bits.append(instance.render_plugin(context=RequestContext(request)))
# return force_unicode(strip_tags(' '.join(bits)))
. Output only the next line. | active = models.BooleanField(_('Active'), default=True, help_text=bs.ACTIVE_FIELD_HELP_TEXT) |
Given snippet: <|code_start|> date_added = models.DateTimeField(_('Date added'), auto_now_add=True)
last_modified = models.DateTimeField(_('Last modified'), auto_now=True)
status = models.IntegerField(_('Status'), choices=STATUS_CODES, default=DRAFT, help_text=_(
'When draft post is visible to staff only, when private to author only, and when public to everyone.'))
date_published = models.DateTimeField(_('Published on'), default=timezone.now)
category = TreeForeignKey(Category, models.SET_NULL, blank=True, null=True, verbose_name=_('Category'))
tags = models.ManyToManyField(Tag, blank=True, related_name='tagged_posts', verbose_name=_('Tags'))
author = models.ForeignKey(USER_MODEL, models.SET_NULL, blank=True, null=True, verbose_name=_('Author'))
featured_image = FilerImageField(
on_delete=models.SET_NULL,
blank=True,
null=True,
verbose_name=_('Featured Image'),
)
translations = TranslatedFields(
title=models.CharField(_('Title'), max_length=255),
slug=models.SlugField(_('Slug'), db_index=True),
description=models.TextField(_('Description'), blank=True),
meta_title=models.CharField(_('Meta title'), max_length=255, blank=True),
meta_description=models.TextField(_('Meta description'), max_length=155, blank=True, help_text=_(
'The text displayed in search engines.')),
meta={'unique_together': [('slug', 'language_code')]},
)
body = PlaceholderField('blogit_post_body', related_name='post_body_set')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from cms.models.fields import PlaceholderField
from cms.utils.i18n import get_current_language
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.models import MPTTModel, TreeForeignKey
from parler.managers import TranslatableManager
from parler.models import TranslatableModel, TranslatedFields
from parler.utils.context import switch_language
from blogit import settings as bs
from blogit.managers import PostManager
from blogit.utils import get_text_from_placeholder
from django.utils.encoding import force_unicode
from django.utils.encoding import force_text as force_unicode
and context:
# Path: blogit/settings.py
# ACTIVE_FIELD_HELP_TEXT = _('Is this object active?')
# TITLE = getattr(settings, 'BLOGIT_TITLE', _('Blogit'))
# DESCRIPTION = getattr(settings, 'BLOGIT_DESCRIPTION', _('This is a blog about everything'))
# FEED_LIMIT = getattr(settings, 'BLOGIT_FEED_LIMIT', 100)
# FEED_ITEM_AUTHOR_NAME = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_NAME', None)
# FEED_ITEM_AUTHOR_EMAIL = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_EMAIL', None)
# FEED_ITEM_DESCRIPTION_FULL = getattr(settings, 'BLOGIT_FEED_ITEM_DESCRIPTION_FULL', False)
# FEED_DEFAULT = getattr(settings, 'BLOGIT_FEED_DEFAULT', 'rss')
# SITEMAP_PRIORITY = getattr(settings, 'BLOGIT_SITEMAP_PRIORITY', 0.5)
# SITEMAP_CHANGEFREQ = getattr(settings, 'BLOGIT_SITEMAP_CHANGEFREQ', 'weekly')
# POSTS_PER_PAGE = getattr(settings, 'BLOGIT_POSTS_PER_PAGE', 10)
# POST_DETAIL_DATE_URL = getattr(settings, 'BLOGIT_POST_DETAIL_DATE_URL', False)
# SINGLE_APPHOOK = getattr(settings, 'BLOGIT_SINGLE_APPHOOK', False)
#
# Path: blogit/managers.py
# class PostManager(TranslatableManager):
# queryset_class = PostQuerySet
#
# def published(self, request, **kwargs):
# queryset = self.public(**kwargs).published()
# if hasattr(request, 'user') and request.user.is_authenticated:
# if request.user.is_staff:
# queryset = queryset | self.draft(**kwargs)
# queryset = queryset | self.private(request.user, **kwargs)
# return queryset
#
# def draft(self, **kwargs):
# return self.get_queryset().filter(status=0, **kwargs)
#
# def private(self, user, **kwargs):
# return self.get_queryset().filter(status=1, author=user, **kwargs)
#
# def public(self, **kwargs):
# return self.get_queryset().filter(status=2, **kwargs)
#
# def hidden(self, **kwargs):
# return self.get_queryset().filter(status=3, **kwargs)
#
# Path: blogit/utils.py
# def get_text_from_placeholder(placeholder, language=None, request=None):
# """
# Returns rendered and strippet text from given placeholder
# """
# if not placeholder:
# return ''
# if not language:
# language = get_current_language()
# if not request:
# request = get_request(language)
#
# bits = []
# plugins = placeholder.cmsplugin_set.filter(language=language)
# for base_plugin in plugins:
# instance, plugin_type = base_plugin.get_plugin_instance()
# if instance is None:
# continue
# bits.append(instance.render_plugin(context=RequestContext(request)))
# return force_unicode(strip_tags(' '.join(bits)))
which might include code, classes, or functions. Output only the next line. | objects = PostManager() |
Here is a snippet: <|code_start|> 'slug': self.safe_translation_getter('slug'),
})
return reverse('blogit_post_detail', kwargs={
'slug': self.safe_translation_getter('slug')})
def get_search_data(self, language=None, request=None):
"""
Returns search text data for current object
"""
if not self.pk:
return ''
bits = [self.name]
description = self.safe_translation_getter('description')
if description:
bits.append(force_unicode(strip_tags(description)))
if self.category:
bits.append(self.category.safe_translation_getter('name'))
description = self.category.safe_translation_getter('description')
if description:
bits.append(force_unicode(strip_tags(description)))
for tag in self.tags.all():
bits.append(tag.safe_translation_getter('name'))
description = tag.safe_translation_getter('description', '')
if description:
bits.append(force_unicode(strip_tags(description)))
<|code_end|>
. Write the next line using the current file imports:
from cms.models.fields import PlaceholderField
from cms.utils.i18n import get_current_language
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.models import MPTTModel, TreeForeignKey
from parler.managers import TranslatableManager
from parler.models import TranslatableModel, TranslatedFields
from parler.utils.context import switch_language
from blogit import settings as bs
from blogit.managers import PostManager
from blogit.utils import get_text_from_placeholder
from django.utils.encoding import force_unicode
from django.utils.encoding import force_text as force_unicode
and context from other files:
# Path: blogit/settings.py
# ACTIVE_FIELD_HELP_TEXT = _('Is this object active?')
# TITLE = getattr(settings, 'BLOGIT_TITLE', _('Blogit'))
# DESCRIPTION = getattr(settings, 'BLOGIT_DESCRIPTION', _('This is a blog about everything'))
# FEED_LIMIT = getattr(settings, 'BLOGIT_FEED_LIMIT', 100)
# FEED_ITEM_AUTHOR_NAME = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_NAME', None)
# FEED_ITEM_AUTHOR_EMAIL = getattr(settings, 'BLOGIT_FEED_ITEM_AUTHOR_EMAIL', None)
# FEED_ITEM_DESCRIPTION_FULL = getattr(settings, 'BLOGIT_FEED_ITEM_DESCRIPTION_FULL', False)
# FEED_DEFAULT = getattr(settings, 'BLOGIT_FEED_DEFAULT', 'rss')
# SITEMAP_PRIORITY = getattr(settings, 'BLOGIT_SITEMAP_PRIORITY', 0.5)
# SITEMAP_CHANGEFREQ = getattr(settings, 'BLOGIT_SITEMAP_CHANGEFREQ', 'weekly')
# POSTS_PER_PAGE = getattr(settings, 'BLOGIT_POSTS_PER_PAGE', 10)
# POST_DETAIL_DATE_URL = getattr(settings, 'BLOGIT_POST_DETAIL_DATE_URL', False)
# SINGLE_APPHOOK = getattr(settings, 'BLOGIT_SINGLE_APPHOOK', False)
#
# Path: blogit/managers.py
# class PostManager(TranslatableManager):
# queryset_class = PostQuerySet
#
# def published(self, request, **kwargs):
# queryset = self.public(**kwargs).published()
# if hasattr(request, 'user') and request.user.is_authenticated:
# if request.user.is_staff:
# queryset = queryset | self.draft(**kwargs)
# queryset = queryset | self.private(request.user, **kwargs)
# return queryset
#
# def draft(self, **kwargs):
# return self.get_queryset().filter(status=0, **kwargs)
#
# def private(self, user, **kwargs):
# return self.get_queryset().filter(status=1, author=user, **kwargs)
#
# def public(self, **kwargs):
# return self.get_queryset().filter(status=2, **kwargs)
#
# def hidden(self, **kwargs):
# return self.get_queryset().filter(status=3, **kwargs)
#
# Path: blogit/utils.py
# def get_text_from_placeholder(placeholder, language=None, request=None):
# """
# Returns rendered and strippet text from given placeholder
# """
# if not placeholder:
# return ''
# if not language:
# language = get_current_language()
# if not request:
# request = get_request(language)
#
# bits = []
# plugins = placeholder.cmsplugin_set.filter(language=language)
# for base_plugin in plugins:
# instance, plugin_type = base_plugin.get_plugin_instance()
# if instance is None:
# continue
# bits.append(instance.render_plugin(context=RequestContext(request)))
# return force_unicode(strip_tags(' '.join(bits)))
, which may include functions, classes, or code. Output only the next line. | bits.append(get_text_from_placeholder(self.body, language, request)) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_numgrad"]
def f1(x):
return -0.5 * np.sum(x**2)
def dfdx1(x):
return -x
def f2(x):
return np.sum(x)
def dfdx2(x):
return np.ones(len(x))
@pytest.mark.parametrize("funcs,gf", product(
[(f1, dfdx1), (f2, dfdx2)],
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from itertools import product
from ...numgrad import numerical_gradient_1, numerical_gradient_2
and context (functions, classes, or occasionally code) from other files:
# Path: emcee3/numgrad.py
# class numerical_gradient_1(object):
# """Wrap a function to numerically compute first order gradients.
#
# The function is expected to take a numpy array as its first argument and
# calling an instance of this object will return the gradient with respect
# to this first argument.
#
# Args:
# f (callable): The function.
# eps (Optional[float]): The step size.
#
# """
#
# def __init__(self, f, eps=1.234e-7):
# self.eps = eps
# self.f = f
#
# def __call__(self, x, *args, **kwargs):
# y0 = self.f(x, *args, **kwargs)
# g = np.zeros(len(x))
# for i, v in enumerate(x):
# x[i] = v + self.eps
# y = self.f(x, *args, **kwargs)
# g[i] = (y - y0) / self.eps
# x[i] = v
# return g
#
# class numerical_gradient_2(object):
# """Wrap a function to numerically compute second order gradients.
#
# The function is expected to take a numpy array as its first argument and
# calling an instance of this object will return the gradient with respect
# to this first argument.
#
# Args:
# f (callable): The function.
# eps (Optional[float]): The step size.
#
# """
#
# def __init__(self, f, eps=1.234e-7):
# self.eps = eps
# self.f = f
#
# def __call__(self, x, *args, **kwargs):
# g = np.zeros(len(x))
# for i, v in enumerate(x):
# x[i] = v + self.eps
# yp = self.f(x, *args, **kwargs)
# x[i] = v - self.eps
# ym = self.f(x, *args, **kwargs)
# g[i] = 0.5 * (yp - ym) / self.eps
# x[i] = v
# return g
. Output only the next line. | [numerical_gradient_1, numerical_gradient_2], |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_numgrad"]
def f1(x):
return -0.5 * np.sum(x**2)
def dfdx1(x):
return -x
def f2(x):
return np.sum(x)
def dfdx2(x):
return np.ones(len(x))
@pytest.mark.parametrize("funcs,gf", product(
[(f1, dfdx1), (f2, dfdx2)],
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from itertools import product
from ...numgrad import numerical_gradient_1, numerical_gradient_2
and context (functions, classes, or occasionally code) from other files:
# Path: emcee3/numgrad.py
# class numerical_gradient_1(object):
# """Wrap a function to numerically compute first order gradients.
#
# The function is expected to take a numpy array as its first argument and
# calling an instance of this object will return the gradient with respect
# to this first argument.
#
# Args:
# f (callable): The function.
# eps (Optional[float]): The step size.
#
# """
#
# def __init__(self, f, eps=1.234e-7):
# self.eps = eps
# self.f = f
#
# def __call__(self, x, *args, **kwargs):
# y0 = self.f(x, *args, **kwargs)
# g = np.zeros(len(x))
# for i, v in enumerate(x):
# x[i] = v + self.eps
# y = self.f(x, *args, **kwargs)
# g[i] = (y - y0) / self.eps
# x[i] = v
# return g
#
# class numerical_gradient_2(object):
# """Wrap a function to numerically compute second order gradients.
#
# The function is expected to take a numpy array as its first argument and
# calling an instance of this object will return the gradient with respect
# to this first argument.
#
# Args:
# f (callable): The function.
# eps (Optional[float]): The step size.
#
# """
#
# def __init__(self, f, eps=1.234e-7):
# self.eps = eps
# self.f = f
#
# def __call__(self, x, *args, **kwargs):
# g = np.zeros(len(x))
# for i, v in enumerate(x):
# x[i] = v + self.eps
# yp = self.f(x, *args, **kwargs)
# x[i] = v - self.eps
# ym = self.f(x, *args, **kwargs)
# g[i] = 0.5 * (yp - ym) / self.eps
# x[i] = v
# return g
. Output only the next line. | [numerical_gradient_1, numerical_gradient_2], |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
try:
except ImportError:
gaussian_kde = None
__all__ = ["KDEMove"]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from scipy.stats import gaussian_kde
from .red_blue import RedBlueMove
and context:
# Path: emcee3/moves/red_blue.py
# class RedBlueMove(object):
# """
# An abstract red-blue ensemble move with parallelization as described in
# `Foreman-Mackey et al. (2013) <http://arxiv.org/abs/1202.3665>`_.
#
# Args:
# nsplits (Optional[int]): The number of sub-ensembles to use. Each
# sub-ensemble is updated in parallel using the other sets as the
# complementary ensemble. The default value is ``2`` and you
# probably won't need to change that.
#
# randomize_split (Optional[bool]): Randomly shuffle walkers between
# sub-ensembles. The same number of walkers will be assigned to
# each sub-ensemble on each iteration. By default, this is ``False``.
#
# live_dangerously (Optional[bool]): By default, an update will fail with
# a ``RuntimeError`` if the number of walkers is smaller than twice
# the dimension of the problem because the walkers would then be
# stuck on a low dimensional subspace. This can be avoided by
# switching between the stretch move and, for example, a
# Metropolis-Hastings step. If you want to do this and suppress the
# error, set ``live_dangerously = True``. Thanks goes (once again)
# to @dstndstn for this wonderful terminology.
#
# """
# def __init__(self,
# nsplits=2,
# randomize_split=False,
# live_dangerously=False):
# self.nsplits = int(nsplits)
# self.live_dangerously = live_dangerously
# self.randomize_split = randomize_split
#
# def setup(self, ensemble):
# pass
#
# def get_proposal(self, ensemble, sample, complement):
# raise NotImplementedError("The proposal must be implemented by "
# "subclasses")
#
# def finalize(self, ensemble):
# pass
#
# def update(self, ensemble):
# """
# Execute a move starting from the given :class:`Ensemble` and updating
# it in-place.
#
# :param ensemble:
# The starting :class:`Ensemble`.
#
# :return ensemble:
# The same ensemble updated in-place.
#
# """
# # Check that the dimensions are compatible.
# nwalkers, ndim = ensemble.nwalkers, ensemble.ndim
# if nwalkers < 2 * ndim and not self.live_dangerously:
# raise RuntimeError("It is unadvisable to use a red-blue move "
# "with fewer walkers than twice the number of "
# "dimensions.")
#
# # Run any move-specific setup.
# self.setup(ensemble)
#
# # Split the ensemble in half and iterate over these two halves.
# inds = np.arange(nwalkers) % self.nsplits
# if self.randomize_split:
# ensemble.random.shuffle(inds)
# for i in range(self.nsplits):
# S1 = inds == i
# S2 = inds != i
#
# # Get the two halves of the ensemble.
# s = ensemble.coords[S1]
# c = ensemble.coords[S2]
#
# # Get the move-specific proposal.
# q, factors = self.get_proposal(ensemble, s, c)
#
# # Compute the lnprobs of the proposed position.
# states = ensemble.propose(q)
#
# # Loop over the walkers and update them accordingly.
# for i, (j, f, state) in enumerate(zip(
# np.arange(len(ensemble))[S1], factors, states)):
# lnpdiff = (
# f +
# state.log_probability -
# ensemble.walkers[j].log_probability
# )
# if lnpdiff > np.log(ensemble.random.rand()):
# state.accepted = True
#
# # Update the ensemble with the accepted walkers.
# ensemble.update(states, subset=S1)
#
# # Do any move-specific cleanup.
# self.finalize(ensemble)
#
# return ensemble
which might include code, classes, or functions. Output only the next line. | class KDEMove(RedBlueMove): |
Next line prediction: <|code_start|>
def get_log_probability(self, **kwargs):
"""Get the chain of log probabilities evaluated at the MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): Take only every ``thin`` steps from the
chain. (default: ``1``)
discard (Optional[int]): Discard the first ``discard`` steps in
the chain as burn-in. (default: ``0``)
Returns:
array[..., nwalkers]: The chain of log probabilities.
"""
return (
self.get_value("log_prior", **kwargs) +
self.get_value("log_likelihood", **kwargs)
)
def get_integrated_autocorr_time(self, **kwargs):
"""Get the integrated autocorrelation time for each dimension.
Any arguments are passed directly to :func:`autocorr.integrated_time`.
Returns:
array[ndim]: The estimated autocorrelation time in each dimension.
"""
<|code_end|>
. Use current file imports:
(import numpy as np
from ..autocorr import integrated_time)
and context including class names, function names, or small code snippets from other files:
# Path: emcee3/autocorr.py
# def integrated_time(x, low=10, high=None, step=1, c=10, full_output=False,
# axis=0, fast=False, quiet=False):
# """Estimate the integrated autocorrelation time of a time series.
#
# This estimate uses the iterative procedure described on page 16 of `Sokal's
# notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ to determine a
# reasonable window size.
#
# Args:
# x: The time series. If multidimensional, set the time axis using the
# ``axis`` keyword argument and the function will be computed for
# every other axis.
# low (Optional[int]): The minimum window size to test. (default: ``10``)
# high (Optional[int]): The maximum window size to test. (default:
# ``x.shape[axis] / (2*c)``)
# step (Optional[int]): The step size for the window search. (default:
# ``1``)
# c (Optional[float]): The minimum number of autocorrelation times
# needed to trust the estimate. (default: ``10``)
# full_output (Optional[bool]): Return the final window size as well as
# the autocorrelation time. (default: ``False``)
# axis (Optional[int]): The time axis of ``x``. Assumed to be the first
# axis if not specified.
# fast (Optional[bool]): If ``True``, only use the first ``2^n`` (for
# the largest power) entries for efficiency. (default: False)
# quiet (Optional[bool]): If ``True``, silence the ``AutocorrError``
# that should occur if the chain is too short for a reliable
# estimate and return ``None`` instead. (default: False)
#
# Returns:
# float or array: An estimate of the integrated autocorrelation time of
# the time series ``x`` computed along the axis ``axis``.
# Optional[int]: The final window size that was used. Only returned if
# ``full_output`` is ``True``.
#
# Raises
# AutocorrError: If the autocorrelation time can't be reliably estimated
# from the chain. This normally means that the chain is too short.
#
# """
# size = 0.5 * x.shape[axis]
# if c * low >= size:
# raise AutocorrError("The chain is too short")
#
# # Compute the autocorrelation function.
# f = function(x, axis=axis, fast=fast)
#
# # Check the dimensions of the array.
# oned = len(f.shape) == 1
# m = [slice(None), ] * len(f.shape)
#
# # Loop over proposed window sizes until convergence is reached.
# if high is None:
# high = int(0.5 * size)
# tau = None
# for M in np.arange(low, high, step).astype(int):
# # Compute the autocorrelation time with the given window.
# if oned:
# # Special case 1D for simplicity.
# tau = 1 + 2 * np.sum(f[1:M])
# else:
# # N-dimensional case.
# m[axis] = slice(1, M)
# tau = 1 + 2 * np.sum(f[m], axis=axis)
#
# # Accept the window size if it satisfies the convergence criterion.
# if np.all(tau > 1.0) and M > c * tau.max():
# if full_output:
# return tau, M
# return tau
#
# # If the autocorrelation time is too long to be estimated reliably
# # from the chain, it should fail.
# if c * tau.max() >= size:
# break
#
# msg = ("The chain is too short to reliably estimate the autocorrelation "
# "time.")
# if tau is not None:
# msg += " Current estimate: \n{0}".format(tau)
# if quiet:
# logging.warn(msg)
# return None
# raise AutocorrError(msg)
. Output only the next line. | return integrated_time(np.mean(self.get_value("coords"), axis=1), |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_simple"]
def test_simple():
<|code_end|>
, generate the next line using the imports in this file:
from ..common import UniformWalker
and context (functions, classes, or occasionally code) from other files:
# Path: emcee3/tests/common.py
# class UniformWalker(SimpleModel):
#
# def __init__(self):
# super(UniformWalker, self).__init__(
# lambda p, *args: 0.0,
# lambda p, *args: 0.0 if np.all((-1 < p) * (p < 1)) else -np.inf,
# args=("nothing", "something")
# )
. Output only the next line. | UniformWalker() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_dtype", "test_serialization", "test_repr"]
def test_dtype(seed=1234):
np.random.seed(seed)
dtype = [
("coords", np.float64, (4, )),
("log_prior", np.float64),
("log_likelihood", np.float64),
("accepted", bool)
]
coords = np.random.randn(4)
<|code_end|>
. Use current file imports:
(import numpy as np
from ...state import State)
and context including class names, function names, or small code snippets from other files:
# Path: emcee3/state.py
# class State(object):
# """The current state of a walker.
#
# This object captures the state of a walker. It will store the coordinates,
# probabilities, and any other computed metadata. Metadata can be added by
# simply adding an attribute to a :class:`State` object. Any attributes with
# names that don't start with an underscore will be serialized by the
# :func:`to_array` method.
#
# Note:
# Unless the ``accepted`` attribute is ``True``, this object can't
# be expected to have the correct data type.
#
# Args:
# coords (array[ndim]): The coordinate vector of the walker's state.
# log_prior (Optional[float]): The log prior evaluated at ``coords``. If
# not provided, it is expected that the
# :func:`Model.compute_log_prior` method of a model will save the
# ``log_prior`` attribute on this object.
# log_likelihood (Optional[float]): The log likelihood evaluated at
# ``coords``. Like ``log_prior``, this should be evaluated by the
# model.
# accepted (Optional[bool]): Was this proposal accepted?
# **kwargs: Any other values to store as metadata.
#
# """
#
# def __init__(self,
# coords,
# log_prior=-np.inf,
# log_likelihood=-np.inf,
# accepted=False,
# **metadata):
# self.coords = coords
# self.log_prior = log_prior
# self.log_likelihood = log_likelihood
# self.accepted = accepted
# for k, v in metadata.items():
# setattr(self, k, v)
#
# def __repr__(self):
# names = self.dtype.names
# values = [
# self.log_prior, self.log_likelihood, self.accepted
# ] + [getattr(self, k) for k in names[4:]]
# r = ", ".join("{0}={1!r}".format(a, b)
# for a, b in zip(names[1:], values))
# return "State({0!r}, {1})".format(self.coords, r)
#
# def __eq__(self, other):
# if not self.dtype == other.dtype:
# return False
# return np.all(self.to_array() == other.to_array())
#
# @property
# def dtype(self):
# base_columns = ["coords", "log_prior", "log_likelihood", "accepted",
# "grad_log_prior", "grad_log_likelihood"]
# columns = []
# for k, v in sorted(self.__dict__.items()):
# if k.startswith("_") or k in base_columns:
# continue
# v = np.atleast_1d(v)
# if v.shape == (1,):
# columns.append((k, v.dtype))
# else:
# columns.append((k, v.dtype, v.shape))
#
# return np.dtype([
# ("coords", np.float64, (len(self.coords),)),
# ("log_prior", np.float64),
# ("log_likelihood", np.float64),
# ("accepted", bool),
# ] + columns)
#
# def to_array(self, out=None):
# """Serialize the state to a structured numpy array representation.
#
# This representation will include all attributes of this instance that
# don't have a name beginning with an underscore. There will also always
# be special fields: ``coords``, ``log_prior``, ``log_likelihood``, and
# ``accepted``.
#
# Args:
# out (Optional[array]): If provided, the state will be serialized
# in place.
#
# Returns:
# array: The serialized state.
#
# """
# if out is None:
# out = np.empty(1, self.dtype)
# for k in out.dtype.names:
# if k.startswith("_"):
# continue
# out[k] = getattr(self, k)
# out["coords"] = self.coords
# out["log_prior"] = self.log_prior
# out["log_likelihood"] = self.log_likelihood
# out["accepted"] = self.accepted
# return out
#
# @classmethod
# def from_array(cls, array):
# """Reconstruct a saved state from a structured numpy array.
#
# Args:
# array (array): An array produced by serializing a state using the
# :func:`to_array` method.
#
# Returns:
# State: The reconstructed state.
#
# """
# self = cls(array["coords"][0],
# log_prior=array["log_prior"][0],
# log_likelihood=array["log_likelihood"][0],
# accepted=array["accepted"][0])
# for k in array.dtype.names:
# if k.startswith("_"):
# continue
# setattr(self, k, array[k][0])
# return self
#
# @property
# def log_probability(self):
# """A helper attribute that provides access to the log probability.
#
# """
# return self.log_prior + self.log_likelihood
#
# @property
# def grad_log_probability(self):
# """A helper attribute that provides access to the log probability.
#
# """
# return self.grad_log_prior + self.grad_log_likelihood
. Output only the next line. | state = State(coords) |
Given the code snippet: <|code_start|>
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
callable, an instance of :class:`SimpleModel`, or another instance
that quacks like a :class:`Model`. If ``model`` is a callable, it
should take a coordinate vector as input and return the evaluated
log-probability up to an additive constant.
coords (Optional[array[nwalkers, ndim]]): The array of walker
coordinate vectors.
pool (Optional): A pool object that exposes a map function for
parallelization purposes.
random (Optional): A numpy-compatible random number generator. By
default, this will be the built-in ``numpy.random`` module but if
you want the ensemble to own its own state, you can supply an
instance of ``numpy.random.RandomState``.
"""
def __init__(self, model, coords, pool=None, random=None):
if is_model(model):
self.model = model
else:
if not callable(model):
raise ValueError("the 'model' must have a "
"'compute_log_probability' method or be "
"callable")
self.model = SimpleModel(model)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .pools import DefaultPool
from .model import is_model, SimpleModel
and context (functions, classes, or occasionally code) from other files:
# Path: emcee3/pools/default.py
# class DefaultPool(object):
#
# def map(self, fn, iterable):
# return imap(fn, iterable)
#
# Path: emcee3/model.py
# def is_model(model):
# return (
# hasattr(model, "compute_log_probability") and
# callable(model.compute_log_probability)
# )
#
# class SimpleModel(Model):
# """The simplest modeling interface.
#
# This model interface wraps functions describing the components of the
# model. At a minimum, a function evaluating the log likelihood (up to a
# constant) must be provided. In this case, the prior function is assumed to
# be uniform and improper. All functions must have the call structure::
#
# log_likelihood(coords, *args)
#
# where ``coords`` is a coordinate vector and ``*args`` can be provided
# using the ``args`` keyword argument. The ``log_likelihood`` and
# ``log_prior`` functions should return scalars and the ``grad_*`` functions
# should return ``numpy.array`` objects of the same length as the input
# ``coords``.
#
# Args:
# log_likelihood (callable): A function that evaluates the log
# likelihood of the model.
# log_prior (Optional[callable]): A function that evaluates the log
# prior of the model. If not provided, this will be assumed to be
# uniform and improper.
# grad_log_likelihood (Optional[callable]): A function that evaluates the
# gradient of the log likelihood of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# grad_log_prior (Optional[callable]): A function that evaluates the
# gradient of the log prior of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# args (Optional[tuple]): Any other arguments to be provided to the
# probability functions.
#
# """
#
# def __init__(self,
# log_likelihood,
# log_prior=None,
# grad_log_likelihood=None,
# grad_log_prior=None,
# args=tuple()):
# # If no prior function is provided, we'll assume it to be flat and
# # improper.
# if log_prior is None:
# log_prior = default_log_prior_function
# grad_log_prior = default_grad_log_prior_function
#
# self.log_prior_func = log_prior
# self.log_likelihood_func = log_likelihood
# self.args = args
#
# # By default, numerically compute gradients.
# if grad_log_prior is None:
# grad_log_prior = numerical_gradient_1(self.log_prior_func)
# self.grad_log_prior_func = grad_log_prior
# if grad_log_likelihood is None:
# grad_log_likelihood = numerical_gradient_1(
# self.log_likelihood_func)
# self.grad_log_likelihood_func = grad_log_likelihood
#
# def compute_log_prior(self, state, **kwargs):
# state.log_prior = self.log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_log_prior.__doc__ = Model.compute_log_prior.__doc__
#
# def compute_grad_log_prior(self, state, **kwargs):
# state.grad_log_prior = self.grad_log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_prior.__doc__ = Model.compute_grad_log_prior.__doc__
#
# def compute_log_likelihood(self, state, **kwargs):
# state.log_likelihood = self.log_likelihood_func(state.coords,
# *(self.args))
# return state
# compute_log_likelihood.__doc__ = Model.compute_log_likelihood.__doc__
#
# def compute_grad_log_likelihood(self, state, **kwargs):
# state.grad_log_likelihood = self.grad_log_likelihood_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_likelihood.__doc__ = \
# Model.compute_grad_log_likelihood.__doc__
#
# def check_grad(self, coords, **kwargs):
# """Check the gradients numerically.
#
# Args:
# coords (array): The coordinates.
#
# Returns:
# bool: If the numerical gradients and analytic gradients satisfy
# ``numpy.allclose``.
#
# """
# com_g = (
# self.grad_log_likelihood_func(coords, *(self.args)) +
# self.grad_log_prior_func(coords, *(self.args))
# )
# num_g = numerical_gradient_2(self.get_lnprob, coords, **kwargs)
# return np.allclose(com_g, num_g)
. Output only the next line. | self.pool = DefaultPool() if pool is None else pool |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["Ensemble"]
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
callable, an instance of :class:`SimpleModel`, or another instance
that quacks like a :class:`Model`. If ``model`` is a callable, it
should take a coordinate vector as input and return the evaluated
log-probability up to an additive constant.
coords (Optional[array[nwalkers, ndim]]): The array of walker
coordinate vectors.
pool (Optional): A pool object that exposes a map function for
parallelization purposes.
random (Optional): A numpy-compatible random number generator. By
default, this will be the built-in ``numpy.random`` module but if
you want the ensemble to own its own state, you can supply an
instance of ``numpy.random.RandomState``.
"""
def __init__(self, model, coords, pool=None, random=None):
<|code_end|>
using the current file's imports:
import numpy as np
from .pools import DefaultPool
from .model import is_model, SimpleModel
and any relevant context from other files:
# Path: emcee3/pools/default.py
# class DefaultPool(object):
#
# def map(self, fn, iterable):
# return imap(fn, iterable)
#
# Path: emcee3/model.py
# def is_model(model):
# return (
# hasattr(model, "compute_log_probability") and
# callable(model.compute_log_probability)
# )
#
# class SimpleModel(Model):
# """The simplest modeling interface.
#
# This model interface wraps functions describing the components of the
# model. At a minimum, a function evaluating the log likelihood (up to a
# constant) must be provided. In this case, the prior function is assumed to
# be uniform and improper. All functions must have the call structure::
#
# log_likelihood(coords, *args)
#
# where ``coords`` is a coordinate vector and ``*args`` can be provided
# using the ``args`` keyword argument. The ``log_likelihood`` and
# ``log_prior`` functions should return scalars and the ``grad_*`` functions
# should return ``numpy.array`` objects of the same length as the input
# ``coords``.
#
# Args:
# log_likelihood (callable): A function that evaluates the log
# likelihood of the model.
# log_prior (Optional[callable]): A function that evaluates the log
# prior of the model. If not provided, this will be assumed to be
# uniform and improper.
# grad_log_likelihood (Optional[callable]): A function that evaluates the
# gradient of the log likelihood of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# grad_log_prior (Optional[callable]): A function that evaluates the
# gradient of the log prior of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# args (Optional[tuple]): Any other arguments to be provided to the
# probability functions.
#
# """
#
# def __init__(self,
# log_likelihood,
# log_prior=None,
# grad_log_likelihood=None,
# grad_log_prior=None,
# args=tuple()):
# # If no prior function is provided, we'll assume it to be flat and
# # improper.
# if log_prior is None:
# log_prior = default_log_prior_function
# grad_log_prior = default_grad_log_prior_function
#
# self.log_prior_func = log_prior
# self.log_likelihood_func = log_likelihood
# self.args = args
#
# # By default, numerically compute gradients.
# if grad_log_prior is None:
# grad_log_prior = numerical_gradient_1(self.log_prior_func)
# self.grad_log_prior_func = grad_log_prior
# if grad_log_likelihood is None:
# grad_log_likelihood = numerical_gradient_1(
# self.log_likelihood_func)
# self.grad_log_likelihood_func = grad_log_likelihood
#
# def compute_log_prior(self, state, **kwargs):
# state.log_prior = self.log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_log_prior.__doc__ = Model.compute_log_prior.__doc__
#
# def compute_grad_log_prior(self, state, **kwargs):
# state.grad_log_prior = self.grad_log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_prior.__doc__ = Model.compute_grad_log_prior.__doc__
#
# def compute_log_likelihood(self, state, **kwargs):
# state.log_likelihood = self.log_likelihood_func(state.coords,
# *(self.args))
# return state
# compute_log_likelihood.__doc__ = Model.compute_log_likelihood.__doc__
#
# def compute_grad_log_likelihood(self, state, **kwargs):
# state.grad_log_likelihood = self.grad_log_likelihood_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_likelihood.__doc__ = \
# Model.compute_grad_log_likelihood.__doc__
#
# def check_grad(self, coords, **kwargs):
# """Check the gradients numerically.
#
# Args:
# coords (array): The coordinates.
#
# Returns:
# bool: If the numerical gradients and analytic gradients satisfy
# ``numpy.allclose``.
#
# """
# com_g = (
# self.grad_log_likelihood_func(coords, *(self.args)) +
# self.grad_log_prior_func(coords, *(self.args))
# )
# num_g = numerical_gradient_2(self.get_lnprob, coords, **kwargs)
# return np.allclose(com_g, num_g)
. Output only the next line. | if is_model(model): |
Predict the next line after this snippet: <|code_start|>__all__ = ["Ensemble"]
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
callable, an instance of :class:`SimpleModel`, or another instance
that quacks like a :class:`Model`. If ``model`` is a callable, it
should take a coordinate vector as input and return the evaluated
log-probability up to an additive constant.
coords (Optional[array[nwalkers, ndim]]): The array of walker
coordinate vectors.
pool (Optional): A pool object that exposes a map function for
parallelization purposes.
random (Optional): A numpy-compatible random number generator. By
default, this will be the built-in ``numpy.random`` module but if
you want the ensemble to own its own state, you can supply an
instance of ``numpy.random.RandomState``.
"""
def __init__(self, model, coords, pool=None, random=None):
if is_model(model):
self.model = model
else:
if not callable(model):
raise ValueError("the 'model' must have a "
"'compute_log_probability' method or be "
"callable")
<|code_end|>
using the current file's imports:
import numpy as np
from .pools import DefaultPool
from .model import is_model, SimpleModel
and any relevant context from other files:
# Path: emcee3/pools/default.py
# class DefaultPool(object):
#
# def map(self, fn, iterable):
# return imap(fn, iterable)
#
# Path: emcee3/model.py
# def is_model(model):
# return (
# hasattr(model, "compute_log_probability") and
# callable(model.compute_log_probability)
# )
#
# class SimpleModel(Model):
# """The simplest modeling interface.
#
# This model interface wraps functions describing the components of the
# model. At a minimum, a function evaluating the log likelihood (up to a
# constant) must be provided. In this case, the prior function is assumed to
# be uniform and improper. All functions must have the call structure::
#
# log_likelihood(coords, *args)
#
# where ``coords`` is a coordinate vector and ``*args`` can be provided
# using the ``args`` keyword argument. The ``log_likelihood`` and
# ``log_prior`` functions should return scalars and the ``grad_*`` functions
# should return ``numpy.array`` objects of the same length as the input
# ``coords``.
#
# Args:
# log_likelihood (callable): A function that evaluates the log
# likelihood of the model.
# log_prior (Optional[callable]): A function that evaluates the log
# prior of the model. If not provided, this will be assumed to be
# uniform and improper.
# grad_log_likelihood (Optional[callable]): A function that evaluates the
# gradient of the log likelihood of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# grad_log_prior (Optional[callable]): A function that evaluates the
# gradient of the log prior of the model. If needed but not
# provided, this will be evaluated numerically using a first order
# method.
# args (Optional[tuple]): Any other arguments to be provided to the
# probability functions.
#
# """
#
# def __init__(self,
# log_likelihood,
# log_prior=None,
# grad_log_likelihood=None,
# grad_log_prior=None,
# args=tuple()):
# # If no prior function is provided, we'll assume it to be flat and
# # improper.
# if log_prior is None:
# log_prior = default_log_prior_function
# grad_log_prior = default_grad_log_prior_function
#
# self.log_prior_func = log_prior
# self.log_likelihood_func = log_likelihood
# self.args = args
#
# # By default, numerically compute gradients.
# if grad_log_prior is None:
# grad_log_prior = numerical_gradient_1(self.log_prior_func)
# self.grad_log_prior_func = grad_log_prior
# if grad_log_likelihood is None:
# grad_log_likelihood = numerical_gradient_1(
# self.log_likelihood_func)
# self.grad_log_likelihood_func = grad_log_likelihood
#
# def compute_log_prior(self, state, **kwargs):
# state.log_prior = self.log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_log_prior.__doc__ = Model.compute_log_prior.__doc__
#
# def compute_grad_log_prior(self, state, **kwargs):
# state.grad_log_prior = self.grad_log_prior_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_prior.__doc__ = Model.compute_grad_log_prior.__doc__
#
# def compute_log_likelihood(self, state, **kwargs):
# state.log_likelihood = self.log_likelihood_func(state.coords,
# *(self.args))
# return state
# compute_log_likelihood.__doc__ = Model.compute_log_likelihood.__doc__
#
# def compute_grad_log_likelihood(self, state, **kwargs):
# state.grad_log_likelihood = self.grad_log_likelihood_func(
# state.coords, *(self.args)
# )
# return state
# compute_grad_log_likelihood.__doc__ = \
# Model.compute_grad_log_likelihood.__doc__
#
# def check_grad(self, coords, **kwargs):
# """Check the gradients numerically.
#
# Args:
# coords (array): The coordinates.
#
# Returns:
# bool: If the numerical gradients and analytic gradients satisfy
# ``numpy.allclose``.
#
# """
# com_g = (
# self.grad_log_likelihood_func(coords, *(self.args)) +
# self.grad_log_prior_func(coords, *(self.args))
# )
# num_g = numerical_gradient_2(self.get_lnprob, coords, **kwargs)
# return np.allclose(com_g, num_g)
. Output only the next line. | self.model = SimpleModel(model) |
Given the following code snippet before the placeholder: <|code_start|>
def __init__(self, random, model, cov, epsilon, nsteps=None):
self.random = random
self.model = model
self.nsteps = nsteps
self.epsilon = epsilon
if len(np.atleast_1d(cov).shape) == 2:
self.cov = _hmc_matrix(np.atleast_2d(cov))
else:
self.cov = _hmc_vector(np.asarray(cov))
def __call__(self, args):
current_state, current_p = args
# Sample the initial momentum.
current_q = current_state.coords
q = current_q
p = current_p
# First take a half step in momentum.
current_state = self.model.compute_grad_log_probability(current_state)
p = p + 0.5 * self.epsilon * current_state.grad_log_probability
# Alternate full steps in position and momentum.
for i in range(self.nsteps):
# First, a full step in position.
q = q + self.epsilon * self.cov.apply(p)
# Then a full step in momentum.
if i < self.nsteps - 1:
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from ..state import State
and context including class names, function names, and sometimes code from other files:
# Path: emcee3/state.py
# class State(object):
# """The current state of a walker.
#
# This object captures the state of a walker. It will store the coordinates,
# probabilities, and any other computed metadata. Metadata can be added by
# simply adding an attribute to a :class:`State` object. Any attributes with
# names that don't start with an underscore will be serialized by the
# :func:`to_array` method.
#
# Note:
# Unless the ``accepted`` attribute is ``True``, this object can't
# be expected to have the correct data type.
#
# Args:
# coords (array[ndim]): The coordinate vector of the walker's state.
# log_prior (Optional[float]): The log prior evaluated at ``coords``. If
# not provided, it is expected that the
# :func:`Model.compute_log_prior` method of a model will save the
# ``log_prior`` attribute on this object.
# log_likelihood (Optional[float]): The log likelihood evaluated at
# ``coords``. Like ``log_prior``, this should be evaluated by the
# model.
# accepted (Optional[bool]): Was this proposal accepted?
# **kwargs: Any other values to store as metadata.
#
# """
#
# def __init__(self,
# coords,
# log_prior=-np.inf,
# log_likelihood=-np.inf,
# accepted=False,
# **metadata):
# self.coords = coords
# self.log_prior = log_prior
# self.log_likelihood = log_likelihood
# self.accepted = accepted
# for k, v in metadata.items():
# setattr(self, k, v)
#
# def __repr__(self):
# names = self.dtype.names
# values = [
# self.log_prior, self.log_likelihood, self.accepted
# ] + [getattr(self, k) for k in names[4:]]
# r = ", ".join("{0}={1!r}".format(a, b)
# for a, b in zip(names[1:], values))
# return "State({0!r}, {1})".format(self.coords, r)
#
# def __eq__(self, other):
# if not self.dtype == other.dtype:
# return False
# return np.all(self.to_array() == other.to_array())
#
# @property
# def dtype(self):
# base_columns = ["coords", "log_prior", "log_likelihood", "accepted",
# "grad_log_prior", "grad_log_likelihood"]
# columns = []
# for k, v in sorted(self.__dict__.items()):
# if k.startswith("_") or k in base_columns:
# continue
# v = np.atleast_1d(v)
# if v.shape == (1,):
# columns.append((k, v.dtype))
# else:
# columns.append((k, v.dtype, v.shape))
#
# return np.dtype([
# ("coords", np.float64, (len(self.coords),)),
# ("log_prior", np.float64),
# ("log_likelihood", np.float64),
# ("accepted", bool),
# ] + columns)
#
# def to_array(self, out=None):
# """Serialize the state to a structured numpy array representation.
#
# This representation will include all attributes of this instance that
# don't have a name beginning with an underscore. There will also always
# be special fields: ``coords``, ``log_prior``, ``log_likelihood``, and
# ``accepted``.
#
# Args:
# out (Optional[array]): If provided, the state will be serialized
# in place.
#
# Returns:
# array: The serialized state.
#
# """
# if out is None:
# out = np.empty(1, self.dtype)
# for k in out.dtype.names:
# if k.startswith("_"):
# continue
# out[k] = getattr(self, k)
# out["coords"] = self.coords
# out["log_prior"] = self.log_prior
# out["log_likelihood"] = self.log_likelihood
# out["accepted"] = self.accepted
# return out
#
# @classmethod
# def from_array(cls, array):
# """Reconstruct a saved state from a structured numpy array.
#
# Args:
# array (array): An array produced by serializing a state using the
# :func:`to_array` method.
#
# Returns:
# State: The reconstructed state.
#
# """
# self = cls(array["coords"][0],
# log_prior=array["log_prior"][0],
# log_likelihood=array["log_likelihood"][0],
# accepted=array["accepted"][0])
# for k in array.dtype.names:
# if k.startswith("_"):
# continue
# setattr(self, k, array[k][0])
# return self
#
# @property
# def log_probability(self):
# """A helper attribute that provides access to the log probability.
#
# """
# return self.log_prior + self.log_likelihood
#
# @property
# def grad_log_probability(self):
# """A helper attribute that provides access to the log probability.
#
# """
# return self.grad_log_prior + self.grad_log_likelihood
. Output only the next line. | state = self.model.compute_grad_log_probability(State(q)) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_nd", "test_too_short"]
def get_chain(seed=1234, ndim=3, N=100000):
np.random.seed(seed)
a = 0.9
x = np.empty((N, ndim))
x[0] = np.zeros(ndim)
for i in range(1, N):
x[i] = x[i-1] * a + np.random.rand(ndim)
return x
def test_1d(seed=1234, ndim=1, N=150000, c=6):
x = get_chain(seed=seed, ndim=ndim, N=N)
<|code_end|>
with the help of current file imports:
import pytest
import numpy as np
from ...autocorr import integrated_time, AutocorrError
and context from other files:
# Path: emcee3/autocorr.py
# def integrated_time(x, low=10, high=None, step=1, c=10, full_output=False,
# axis=0, fast=False, quiet=False):
# """Estimate the integrated autocorrelation time of a time series.
#
# This estimate uses the iterative procedure described on page 16 of `Sokal's
# notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ to determine a
# reasonable window size.
#
# Args:
# x: The time series. If multidimensional, set the time axis using the
# ``axis`` keyword argument and the function will be computed for
# every other axis.
# low (Optional[int]): The minimum window size to test. (default: ``10``)
# high (Optional[int]): The maximum window size to test. (default:
# ``x.shape[axis] / (2*c)``)
# step (Optional[int]): The step size for the window search. (default:
# ``1``)
# c (Optional[float]): The minimum number of autocorrelation times
# needed to trust the estimate. (default: ``10``)
# full_output (Optional[bool]): Return the final window size as well as
# the autocorrelation time. (default: ``False``)
# axis (Optional[int]): The time axis of ``x``. Assumed to be the first
# axis if not specified.
# fast (Optional[bool]): If ``True``, only use the first ``2^n`` (for
# the largest power) entries for efficiency. (default: False)
# quiet (Optional[bool]): If ``True``, silence the ``AutocorrError``
# that should occur if the chain is too short for a reliable
# estimate and return ``None`` instead. (default: False)
#
# Returns:
# float or array: An estimate of the integrated autocorrelation time of
# the time series ``x`` computed along the axis ``axis``.
# Optional[int]: The final window size that was used. Only returned if
# ``full_output`` is ``True``.
#
# Raises
# AutocorrError: If the autocorrelation time can't be reliably estimated
# from the chain. This normally means that the chain is too short.
#
# """
# size = 0.5 * x.shape[axis]
# if c * low >= size:
# raise AutocorrError("The chain is too short")
#
# # Compute the autocorrelation function.
# f = function(x, axis=axis, fast=fast)
#
# # Check the dimensions of the array.
# oned = len(f.shape) == 1
# m = [slice(None), ] * len(f.shape)
#
# # Loop over proposed window sizes until convergence is reached.
# if high is None:
# high = int(0.5 * size)
# tau = None
# for M in np.arange(low, high, step).astype(int):
# # Compute the autocorrelation time with the given window.
# if oned:
# # Special case 1D for simplicity.
# tau = 1 + 2 * np.sum(f[1:M])
# else:
# # N-dimensional case.
# m[axis] = slice(1, M)
# tau = 1 + 2 * np.sum(f[m], axis=axis)
#
# # Accept the window size if it satisfies the convergence criterion.
# if np.all(tau > 1.0) and M > c * tau.max():
# if full_output:
# return tau, M
# return tau
#
# # If the autocorrelation time is too long to be estimated reliably
# # from the chain, it should fail.
# if c * tau.max() >= size:
# break
#
# msg = ("The chain is too short to reliably estimate the autocorrelation "
# "time.")
# if tau is not None:
# msg += " Current estimate: \n{0}".format(tau)
# if quiet:
# logging.warn(msg)
# return None
# raise AutocorrError(msg)
#
# class AutocorrError(Exception):
# """Raised if the chain is too short to estimate an autocorrelation time.
#
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | tau, M = integrated_time(x, c=c, full_output=True) |
Here is a snippet: <|code_start|>
__all__ = ["test_nd", "test_too_short"]
def get_chain(seed=1234, ndim=3, N=100000):
np.random.seed(seed)
a = 0.9
x = np.empty((N, ndim))
x[0] = np.zeros(ndim)
for i in range(1, N):
x[i] = x[i-1] * a + np.random.rand(ndim)
return x
def test_1d(seed=1234, ndim=1, N=150000, c=6):
x = get_chain(seed=seed, ndim=ndim, N=N)
tau, M = integrated_time(x, c=c, full_output=True)
assert np.all(M > c * tau)
assert np.all(np.abs(tau - 19.0) / 19. < 0.2)
def test_nd(seed=1234, ndim=3, N=150000):
x = get_chain(seed=seed, ndim=ndim, N=N)
tau = integrated_time(x)
assert np.all(np.abs(tau - 19.0) / 19. < 0.2)
def test_too_short(seed=1234, ndim=3, N=500):
x = get_chain(seed=seed, ndim=ndim, N=N)
<|code_end|>
. Write the next line using the current file imports:
import pytest
import numpy as np
from ...autocorr import integrated_time, AutocorrError
and context from other files:
# Path: emcee3/autocorr.py
# def integrated_time(x, low=10, high=None, step=1, c=10, full_output=False,
# axis=0, fast=False, quiet=False):
# """Estimate the integrated autocorrelation time of a time series.
#
# This estimate uses the iterative procedure described on page 16 of `Sokal's
# notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ to determine a
# reasonable window size.
#
# Args:
# x: The time series. If multidimensional, set the time axis using the
# ``axis`` keyword argument and the function will be computed for
# every other axis.
# low (Optional[int]): The minimum window size to test. (default: ``10``)
# high (Optional[int]): The maximum window size to test. (default:
# ``x.shape[axis] / (2*c)``)
# step (Optional[int]): The step size for the window search. (default:
# ``1``)
# c (Optional[float]): The minimum number of autocorrelation times
# needed to trust the estimate. (default: ``10``)
# full_output (Optional[bool]): Return the final window size as well as
# the autocorrelation time. (default: ``False``)
# axis (Optional[int]): The time axis of ``x``. Assumed to be the first
# axis if not specified.
# fast (Optional[bool]): If ``True``, only use the first ``2^n`` (for
# the largest power) entries for efficiency. (default: False)
# quiet (Optional[bool]): If ``True``, silence the ``AutocorrError``
# that should occur if the chain is too short for a reliable
# estimate and return ``None`` instead. (default: False)
#
# Returns:
# float or array: An estimate of the integrated autocorrelation time of
# the time series ``x`` computed along the axis ``axis``.
# Optional[int]: The final window size that was used. Only returned if
# ``full_output`` is ``True``.
#
# Raises
# AutocorrError: If the autocorrelation time can't be reliably estimated
# from the chain. This normally means that the chain is too short.
#
# """
# size = 0.5 * x.shape[axis]
# if c * low >= size:
# raise AutocorrError("The chain is too short")
#
# # Compute the autocorrelation function.
# f = function(x, axis=axis, fast=fast)
#
# # Check the dimensions of the array.
# oned = len(f.shape) == 1
# m = [slice(None), ] * len(f.shape)
#
# # Loop over proposed window sizes until convergence is reached.
# if high is None:
# high = int(0.5 * size)
# tau = None
# for M in np.arange(low, high, step).astype(int):
# # Compute the autocorrelation time with the given window.
# if oned:
# # Special case 1D for simplicity.
# tau = 1 + 2 * np.sum(f[1:M])
# else:
# # N-dimensional case.
# m[axis] = slice(1, M)
# tau = 1 + 2 * np.sum(f[m], axis=axis)
#
# # Accept the window size if it satisfies the convergence criterion.
# if np.all(tau > 1.0) and M > c * tau.max():
# if full_output:
# return tau, M
# return tau
#
# # If the autocorrelation time is too long to be estimated reliably
# # from the chain, it should fail.
# if c * tau.max() >= size:
# break
#
# msg = ("The chain is too short to reliably estimate the autocorrelation "
# "time.")
# if tau is not None:
# msg += " Current estimate: \n{0}".format(tau)
# if quiet:
# logging.warn(msg)
# return None
# raise AutocorrError(msg)
#
# class AutocorrError(Exception):
# """Raised if the chain is too short to estimate an autocorrelation time.
#
# """
# pass
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(AutocorrError): |
Predict the next line for this snippet: <|code_start|>sys.path.insert(0, '/Users/nick/dev/conversation')
parser = optparse.OptionParser()
parser.add_option('-s', '--start',
action="store", dest="start_date",
help="start date", default="today")
options, args = parser.parse_args()
if options.start_date == "today":
options.start_date = datetime.today()
start_date_str = options.start_date
start_date = datetime.strptime(start_date_str, "%m-%d-%Y")
end_date = start_date + timedelta(days=7)
<|code_end|>
with the help of current file imports:
import sys
import settings
import logging
import optparse
from datetime import datetime, timedelta
from lib import statsdb, postsdb
and context from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
, which may contain function names, class names, or code. Output only the next line. | count = postsdb.get_post_count_for_range(start_date, end_date) |
Based on the snippet: <|code_start|>try:
sys.path.insert(0, '/Users/nick/dev/theconversation')
except:
print "could not import -- must be running on heroku"
cio = CustomerIO(settings.get('customer_io_site_id'), settings.get('customer_io_api_key'))
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import settings
from customerio import CustomerIO
from lib import userdb
and context (classes, functions, sometimes code) from other files:
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | users = userdb.get_all() |
Predict the next line after this snippet: <|code_start|> userdb.save_user(user)
self.redirect("/user/%s/settings?msg=updated" % user['user']['screen_name'])
###########################
### LOG USER OUT OF ACCOUNT
### /auth/logout
###########################
class LogOut(app.basic.BaseHandler):
def get(self):
self.clear_all_cookies()
self.redirect(self.get_argument('next', '/'))
##########################
### USER PROFILE
### /user/(.+)
##########################
class Profile(app.basic.BaseHandler):
def get(self, screen_name, section="shares"):
user = userdb.get_user_by_screen_name(screen_name)
if not user:
raise tornado.web.HTTPError(404)
view = "profile"
#section = self.get_argument('section', 'shares')
tag = self.get_argument('tag', '')
per_page = int(self.get_argument('per_page', 10))
page = int(self.get_argument('page',1))
if section == 'mentions':
# get the @ mention list for this user
<|code_end|>
using the current file's imports:
import tornado.web
import app.basic
from lib import disqus
from lib import mentionsdb
from lib import postsdb
from lib import tagsdb
from lib import userdb
and any relevant context from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | posts = mentionsdb.get_mentions_by_user(screen_name.lower(), per_page, page) |
Continue the code snippet: <|code_start|> email = self.get_argument('email', '')
subscribe_to = self.get_argument('subscribe_to', '')
error = ''
status = ''
slug = ''
if close_popup != '':
status = 'close_popup'
# get the current user's email value
user = userdb.get_user_by_screen_name(self.current_user)
if user:
# Clear the existing email address
if email == '':
if subscribe_to == '':
user['email_address'] = ''
self.set_secure_cookie('email_address', '')
userdb.save_user(user)
error = 'Your email address has been cleared.'
else:
# make sure someone else isn't already using this email
existing = userdb.get_user_by_email(email)
if existing and existing['user']['id_str'] != user['user']['id_str']:
error = 'This email address is already in use.'
else:
# OK to save as user's email
user['email_address'] = email
userdb.save_user(user)
self.set_secure_cookie('email_address', email)
if subscribe_to != '':
<|code_end|>
. Use current file imports:
import tornado.web
import app.basic
from lib import disqus
from lib import mentionsdb
from lib import postsdb
from lib import tagsdb
from lib import userdb
and context (classes, functions, or code) from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | post = postsdb.get_post_by_slug(subscribe_to) |
Predict the next line for this snippet: <|code_start|> self.clear_all_cookies()
self.redirect(self.get_argument('next', '/'))
##########################
### USER PROFILE
### /user/(.+)
##########################
class Profile(app.basic.BaseHandler):
def get(self, screen_name, section="shares"):
user = userdb.get_user_by_screen_name(screen_name)
if not user:
raise tornado.web.HTTPError(404)
view = "profile"
#section = self.get_argument('section', 'shares')
tag = self.get_argument('tag', '')
per_page = int(self.get_argument('per_page', 10))
page = int(self.get_argument('page',1))
if section == 'mentions':
# get the @ mention list for this user
posts = mentionsdb.get_mentions_by_user(screen_name.lower(), per_page, page)
elif section =='bumps':
posts = postsdb.get_posts_by_bumps(screen_name, per_page, page)
else:
if tag == '':
posts = postsdb.get_posts_by_screen_name(screen_name, per_page, page)
else:
posts = postsdb.get_posts_by_screen_name_and_tag(screen_name, tag, per_page, page)
# also get the list of tags this user has put in
<|code_end|>
with the help of current file imports:
import tornado.web
import app.basic
from lib import disqus
from lib import mentionsdb
from lib import postsdb
from lib import tagsdb
from lib import userdb
and context from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
, which may contain function names, class names, or code. Output only the next line. | tags = tagsdb.get_user_tags(screen_name) |
Next line prediction: <|code_start|>
###########################
### EMAIL SETTINGS
### /auth/email/?
###########################
class EmailSettings(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self):
next_page = self.get_argument('next', '')
subscribe_to = self.get_argument('subscribe_to', '')
error = ''
email = ''
status = 'enter_email'
# get the current user's email value
<|code_end|>
. Use current file imports:
(import tornado.web
import app.basic
from lib import disqus
from lib import mentionsdb
from lib import postsdb
from lib import tagsdb
from lib import userdb)
and context including class names, function names, or small code snippets from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | user = userdb.get_user_by_screen_name(self.current_user) |
Using the snippet: <|code_start|> auth_url = auth.get_authorization_url(True)
self.set_secure_cookie("request_token_key", auth.request_token.key)
self.set_secure_cookie("request_token_secret", auth.request_token.secret)
redirect = self.get_argument('next', '/')
self.set_secure_cookie("twitter_auth_redirect", redirect)
self.redirect(auth_url)
##############################
### RESPONSE FROM TWITTER AUTH
### /twitter
##############################
class Twitter(app.basic.BaseHandler):
def get(self):
oauth_verifier = self.get_argument('oauth_verifier', '')
consumer_key = settings.get('twitter_consumer_key')
consumer_secret = settings.get('twitter_consumer_secret')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret, secure=True)
auth.set_request_token(self.get_secure_cookie('request_token_key'), self.get_secure_cookie('request_token_secret'))
auth.get_access_token(oauth_verifier)
screen_name = auth.get_username()
bounce_to = self.get_secure_cookie('twitter_auth_redirect') or '/'
access_token = {
'secret': auth.access_token.secret,
'user_id': '',
'screen_name': '',
'key': auth.access_token.key
}
# check if we have this user already or not in the system
<|code_end|>
, determine the next line of code. You have imports:
import tweepy
import app.basic
import settings
from lib import userdb
and context (class names, function names, or code) available:
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | user = userdb.get_user_by_screen_name(screen_name) |
Here is a snippet: <|code_start|>
class BaseHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
#user = self.get_current_user()
#css_file = "%s/css/threatvector.css" % settings.tornado_config['static_path']
#css_modified_time = os.path.getmtime(css_file)
self.vars = {
#'user': user,
#'css_modified_time': css_modified_time
}
def head(self, *args, **kwargs):
return
def render(self, template, **kwargs):
# add any variables we want available to all templates
kwargs['user_obj'] = None
<|code_end|>
. Write the next line using the current file imports:
import tornado.web
import requests
import settings
import simplejson as json
import os
import httplib
import logging
from datetime import datetime, timedelta
from lib import userdb
and context from other files:
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
, which may include functions, classes, or code. Output only the next line. | kwargs['user_obj'] = userdb.get_user_by_screen_name(self.current_user) |
Predict the next line for this snippet: <|code_start|>
#########################
### Alerting to share owner (and other subscribers) on new Disqus comments
### /api/incr_comment_count
#########################
class DisqusCallback(app.basic.BaseHandler):
def get(self):
comment = self.get_argument('comment', '')
post_slug = self.get_argument('post', '')
<|code_end|>
with the help of current file imports:
import app.basic
import logging
import settings
import datetime
from lib import disqus
from lib import postsdb
from lib import userdb
and context from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
, which may contain function names, class names, or code. Output only the next line. | post = postsdb.get_post_by_slug(post_slug) |
Given the code snippet: <|code_start|>
#########################
### Alerting to share owner (and other subscribers) on new Disqus comments
### /api/incr_comment_count
#########################
class DisqusCallback(app.basic.BaseHandler):
def get(self):
comment = self.get_argument('comment', '')
post_slug = self.get_argument('post', '')
post = postsdb.get_post_by_slug(post_slug)
if post:
# increment the comment count for this post
post['comment_count'] += 1
postsdb.save_post(post)
# determine if anyone is subscribed to this post (for email alerts)
if len(post['subscribed']) > 0:
# attempt to get the current user's email (we don't need to alert them)
author_email = ''
if self.current_user:
<|code_end|>
, generate the next line using the imports in this file:
import app.basic
import logging
import settings
import datetime
from lib import disqus
from lib import postsdb
from lib import userdb
and context (functions, classes, or occasionally code) from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | author = userdb.get_user_by_screen_name(self.current_user) |
Here is a snippet: <|code_start|>
######################
### WEEKLY STATS
### /stats/shares/weekly
######################
class WeeklyShareStats(app.basic.BaseHandler):
def get(self):
# get the stats based on the past 7 days
today = datetime.today()
week_ago = today + timedelta(days=-7)
single_post_count = 0
<|code_end|>
. Write the next line using the current file imports:
import app.basic
from datetime import datetime, timedelta
from lib import postsdb
and context from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
, which may include functions, classes, or code. Output only the next line. | unique_posters = postsdb.get_unique_posters(week_ago, today) |
Based on the snippet: <|code_start|>
# track emails sent to users
"""
{
_id: ...,
timestamp: Date(),
subject: "",
body: "",
recipients: []
}
"""
db.user_info.ensure_index('wants_daily_email')
#
# Construct a daily email
#
def construct_daily_email(slugs):
from_email = "web@usv.com"
subject = "Top USV.com posts for %s" % datetime.today().strftime("%a %b %d, %Y")
body_html = "<p>Here are the posts with the mosts for today:</p><hr />"
email_name = "Daily %s" % datetime.today().strftime("%a %b %d, %Y")
posts = []
for slug in slugs:
<|code_end|>
, predict the immediate next line with the help of imports:
from mongo import db
from datetime import datetime
from lib import postsdb, userdb
import pymongo
import json
import logging
import settings
import urllib2
import requests
and context (classes, functions, sometimes code) from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | post = postsdb.get_post_by_slug(slug) |
Given the code snippet: <|code_start|> body_html += "<p>discussion: <a href='http://%s/posts/%s'>http://%s/posts/%s</a></p>" % (settings.get('base_url'), post['slug'], settings.get('base_url'), post['slug'])
body_html += "<hr />"
body_html += "Want to unsubscribe? Visit http://%s/user/settings" % settings.get('base_url')
email = {
'from': from_email,
'subject': subject,
'body_html': body_html
}
# create the email
# POST https://api.sendgrid.com/api/newsletter/add.json
# @identity (created in advance == the sender's identity), @name (of email), @subject, @text, @html
api_link = 'https://api.sendgrid.com/api/newsletter/add.json'
params = {
'identity': settings.get('sendgrid_sender_identity'),
'name': email_name,
'subject': email['subject'],
'text': '', #to do get text version,
'html': email['body_html']
}
result = do_api_request(api_link, method="POST", params=params)
return result
#
# Setup Email List
#
def setup_email_list():
email_sent = False
<|code_end|>
, generate the next line using the imports in this file:
from mongo import db
from datetime import datetime
from lib import postsdb, userdb
import pymongo
import json
import logging
import settings
import urllib2
import requests
and context (functions, classes, or occasionally code) from other files:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
. Output only the next line. | recipients = userdb.get_newsletter_recipients() |
Here is a snippet: <|code_start|> def get(self):
if not self.current_user_can('delete_users'):
self.redirect('/')
else:
msg = self.get_argument('msg', '')
self.render('admin/delete_user.html', msg=msg)
@tornado.web.authenticated
def post(self):
if not self.current_user_can('delete_users'):
self.redirect('/')
else:
msg = self.get_argument('msg', '')
post_slug = self.get_argument('post_slug', '')
post = postsdb.get_post_by_slug(post_slug)
if post:
# get the author of this post
screen_name = post['user']['screen_name']
postsdb.delete_all_posts_by_user(screen_name)
self.ender('admin/delete_user.html', msg=msg)
###########################
### Create a new hackpad
### /generate_hackpad/?
###########################
class GenerateNewHackpad(app.basic.BaseHandler):
def get(self):
if self.current_user not in settings.get('staff'):
self.redirect('/')
else:
<|code_end|>
. Write the next line using the current file imports:
import app.basic
import tornado.web
import settings
import logging
import json
import requests
from datetime import datetime, date
from lib import companiesdb
from lib import hackpad
from lib import postsdb
from lib import userdb
from lib import disqus
from lib import emailsdb
from disqusapi import DisqusAPI
from disqusapi import DisqusAPI
and context from other files:
# Path: lib/hackpad.py
# def list_all():
# def create_hackpad():
# def do_api_request(path, method, post_data={}, body=''):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/emailsdb.py
# def construct_daily_email(slugs):
# def setup_email_list():
# def add_list_to_email():
# def send_email():
# def log_daily_email(email, recipient_usernames):
# def get_daily_email_log():
# def do_api_request(api_link, method='GET', params={}):
, which may include functions, classes, or code. Output only the next line. | hackpads = hackpad.create_hackpad() |
Given snippet: <|code_start|>
############################
# ADMIN NEWSLETTER
# /admin/newsletter
############################
class DailyEmail(app.basic.BaseHandler):
def get(self):
posts = postsdb.get_hot_posts()
has_previewed = self.get_argument("preview", False)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import app.basic
import tornado.web
import settings
import logging
import json
import requests
from datetime import datetime, date
from lib import companiesdb
from lib import hackpad
from lib import postsdb
from lib import userdb
from lib import disqus
from lib import emailsdb
from disqusapi import DisqusAPI
from disqusapi import DisqusAPI
and context:
# Path: lib/hackpad.py
# def list_all():
# def create_hackpad():
# def do_api_request(path, method, post_data={}, body=''):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/emailsdb.py
# def construct_daily_email(slugs):
# def setup_email_list():
# def add_list_to_email():
# def send_email():
# def log_daily_email(email, recipient_usernames):
# def get_daily_email_log():
# def do_api_request(api_link, method='GET', params={}):
which might include code, classes, or functions. Output only the next line. | recipients = userdb.get_newsletter_recipients() |
Given the code snippet: <|code_start|>
############################
# ADMIN NEWSLETTER
# /admin/newsletter
############################
class DailyEmail(app.basic.BaseHandler):
def get(self):
posts = postsdb.get_hot_posts()
has_previewed = self.get_argument("preview", False)
recipients = userdb.get_newsletter_recipients()
#on this page, you'll choose from hot posts and POST the selections to the email form`
self.render('admin/daily_email.html')
def post(self):
if not self.current_user_can('send_daily_email'):
raise tornado.web.HTTPError(401)
action = self.get_argument('action', None)
if not action:
return self.write("Select an action")
if action == "setup_email":
posts = postsdb.get_hot_posts_by_day(datetime.today())
slugs = []
for i, post in enumerate(posts):
if i < 5:
slugs.append(post['slug'])
<|code_end|>
, generate the next line using the imports in this file:
import app.basic
import tornado.web
import settings
import logging
import json
import requests
from datetime import datetime, date
from lib import companiesdb
from lib import hackpad
from lib import postsdb
from lib import userdb
from lib import disqus
from lib import emailsdb
from disqusapi import DisqusAPI
from disqusapi import DisqusAPI
and context (functions, classes, or occasionally code) from other files:
# Path: lib/hackpad.py
# def list_all():
# def create_hackpad():
# def do_api_request(path, method, post_data={}, body=''):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/emailsdb.py
# def construct_daily_email(slugs):
# def setup_email_list():
# def add_list_to_email():
# def send_email():
# def log_daily_email(email, recipient_usernames):
# def get_daily_email_log():
# def do_api_request(api_link, method='GET', params={}):
. Output only the next line. | response1 = emailsdb.construct_daily_email(slugs) |
Using the snippet: <|code_start|> post['muted'] = False
post['comment_count'] = 0
post['disqus_thread_id_str'] = ''
post['sort_score'] = 0.0
post['downvotes'] = 0
post['hackpad_url'] = ''
post['date_created'] = datetime.datetime.now()
post['user_id_str'] = user['user']['id_str']
post['username'] = self.current_user
post['user'] = user['user']
post['votes'] = 1
post['voted_users'] = [user['user']]
#save it
post['slug'] = postsdb.insert_post(post)
msg = 'success'
else:
# this is an existing post.
# attempt to edit the post (make sure they are the author)
saved_post = postsdb.get_post_by_slug(post['slug'])
if saved_post and self.current_user == saved_post['user']['screen_name']:
# looks good - let's update the saved_post values to new values
for key in post.keys():
saved_post[key] = post[key]
# finally let's save the updates
postsdb.save_post(saved_post)
msg = 'success'
# log any @ mentions in the post
mentions = re.findall(r'@([^\s]+)', post['body_raw'])
for mention in mentions:
<|code_end|>
, determine the next line of code. You have imports:
import app.basic
import logging
import re
import settings
import tornado.web
import tornado.options
import urllib
import datetime
import time
from urlparse import urlparse
from lib import bitly
from lib import google
from lib import mentionsdb
from lib import postsdb
from lib import sanitize
from lib import tagsdb
from lib import userdb
from lib import disqus
from lib import template_helpers
and context (class names, function names, or code) available:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/template_helpers.py
# def tinymce_valid_elements_wrapper(media=True):
# def twitter_avatar_size(url, size):
# def pretty_date(d):
# def post_permalink(p):
. Output only the next line. | mentionsdb.add_mention(mention.lower(), post['slug']) |
Using the snippet: <|code_start|>#-*- coding:utf-8 -*-
###############
### New Post
### /posts
###############
class NewPost(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self):
post = {}
post['title'] = self.get_argument('title', '')
post['url'] = self.get_argument('url', '')
is_bookmarklet = False
if self.request.path.find('/bookmarklet') == 0:
is_bookmarklet = True
self.render('post/new_post.html', post=post, is_bookmarklet=is_bookmarklet)
###############
### EDIT A POST
### /posts/([^\/]+)/edit
###############
class EditPost(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self, slug):
<|code_end|>
, determine the next line of code. You have imports:
import app.basic
import logging
import re
import settings
import tornado.web
import tornado.options
import urllib
import datetime
import time
from urlparse import urlparse
from lib import bitly
from lib import google
from lib import mentionsdb
from lib import postsdb
from lib import sanitize
from lib import tagsdb
from lib import userdb
from lib import disqus
from lib import template_helpers
and context (class names, function names, or code) available:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/template_helpers.py
# def tinymce_valid_elements_wrapper(media=True):
# def twitter_avatar_size(url, size):
# def pretty_date(d):
# def post_permalink(p):
. Output only the next line. | post = postsdb.get_post_by_slug(slug) |
Given the code snippet: <|code_start|> post['title'] = self.get_argument('title', '')
post['url'] = self.get_argument('url', '')
is_bookmarklet = False
if self.request.path.find('/bookmarklet') == 0:
is_bookmarklet = True
self.render('post/new_post.html', post=post, is_bookmarklet=is_bookmarklet)
###############
### EDIT A POST
### /posts/([^\/]+)/edit
###############
class EditPost(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self, slug):
post = postsdb.get_post_by_slug(slug)
if post and post['user']['screen_name'] == self.current_user or self.current_user_can('edit_posts'):
# available to edit this post
self.render('post/edit_post.html', post=post)
else:
# not available to edit right now
self.redirect('/posts/%s' % slug)
##################
### FEATURED POSTS
### /featured.*$
##################
class FeaturedPosts(app.basic.BaseHandler):
def get(self, tag=None):
featured_posts = postsdb.get_featured_posts(1000, 1)
<|code_end|>
, generate the next line using the imports in this file:
import app.basic
import logging
import re
import settings
import tornado.web
import tornado.options
import urllib
import datetime
import time
from urlparse import urlparse
from lib import bitly
from lib import google
from lib import mentionsdb
from lib import postsdb
from lib import sanitize
from lib import tagsdb
from lib import userdb
from lib import disqus
from lib import template_helpers
and context (functions, classes, or occasionally code) from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/template_helpers.py
# def tinymce_valid_elements_wrapper(media=True):
# def twitter_avatar_size(url, size):
# def pretty_date(d):
# def post_permalink(p):
. Output only the next line. | tags_alpha = tagsdb.get_all_tags(sort="alpha") |
Given snippet: <|code_start|> # check if there is an existing URL
if post['url'] != '':
url = urlparse(post['url'])
netloc = url.netloc.split('.')
if netloc[0] == 'www':
del netloc[0]
path = url.path
if path and path[-1] == '/':
path = path[:-1]
url = '%s%s' % ('.'.join(netloc), path)
post['normalized_url'] = url
long_url = post['url']
if long_url.find('goo.gl') > -1:
long_url = google.expand_url(post['url'])
if long_url.find('bit.ly') > -1 or long_url.find('bitly.com') > -1:
long_url = bitly.expand_url(post['url'].replace('http://bitly.com','').replace('http://bit.ly',''))
post['domain'] = urlparse(long_url).netloc
ok_to_post = True
dups = postsdb.get_posts_by_normalized_url(post.get('normalized_url', ""), 1)
if post['url'] != '' and len(dups) > 0 and bypass_dup_check != "true":
##
## If there are dupes, kick them back to the post add form
##
return (self.render('post/new_post.html', post=post, dups=dups))
# Handle tags
post['tags'] = [t.strip().lower() for t in post['tags']]
post['tags'] = [t for t in post['tags'] if t]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import app.basic
import logging
import re
import settings
import tornado.web
import tornado.options
import urllib
import datetime
import time
from urlparse import urlparse
from lib import bitly
from lib import google
from lib import mentionsdb
from lib import postsdb
from lib import sanitize
from lib import tagsdb
from lib import userdb
from lib import disqus
from lib import template_helpers
and context:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/template_helpers.py
# def tinymce_valid_elements_wrapper(media=True):
# def twitter_avatar_size(url, size):
# def pretty_date(d):
# def post_permalink(p):
which might include code, classes, or functions. Output only the next line. | userdb.add_tags_to_user(self.current_user, post['tags']) |
Predict the next line for this snippet: <|code_start|> def get(self, slug):
# nothing to see here
return
def post(self, slug):
# user must be logged in
msg = {}
if not self.current_user:
msg = {'error': 'You must be logged in to bump.', 'redirect': True}
else:
post = postsdb.get_post_by_slug(slug)
if post:
can_vote = True
for u in post['voted_users']:
if u['username'] == self.current_user:
can_vote = False
if not can_vote:
msg = {'error': 'You have already upvoted this post.'}
else:
user = userdb.get_user_by_screen_name(self.current_user)
# Increment the vote count
post['votes'] += 1
post['voted_users'].append(user['user'])
postsdb.save_post(post)
msg = {'votes': post['votes']}
# send email notification to post author
author = userdb.get_user_by_screen_name(post['user']['username'])
if 'email_address' in author.keys():
subject = "[#usvconversation] @%s just bumped up your post: %s" % (self.current_user, post['title'])
<|code_end|>
with the help of current file imports:
import app.basic
import logging
import re
import settings
import tornado.web
import tornado.options
import urllib
import datetime
import time
from urlparse import urlparse
from lib import bitly
from lib import google
from lib import mentionsdb
from lib import postsdb
from lib import sanitize
from lib import tagsdb
from lib import userdb
from lib import disqus
from lib import template_helpers
and context from other files:
# Path: lib/mentionsdb.py
# def add_mention(screen_name, slug):
# def get_mentions_by_user(screen_name, per_page, page):
#
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/tagsdb.py
# def get_user_tags(screen_name):
# def get_all_tags(sort=None):
# def get_hot_tags():
# def get_user_tags(screen_name):
# def save_tag(tag):
#
# Path: lib/userdb.py
# def get_all():
# def get_user_by_id_str(id_str):
# def get_user_by_screen_name(screen_name):
# def get_user_by_email(email_address):
# def get_disqus_users():
# def get_newsletter_recipients():
# def create_new_user(user, access_token):
# def save_user(user):
# def get_user_count():
# def add_tags_to_user(screen_name, tags=[]):
# def update_twitter(id_str=None, api=None):
# def update_twitter_profile_images():
#
# Path: lib/template_helpers.py
# def tinymce_valid_elements_wrapper(media=True):
# def twitter_avatar_size(url, size):
# def pretty_date(d):
# def post_permalink(p):
, which may contain function names, class names, or code. Output only the next line. | text = "Woo!\n\n%s" % template_helpers.post_permalink(post) |
Using the snippet: <|code_start|># Run by Heroku scheduler every night
# If running locally, uncomment below imports
sys.path.insert(0, '/Users/nick/dev/usv/usv.com')
# 1) get 5 slugs
posts = postsdb.get_hot_posts_by_day(datetime.today())
slugs = []
for i, post in enumerate(posts):
if i < 5:
slugs.append(post['slug'])
# 2) construct email
#request1 = emailsdb.construct_daily_email(slugs)
# Setup list for the day
#if request1['message'] == "success":
# request2 = emailsdb.setup_email_list()
# Add list to email
#if request2['message'] == "success":
<|code_end|>
, determine the next line of code. You have imports:
import sys
import settings
import requests
import logging
import csv
from datetime import datetime
from lib import postsdb, emailsdb
and context (class names, function names, or code) available:
# Path: lib/postsdb.py
# def get_post_by_slug(slug):
# def get_all():
# def get_posts_by_bumps(screen_name, per_page, page):
# def get_posts_by_query(query, per_page=10, page=1):
# def get_posts_by_tag(tag):
# def get_posts_by_screen_name(screen_name, per_page=10, page=1):
# def get_posts_by_screen_name_and_tag(screen_name, tag, per_page=10, page=1):
# def get_featured_posts(per_page=10, page=1):
# def get_new_posts(per_page=50, page=1):
# def get_hot_posts(per_page=50, page=1):
# def get_hot_posts_by_day(day=date.today(), hide_featured=False):
# def get_daily_posts_by_sort_score(min_score=8):
# def get_hot_posts_24hr(start=datetime.now()):
# def get_sad_posts(per_page=50, page=1):
# def get_deleted_posts(per_page=50, page=1):
# def get_unique_posters(start_date, end_date):
# def get_featured_posts_count():
# def get_post_count_by_query(query):
# def get_post_count():
# def get_post_count_for_range(start_date, end_date):
# def get_delete_posts_count():
# def get_post_count_by_tag(tag):
# def get_latest_staff_posts_by_tag(tag, limit=10):
# def get_posts_by_normalized_url(normalized_url, limit):
# def get_posts_with_min_votes(min_votes):
# def get_hot_posts_past_week():
# def get_related_posts_by_tag(tag):
# def add_subscriber_to_post(slug, email):
# def remove_subscriber_from_post(slug, email):
# def save_post(post):
# def update_post_score(slug, score, scores):
# def delete_all_posts_by_user(screen_name):
# def insert_post(post):
# def sort_posts(day="all"):
#
# Path: lib/emailsdb.py
# def construct_daily_email(slugs):
# def setup_email_list():
# def add_list_to_email():
# def send_email():
# def log_daily_email(email, recipient_usernames):
# def get_daily_email_log():
# def do_api_request(api_link, method='GET', params={}):
. Output only the next line. | request3 = emailsdb.add_list_to_email() |
Continue the code snippet: <|code_start|>
def opendap_metadata(opendap_url):
response = urllib.urlopen(opendap_url + ".das")
return response.read()
def load(url, frm, name):
if url.split(".")[-1] != "gz":
url = url + "gz"
if frm == "ASCII":
<|code_end|>
. Use current file imports:
from pydap.client import open_url
from netcdftime import utime
from giscube.config import MEDIA_ROOT, MEDIA_URL
import numpy as np
import urllib
and context (classes, functions, or code) from other files:
# Path: giscube/config.py
# MEDIA_ROOT = '{0}/giscube_app/static/'.format(current_dir)
#
# MEDIA_URL = 'uploaded_files/'
. Output only the next line. | urllib.urlretrieve ("{0}.ascii".format(url), "{0}{1}".format(MEDIA_ROOT + MEDIA_URL, "{0}.ascii".format(name))) |
Continue the code snippet: <|code_start|>
def opendap_metadata(opendap_url):
response = urllib.urlopen(opendap_url + ".das")
return response.read()
def load(url, frm, name):
if url.split(".")[-1] != "gz":
url = url + "gz"
if frm == "ASCII":
<|code_end|>
. Use current file imports:
from pydap.client import open_url
from netcdftime import utime
from giscube.config import MEDIA_ROOT, MEDIA_URL
import numpy as np
import urllib
and context (classes, functions, or code) from other files:
# Path: giscube/config.py
# MEDIA_ROOT = '{0}/giscube_app/static/'.format(current_dir)
#
# MEDIA_URL = 'uploaded_files/'
. Output only the next line. | urllib.urlretrieve ("{0}.ascii".format(url), "{0}{1}".format(MEDIA_ROOT + MEDIA_URL, "{0}.ascii".format(name))) |
Given snippet: <|code_start|>
@dajaxice_register(method='GET')
def opendap_getdata(request, opendap_url, frm, opendap_out_name):
if frm == "nc3" or frm == "nc4":
check_frm = "nc"
else:
check_frm = frm
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, shutil
import numpy as np
import json
from netCDF4 import Dataset
from dajaxice.decorators import dajaxice_register
from giscube.config import MEDIA_ROOT, MEDIA_URL
from scripts.extract_shp_table import extract_shp_table
from scripts.metadata import get_nc_data
from scripts.conversion import nc_to_gtif, nc_to_geojson, shp_to_kml, convert_geotiff_to_kml, shp_to_tif, shp_to_json, geotiff_to_point_shp, geotiff_to_point_json, convert_coord_to_point_shp
from scripts.spatial_analysis import buffer_shapefile, find_point_inside_feature
from scripts.clip_geotiff_by_shp import clip_geotiff_by_shp
from scripts.data_management import change_geotiff_resolution, color_table_on_geotiff
from scripts.opendap import load as load_opendap
from scripts.opendap import opendap_metadata
and context:
# Path: giscube/config.py
# MEDIA_ROOT = '{0}/giscube_app/static/'.format(current_dir)
#
# MEDIA_URL = 'uploaded_files/'
which might include code, classes, or functions. Output only the next line. | if os.path.isfile('{0}{1}{2}'.format(MEDIA_ROOT, MEDIA_URL, '{0}.{1}'.format(opendap_out_name, check_frm))): |
Predict the next line for this snippet: <|code_start|>
@dajaxice_register(method='GET')
def opendap_getdata(request, opendap_url, frm, opendap_out_name):
if frm == "nc3" or frm == "nc4":
check_frm = "nc"
else:
check_frm = frm
<|code_end|>
with the help of current file imports:
import os, shutil
import numpy as np
import json
from netCDF4 import Dataset
from dajaxice.decorators import dajaxice_register
from giscube.config import MEDIA_ROOT, MEDIA_URL
from scripts.extract_shp_table import extract_shp_table
from scripts.metadata import get_nc_data
from scripts.conversion import nc_to_gtif, nc_to_geojson, shp_to_kml, convert_geotiff_to_kml, shp_to_tif, shp_to_json, geotiff_to_point_shp, geotiff_to_point_json, convert_coord_to_point_shp
from scripts.spatial_analysis import buffer_shapefile, find_point_inside_feature
from scripts.clip_geotiff_by_shp import clip_geotiff_by_shp
from scripts.data_management import change_geotiff_resolution, color_table_on_geotiff
from scripts.opendap import load as load_opendap
from scripts.opendap import opendap_metadata
and context from other files:
# Path: giscube/config.py
# MEDIA_ROOT = '{0}/giscube_app/static/'.format(current_dir)
#
# MEDIA_URL = 'uploaded_files/'
, which may contain function names, class names, or code. Output only the next line. | if os.path.isfile('{0}{1}{2}'.format(MEDIA_ROOT, MEDIA_URL, '{0}.{1}'.format(opendap_out_name, check_frm))): |
Continue the code snippet: <|code_start|>
class BackendTests(TestCase):
"""
Tests for LazySignupBackend
"""
def setUp(self):
<|code_end|>
. Use current file imports:
from django.contrib.auth import get_user_model
from django.test import TestCase
from lazysignup.backends import LazySignupBackend
and context (classes, functions, or code) from other files:
# Path: lazysignup/backends.py
# class LazySignupBackend(ModelBackend):
#
# def authenticate(self, request=None, username=None):
# user_class = LazyUser.get_user_class()
# try:
# return user_class.objects.get(**{
# get_user_model().USERNAME_FIELD: username
# })
# except user_class.DoesNotExist:
# return None
#
# def get_user(self, user_id):
# # Annotate the user with our backend so it's always available,
# # not just when authenticate() has been called. This will be
# # used by the is_lazy_user filter.
# user_class = LazyUser.get_user_class()
# try:
# user = user_class.objects.get(pk=user_id)
# except user_class.DoesNotExist:
# user = None
# else:
# user.backend = 'lazysignup.backends.LazySignupBackend'
# return user
. Output only the next line. | self.backend = LazySignupBackend() |
Using the snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" Convert a temporary user to a real one. Reject users who don't
appear to be temporary users (ie. they have a usable password)
"""
redirect_to = 'lazysignup_convert_done'
if form_class is None:
if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
else:
form_class = UserCreationForm
# If we've got an anonymous user, redirect to login
if request.user.is_anonymous:
return HttpResponseRedirect(anonymous_redirect)
if request.method == 'POST':
redirect_to = request.POST.get(redirect_field_name) or redirect_to
form = form_class(request.POST, instance=request.user)
if form.is_valid():
try:
LazyUser.objects.convert(form)
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from lazysignup.decorators import allow_lazy_user
from lazysignup.exceptions import NotLazyError
from lazysignup.models import LazyUser
from lazysignup.forms import UserCreationForm
from lazysignup import constants
and context (class names, function names, or code) available:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
#
# Path: lazysignup/forms.py
# class UserCreationForm(UserCreationFormBase):
#
# def get_credentials(self):
# return {
# 'username': self.cleaned_data['username'],
# 'password': self.cleaned_data['password1']}
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | except NotLazyError: |
Given the following code snippet before the placeholder: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" Convert a temporary user to a real one. Reject users who don't
appear to be temporary users (ie. they have a usable password)
"""
redirect_to = 'lazysignup_convert_done'
if form_class is None:
if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
else:
form_class = UserCreationForm
# If we've got an anonymous user, redirect to login
if request.user.is_anonymous:
return HttpResponseRedirect(anonymous_redirect)
if request.method == 'POST':
redirect_to = request.POST.get(redirect_field_name) or redirect_to
form = form_class(request.POST, instance=request.user)
if form.is_valid():
try:
<|code_end|>
, predict the next line using imports from the current file:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from lazysignup.decorators import allow_lazy_user
from lazysignup.exceptions import NotLazyError
from lazysignup.models import LazyUser
from lazysignup.forms import UserCreationForm
from lazysignup import constants
and context including class names, function names, and sometimes code from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
#
# Path: lazysignup/forms.py
# class UserCreationForm(UserCreationFormBase):
#
# def get_credentials(self):
# return {
# 'username': self.cleaned_data['username'],
# 'password': self.cleaned_data['password1']}
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | LazyUser.objects.convert(form) |
Predict the next line after this snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" Convert a temporary user to a real one. Reject users who don't
appear to be temporary users (ie. they have a usable password)
"""
redirect_to = 'lazysignup_convert_done'
if form_class is None:
if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
else:
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from lazysignup.decorators import allow_lazy_user
from lazysignup.exceptions import NotLazyError
from lazysignup.models import LazyUser
from lazysignup.forms import UserCreationForm
from lazysignup import constants
and any relevant context from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
#
# Path: lazysignup/forms.py
# class UserCreationForm(UserCreationFormBase):
#
# def get_credentials(self):
# return {
# 'username': self.cleaned_data['username'],
# 'password': self.cleaned_data['password1']}
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | form_class = UserCreationForm |
Given the code snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" Convert a temporary user to a real one. Reject users who don't
appear to be temporary users (ie. they have a usable password)
"""
redirect_to = 'lazysignup_convert_done'
if form_class is None:
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from lazysignup.decorators import allow_lazy_user
from lazysignup.exceptions import NotLazyError
from lazysignup.models import LazyUser
from lazysignup.forms import UserCreationForm
from lazysignup import constants
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
#
# Path: lazysignup/forms.py
# class UserCreationForm(UserCreationFormBase):
#
# def get_credentials(self):
# return {
# 'username': self.cleaned_data['username'],
# 'password': self.cleaned_data['password1']}
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None: |
Next line prediction: <|code_start|>
class LazyUserManagerTests(TestCase):
"""
Tests for LazyUserManager
"""
def test_generate_username_no_method(self):
"""
Tests auto generated UUID username
"""
mock_user_class = Mock(generate_username=1)
del mock_user_class.generate_username
mock_user_class._meta.get_field.return_value.max_length = 32
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from mock import Mock
from lazysignup.models import LazyUser)
and context including class names, function names, or small code snippets from other files:
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
. Output only the next line. | username = LazyUser.objects.generate_username(mock_user_class) |
Given the code snippet: <|code_start|>
class Command(BaseCommand):
help = u"""Remove all users whose sessions have expired and who haven't
set a password. This assumes you are using database sessions"""
def handle(self, **options):
# Delete each of these users. We don't use the queryset delete()
# because we want cascades to work (including, of course, the LazyUser
# object itself)
for lazy_user in self.to_delete():
lazy_user.user.delete()
def to_delete(self):
delete_before = datetime.datetime.now() - datetime.timedelta(
seconds=settings.SESSION_COOKIE_AGE)
<|code_end|>
, generate the next line using the imports in this file:
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from lazysignup.models import LazyUser
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
. Output only the next line. | return LazyUser.objects.filter( |
Continue the code snippet: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
<|code_end|>
. Use current file imports:
from django.http import HttpResponse
from lazysignup.decorators import allow_lazy_user, require_lazy_user, require_nonlazy_user
and context (classes, functions, or code) from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# def require_lazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
#
# def require_nonlazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if not is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
. Output only the next line. | @allow_lazy_user |
Based on the snippet: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
@allow_lazy_user
def lazy_view(request):
r = HttpResponse()
if request.user.is_anonymous or request.user.has_usable_password():
r.status_code = 500
return r
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse
from lazysignup.decorators import allow_lazy_user, require_lazy_user, require_nonlazy_user
and context (classes, functions, sometimes code) from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# def require_lazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
#
# def require_nonlazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if not is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
. Output only the next line. | @require_lazy_user("view-for-nonlazy-users") |
Given the following code snippet before the placeholder: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
@allow_lazy_user
def lazy_view(request):
r = HttpResponse()
if request.user.is_anonymous or request.user.has_usable_password():
r.status_code = 500
return r
@require_lazy_user("view-for-nonlazy-users")
def requires_lazy_view(request):
return HttpResponse()
<|code_end|>
, predict the next line using imports from the current file:
from django.http import HttpResponse
from lazysignup.decorators import allow_lazy_user, require_lazy_user, require_nonlazy_user
and context including class names, function names, and sometimes code from other files:
# Path: lazysignup/decorators.py
# def allow_lazy_user(func):
# def wrapped(request, *args, **kwargs):
# assert hasattr(request, 'session'), ("You need to have the session "
# "app installed")
# if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# # If the user agent is one we ignore, bail early
# ignore = False
# request_user_agent = request.META.get('HTTP_USER_AGENT', '')
# for user_agent in USER_AGENT_BLACKLIST:
# if user_agent.search(request_user_agent):
# ignore = True
# break
#
# # If there's already a key in the session for a valid user, then
# # we don't need to do anything. If the user isn't valid, then
# # get_user will return an anonymous user
# if get_user(request).is_anonymous and not ignore:
# # If not, then we have to create a user, and log them in.
# from lazysignup.models import LazyUser
# user, username = LazyUser.objects.create_lazy_user()
# request.user = None
# user = authenticate(username=username)
# assert user, ("Lazy user creation and authentication "
# "failed. Have you got "
# "lazysignup.backends.LazySignupBackend in "
# "AUTHENTICATION_BACKENDS?")
# # Set the user id in the session here to prevent the login
# # call cycling the session key.
# request.session[SESSION_KEY] = user.id
# login(request, user)
# return func(request, *args, **kwargs)
#
# return wraps(func)(wrapped)
#
# def require_lazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
#
# def require_nonlazy_user(*redirect_args, **redirect_kwargs):
# def decorator(func):
# @wraps(func, assigned=WRAPPER_ASSIGNMENTS)
# def inner(request, *args, **kwargs):
# if not is_lazy_user(request.user):
# return func(request, *args, **kwargs)
# else:
# return redirect(*redirect_args, **redirect_kwargs)
# return inner
# return decorator
. Output only the next line. | @require_nonlazy_user("view-for-lazy-users") |
Given the following code snippet before the placeholder: <|code_start|> """ Hardcoded credentials to demonstrate that the get_credentials method
is being used
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.RegexField(
label=_("Username"), max_length=30,
regex=r'^[\w.@+-]+$',
help_text=_("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")})
password1 = forms.CharField(
label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(
label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
def get_credentials(self):
return {
'username': 'demo',
'password': 'demo',
}
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from custom_user_tests.models import CustomUser
from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
and context including class names, function names, and sometimes code from other files:
# Path: custom_user_tests/models.py
# class CustomUser(AbstractBaseUser, PermissionsMixin):
# objects = UserManager()
# my_custom_field = models.CharField(max_length=50, blank=True, null=True)
#
# class Meta:
# app_label = 'custom_user_tests'
# verbose_name = _('user')
# verbose_name_plural = _('users')
#
# username = models.CharField(
# _('username'), max_length=30, unique=True,
# help_text=_('Required. 30 characters or fewer. Letters, digits and '
# '@/./+/-/_ only.'),
# validators=[
# validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
# ])
# first_name = models.CharField(_('first name'), max_length=30, blank=True)
# last_name = models.CharField(_('last name'), max_length=30, blank=True)
# email = models.EmailField(_('email address'), blank=True)
# is_staff = models.BooleanField(
# _('staff status'), default=False,
# help_text=_('Designates whether the user can log into this admin '
# 'site.'))
# is_active = models.BooleanField(
# _('active'), default=True,
# help_text=_('Designates whether this user should be treated as '
# 'active. Unselect this instead of deleting accounts.'))
# date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
#
# USERNAME_FIELD = 'username'
# REQUIRED_FIELDS = ['email']
#
# def get_full_name(self):
# """
# Returns the first_name plus the last_name, with a space in between.
# """
# full_name = '%s %s' % (self.first_name, self.last_name)
# return full_name.strip()
#
# def get_short_name(self):
# "Returns the short name for the user."
# return self.first_name
. Output only the next line. | model = CustomUser |
Given the code snippet: <|code_start|>
class CustomUserModelTests(TestCase):
"""
Test for custom user model
"""
def setUp(self):
super(CustomUserModelTests, self).setUp()
self.request = HttpRequest()
SessionMiddleware().process_request(self.request)
# We have to save the session to cause a session key to be generated.
self.request.session.save()
def test_good_custom_convert_form(self):
self.client.get('/lazy/')
self.client.post(reverse('test_good_convert'), {
'username': 'foo',
'password1': 'password',
'password2': 'password',
})
users = get_user_model().objects.all()
self.assertEqual(1, len(users))
user = users[0]
# The credentials returned by get_credentials should have been used
self.assertEqual(user, authenticate(username='demo', password='demo'))
# The user should no longer be lazy
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth import get_user_model, authenticate
from django.contrib.sessions.middleware import SessionMiddleware
from django.urls import reverse
from django.http import HttpRequest
from django.test import TestCase
from lazysignup.utils import is_lazy_user
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
. Output only the next line. | self.assertFalse(is_lazy_user(user)) |
Predict the next line for this snippet: <|code_start|>
class LazyUserModelTests(TestCase):
"""
Tests for LazyUser Model
"""
def setUp(self):
super(LazyUserModelTests, self).setUp()
def test_str(self):
"""
Tests str method on LazyUser
"""
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from lazysignup.models import LazyUser
and context from other files:
# Path: lazysignup/models.py
# class LazyUser(models.Model):
# user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE)
# created = models.DateTimeField(default=now, db_index=True)
# objects = LazyUserManager()
#
# @classmethod
# def get_user_class(cls):
# related_user_field = cls._meta.get_field('user')
# # Django < 1.9 has rel.to
# if hasattr(related_user_field, 'rel'):
# rel_to = related_user_field.rel.to if related_user_field.rel else None
# elif hasattr(related_user_field, 'remote_field'):
# rel_to = related_user_field.remote_field.model if related_user_field.remote_field else None
# return rel_to
#
# def __str__(self):
# return '{0}:{1}'.format(self.user, self.created)
, which may contain function names, class names, or code. Output only the next line. | user, username = LazyUser.objects.create_lazy_user() |
Here is a snippet: <|code_start|>
if settings.AUTH_USER_MODEL is 'auth.User': # pragma: no cover
else: # pragma: no cover
admin.autodiscover()
# URL test patterns for lazysignup. Use this file to ensure a consistent
# set of URL patterns are used when running unit tests.
urlpatterns = [
url(r'^admin/?', admin.site.urls),
url(r'^convert/', include('lazysignup.urls')),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url, include
from django.contrib.auth.forms import UserCreationForm
from django.conf import settings
from lazysignup.tests.forms import GoodUserCreationForm
from custom_user_tests.forms import GoodUserCreationForm
from django.contrib import admin
from lazysignup import views
from lazysignup.tests import views as test_views
from django.contrib import admin
and context from other files:
# Path: lazysignup/views.py
# def convert(request, form_class=None,
# redirect_field_name='redirect_to',
# anonymous_redirect=settings.LOGIN_URL,
# template_name='lazysignup/convert.html',
# ajax_template_name='lazysignup/convert_ajax.html'):
#
# Path: lazysignup/tests/views.py
# def view(request):
# def lazy_view(request):
# def requires_lazy_view(request):
# def requires_nonlazy_view(request):
, which may include functions, classes, or code. Output only the next line. | url(r'^custom_convert/', views.convert, { |
Using the snippet: <|code_start|>
if settings.AUTH_USER_MODEL is 'auth.User': # pragma: no cover
else: # pragma: no cover
admin.autodiscover()
# URL test patterns for lazysignup. Use this file to ensure a consistent
# set of URL patterns are used when running unit tests.
urlpatterns = [
url(r'^admin/?', admin.site.urls),
url(r'^convert/', include('lazysignup.urls')),
url(r'^custom_convert/', views.convert, {
'template_name': 'lazysignup/done.html'
}),
url(r'^custom_convert_ajax/', views.convert, {
'ajax_template_name': 'lazysignup/done.html'
}),
]
urlpatterns += [
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url, include
from django.contrib.auth.forms import UserCreationForm
from django.conf import settings
from lazysignup.tests.forms import GoodUserCreationForm
from custom_user_tests.forms import GoodUserCreationForm
from django.contrib import admin
from lazysignup import views
from lazysignup.tests import views as test_views
from django.contrib import admin
and context (class names, function names, or code) available:
# Path: lazysignup/views.py
# def convert(request, form_class=None,
# redirect_field_name='redirect_to',
# anonymous_redirect=settings.LOGIN_URL,
# template_name='lazysignup/convert.html',
# ajax_template_name='lazysignup/convert_ajax.html'):
#
# Path: lazysignup/tests/views.py
# def view(request):
# def lazy_view(request):
# def requires_lazy_view(request):
# def requires_nonlazy_view(request):
. Output only the next line. | url(r'^nolazy/$', test_views.view, name='test_view'), |
Given the code snippet: <|code_start|>
DEFAULT_BLACKLIST = (
'slurp',
'googlebot',
'yandex',
'msnbot',
'baiduspider',
)
for user_agent in getattr(settings, 'LAZYSIGNUP_USER_AGENT_BLACKLIST', DEFAULT_BLACKLIST):
<|code_end|>
, generate the next line using the imports in this file:
import re
import uuid
import six
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.exceptions import NotLazyError
from lazysignup.utils import is_lazy_user
from lazysignup.signals import converted
from lazysignup import constants
from django.contrib.auth import get_user_model
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
#
# Path: lazysignup/signals.py
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | USER_AGENT_BLACKLIST.append(re.compile(user_agent, re.I)) |
Predict the next line for this snippet: <|code_start|>class LazyUserManager(models.Manager):
def __hash__(self):
"""
Implemented so signal can be sent in .convert() for Django 1.8
"""
return hash(str(self))
username_field = get_user_model().USERNAME_FIELD
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_class()
username = self.generate_username(user_class)
user = user_class.objects.create_user(username, '')
self.create(user=user)
return user, username
def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is_lazy_user(form.instance):
<|code_end|>
with the help of current file imports:
import re
import uuid
import six
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.exceptions import NotLazyError
from lazysignup.utils import is_lazy_user
from lazysignup.signals import converted
from lazysignup import constants
from django.contrib.auth import get_user_model
and context from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
#
# Path: lazysignup/signals.py
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
, which may contain function names, class names, or code. Output only the next line. | raise NotLazyError('You cannot convert a non-lazy user') |
Here is a snippet: <|code_start|>
class LazyUserManager(models.Manager):
def __hash__(self):
"""
Implemented so signal can be sent in .convert() for Django 1.8
"""
return hash(str(self))
username_field = get_user_model().USERNAME_FIELD
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_class()
username = self.generate_username(user_class)
user = user_class.objects.create_user(username, '')
self.create(user=user)
return user, username
def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
<|code_end|>
. Write the next line using the current file imports:
import re
import uuid
import six
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.exceptions import NotLazyError
from lazysignup.utils import is_lazy_user
from lazysignup.signals import converted
from lazysignup import constants
from django.contrib.auth import get_user_model
and context from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
#
# Path: lazysignup/signals.py
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
, which may include functions, classes, or code. Output only the next line. | if not is_lazy_user(form.instance): |
Given the code snippet: <|code_start|>
username_field = get_user_model().USERNAME_FIELD
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_class()
username = self.generate_username(user_class)
user = user_class.objects.create_user(username, '')
self.create(user=user)
return user, username
def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is_lazy_user(form.instance):
raise NotLazyError('You cannot convert a non-lazy user')
user = form.save()
# We need to remove the LazyUser instance assocated with the
# newly-converted user
self.filter(user=user).delete()
<|code_end|>
, generate the next line using the imports in this file:
import re
import uuid
import six
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.exceptions import NotLazyError
from lazysignup.utils import is_lazy_user
from lazysignup.signals import converted
from lazysignup import constants
from django.contrib.auth import get_user_model
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
#
# Path: lazysignup/signals.py
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | converted.send(self, user=user) |
Given the code snippet: <|code_start|>
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is_lazy_user(form.instance):
raise NotLazyError('You cannot convert a non-lazy user')
user = form.save()
# We need to remove the LazyUser instance assocated with the
# newly-converted user
self.filter(user=user).delete()
converted.send(self, user=user)
return user
def generate_username(self, user_class):
""" Generate a new username for a user
"""
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
return uuid.uuid4().hex[:max_length]
@six.python_2_unicode_compatible
class LazyUser(models.Model):
<|code_end|>
, generate the next line using the imports in this file:
import re
import uuid
import six
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.exceptions import NotLazyError
from lazysignup.utils import is_lazy_user
from lazysignup.signals import converted
from lazysignup import constants
from django.contrib.auth import get_user_model
and context (functions, classes, or occasionally code) from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/exceptions.py
# class NotLazyError(TypeError):
# """ Raised when an operation is attempted on a non-lazy user """
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
#
# Path: lazysignup/signals.py
#
# Path: lazysignup/constants.py
# LAZYSIGNUP_USER_MODEL = getattr(settings, 'LAZYSIGNUP_USER_MODEL', settings.AUTH_USER_MODEL)
# LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = getattr(
# settings,
# 'LAZYSIGNUP_CUSTOM_USER_CREATION_FORM',
# None
# )
# DEFAULT_BLACKLIST = (
# 'slurp',
# 'googlebot',
# 'yandex',
# 'msnbot',
# 'baiduspider',
# )
# USER_AGENT_BLACKLIST = []
. Output only the next line. | user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE) |
Using the snippet: <|code_start|>
ALLOW_LAZY_REGISTRY = {}
def allow_lazy_user(func):
def wrapped(request, *args, **kwargs):
assert hasattr(request, 'session'), ("You need to have the session "
"app installed")
if getattr(settings, 'LAZYSIGNUP_ENABLE', True):
# If the user agent is one we ignore, bail early
ignore = False
request_user_agent = request.META.get('HTTP_USER_AGENT', '')
<|code_end|>
, determine the next line of code. You have imports:
from functools import wraps
from django.conf import settings
from django.contrib.auth import SESSION_KEY
from django.contrib.auth import authenticate
from django.contrib.auth import get_user
from django.contrib.auth import login
from django.shortcuts import redirect
from functools import WRAPPER_ASSIGNMENTS
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.utils import is_lazy_user
from lazysignup.models import LazyUser
and context (class names, function names, or code) available:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
. Output only the next line. | for user_agent in USER_AGENT_BLACKLIST: |
Based on the snippet: <|code_start|> for user_agent in USER_AGENT_BLACKLIST:
if user_agent.search(request_user_agent):
ignore = True
break
# If there's already a key in the session for a valid user, then
# we don't need to do anything. If the user isn't valid, then
# get_user will return an anonymous user
if get_user(request).is_anonymous and not ignore:
# If not, then we have to create a user, and log them in.
user, username = LazyUser.objects.create_lazy_user()
request.user = None
user = authenticate(username=username)
assert user, ("Lazy user creation and authentication "
"failed. Have you got "
"lazysignup.backends.LazySignupBackend in "
"AUTHENTICATION_BACKENDS?")
# Set the user id in the session here to prevent the login
# call cycling the session key.
request.session[SESSION_KEY] = user.id
login(request, user)
return func(request, *args, **kwargs)
return wraps(func)(wrapped)
def require_lazy_user(*redirect_args, **redirect_kwargs):
def decorator(func):
@wraps(func, assigned=WRAPPER_ASSIGNMENTS)
def inner(request, *args, **kwargs):
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import wraps
from django.conf import settings
from django.contrib.auth import SESSION_KEY
from django.contrib.auth import authenticate
from django.contrib.auth import get_user
from django.contrib.auth import login
from django.shortcuts import redirect
from functools import WRAPPER_ASSIGNMENTS
from lazysignup.constants import USER_AGENT_BLACKLIST
from lazysignup.utils import is_lazy_user
from lazysignup.models import LazyUser
and context (classes, functions, sometimes code) from other files:
# Path: lazysignup/constants.py
# USER_AGENT_BLACKLIST = []
#
# Path: lazysignup/utils.py
# def is_lazy_user(user):
# """ Return True if the passed user is a lazy user. """
# # Anonymous users are not lazy.
#
# if user.is_anonymous:
# return False
#
# # Check the user backend. If the lazy signup backend
# # authenticated them, then the user is lazy.
# backend = getattr(user, 'backend', None)
# if backend == 'lazysignup.backends.LazySignupBackend':
# return True
#
# # Otherwise, we have to fall back to checking the database.
# from lazysignup.models import LazyUser
# return bool(LazyUser.objects.filter(user=user).count() > 0)
. Output only the next line. | if is_lazy_user(request.user): |
Next line prediction: <|code_start|>
urlpatterns = patterns(
'',
url(r'^game/update/(?P<pk>\w+)/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.game import views)
and context including class names, function names, or small code snippets from other files:
# Path: hubcave/game/views.py
# class GameRedirectView(RedirectView):
# class GameDetail(DetailView):
# class GameUpdate(UpdateView):
# def get_redirect_url(self, *args, **kwargs):
# def get_template_names(self):
# def get_context_data(self, **kwargs):
# def dispatch(self, request, *args, **kwargs):
# def form_valid(self, form):
. Output only the next line. | login_required(views.GameUpdate.as_view(), login_url='/'), |
Predict the next line for this snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^profile/(?P<pk>\w+)/$',
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.userprofile.views import ProfileDetail
and context from other files:
# Path: hubcave/userprofile/views.py
# class ProfileDetail(DetailView):
# model = User
#
# def dispatch(self, request, *args, **kwargs):
# return super(ProfileDetail, self).dispatch(request, *args, **kwargs)
#
# def get_template_names(self):
# return ['userprofile/profile_detail.html']
#
# def get_context_data(self, **kwargs):
# # Call the base implementation first to get a context
# context = super(ProfileDetail, self).get_context_data(**kwargs)
# context['users_games'] = Game.objects.filter(user=self.object)
# profile = UserProfile.objects.get_or_create(user=self.object)
# return context
, which may contain function names, class names, or code. Output only the next line. | login_required(ProfileDetail.as_view(), login_url='/'), |
Given the code snippet: <|code_start|>
socketio.sdjango.autodiscover()
admin.autodiscover()
urlpatterns = patterns(
'',
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from hubcave.core import views
import socketio.sdjango
and context (functions, classes, or occasionally code) from other files:
# Path: hubcave/core/views.py
# class Index(TemplateView):
# def dispatch(self, request, *args, **kwargs):
. Output only the next line. | url(r'^$', views.Index.as_view(), name='index'), |
Next line prediction: <|code_start|>
# Create your views here.
class ProfileDetail(DetailView):
model = User
def dispatch(self, request, *args, **kwargs):
return super(ProfileDetail, self).dispatch(request, *args, **kwargs)
def get_template_names(self):
return ['userprofile/profile_detail.html']
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(ProfileDetail, self).get_context_data(**kwargs)
context['users_games'] = Game.objects.filter(user=self.object)
<|code_end|>
. Use current file imports:
(from django.shortcuts import render
from django.views.generic import UpdateView, DetailView, CreateView
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth.models import User
from hubcave.userprofile.models import UserProfile
from hubcave.game.models import Game)
and context including class names, function names, or small code snippets from other files:
# Path: hubcave/userprofile/models.py
# class UserProfile(models.Model):
# user = models.ForeignKey(User)
# gold = models.IntegerField(default=0)
# health = models.IntegerField(default=100)
#
# Path: hubcave/game/models.py
# class Game(models.Model):
# user = models.ForeignKey(User)
# repository = models.CharField(max_length=255, unique=True)
# map_data = models.BinaryField(null=True)
# starting_x = models.IntegerField(null=True)
# starting_y = models.IntegerField(null=True)
# map_type = models.CharField(max_length=255, default="maze")
# updated = models.DateTimeField(default=datetime.now, blank=True)
# # Whether the repo has been deleted on GitHub, not in the game.
# repository_deleted = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "{}/{}".format(self.user, self.repository)
#
# @property
# def token(self):
# return self.user.social_auth.get(provider='github').extra_data['access_token']
#
# def api_repo(self):
# """
# Query github API for data necessary to build map. Update the
# object instance with size and commits
# """
#
# g = Github(self.token)
# return g.get_user().get_repo(self.repository)
#
# def generate_or_update_map(self):
# if self.map_data is None:
# self.generate_map()
# else:
# self.update_map()
#
# def update_map(self):
# repo = self.api_repo()
#
# commits = repo.get_commits(since=self.updated)
# self.updated = datetime.now()
# self.save()
#
# for c in commits:
# i = Item.objects.get(kind='gold')
# self.drop_item(i)
#
# def generate_map(self):
# """
# """
# # self.update_repo_magnitude()
# gmap = Map()
#
# structure = None
# if self.map_type == "cave":
# (starting_x, starting_y), structure = random_walk()
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# else:
# map_size = 10
# (starting_x, starting_y), structure = min_cost_spanning_tree(map_size, map_size)
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# for i, row in enumerate(structure):
# for j, el in enumerate(row):
# blk = gmap.blockdata.add()
# blk.blktype = el
# blk.x = i
# blk.y = j
# self.map_data = gmap.SerializeToString()
# self.save()
#
# def map_dict(self):
# gmap = Map()
# gmap.ParseFromString(self.map_data)
# return protobuf_to_dict(gmap)
#
# def points_dict(self):
# ret = {}
# max_x = max_y = 0
# d = self.map_dict()
# for b in d['blockdata']:
# if b['x'] not in ret:
# ret[b['x']] = {}
# ret[b['x']][b['y']] = b['blktype']
# if b['x'] > max_x:
# max_x = b['x']
# if b['y'] > max_y:
# max_y = b['y']
#
# return (ret, max_x, max_y)
#
# def drop_item(self, item, item_location=None):
# """
# Drop an item onto the map, either at a random or specified
# location
# """
# if not item_location:
# d, max_x, max_y = self.points_dict()
# while True:
# item_location = (floor(random()*max_x),
# floor(random()*max_y))
# if d[item_location[0]][item_location[1]]:
# break
#
# print "Dropping item {} in {}".format(item.kind, self.repository)
# return MapItem.objects.create(game=self,
# item=item,
# x=item_location[0],
# y=item_location[1])
. Output only the next line. | profile = UserProfile.objects.get_or_create(user=self.object) |
Here is a snippet: <|code_start|>
# Create your views here.
class ProfileDetail(DetailView):
model = User
def dispatch(self, request, *args, **kwargs):
return super(ProfileDetail, self).dispatch(request, *args, **kwargs)
def get_template_names(self):
return ['userprofile/profile_detail.html']
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(ProfileDetail, self).get_context_data(**kwargs)
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render
from django.views.generic import UpdateView, DetailView, CreateView
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth.models import User
from hubcave.userprofile.models import UserProfile
from hubcave.game.models import Game
and context from other files:
# Path: hubcave/userprofile/models.py
# class UserProfile(models.Model):
# user = models.ForeignKey(User)
# gold = models.IntegerField(default=0)
# health = models.IntegerField(default=100)
#
# Path: hubcave/game/models.py
# class Game(models.Model):
# user = models.ForeignKey(User)
# repository = models.CharField(max_length=255, unique=True)
# map_data = models.BinaryField(null=True)
# starting_x = models.IntegerField(null=True)
# starting_y = models.IntegerField(null=True)
# map_type = models.CharField(max_length=255, default="maze")
# updated = models.DateTimeField(default=datetime.now, blank=True)
# # Whether the repo has been deleted on GitHub, not in the game.
# repository_deleted = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "{}/{}".format(self.user, self.repository)
#
# @property
# def token(self):
# return self.user.social_auth.get(provider='github').extra_data['access_token']
#
# def api_repo(self):
# """
# Query github API for data necessary to build map. Update the
# object instance with size and commits
# """
#
# g = Github(self.token)
# return g.get_user().get_repo(self.repository)
#
# def generate_or_update_map(self):
# if self.map_data is None:
# self.generate_map()
# else:
# self.update_map()
#
# def update_map(self):
# repo = self.api_repo()
#
# commits = repo.get_commits(since=self.updated)
# self.updated = datetime.now()
# self.save()
#
# for c in commits:
# i = Item.objects.get(kind='gold')
# self.drop_item(i)
#
# def generate_map(self):
# """
# """
# # self.update_repo_magnitude()
# gmap = Map()
#
# structure = None
# if self.map_type == "cave":
# (starting_x, starting_y), structure = random_walk()
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# else:
# map_size = 10
# (starting_x, starting_y), structure = min_cost_spanning_tree(map_size, map_size)
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# for i, row in enumerate(structure):
# for j, el in enumerate(row):
# blk = gmap.blockdata.add()
# blk.blktype = el
# blk.x = i
# blk.y = j
# self.map_data = gmap.SerializeToString()
# self.save()
#
# def map_dict(self):
# gmap = Map()
# gmap.ParseFromString(self.map_data)
# return protobuf_to_dict(gmap)
#
# def points_dict(self):
# ret = {}
# max_x = max_y = 0
# d = self.map_dict()
# for b in d['blockdata']:
# if b['x'] not in ret:
# ret[b['x']] = {}
# ret[b['x']][b['y']] = b['blktype']
# if b['x'] > max_x:
# max_x = b['x']
# if b['y'] > max_y:
# max_y = b['y']
#
# return (ret, max_x, max_y)
#
# def drop_item(self, item, item_location=None):
# """
# Drop an item onto the map, either at a random or specified
# location
# """
# if not item_location:
# d, max_x, max_y = self.points_dict()
# while True:
# item_location = (floor(random()*max_x),
# floor(random()*max_y))
# if d[item_location[0]][item_location[1]]:
# break
#
# print "Dropping item {} in {}".format(item.kind, self.repository)
# return MapItem.objects.create(game=self,
# item=item,
# x=item_location[0],
# y=item_location[1])
, which may include functions, classes, or code. Output only the next line. | context['users_games'] = Game.objects.filter(user=self.object) |
Given the following code snippet before the placeholder: <|code_start|>"""
This is a hacky way of having items do arbitrary things
"""
def add_to_inventory(ns, item):
def check_size():
<|code_end|>
, predict the next line using imports from the current file:
from hubcave.game.models import InventoryItem, StackableInventoryItem
and context including class names, function names, and sometimes code from other files:
# Path: hubcave/game/models.py
# class InventoryItem(models.Model):
# inventory = models.ForeignKey(Inventory, related_name="items")
# item = models.ForeignKey(Item, related_name="i_instances")
#
# objects = InheritanceManager()
#
# class StackableInventoryItem(InventoryItem):
# count = models.IntegerField()
. Output only the next line. | if len(InventoryItem.objects.filter(inventory=ns.inventory)) > 9: |
Given snippet: <|code_start|>"""
This is a hacky way of having items do arbitrary things
"""
def add_to_inventory(ns, item):
def check_size():
if len(InventoryItem.objects.filter(inventory=ns.inventory)) > 9:
raise Exception("Can't add any more")
if not item.item.stackable:
check_size()
new_item = InventoryItem.objects.create(inventory=ns.inventory,
item=item.item)
else:
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from hubcave.game.models import InventoryItem, StackableInventoryItem
and context:
# Path: hubcave/game/models.py
# class InventoryItem(models.Model):
# inventory = models.ForeignKey(Inventory, related_name="items")
# item = models.ForeignKey(Item, related_name="i_instances")
#
# objects = InheritanceManager()
#
# class StackableInventoryItem(InventoryItem):
# count = models.IntegerField()
which might include code, classes, or functions. Output only the next line. | new_item = StackableInventoryItem.objects.get( |
Using the snippet: <|code_start|>
# Add the project to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
sys.stdout = sys.stderr
# Configure the application (Logan)
configure()
<|code_end|>
, determine the next line of code. You have imports:
import os
import os.path
import sys
from thread import start_new_thread
from hubcave.utils.runner import configure
from hubcave.game.management.commands.runserver_socketio import run_socket_server, get_handler
from django.core.wsgi import get_wsgi_application
and context (class names, function names, or code) available:
# Path: hubcave/utils/runner.py
# def configure():
# configure_app(
# project='hubcave',
# default_config_path='~/.hubcave/settings.py',
# default_settings='hubcave.core.settings.base',
# settings_initializer=generate_settings,
# settings_envvar='HUBCAVE_CONF',
# )
#
# Path: hubcave/game/management/commands/runserver_socketio.py
# def run_socket_server(addr, port, *args, **options):
# bind = (addr, int(port))
# print
# print "SocketIOServer running on %s:%s" % bind
# print
# handler = get_handler(*args, **options)
# server = SocketIOServer(bind, handler,
# heartbeat_interval=5,
# heartbeat_timeout=30,
# resource="socket.io",
# policy_server=True)
# server.serve_forever()
#
# def get_handler(*args, **options):
# """
# Returns the django.contrib.staticfiles handler.
# """
# handler = WSGIHandler()
# try:
# from django.contrib.staticfiles.handlers import StaticFilesHandler
# except ImportError:
# return handler
# use_static_handler = options.get('use_static_handler', True)
# insecure_serving = options.get('insecure_serving', False)
# if (settings.DEBUG and use_static_handler or
# (use_static_handler and insecure_serving)):
# handler = StaticFilesHandler(handler)
# return handler
. Output only the next line. | start_new_thread(run_socket_server, ("0.0.0.0", "8018")) |
Here is a snippet: <|code_start|>
# Create your models here.
class Dashboard(models.Model):
user = models.ForeignKey(User)
@property
def token(self):
return self.user.social_auth.get(provider='github').extra_data['access_token']
def get_or_update_games(self):
"""
Update the game list for the user. Do not prune deleted repositories
"""
g = Github(self.token)
gh_user = g.get_user()
all_repos = filter(lambda r: not r.fork, gh_user.get_repos())
new_repos = []
try:
<|code_end|>
. Write the next line using the current file imports:
from github import Github
from django.db import models
from django.contrib.auth.models import User
from hubcave.game.models import Game
and context from other files:
# Path: hubcave/game/models.py
# class Game(models.Model):
# user = models.ForeignKey(User)
# repository = models.CharField(max_length=255, unique=True)
# map_data = models.BinaryField(null=True)
# starting_x = models.IntegerField(null=True)
# starting_y = models.IntegerField(null=True)
# map_type = models.CharField(max_length=255, default="maze")
# updated = models.DateTimeField(default=datetime.now, blank=True)
# # Whether the repo has been deleted on GitHub, not in the game.
# repository_deleted = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "{}/{}".format(self.user, self.repository)
#
# @property
# def token(self):
# return self.user.social_auth.get(provider='github').extra_data['access_token']
#
# def api_repo(self):
# """
# Query github API for data necessary to build map. Update the
# object instance with size and commits
# """
#
# g = Github(self.token)
# return g.get_user().get_repo(self.repository)
#
# def generate_or_update_map(self):
# if self.map_data is None:
# self.generate_map()
# else:
# self.update_map()
#
# def update_map(self):
# repo = self.api_repo()
#
# commits = repo.get_commits(since=self.updated)
# self.updated = datetime.now()
# self.save()
#
# for c in commits:
# i = Item.objects.get(kind='gold')
# self.drop_item(i)
#
# def generate_map(self):
# """
# """
# # self.update_repo_magnitude()
# gmap = Map()
#
# structure = None
# if self.map_type == "cave":
# (starting_x, starting_y), structure = random_walk()
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# else:
# map_size = 10
# (starting_x, starting_y), structure = min_cost_spanning_tree(map_size, map_size)
# self.starting_x = starting_x
# gmap.starting_x = starting_x
# self.starting_y = starting_y
# gmap.starting_y = starting_y
# for i, row in enumerate(structure):
# for j, el in enumerate(row):
# blk = gmap.blockdata.add()
# blk.blktype = el
# blk.x = i
# blk.y = j
# self.map_data = gmap.SerializeToString()
# self.save()
#
# def map_dict(self):
# gmap = Map()
# gmap.ParseFromString(self.map_data)
# return protobuf_to_dict(gmap)
#
# def points_dict(self):
# ret = {}
# max_x = max_y = 0
# d = self.map_dict()
# for b in d['blockdata']:
# if b['x'] not in ret:
# ret[b['x']] = {}
# ret[b['x']][b['y']] = b['blktype']
# if b['x'] > max_x:
# max_x = b['x']
# if b['y'] > max_y:
# max_y = b['y']
#
# return (ret, max_x, max_y)
#
# def drop_item(self, item, item_location=None):
# """
# Drop an item onto the map, either at a random or specified
# location
# """
# if not item_location:
# d, max_x, max_y = self.points_dict()
# while True:
# item_location = (floor(random()*max_x),
# floor(random()*max_y))
# if d[item_location[0]][item_location[1]]:
# break
#
# print "Dropping item {} in {}".format(item.kind, self.repository)
# return MapItem.objects.create(game=self,
# item=item,
# x=item_location[0],
# y=item_location[1])
, which may include functions, classes, or code. Output only the next line. | all_games = Game.objects.filter(user=self.user) |
Continue the code snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^dashboard/$',
<|code_end|>
. Use current file imports:
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.dashboard.views import DashboardView
and context (classes, functions, or code) from other files:
# Path: hubcave/dashboard/views.py
# class DashboardView(TemplateView):
# template_name = 'dashboard.html'
#
# def active_users(self):
# # Query all non-expired sessions
# sessions = Session.objects.filter(expire_date__gte=datetime.now())
# uid_list = []
#
# # Build a list of user ids from that query
# for session in sessions:
# data = session.get_decoded()
# uid_list.append(data.get('_auth_user_id', None))
#
# # Query all logged in users based on id list
# return User.objects.filter(id__in=uid_list)
#
# def get_context_data(self, **kwargs):
# context = super(DashboardView, self).get_context_data(**kwargs)
# # Display repositories
# dash, _ = Dashboard.objects.get_or_create(user=self.request.user)
# inventory, _ = Inventory.objects.get_or_create(user=self.request.user)
# try:
# dash.get_or_update_games()
# except:
# print("Failed to get or update games")
#
# context['popular_games'] = Game.objects.annotate(Count('players')).order_by('-players__count')[:15]
# context['sidebar_users'] = self.active_users()
# context['sidebar_games'] = Game.objects.filter(user=self.request.user)
# return context
. Output only the next line. | login_required(DashboardView.as_view(), login_url='/'), |
Based on the snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choices)
class UserPolicyForm(forms.Form):
MAX_POLICIES = 8
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.contrib.auth.models import User
from tutelary.models import Policy
from .models import Organisation, Project
and context (classes, functions, sometimes code) from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# Path: example/exampleapp/models.py
# class Organisation(models.Model):
# name = models.CharField(max_length=100)
#
# class Meta:
# ordering = ('name',)
#
# class TutelaryMeta:
# perm_type = 'organisation'
# path_fields = ('name',)
# actions = [
# ('organisation.list', {'permissions_object': None}),
# ('organisation.create', {'permissions_object': None}),
# 'organisation.delete'
# ]
#
# def __str__(self):
# return self.name
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# organisation = models.ForeignKey(Organisation)
#
# class Meta:
# ordering = ('organisation', 'name')
#
# class TutelaryMeta:
# perm_type = 'project'
# path_fields = ('organisation', 'name')
# actions = [
# ('project.list', {'permissions_object': 'organisation'}),
# ('project.create', {'permissions_object': 'organisation'}),
# 'project.delete'
# ]
#
# def __str__(self):
# return self.name
. Output only the next line. | policy = forms.ModelChoiceField(queryset=Policy.objects.all(), |
Predict the next line after this snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choices)
class UserPolicyForm(forms.Form):
MAX_POLICIES = 8
policy = forms.ModelChoiceField(queryset=Policy.objects.all(),
required=False)
organisation = forms.ModelChoiceField(
<|code_end|>
using the current file's imports:
from django import forms
from django.contrib.auth.models import User
from tutelary.models import Policy
from .models import Organisation, Project
and any relevant context from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# Path: example/exampleapp/models.py
# class Organisation(models.Model):
# name = models.CharField(max_length=100)
#
# class Meta:
# ordering = ('name',)
#
# class TutelaryMeta:
# perm_type = 'organisation'
# path_fields = ('name',)
# actions = [
# ('organisation.list', {'permissions_object': None}),
# ('organisation.create', {'permissions_object': None}),
# 'organisation.delete'
# ]
#
# def __str__(self):
# return self.name
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# organisation = models.ForeignKey(Organisation)
#
# class Meta:
# ordering = ('organisation', 'name')
#
# class TutelaryMeta:
# perm_type = 'project'
# path_fields = ('organisation', 'name')
# actions = [
# ('project.list', {'permissions_object': 'organisation'}),
# ('project.create', {'permissions_object': 'organisation'}),
# 'project.delete'
# ]
#
# def __str__(self):
# return self.name
. Output only the next line. | queryset=Organisation.objects.all(), empty_label='*', required=False |
Predict the next line after this snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choices)
class UserPolicyForm(forms.Form):
MAX_POLICIES = 8
policy = forms.ModelChoiceField(queryset=Policy.objects.all(),
required=False)
organisation = forms.ModelChoiceField(
queryset=Organisation.objects.all(), empty_label='*', required=False
)
project = forms.ModelChoiceField(
<|code_end|>
using the current file's imports:
from django import forms
from django.contrib.auth.models import User
from tutelary.models import Policy
from .models import Organisation, Project
and any relevant context from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# Path: example/exampleapp/models.py
# class Organisation(models.Model):
# name = models.CharField(max_length=100)
#
# class Meta:
# ordering = ('name',)
#
# class TutelaryMeta:
# perm_type = 'organisation'
# path_fields = ('name',)
# actions = [
# ('organisation.list', {'permissions_object': None}),
# ('organisation.create', {'permissions_object': None}),
# 'organisation.delete'
# ]
#
# def __str__(self):
# return self.name
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# organisation = models.ForeignKey(Organisation)
#
# class Meta:
# ordering = ('organisation', 'name')
#
# class TutelaryMeta:
# perm_type = 'project'
# path_fields = ('organisation', 'name')
# actions = [
# ('project.list', {'permissions_object': 'organisation'}),
# ('project.create', {'permissions_object': 'organisation'}),
# 'project.delete'
# ]
#
# def __str__(self):
# return self.name
. Output only the next line. | queryset=Project.objects.all(), empty_label='*', required=False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.