Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import re
from collections import OrderedDict
from django.contrib... | EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context' |
Predict the next line for this snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
<|code_end|>
with the help of current file imports:
import datetime
import re
from collections import OrderedDict
from django.contrib.... | EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context' |
Given snippet: <|code_start|>
# reserved bamboo keys
BAMBOO_RESERVED_KEY_PREFIX = '^^'
DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'dataset_id'
INDEX = BAMBOO_RESERVED_KEY_PREFIX + 'index'
PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id'
BAMBOO_RESERVED_KEYS = [
DATASET_ID,
INDEX,
PARE... | return add_constant_column(df, dataset_id, DATASET_ID) if not\ |
Next line prediction: <|code_start|>
def __parse_dates(dframe):
for i, dtype in enumerate(dframe.dtypes):
if dtype.type == np.object_:
column = dframe.columns[i]
new_column = _convert_column_to_date(dframe, column)
if not new_column is None:
dframe[col... | def __parse_dates_schema(dframe, schema): |
Next line prediction: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
def _add_bamboo_reserved_keys(self, value=1):
for key in BAMBOO_RESERVED_KEYS:
column = Series([value] * len(self.dframe))
... | self.dframe = self.dframe.join(column) |
Predict the next line after this snippet: <|code_start|> def test_add_parent_column(self):
value = 1
self._add_bamboo_reserved_keys(value)
for index, item in self.dframe[PARENT_DATASET_ID].iteritems():
self.assertEqual(item, value)
def test_remove_reserved_keys(self):
... | self.assertFalse(key in dframe.columns) |
Continue the code snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
def _add_bamboo_reserved_keys(self, value=1):
for key in BAMBOO_RESERVED_KEYS:
column = Series([value] * len(self.dframe... | column.name = key |
Next line prediction: <|code_start|>
def test_remove_reserved_keys(self):
self._add_bamboo_reserved_keys()
for key in BAMBOO_RESERVED_KEYS:
self.assertTrue(key in self.dframe.columns)
dframe = remove_reserved_keys(self.dframe)
for key in BAMBOO_RESERVED_KEYS:
... | column = Series([parent_id] * len_parent_rows) |
Given snippet: <|code_start|>
class TestVersion(TestBase):
def setUp(self):
TestBase.setUp(self)
self.controller = Version()
def test_index(self):
response = json.loads(self.controller.index())
response_keys = response.keys()
keys = [
'version',
... | 'branch', |
Predict the next line for this snippet: <|code_start|>
class TestVersion(TestBase):
def setUp(self):
TestBase.setUp(self)
self.controller = Version()
def test_index(self):
response = json.loads(self.controller.index())
response_keys = response.keys()
keys = [
... | 'description', |
Given snippet: <|code_start|># template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links t... | htmlhelp_basename = 'bamboodoc' |
Given the code snippet: <|code_start|>#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file n... | ('index', 'bamboo.tex', u'bamboo Documentation', |
Next line prediction: <|code_start|>
BROKER_BACKEND = 'mongodb'
BROKER_URL = 'mongodb://localhost:27017/%s' % settings.DATABASE_NAME
CELERY_RESULT_BACKEND = 'mongodb'
CELERY_MONGODB_BACKEND_SETTINGS = {
'host': 'localhost',
'port': 27017,
'database': settings.DATABASE_NAME,
'taskmeta_collection': 'celer... | CELERY_IMPORTS = ( |
Using the snippet: <|code_start|>
ERROR_RESPONSE_BODY = """
<html><body><p>Sorry, an error occured. We are working to resolve it.
</p><p>For more help please email the <a
href= 'https://groups.google.com/forum/#!forum/bamboo-dev'>bamboo-dev
list</a></p></body></html>"""
def handle_error():
cherr... | '[ERROR] 500 Error in Bamboo', |
Based on the snippet: <|code_start|>
def requires_async(func):
@wraps(func)
def wrapper(*args, **kwargs):
set_async(True)
result = func(*args, **kwargs)
set_async(False)
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import wraps
from bamboo.co... | return result |
Here is a snippet: <|code_start|>
def requires_async(func):
@wraps(func)
def wrapper(*args, **kwargs):
set_async(True)
result = func(*args, **kwargs)
set_async(False)
return result
return wrapper
def run_profiler(func):
@wraps(func)
def wrapper(*args, **kwargs):
... | return wrapper |
Next line prediction: <|code_start|> 'std(amount)': ['amount'],
'max(amount)': ['amount'],
'mean(amount)': ['amount'],
'median(amount)': ['amount'],
'min(amount)': ['amount'],
'sum(amount)': ['amount'],
'sum(gps_latitude)': ['gps_latitude'],
'ratio(amount, gps_latitude)': ['amount', 'gps_... | 'ratio(amount, gps_latitude)': 3.184639, |
Predict the next line after this snippet: <|code_start|>
class TestBamboo(TestBase):
def setUp(self):
TestBase.setUp(self)
def test_bambooapp(self):
# this tests that importing bamboo.bambooapp succeeds
pass
def test_pep8(self):
result = call(['pep8', '.'])
<|code_end|>
... | self.assertEqual(result, 0, "Code is not pep8.") |
Given the following code snippet before the placeholder: <|code_start|>
def group_join(groups, left, other):
if groups:
other.set_index(groups, inplace=True)
<|code_end|>
, predict the next line using imports from the current file:
from pandas import concat
from bamboo.core.aggregations import AGGREGATI... | return left.join(other, on=groups if len(groups) else None) |
Based on the snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
<|code_end|>
, predict the immediate next line with the help of imports:
from bamboo.lib.jsontools import df_to_json, df_to_jsondict
from bamboo.test... | def test_to_jsondict(self): |
Continue the code snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
<|code_end|>
. Use current file imports:
from bamboo.lib.jsontools import df_to_json, df_to_jsondict
from bamboo.tests.test_base import TestBase... | def test_to_jsondict(self): |
Using the snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
<|code_end|>
, determine the next line of code. You have imports:
from bamboo.lib.jsontools import df_to_json, df_to_jsondict
from bamboo.tests.test_bas... | def test_to_jsondict(self): |
Using the snippet: <|code_start|>
def parse_order_by(order_by):
if order_by:
if order_by[0] in ('-', '+'):
sort_dir, field = -1 if order_by[0] == '-' else 1, order_by[1:]
else:
sort_dir, field = 1, order_by
order_by = [(field, sort_dir)]
return order_by
<|cod... | def parse_dates_from_query(query, dataset): |
Given the following code snippet before the placeholder: <|code_start|>
def parse_order_by(order_by):
if order_by:
if order_by[0] in ('-', '+'):
sort_dir, field = -1 if order_by[0] == '-' else 1, order_by[1:]
else:
sort_dir, field = 1, order_by
<|code_end|>
, predict the ne... | order_by = [(field, sort_dir)] |
Given the code snippet: <|code_start|>
class TestDecorators(TestBase):
def setUp(self):
def test_func():
<|code_end|>
, generate the next line using the imports in this file:
from bamboo.tests import decorators as test_decorators
from bamboo.tests.test_base import TestBase
and context (functions, classe... | pass |
Using the snippet: <|code_start|>
class TestDecorators(TestBase):
def setUp(self):
def test_func():
pass
self._test_func = test_func
def _test_decorator(self, func):
wrapped_test_func = func(self._test_func)
self.assertTrue(hasattr(wrapped_test_func, '__call__'))
<... | wrapped_test_func() |
Predict the next line for this snippet: <|code_start|># future must be first
from __future__ import division
def extract_binary_children(parent):
children = [parent.value[0]]
for oper, val in parent.operator_operands(parent.value[1:]):
children.append(val)
<|code_end|>
with the help of current fi... | return children |
Next line prediction: <|code_start|># future must be first
from __future__ import division
def extract_binary_children(parent):
children = [parent.value[0]]
for oper, val in parent.operator_operands(parent.value[1:]):
children.append(val)
return children
<|code_end|>
. Use current file impor... | class EvalTerm(object): |
Based on the snippet: <|code_start|># future must be first
from __future__ import division
def extract_binary_children(parent):
children = [parent.value[0]]
for oper, val in parent.operator_operands(parent.value[1:]):
<|code_end|>
, predict the immediate next line with the help of imports:
import operator... | children.append(val) |
Predict the next line for this snippet: <|code_start|># future must be first
from __future__ import division
def extract_binary_children(parent):
children = [parent.value[0]]
for oper, val in parent.operator_operands(parent.value[1:]):
<|code_end|>
with the help of current file imports:
import operator
i... | children.append(val) |
Continue the code snippet: <|code_start|># future must be first
from __future__ import division
def extract_binary_children(parent):
children = [parent.value[0]]
for oper, val in parent.operator_operands(parent.value[1:]):
children.append(val)
<|code_end|>
. Use current file imports:
import opera... | return children |
Given the code snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
<|code_end|>
, generate the next line using the imports in this file:
from bamboo.lib.mongo import df_mongo_decode, MONGO_ID
from bamboo.tests.test_base import TestBase
and context (functions, classes... | self.dframe = self.get_data('good_eats.csv') |
Here is a snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
<|code_end|>
. Write the next line using the current file imports:
from bamboo.lib.mongo import df_mongo_decode, MONGO_ID
from bamboo.tests.test_base im... | def test_decode_reserved_keys(self): |
Predict the next line after this snippet: <|code_start|>
class TestFrame(TestBase):
def setUp(self):
TestBase.setUp(self)
self.dframe = self.get_data('good_eats.csv')
<|code_end|>
using the current file's imports:
from bamboo.lib.mongo import df_mongo_decode, MONGO_ID
from bamboo.tests.test_bas... | def test_decode_reserved_keys(self): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
sys.path.append(os.getcwd())
# use routes dispatcher
dispatcher = cherrypy.dispatch.RoutesDispatcher()
routes_conf = {'/': {'request.dispatch': dispatcher}}
local_conf = 'bamboo/config/local.conf'
# connect routes
connect_routes(dispatcher)
# global ... | app.merge(local_conf) |
Predict the next line after this snippet: <|code_start|>
register = Library()
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
<|code_e... | except VariableDoesNotExist: |
Here is a snippet: <|code_start|>
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
except VariableDoesNotExist:
return... | @register.tag |
Here is a snippet: <|code_start|> class Meta(object):
fields = ['content_type', 'name', 'position']
def __init__(self, *args, **kwargs):
qs = ContentType.objects.all()
content_type = ContentTypeChoiceField(
self.admin_site, qs, label=_('content type')
)
self.b... | can_order=can_order, can_delete=can_delete) |
Continue the code snippet: <|code_start|>
class GenericInlineModelAdmin(generic.GenericInlineModelAdmin,
InlineModelAdmin,
BaseModelAdmin):
pass
class GenericStackedInline(GenericInlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
<|co... | class GenericTabularInline(GenericInlineModelAdmin): |
Given the code snippet: <|code_start|>
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
# (r'^scorecard/agency/(?P<agency_id>\d+)/', 'metrics.views.get_agency_detail'),
# (r'^scorecard/program/(?P<program_id>\d+)/', '... | url(r'^methodology/', direct_to_template, {'template': 'methodology.html'}, name='methodology'), |
Given snippet: <|code_start|>"""Defines the format for agency submission files to USASpending, along with
a lazy record parser."""
class FAADSPlusFormat(object):
# Based on table from memo m09-19 pages 14-15, which defines the
# agency submission record format
FIELDS = [
('CFDA Program Number', ... | ('Recipient County Name', 'recipient_county_name', 21), |
Next line prediction: <|code_start|>
def find_possible_mistakes():
fins = Program.objects.filter(types_of_assistance__financial=True).distinct().order_by('agency')
csv_out = csv.writer(open('greater_than_50_pct_change.csv', 'w'))
for f in fins:
<|code_end|>
. Use current file imports:
(from metrics.models... | obs = ProgramObligation.objects.filter(type=1, program=f).order_by('fiscal_year') |
Predict the next line for this snippet: <|code_start|>
def parse_date(date_candidate):
formats = ('%Y-%m-%d', '%Y%m%d', '%m/%d/%Y', '%m/%d/%y')
for fmt in formats:
try:
parsed_date = datetime.strptime(date_candidate, fmt).date()
return parsed_date
<|code_end|>
with the help of ... | except ValueError: |
Predict the next line after this snippet: <|code_start|>
def update_obligation(new_obligation, program):
old_obligation = program.obligation
program.obligation = int(new_obligation)
if program.usaspending_obligation:
program.delta = program.usaspending_obligation - program.obligation
else:... | program.corrected = True |
Continue the code snippet: <|code_start|> for row in rows:
agg = USASpendingAggregate(fiscal_year=row['fiscal_year'])
agg.total_federal_funding = row['fed_funding_amount']
agg.save()
usa_query = "SELECT cfda_program_num, fiscal_year, SUM(fed_funding_amount) as fed_funding_amount, SUM(fac... | try: |
Continue the code snippet: <|code_start|>
#Metric for consistency in USASpending versus CFDA reported obligations
def fix_cfda():
#Identify possible cfda mistakes
fin_programs = Program.objects.filter(types_of_assistance__financial=True)
fin_obligations = ProgramObligation.objects.filter(program_... | outliers = over_programs.filter(weighted_delta__gte=str(avg_new)) |
Given snippet: <|code_start|>
print "----- Sample Size -----"
for fy in FISCAL_YEARS:
timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum']
usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=fy).total_federal_funding
sample_pct =... | print "----- Average Lag (program) -----" |
Given the following code snippet before the placeholder: <|code_start|>
print "----- Sample Size -----"
for fy in FISCAL_YEARS:
timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum']
usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=... | print "----- Average Lag (program) -----" |
Given the following code snippet before the placeholder: <|code_start|>
print "----- Sample Size -----"
for fy in FISCAL_YEARS:
timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum']
usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=... | print "%d: %d mean (days), %.1f stdev" % (fy, mean(lag_values), std(lag_values)) |
Given the code snippet: <|code_start|> self.assertEquals(getEdge(graphs[0], 1, 2), 1)
self.assertEquals(getEdge(graphs[0], 1, 18), 1)
self.assertEquals(getEdge(graphs[0],2, 3), 1)
self.assertEquals(getEdge(graphs[0],2, 19), 1)
self.assertEquals(getEdge(graphs[0],3, 4), 1)
... | self.assertEquals(graphs[1].getNumEdges(), 20) |
Using the snippet: <|code_start|> self.assertEquals(graphs[0].getNumVertices(), 26)
self.assertEquals(graphs[0].getNumEdges(), 28)
def getEdge(graph, i, j):
return graph.getEdge(i-1, j-1)
self.assertEquals(getEdge(graphs[0], 1, 6), 1)
self.assertEquals(getEdge(graphs... | self.assertEquals(getEdge(graphs[0],13, 15), 1) |
Continue the code snippet: <|code_start|>
self.assertEquals(graph.getEdge(0, 1), 1)
self.assertEquals(graph.getEdge(2, 4), 1)
self.assertEquals(graph.getEdge(2, 2), 1)
self.assertEquals(graph.getEdge(4, 0), 1)
#Now test reading a file with the same graph but vertices indexed dif... | self.assertEquals(graph.getEdge(4, 0), 1) |
Given the code snippet: <|code_start|>
class SimpleGraphReaderTest(unittest.TestCase):
def testReadGraph(self):
fileName = PathDefaults.getDataDir() + "test/simpleGraph.txt"
graphReader = SimpleGraphReader()
graph = graphReader.readFromFile(fileName)
<|code_end|>
, generate the next l... | logging.debug((graph.getAllEdges())) |
Here is a snippet: <|code_start|>
class PathDefaultsTestCase(unittest.TestCase):
def testGetProjectDir(self):
print((PathDefaults.getSourceDir()))
<|code_end|>
. Write the next line using the current file imports:
import unittest
from apgl.util.PathDefaults import PathDefaults
and context from... | def testGetDataDir(self): |
Given snippet: <|code_start|> return res
def _has_nonprintable_char(s):
chars = enumerate((unicodedata.category(char) == "Cc", char) for char in s)
for pos, (unprintable, char) in chars:
if unprintable:
return (
s.encode("unicode_escape").decode("utf-8"),
... | return path |
Given snippet: <|code_start|>def _flatten(t):
res = []
def flatten_rec(g):
if isinstance(g, str) or hasattr(g, "__fspath__"):
res.append(g)
elif isinstance(g, collections.abc.Mapping):
for k, v in g.items():
flatten_rec(v)
else:
for v ... | if not path: |
Based on the snippet: <|code_start|> res = []
def flatten_rec(g):
if isinstance(g, str) or hasattr(g, "__fspath__"):
res.append(g)
elif isinstance(g, collections.abc.Mapping):
for k, v in g.items():
flatten_rec(v)
else:
for v in g:
... | msg = 'Target "{}" has an empty {} path.'.format(target_name, mode) |
Here is a snippet: <|code_start|> if isinstance(g, str) or hasattr(g, "__fspath__"):
res.append(g)
elif isinstance(g, collections.abc.Mapping):
for k, v in g.items():
flatten_rec(v)
else:
for v in g:
flatten_rec(v)
flatten_r... | result = _has_nonprintable_char(path) |
Using the snippet: <|code_start|>class Backend:
"""Base class for backends."""
option_defaults = {}
log_manager = FileLogManager()
@classmethod
def list(cls):
"""Return the names of all registered backends."""
return set(_load_backends().keys())
@classmethod
def from_name(... | return cls.from_name(config["backend"]) |
Predict the next line after this snippet: <|code_start|> """Return the names of all registered backends."""
return set(_load_backends().keys())
@classmethod
def from_name(cls, name):
"""Return backend class for the backend given by `name`.
Returns the backend class registered wi... | def status(self, target): |
Here is a snippet: <|code_start|>
@classmethod
def list(cls):
"""Return the names of all registered backends."""
return set(_load_backends().keys())
@classmethod
def from_name(cls, name):
"""Return backend class for the backend given by `name`.
Returns the backend class... | def __exit__(self, exc_type, exc_val, exc_tb): |
Given the following code snippet before the placeholder: <|code_start|> """Return the names of all registered backends."""
return set(_load_backends().keys())
@classmethod
def from_name(cls, name):
"""Return backend class for the backend given by `name`.
Returns the backend clas... | def status(self, target): |
Using the snippet: <|code_start|>
if sys.version_info < (3, 10):
else:
logger = logging.getLogger(__name__)
__all__ = ("Backend", "Status")
def _load_backends():
<|code_end|>
, determine the next line of code. You have imports:
import sys
import logging
from importlib_metadata import entry_points
from i... | return {ep.name: ep.load() for ep in entry_points(group="gwf.backends")} |
Given the code snippet: <|code_start|>
def _find_exe(name):
exe = shutil.which(name)
if exe is None:
raise BackendError(
<|code_end|>
, generate the next line using the imports in this file:
import shutil
import subprocess
from .exceptions import BackendError
and context (functions, classes, or occa... | f'Could not find executable "{name}". This backend requires Slurm ' |
Predict the next line for this snippet: <|code_start|>
@click.command()
@click.option(
"-n",
"--num-workers",
type=int,
default=config.get("local.num_workers", multiprocessing.cpu_count()),
help="Number of workers to spawn.",
)
@click.option(
"-p",
"--port",
type=int,
default=conf... | ) |
Next line prediction: <|code_start|>
@click.command()
@click.option(
"-n",
"--num-workers",
type=int,
default=config.get("local.num_workers", multiprocessing.cpu_count()),
help="Number of workers to spawn.",
)
@click.option(
"-p",
"--port",
type=int,
default=config.get("local.port... | ) |
Using the snippet: <|code_start|>
def humanbool(x):
if x in ("true", "yes"):
return True
elif x in ("false", "no"):
return False
raise TypeError("x is not a boolean.")
<|code_end|>
, determine the next line of code. You have imports:
import click
from ..conf import config as _config
an... | def cast_value(value): |
Predict the next line after this snippet: <|code_start|>
banner = r"""
.-_'''-. .--. .--. ________
'_( )_ \ | |_ | || |
|(_ o _)| ' | _( )_ | || .----'
. (_,_)/___| |(_ o _) | || _|____
| | .-----.| (_,_) \ | ||_( )_ |
<|code_end|>
using the current file's imports:
from pathl... | ' \ '- .'| |/ \| |(_ o._)__| |
Next line prediction: <|code_start|>
banner = r"""
.-_'''-. .--. .--. ________
'_( )_ \ | |_ | || |
|(_ o _)| ' | _( )_ | || .----'
. (_,_)/___| |(_ o _) | || _|____
| | .-----.| (_,_) \ | ||_( )_ |
' \ '- .'| |/ \| |(_ o._)__|
\ `-'` | | ' /\ ` ||(_,_)
\ ... | `'-...-' `---' `---`'---'""" |
Next line prediction: <|code_start|>
class EntryMixin:
date_field = "pub_date"
model = Entry
class CategoryMixin:
model = Category
class EntryArchiveIndex(EntryMixin, generic.ArchiveIndexView):
pass
class EntryArchiveYear(EntryMixin, generic.YearArchiveView):
make_object_list = True
class ... | pass |
Next line prediction: <|code_start|>
class EntryMixin:
date_field = "pub_date"
model = Entry
<|code_end|>
. Use current file imports:
(from django.views import generic
from .models import Category, Entry)
and context including class names, function names, or small code snippets from other files:
# Path: ... | class CategoryMixin: |
Given the code snippet: <|code_start|>
@admin.register(License)
class LicenseAdmin(admin.ModelAdmin):
list_display = ("name",)
prepopulated_fields = {"slug": ("name",)}
class VersionInline(admin.StackedInline):
fields = ("version", "status", "release_date", "is_latest", "license")
model = Version
... | ) |
Next line prediction: <|code_start|>
@admin.register(License)
class LicenseAdmin(admin.ModelAdmin):
list_display = ("name",)
prepopulated_fields = {"slug": ("name",)}
class VersionInline(admin.StackedInline):
fields = ("version", "status", "release_date", "is_latest", "license")
model = Version
@... | ), |
Given the code snippet: <|code_start|>
@admin.register(License)
class LicenseAdmin(admin.ModelAdmin):
list_display = ("name",)
prepopulated_fields = {"slug": ("name",)}
class VersionInline(admin.StackedInline):
fields = ("version", "status", "release_date", "is_latest", "license")
model = Version
... | class ProjectAdmin(admin.ModelAdmin): |
Based on the snippet: <|code_start|>
class ProjectMixin(object):
model = Project
def get_queryset(self):
return super().get_queryset().public()
class VersionMixin(object):
model = Version
class ProjectDetail(ProjectMixin, generic.DetailView):
pass
class ProjectList(ProjectMixin, generi... | class VersionDetail(VersionMixin, generic.DetailView): |
Predict the next line after this snippet: <|code_start|>
class ProjectMixin(object):
model = Project
def get_queryset(self):
return super().get_queryset().public()
class VersionMixin(object):
model = Version
<|code_end|>
using the current file's imports:
import typing
from django.db import... | class ProjectDetail(ProjectMixin, generic.DetailView): |
Predict the next line for this snippet: <|code_start|>
app_name = "blog"
urlpatterns = [
path("entries/", EntriesFeed(), name="entries"),
path("categories/<slug:slug>/", CategoryFeed(), name="category"),
<|code_end|>
with the help of current file imports:
from django.urls import path
from blog.feeds impor... | ] |
Here is a snippet: <|code_start|>
app_name = "blog"
urlpatterns = [
path("", views.EntryArchiveIndex.as_view(), name="index"),
path("<int:year>/", views.EntryArchiveYear.as_view(), name="year"),
path("<int:year>/<str:month>/", views.EntryArchiveMonth.as_view(), name="month"),
path(
"<int:yea... | name="entry", |
Given the code snippet: <|code_start|> )
list_display = ("title", "slug", "num_live_entries")
list_display_links = ("title", "slug")
prepopulated_fields = {"slug": ("title",)}
def num_live_entries(self, obj: Category) -> int:
return obj.live_entries.count()
num_live_entries.short_desc... | def get_queryset(self, request: HttpRequest) -> models.QuerySet: |
Here is a snippet: <|code_start|>@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
fieldsets = (
("Metadata", {"fields": ("title", "slug")}),
(None, {"fields": ("description",)}),
)
list_display = ("title", "slug", "num_live_entries")
list_display_links = ("title", "slug"... | list_display_links = ("title",) |
Continue the code snippet: <|code_start|>
current_site = Site.objects.get_current()
class EntriesFeed(Feed):
author_name = "James Bennett"
copyright = "https://{}/about/copyright/".format(current_site.domain)
description = "Latest entriess"
feed_type = Atom1Feed
item_copyright = "https://{}/abo... | feed_url = "https://{}/feeds/entries/".format(current_site.domain) |
Given snippet: <|code_start|># encoding: utf-8
__all__ = [
u'encrypt',
u'encrypt_bytes',
u'decrypt',
u'decrypt_bytes',
]
logger = logging.getLogger(__name__)
def _prep_key(key=None):
key = key or settings.DJENGA_ENCRYPTION_KEY
return _as_bytes(key)
def _gcm_pack(header, cipher_text, tag... | values = [ b64encode(x).decode('utf-8') for x in values ] |
Using the snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djenga_tests.settings')
class DjengaCelery(Celery):
def __init__(self, main=None, loader=None, backend=Non... | autofinalize=autofinalize, namespace=namespace, |
Continue the code snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djenga_tests.settings')
class DjengaCelery(Celery):
def __init__(self, main=None, loader=None, bac... | autofinalize=True, namespace=None, strict_typing=True, |
Next line prediction: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> bytes:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
data = client.encrypt(KeyId=alias, Plaintext=plain_text)
return ... | return data.decode('utf-8') |
Next line prediction: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> bytes:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
<|code_end|>
. Use current file imports:
(from .helpers import _as_byt... | data = client.encrypt(KeyId=alias, Plaintext=plain_text) |
Here is a snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> bytes:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
data = client.encrypt(KeyId=alias, Plaintext=plain_text)
return da... | def decrypt_bytes( |
Next line prediction: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> bytes:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
data = client.encrypt(KeyId=alias, Plaintext=plain_text)
return... | data = decrypt_bytes(cipher_text, region, profile) |
Given the code snippet: <|code_start|>
__all__ = [ 'JsonFormatterTest', ]
log = logging.getLogger(__name__)
class JsonFormatterTest(TestCase):
def test_json_formatter(self):
formatter = JsonFormatter()
with self.assertLogs(log) as log_context:
for handler in log.handlers:
<|code_end|>... | handler.setFormatter(formatter) |
Next line prediction: <|code_start|>
__all__ = [ 'JsonFormatterTest', ]
log = logging.getLogger(__name__)
class JsonFormatterTest(TestCase):
def test_json_formatter(self):
formatter = JsonFormatter()
with self.assertLogs(log) as log_context:
for handler in log.handlers:
... | self.assertEquals('test exception', data['exception_args'][0]) |
Based on the snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
<|code_end|>
, predict the immediate next line with the help of imports:
... | response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') |
Here is a snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')
... | return plain_text |
Using the snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')
... | return plain_text |
Given the code snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')... | return value |
Given the code snippet: <|code_start|>
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')... | header = response['CiphertextBlob'] |
Predict the next line for this snippet: <|code_start|> plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> str:
client = _get_client(region, profile)
alias = _prefix_alias(alias)
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')
... | return data |
Given snippet: <|code_start|>
class Command(BaseCommand):
def add_arguments(self, parser: ArgumentParser):
parser.add_argument(
'-n', '--count',
dest='count',
type=int,
help='number of animal pairs to output',
metavar='count',
default=... | for _ in range(count): |
Given the code snippet: <|code_start|>
class ExampleTest(IntegrationTest):
def test_add(self):
x = 1 + 1
self.assert_equal(x, 2)
x += 5
<|code_end|>
, generate the next line using the imports in this file:
from djenga.test import IntegrationTest
and context (functions, classes, or occasio... | self.assert_equal(7, x) |
Next line prediction: <|code_start|>
class SecondTest(IntegrationTest):
def test_add(self):
x = 1 + 1
<|code_end|>
. Use current file imports:
(from djenga.test import IntegrationTest)
and context including class names, function names, or small code snippets from other files:
# Path: djenga/test/integra... | self.assert_equal(x, 2) |
Predict the next line after this snippet: <|code_start|>
def test_maximal():
items = map(frozenset, ((1,), (2,), (3,), (1, 2)))
assert set(tools.maximal(items)) == {frozenset([3]), frozenset([1, 2])}
def test_sha256sum(tmp_path):
filepath = tmp_path / 'spam.txt'
filepath.write_text('spam', encoding=... | assert result == '4e388ab32b10dc8dbc7e28144f552830adc74787c1e2c0824032078a79f227fb' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.