Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> report += f"{''.join(footers_f)}\n"
return report
def get_flat_report_header(headers, width=14):
header_lists = get_flat_report_header_lists(headers, width)
report_header = ""
for i in range(len(header_lists[0])):
row = [line[i] for line in header_lists]
... | parts = re.split(HEADER_SPLIT, header) |
Here is a snippet: <|code_start|> footers = rows[FOOTER_ROW][:ACCOUNT_PAYEE_COLUMN]
dashes = [f"{'-' * (AMOUNT_WIDTH - 2):>{AMOUNT_WIDTH}}" for x in footers]
footers_f = [util.get_colored_amount(t, AMOUNT_WIDTH) for t in footers]
report += f"{Colorable('white', ''.join(dashes))}\n"
report += f"{''.jo... | for header in headers: |
Here is a snippet: <|code_start|>
with futures.ThreadPoolExecutor(max_workers=50) as executor:
to_do = []
ending = ()
for period_name in period_names:
if current_period and current_period == period_name:
ending = ("--end", "tomorrow")
future = executo... | return period_name, column |
Predict the next line for this snippet: <|code_start|> # double count them in line items but not in the total.
# In the column total, which is "our" total and what will be shown in
# the report, we will get the wrong sum. Let's warn when this happens.
# (Which means ledgerbil's stance is that you really... | "--depth", |
Given snippet: <|code_start|> if args.transpose:
rows = list(map(list, zip(*rows)))
if args.csv:
return get_csv_report(rows, tabs=args.tab)
if args.transpose:
# Move account/payee back to the right side
for row in rows:
row.append(row.pop(0))
return get_flat... | AMOUNT_WIDTH = 14 # width of columns with amounts |
Continue the code snippet: <|code_start|> else:
networth = 0
column = {"net worth": networth}
return column
def get_rows(
row_headers,
columns,
period_names,
sort=SORT_DEFAULT,
limit_rows=0,
total_only=False,
no_total=False,
):
ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
... | reverse_sort = False |
Given snippet: <|code_start|>
class OwnerOnly:
__slots__ = ('bot',)
def __init__(self, bot: Yasen):
self.bot = bot
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from discord import Forbidden, TextChannel
from discord.embeds import Embed
from discord.ext.command... | async def __local_check(self, ctx: Context): |
Given snippet: <|code_start|>
class ConvertRegion(Converter):
__slots__ = ()
async def convert(self, ctx, argument) -> Region:
try:
return Region[str(argument).upper()] if argument else Region.NA
except KeyError:
raise BadArgument('Please enter a region in `NA, EU, RU,... | if id_ is not None: |
Here is a snippet: <|code_start|> raise BadArgument('Please enter a region in `NA, EU, RU, AS`')
async def get_player_id(ctx: Context, name, region: Region):
if not name:
raise BadArgument('Please enter a player name.')
bot = ctx.bot
wows_api = bot.wows_api
logger = bot.logger
d... | async def get_clan_id(ctx: Context, name, region: Region): |
Using the snippet: <|code_start|> data_manager = bot.data_manager
members, _ = leading_members(ctx, name)
if not members:
id_ = await gpid(region, wows_api, logger, name)
if id_ is not None:
return id_
raise BadArgument(f'Player **{name}** not found!')
member = members... | raise BadArgument(f'Clan **{name}** not found!') |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Gets information from ENVI header file and prints this to screen or saves
to a text file.
Author: Dan Clewley
Creation Date: 07/08/2015
read_hdr_file written by Ben Taylor
"""
###########################################################
# ... | a CSV file. |
Using the snippet: <|code_start|> "binning, temp, all", default = "fps, tint")
parser.add_argument("-c","--outcsv", required=False, type=str,
help="Output file to store values for each band to")
parser.add_argument("-k","--keep_order", required=False, actio... | } |
Using the snippet: <|code_start|> if os.path.isfile(args.targetheader[0] + '.bak'):
print("Backup file {}.bak already exists. Please remove "
"and retry".format(args.targetheader[0]), file=sys.stderr)
sys.exit(1)
shutil.copy2(args.targetheader[0],args.targetheade... | run_copy_header(args.sourceheader[0], args.targetheader[0], args.keys) |
Continue the code snippet: <|code_start|>
class BookIndex(models.Model):
book_index_pk = models.AutoField(primary_key=True)
bytes = models.TextField()
filename = models.CharField(max_length=255)
mimetype = models.CharField(max_length=50)
class BookPages(models.Model):
book_pages_pk = models.AutoFi... | upload_to='model_filefields_example.BookPages/bytes/filename/mimetype', |
Next line prediction: <|code_start|> blank=True, null=True
)
pages = models.FileField(
upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
blank=True, null=True
)
cover = models.ImageField(
upload_to='model_filefields_example.BookCover/bytes/filename/mi... | filename = models.CharField(max_length=255) |
Here is a snippet: <|code_start|> )
pages = models.FileField(
upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
blank=True, null=True
)
cover = models.ImageField(
upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
blank=True, null... | mimetype = models.CharField(max_length=50) |
Continue the code snippet: <|code_start|># project
urlpatterns = [
url(r'^download/', views.get_file, {'add_attachment_headers': True},
name='db_file_storage.download_file'),
url(r'^get/', views.get_file, {'add_attachment_headers': False},
<|code_end|>
. Use current file imports:
from . import views
... | name='db_file_storage.get_file') |
Given the code snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='name',
mimety... | context = {'song': song, 'artist': artist, |
Given the code snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='name',
mimety... | form_list = list(form_list) |
Predict the next line after this snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='nam... | if sys.version_info.major == 3: # python3 |
Given snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
<|code_end|>
, continue by predicting the next line. C... | filename_field='name', |
Given the code snippet: <|code_start|>
saved_device = SoundDevice.objects.get(id=device_id)
saved_device.instruction_manual.open('r')
saved_device_file_content_string = \
saved_device.instruction_manual.read()
saved_device.instruction_manual.close()
self.assertEqual(... | self.assertEqual( |
Given the following code snippet before the placeholder: <|code_start|> save_new_url = reverse('model_files:book.add')
download_url = reverse('db_file_storage.download_file')
#
# Add "Inferno" book without index or pages.
#
form_data = {'name': 'Inferno'}
self.cli... | self.verify_file(url, 'inferno_index.txt') |
Here is a snippet: <|code_start|>
def get_file_path(file_name):
return os.path.join(settings.TEST_FILES_DIR, file_name)
class AddEditAndDeleteBooksTestCase(TestCase):
def test_download(self):
# Create book
save_url = reverse('model_files:book.add')
index_file = open(get_file_path('in... | def test_download_with_extra_headers(self): |
Predict the next line after this snippet: <|code_start|> # Assert that the mimetype of the saved file is correct
self.assertEqual(
mimetypes.guess_type(file_name)[0],
response['Content-Type']
)
def test_files_operations(self):
save_new_url = reverse('model_fil... | self.client.post(edit_inferno_url, form_data, follow=True) |
Continue the code snippet: <|code_start|> response = self.client.get(download_url)
self.assertEqual(response.status_code, 200)
# Invalid name
download_url = reverse('db_file_storage.download_file')
download_url += '?' + urlencode({'name': 'invalid_name'})
response = self.... | index_file = open(get_file_path('inferno_index.txt')) |
Continue the code snippet: <|code_start|> # Assert that the mimetype of the saved file is correct
self.assertEqual(
mimetypes.guess_type(file_name)[0],
response['Content-Type']
)
def test_files_operations(self):
save_new_url = reverse('model_files:book.add')
... | self.client.post(edit_inferno_url, form_data, follow=True) |
Predict the next line for this snippet: <|code_start|> 'index-clear': 'on'}
self.client.post(edit_lost_symbol_url, form_data, follow=True)
lost_symbol = Book.objects.get(name='Lost Symbol')
inferno = Book.objects.get(name='Inferno')
# Assert one BookIndex was deleted
... | self.assertEqual(lost_symbol.index.name, '') |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInp... | exclude = [] |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInp... | class Meta(object): |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInp... | } |
Given the following code snippet before the placeholder: <|code_start|># project
app_name = 'form_wizard_example'
urlpatterns = [
url(r'^song_lyrics/$', SongLyricsWizard.as_view(), name='song_lyrics'),
<|code_end|>
, predict the next line using imports from the current file:
from .views import SongLyricsWizard
... | ] |
Based on the snippet: <|code_start|> '0-song': 'Californication',
'0-artist': 'Red Hot Chili Peppers'
}
response = self.client.post(url, form_data)
self.assertEqual(response.status_code, 200)
# second step - file
path = os.path.join(settings.TEST_FILES_DIR... | some_lines = ( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# python
from __future__ import unicode_literals
# django
# third party
# project
class FormWizardTestCase(TestCase):
def test_fixed_model_storage_requires_fixed_model_fields(self):
with self.assertRaises(KeyError):
FixedModelDa... | 'song_lyrics_wizard-current_step': '0', |
Continue the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
name='bo... | CreateView.as_view( |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
<|code_end|>
, generate the next line using the imports in this file:
from django.views.generic i... | template_name='model_filefields_example/book_list.html' |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
<|code_end|>
, gene... | name='book.list' |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
name='book.... | CreateView.as_view( |
Predict the next line after this snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
<|code_end|>
using the current file's imports:
from django.views.generic impor... | template_name='model_filefields_example/book_list.html' |
Given snippet: <|code_start|> CreateView.as_view(
model=Book,
form_class=BookForm,
template_name='model_filefields_example/book_form.html',
success_url=reverse_lazy('model_files:book.list')
),
name='book.add'
),
url(
r'^books/edit/(?... | 'add_attachment_headers': True, |
Here is a snippet: <|code_start|> hbox.addStretch()
self.setLayout(hbox)
self.setFrameStyle(QFrame.Panel | QFrame.Raised)
self.setLineWidth(2)
self.setStyleSheet('QFrame{background-color: #999; border-radius: 10px;}')
class CheckableComboBox(QtGui.QComboBox):
def __init__(se... | newitem = QTableWidgetItem(str(item)) |
Given the code snippet: <|code_start|> if types:
ui_list.model().clear()
for typ in types:
for f in project.files:
item = QStandardItem(f['name'])
item.setDropEnabled(False)
if f['type'] != typ:
continue
i... | for i in range(widget.toolbutton.count()): |
Given the following code snippet before the placeholder: <|code_start|># def refresh_all_list(project, video_list, indices, last_manips_to_display=['All']):
# video_list.model().clear()
# for f in project.files:
# item = QStandardItem(f['name'])
# item.setDropEnabled(False)
# if f['type'... | ui_list.model().clear() |
Predict the next line after this snippet: <|code_start|> # + '.npy')
# widget.selected_videos = [x for x in widget.selected_videos if x != vidpath]
widget.selected_videos = []
for index in widget.video_list.selectedIndexes():
vidpath = str(os.path.normpath(os.path.join(widge... | }) |
Continue the code snippet: <|code_start|> required to allow ROIs to be drawn over the top of each other """
def __init__(self, radius, typ=None, pen=(200, 200, 220), parent=None, deletable=False):
pgROI.Handle.__init__(self,radius, typ, pen, parent, deletable)
self.setSelectable(True)
... | else: |
Given the code snippet: <|code_start|> def callback(value):
progress.setValue(int(value * 100))
QApplication.processEvents()
try:
fileconverter.raw2npy(filename, path, dtype, width, height, channels, channel, callback)
except:
warn_msg = "Continue trying to convert raw to npy despi... | qtutil.critical("Rebinning raw failed. Please check your scale factor. Use the Help -> 'Whats this' feature" |
Continue the code snippet: <|code_start|>
def get_size(self, path):
"""Method to get the size
"""
raise NotImplementedError(
"You must implement get_size(self, path) on your storage %s" %
self.__class__.__name__)
def fetch(name):
try:
# XXX The noqa belo... | in pkgutil.iter_modules(docker_registry.drivers.__path__)] |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
# this must happen before anything else
gevent.monkey.patch_all()
cfg = config.load()
if cfg.standalone:
# If standalone mode is enabled, load the fake Index routes
logger = logging.getLogger(__name__)
DES... | GUNICORN_GRACEFUL_TIMEOUT: timeout in seconds for graceful worker restart |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
# this must happen before anything else
gevent.monkey.patch_all()
cfg = config.load()
if cfg.standalone:
# If standalone mode is enabled, load the fake Index routes
logger = logging.getLogger(__name__)
DESCRIPTION... | GUNICORN_GROUP: unix group to downgrade priviledges to |
Based on the snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License... | assert resultdriver.scheme == self.scheme |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
_new_relic_ini = env.source('NEW_RELIC_INI')
if _new_relic_ini:
try:
newrelic.agent.initialize(
_new_relic_ini,
env.source('NEW_RELIC_STAGE'))
except Exception as e:
raise(Exception('Faile... | stderr_logger.setFormatter( |
Continue the code snippet: <|code_start|>
class UserProfileTest(TestCase):
def setUp(self):
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dickweed', 'email2@email.com', 'password')
self.up1 = UserProfile.objects.create(user=... | def test_user_profile_ownership(self): |
Continue the code snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dick... | self.t1.save() |
Predict the next line for this snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.crea... | def test_team_game_relationship(self): |
Predict the next line for this snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.crea... | def test_team_game_relationship(self): |
Predict the next line after this snippet: <|code_start|>
class UserFormTest(TestCase):
def setUp(self):
self.user_form_data = {
'username': 'sn1par_eugene',
'password': 'bloxwich',
'email': 'h00bastankR0x@aol.com'
}
self.user_profile_form_data = {
<|code_e... | 'name': "Eugene M'TnDew", |
Given snippet: <|code_start|>
class UserFormTest(TestCase):
def setUp(self):
self.user_form_data = {
'username': 'sn1par_eugene',
'password': 'bloxwich',
'email': 'h00bastankR0x@aol.com'
}
self.user_profile_form_data = {
'name': "Eugene M'TnDew... | } |
Next line prediction: <|code_start|> ast = data_tools.bash_parser(cmd)
if ast:
command = get_command(cmd)
print('extracted: {}'.format(cmd))
url.commands.add(command... | def populate_tag_commands(): |
Predict the next line for this snippet: <|code_start|> if not URLTag.objects.filter(url__str=url, tag=utility):
URLTag.objects.create(url=get_url(url), tag=utility)
print("Add {}, {}".format(url, utility))
def load_commands_in_url(stackoverflow_dump_path):
url_prefix = 'h... | cmd.tags.clear() |
Using the snippet: <|code_start|> url.commands.clear()
print(url.str)
for answer_body, in db.cursor().execute("""
SELECT answers.Body FROM answers
WHERE answers.ParentId = ?""", (url.str[len(url_prefix):],)):
url.html_content = ... | if len(cmd.str) > 600: |
Given the following code snippet before the placeholder: <|code_start|> cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_par... | def populate_tag_annotations(): |
Using the snippet: <|code_start|> "tellina_learning_module")
sys.path.append(learning_module_dir)
CODE_REGEX = re.compile(r"<pre><code>([^<]+\n[^<]*)<\/code><\/pre>")
def extract_code(text):
for match in CODE_REGEX.findall(text):
if match.strip():
yield html... | with open(input_file_path, 'rb') as f: |
Given the following code snippet before the placeholder: <|code_start|>
learning_module_dir = os.path.join(os.path.dirname(__file__), '..', '..',
"tellina_learning_module")
sys.path.append(learning_module_dir)
CODE_REGEX = re.compile(r"<pre><code>([^<]+\n[^<]*)<\/code><\/pre>")
d... | cmd = cmd[:comment.start()] |
Using the snippet: <|code_start|> if cmd.startswith('# '):
cmd = cmd[2:]
comment = re.search(r'\s+#\s+', cmd)
if comment:
old_cmd = cmd
cmd = cmd[:comment.start()]
print('Remove comment: {} -> {}'.format(old_cmd, cmd))
cmd = cmd.strip()
... | print(url.str) |
Given the following code snippet before the placeholder: <|code_start|> url.html_content = answer_body
for code_block in extract_code(url.html_content):
for cmd in extract_oneliners_from_code(code_block):
ast = data_tools.bash_parser(cmd)
... | cmd.template = template |
Here is a snippet: <|code_start|> cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_parser(cmd.str)
template = da... | def populate_tag_annotations(): |
Here is a snippet: <|code_start|> if Command.objects.filter(str=command_str).exists():
cmd = Command.objects.get(str=command_str)
else:
cmd = Command.objects.create(str=command_str)
ast = data_tools.bash_parser(command_str)
for utility in data_tools.get_utilities(ast):
... | d.update({'status': status}) |
Predict the next line for this snippet: <|code_start|> html = urllib.request.urlopen(hypothes_prefix + url, timeout=2)
except urllib.error.URLError:
print("Error: extract_text_from_url() urllib2.URLError")
# return "", randomstr(180)
return None, None
except socket.timeout:
... | cmd.template = template |
Continue the code snippet: <|code_start|> return None, None
except ssl.SSLError:
print("Error: extract_text_from_url() ssl.SSLError")
# return "", randomstr(180)
return None, None
return html.read()
def get_nl(nl_str):
nl, _ = NL.objects.get_or_create(str=nl_str.strip())
... | def get_url(url_str): |
Predict the next line for this snippet: <|code_start|>
sys.path.append(os.path.join(
os.path.dirname(__file__), "..", "tellina_learning_module"))
# Number of translations to show
NUM_TRANSLATIONS = 20
def extract_html(url):
hypothes_prefix = "https://via.hypothes.is/"
<|code_end|>
with the help of curren... | try: |
Based on the snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
... | def crash_in_polygon(request): |
Given snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
@view_... | crashes_coll = request.db.crashes |
Based on the snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
... | request.response.content_type = 'application/json' |
Predict the next line for this snippet: <|code_start|> http403.status = 403
return http403
form = EditUserForm(request.POST or None, user=request.user)
if form.is_valid():
for key, value in form.cleaned_data.iteritems():
if key in ['gittip']:
continue
... | return render(request, template_name, |
Here is a snippet: <|code_start|>
if user.key != request.user.key:
http403 = HttpResponse("This ain't you!")
http403.status = 403
return http403
form = EditAddressForm(request.POST or None, user=user)
if form.is_valid():
for key, value in form.cleaned_data.iteritems():
... | auth = UserSocialAuth.objects.get(provider="email", uid=email) |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
args = '<project.json>'
help = 'Load projects from json file'
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('Must supply a JSON file of projects.')
with open(args[0], 'r') as project... | projects = json.loads(project_file.read()) |
Based on the snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^blog/$', ListView.as_view(model=Blog),
name="blog"),
url(r'^blog/(?P<slug>[-_\w]+)/$', DetailView.as_view(model=Blog),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import patte... | name="view_blog_post"), |
Given the code snippet: <|code_start|>
urlpatterns = patterns(
'july.game.views',
url(r'^leaders/$',
views.GameBoard.as_view(),
name='leaders'),
url(r'^leaders/(?P<year>\d{4})/(?P<month>\d{1,2})/((?P<day>\d{1,2})/)?$',
views.GameBoard.as_view(),
name='leaders'),
url(r'^... | name='locations'), |
Based on the snippet: <|code_start|>
class BlogAdmin(admin.ModelAdmin):
list_display = ['title', 'user', 'slug', 'posted', 'category']
raw_id_fields = ['user']
prepopulated_fields = {'slug': ['title']}
def get_changeform_initial_data(self, request):
# For Django 1.7
initial = {}
<|co... | initial['user'] = request.user.pk |
Using the snippet: <|code_start|>
class BlogAdmin(admin.ModelAdmin):
list_display = ['title', 'user', 'slug', 'posted', 'category']
raw_id_fields = ['user']
prepopulated_fields = {'slug': ['title']}
def get_changeform_initial_data(self, request):
# For Django 1.7
initial = {}
... | list_display = ['title', 'slug'] |
Next line prediction: <|code_start|>
v1_api = Api(api_name='v1')
v1_api.register(api.CommitResource())
v1_api.register(api.ProjectResource())
v1_api.register(api.UserResource())
v1_api.register(api.LocationResource())
v1_api.register(api.TeamResource())
admin.autodiscover()
urlpatterns = patterns(
'',
# Th... | url(r'^register/$', 'july.views.register', name="register"), |
Continue the code snippet: <|code_start|>
urlpatterns = patterns(
'july.people.views',
url(r'^(?P<username>[\w.@+-]+)/$',
views.UserProfile.as_view(),
name='member-profile'),
url(r'^(?P<username>[\w.@+-]+)/edit/$',
'edit_profile', name='edit-profile'),
url(r'^(?P<username>[\w.@... | 'delete_email', name='delete-email'), |
Predict the next line for this snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
<|code_end|>
with the help of current file imports:
import logging
from django.core.management.base import BaseCo... | action='store_true', |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
action='store_true',
dest='commit',
default=False,
help='Actually move the items.'),
... | fine = 0 |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
action='store_true',
<|code_end|>
using the current file's imports:
import logging
from django.core... | dest='commit', |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def markup(value):
extensions = ["markdown.extensions.nl2br"]
val = force_unicode(value)
html = markdown(val, extensions=extensions, enable_attributes=False)
return mark_... | return { |
Given the code snippet: <|code_start|> dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
else:
title = 'No title'
print 'NO TITLE:', path
if dom.find('author') != None and dom.f... | print 'MALFORMED:', path |
Based on the snippet: <|code_start|> copyright = ''
#this code is direct copy from db.py song_save
if dom.find('chunk/line') != None: #don't die if no content
content = ''
for line in dom.findall('chunk/line'):
content += re.sub('<c.*?c>', '', ET.tostring(line).replace('<lin... | pass #songbook not found, error thrown, lets add it to the db! |
Given the code snippet: <|code_start|> break # we found it and removed it -- done.
return songbooks
def sync_songs():
songlist = glob.glob('songs/*')
for song in songlist:
#print 'Song:', song
path = song.replace('\\', '/')
try:
if Song.byPath(path): #skip existing songs in the db
... | copyright = dom.find('copyright').text |
Next line prediction: <|code_start|>
def songbooks():
songbooks = [songbooks for songbooks in Songbook.select(orderBy=Songbook.q.title)]
songbooks.sort(key=lambda x: x.title.lower() or 'No Title')
# save and the remove the all songs songbook from the songbook list
for i in range(len(songbooks)):
if songb... | if dom.find('author') != None and dom.find('author').text != None: #don't die if no author |
Continue the code snippet: <|code_start|>except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):
turbogears.update_config(configfile="dev.cfg",
modulename="webapp.co... | title = 'No title' |
Given the code snippet: <|code_start|>#!/usr/bin/env python
try: # try c version for speed then fall back to python
except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):... | modulename="webapp.config") |
Using the snippet: <|code_start|>try: # try c version for speed then fall back to python
except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):
turbogears.update_config... | else: |
Next line prediction: <|code_start|>#
# This file is part of casiopeia.
#
# Copyright 2014-2016 Adrian Bürger, Moritz Diehl
#
# casiopeia is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3... | system = "system" |
Given the following code snippet before the placeholder: <|code_start|> n_p = 3
pdata_ref = np.random.rand(n_p, 2)
self.assertRaises(ValueError, \
inputchecks.check_parameter_data, pdata_ref, n_p)
class CheckMeasurementData(unittest.TestCase):
def setUp(self):
self.n... | assert_array_equal(ydata, ydata_ref) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.INFO)
START_TIME = time.time()
class RespHandler(object):
@classmethod
def on_open(self, ws):
logging.debug("Client connected")
to_send = {'act': 'login'}
ws.send(json.d... | to_send = {'act': 'sleep', 'req': 4} |
Given the following code snippet before the placeholder: <|code_start|>
class Test_API(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
... | found = self.sample.savvyize(path) |
Predict the next line for this snippet: <|code_start|> cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
for classifierpath in os.listdir(path):
if os.path.isfile(os.path.join(path, classi... | found = [module for module in found if not module.endswith('.pyc')] # NB Python3 is accounted |
Predict the next line for this snippet: <|code_start|>
class Test_API(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
for classifier... | found = self.sample.savvyize(path) |
Next line prediction: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.DEBUG)
START_TIME = time.time()
class RespHandler(object):
@classmethod
def on_error(self, ws, error):
logging.error(error)
@classmethod
def on_close(self, ws):
logging.debug("Closed")
... | def on_open(self, ws): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.