Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
@ajax()
def xhr_rss(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'profile/rss.html', {
'feed': get_rss_feed(user.profile.rss_url),
})
@login_required
def edit(request):
if request.method == '... | if request.method == 'POST': |
Continue the code snippet: <|code_start|>
class AutomaticLoginMiddleware(object):
def process_request(self, request):
token = request.GET.get(app_settings.KEY)
if not token:
return
r = redirect(strip_token(request.get_full_path()))
try:
pk = int(token.split... | try: |
Continue the code snippet: <|code_start|>
class AutomaticLoginMiddleware(object):
def process_request(self, request):
token = request.GET.get(app_settings.KEY)
if not token:
return
r = redirect(strip_token(request.get_full_path()))
try:
pk = int(token.split... | if getattr(request.user, 'pk', request.user.id) == pk: |
Predict the next line after this snippet: <|code_start|> try:
pk = int(token.split(':', 1)[0])
# Only change user if necessary. We strip the token in any case.
# The AnonymousUser class has no 'pk' attribute (#18093)
if getattr(request.user, 'pk', request.user.id)... | def render(self, request, user, token, path): |
Predict the next line after this snippet: <|code_start|> self.cleaned_data['first_name'],
self.cleaned_data['last_name'],
)
user = User(
is_active=False,
first_name=self.cleaned_data['first_name'],
last_name=self.cleaned_data['last_name'],
... | 'user': user, |
Next line prediction: <|code_start|>
@debug_required
def content(request):
current = []
if request.user.is_authenticated():
for field in User._meta.fields:
if field.name == 'password':
continue
current.append(
(field.attname, getattr(request.user... | @csrf_exempt |
Given the following code snippet before the placeholder: <|code_start|>
@debug_required
def content(request):
current = []
if request.user.is_authenticated():
<|code_end|>
, predict the next line using imports from the current file:
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from dj... | for field in User._meta.fields: |
Predict the next line for this snippet: <|code_start|> "Your email adddress was successfully confirmed.",
)
else:
messages.error(
request,
"There was an error confirming your email address.",
)
return redirect('profile:emails:view')
@login_required
de... | }) |
Predict the next line after this snippet: <|code_start|>def add(request):
if request.method == 'POST':
form = EmailForm(request.user, request.POST)
if form.is_valid():
form.send_email()
messages.success(
request,
"Please check your email inbo... | messages.error(request, "Cannot delete last remaining email address.") |
Given snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this d... | city = models.CharField(max_length=100, blank=True) |
Based on the snippet: <|code_start|>
class Profile(PerUserData('profile')):
account_type = EnumField(AccountEnum, default=AccountEnum.INDIVIDUAL)
biography = models.TextField()
display_name = models.CharField(max_length=100)
organisation = models.CharField(max_length=100, blank=True)
address_1 =... | return self.display_name |
Next line prediction: <|code_start|> 'country',
)
def clean_organisation(self):
val = self.cleaned_data['organisation']
if self.instance.account_type != AccountEnum.INDIVIDUAL and val == '':
raise forms.ValidationError(
"Required field for company/non... | username = forms.RegexField(regex=r'^[\w-]+$') |
Given snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this d... | 'rss_url', |
Given snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this d... | ): |
Using the snippet: <|code_start|> if request.method == 'POST':
form = ForgotPasswordForm(request.POST)
if form.is_valid():
form.save()
return redirect('passwords:forgot-password-done')
else:
form = ForgotPasswordForm()
return render(request, 'passwords/forg... | else: |
Based on the snippet: <|code_start|>
return redirect('passwords:forgot-password-done')
else:
form = ForgotPasswordForm()
return render(request, 'passwords/forgot_password.html', {
'form': form,
})
def forgot_password_done(request):
return render(request, 'passwords/forgot_... | }) |
Predict the next line for this snippet: <|code_start|>def add_edit(request, link_id=None):
if link_id:
link = get_object_or_404(request.user.links, pk=link_id)
else:
link = None
if request.method == 'POST':
form = LinkForm(request.POST, instance=link)
if form.is_valid():
... | @login_required |
Given the code snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory ... | if form.is_valid(): |
Predict the next line after this snippet: <|code_start|> if hasattr(base, 'items'):
items.extend(base.items.items())
for n, item in list(attrs.items()):
if isinstance(item, Item):
if item.value in used_values:
raise ValueError(
... | } |
Using the snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory of th... | ) |
Next line prediction: <|code_start|>
class GetName(QtGui.QDialog):
def __init__(self, caption, path, parent=None):
QtGui.QDialog.__init__(self, parent, QtCore.Qt.Window |
QtCore.Qt.WindowCloseButtonHint)
self.setWindowTitle(caption)
self.path = path
<|cod... | mainLayout = QtGui.QVBoxLayout() |
Predict the next line after this snippet: <|code_start|> def setUI(self, index):
self.useData.SETTINGS["UI"] = self.uiBox.currentText()
if index == 0:
self.mainApp.setStyleSheet(StyleSheet.globalStyle)
else:
self.mainApp.setStyleSheet(None)
isCustom = (index ==... | message = QtGui.QMessageBox.warning(self, "Export", str(err)) |
Here is a snippet: <|code_start|> self.setStyleSheet(StyleSheet.viewSwitcherStyle)
self.addButton(QtGui.QIcon(
os.path.join("Resources", "images", "notes_selected")), "Editor")
self.addButton(QtGui.QIcon(
os.path.join("Resources", "images", "notes")), "Snapshot")
... | self.buttonGroup.setId(button, self.lastIndex) |
Next line prediction: <|code_start|>
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
STATIC_SITEMAP_DIR = os.path.join(settings.PROJECT_ROOT,'apps/census/static/sitemap')
def dev_sitemap_serve(request, path, insecure=False, **kwargs):
path = path.lstrip('/')
<|code_end|>
. Use current ... | absolute_path = os.path.join(STATIC_SITEMAP_DIR,path) |
Given the following code snippet before the placeholder: <|code_start|>
class ParseTestCase(TestCase):
def setUp(self):
self.view = GeographyDetailView()
def test_parse_typical(self):
(geoid,slug) = self.view.parse_fragment('16000US1714000-chicago-il')
self.assertEqual(geoid,'16000US171... | (geoid,slug) = self.view.parse_fragment('61000US50E-O') |
Here is a snippet: <|code_start|> id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin, ValidationMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), uniq... | result = True |
Using the snippet: <|code_start|> db.session.commit()
email_token = generate_confirmation_token(user.email)
confirm_url = url_for('.confirm_email', token=email_token, _external=True)
mail = Mail()
msg = Message("Please confirm your account", sender="example_rest_blog@gmail.com", recipients=[use... | @users_bp.route('/confirm/<token>') |
Next line prediction: <|code_start|> confirmation_url=confirm_url,
user=user
)
msg.html = render_template(
"email/confirmation_email.html",
confirmation_url=confirm_url,
user=user
)
mail.send(msg)
return jsonify({
'id': user.id,
'message': 'Use... | flash('You have confirmed your account. Thanks!', 'success') |
Given snippet: <|code_start|> 'message': 'User successfully created, please check your email to activate your account'
})
def generate_confirmation_token(email):
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
return serializer.dumps(email, salt=app.config['SECURITY_PASSWORD_SALT'])
... | max_age=expiration |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
users_bp = Blueprint('users', __name__)
@users_bp.errorhandler(CheckError)
def hook_validation_error(e):
response = jsonify(
{
'status': 400,
<|code_end|>
, generate the next line using the... | 'error': 'BAD REQUEST', |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
class CheckError(ValueError):
pass
mail = Mail()
cors = CORS()
datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(datastore=datastore)
jwt = JWT()
@j... | if user is not None: |
Continue the code snippet: <|code_start|>
@jwt.authentication_handler
def custom_authentication_handler(username, password):
user = datastore.find_user(email=username)
if user is not None:
if not user.is_active:
abort(401)
if username == user.email and user.check_password(password):... | identity = getattr(identity, 'id') or identity['id'] |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
migrate = Migrate(app, db)
manager = Manager(app)
def make_context():
return {'app': app}
manager.add_command('server', Server(host='0.0.0.0', port=8001, use_debugger=True, use_reloader=True))
manager.add_command(... | if __name__ == '__main__': |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
migrate = Migrate(app, db)
manager = Manager(app)
def make_context():
return {'app': app}
<|code_end|>
. Write the next line using the current file imports:
from flask.ext.migrate import Migrate, MigrateCommand
f... | manager.add_command('server', Server(host='0.0.0.0', port=8001, use_debugger=True, use_reloader=True)) |
Given the code snippet: <|code_start|> raise ProcessingException(description='Only admins can access this view', code=401)
@jwt_required()
def auth_func(instance_id=None, **kwargs):
del instance_id
del kwargs
def auth_without_jwt(instance_id=None, **kwargs):
del instance_id
del kwargs
api_manage... | include_columns=['id', 'title', 'text', 'author', 'created_at'], |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
logger = logging.getLogger(__name__)
configuration_object = os.environ.get('FLASK_CONFIGURATION') or 'configuration.local'
REST_API_PREFIX = None
try:
exec('from {configuration_o... | def is_authorized(user, instance): |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# pylint: disable=E1103
Shape = Tuple[int, ...]
# noinspection PyPep8
def generate_jakes_samples(
Fd: float,
<|code_end|>
, predict the immediate next line with the help of imports:
import math
import numpy as np
from typing import Any, Optional, ... | Ts: float = 1e-3, |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# See the link below for an "argparse + configobj" option
# http://mail.scipy.org/pipermail/numpy-discussion/2011-November/059332.html
if __name__ == '__main__':
config_file_name = 'psk_simulation_config.txt'
# Spec could be also the name of a file con... | M=integer(min=4, max=512, default=4) |
Using the snippet: <|code_start|> cp_size: int,
num_used_subcarriers: Optional[int] = None) -> None:
"""
Initialize the OFDM object.
Parameters
----------
fft_size : int
Size of the FFT and IFFT used by the OFDM class.
cp_size... | def set_parameters(self, |
Continue the code snippet: <|code_start|> \\pgfdeclarelayer{{foreground}}
\\pgfsetlayers{{background,main,foreground}}
\\begin{{tikzpicture}}[every node/.style={{scale=0.8}}]
%% Desenha eixos
\\coordinate (origem) at (0,0);
\\def\\YMax{{ {YMax} }}
\\def\\XMax{{ {XMax} }}
\\dr... | }} |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# http://www.doughellmann.com/PyMOTW/struct/
# import struct
# import binascii
"""
Module with class for some fundamental modulators, such as PSK and M-QAM.
All fundamental modulators inherit from the `Modulator` class and should
call the self.setConstellation... | try: |
Using the snippet: <|code_start|>
# http://www.doughellmann.com/PyMOTW/struct/
# import struct
# import binascii
"""
Module with class for some fundamental modulators, such as PSK and M-QAM.
All fundamental modulators inherit from the `Modulator` class and should
call the self.setConstellation method in their __init__... | class Modulator: |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# http://www.doughellmann.com/PyMOTW/struct/
# import struct
# import binascii
"""
Module with class for some fundamental modulators, such as PSK and M-QAM.
All fundamental modulators inherit from the `Modulator` class and should
call the self.setConstellation... | __all__ = ['Modulator', 'PSK', 'QPSK', 'BPSK', 'QAM'] |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# http://www.doughellmann.com/PyMOTW/struct/
# import struct
# import binascii
"""
Module with class for some fundamental modulators, such as PSK and M-QAM.
All fundamental modulators inherit from the `Modulator` class and should
call the sel... | _MATPLOTLIB_AVAILABLE = False |
Given snippet: <|code_start|>#!/usr/bin/env python
# http://www.doughellmann.com/PyMOTW/struct/
# import struct
# import binascii
"""
Module with class for some fundamental modulators, such as PSK and M-QAM.
All fundamental modulators inherit from the `Modulator` class and should
call the self.setConstellation method... | PI = np.pi |
Next line prediction: <|code_start|>
TrainingConfigs = namedtuple('TrainingConfigs',
['src_vocab', 'trg_vocab', 'params',
'train_src_file', 'train_trg_file',
'test_src_file', 'test_trg_file',
'beam_si... | 'state_size': 512, |
Using the snippet: <|code_start|>
class MyLayer(Layer):
def __init__(self, base_name=None, name=None, dtype=None, **kwargs):
super(MyLayer, self).__init__(['weight', 'bias'], base_name, name,
dtype, **kwargs)
def test_base():
graph = Graph()
graph.clear_layers... | test_base() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Author: Sword York
# GitHub: https://github.com/SwordYork/sequencing
# No rights reserved.
#
class MyLayer(Layer):
def __init__(self, base_name=None, name=None, dtype=None, **kwargs):
super(MyLayer, self).__init__(['weight', 'bias'], base_... | graph.clear_layers() |
Given the code snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | self.vlan = args[0] |
Predict the next line for this snippet: <|code_start|>
def write_invisible(self, data):
self.child.sendline(data.encode())
self.read("\r\n")
def write_stars(self, data):
self.child.sendline(data.encode())
self.read(len(data) * "*" + "\r\n")
def write_raw(self, data):
... | return 'telnet %s %s' \ |
Based on the snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | def get_prompt(self): |
Based on the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | for line in data: |
Given the code snippet: <|code_start|> assert_that(str(expect.exception), is_(
"Error [1000]: CLI command 1 of 1 'show vlan 999' failed: could not run command "
"[VLAN 999 not found in current VLAN database]"
))
assert_that(expect.exception.output, is_([
{
... | class AnyId(object): |
Based on the snippet: <|code_start|># 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 for the specific language governing permissions and
# limitations under the License.
class DellUnprivilegedTest(Protocol... | def test_no_password_works_for_legacy_reasons(self, t): |
Here is a snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | def test_entering_enable_mode_requires_a_password(self, t): |
Here is a snippet: <|code_start|>
class DellUnprivilegedTest(ProtocolTest):
__test__ = False
tester_class = SshTester
test_switch = "dell"
@with_protocol
def test_entering_enable_mode_requires_a_password(self, t):
t.write("enable")
t.read("Password:")
t.write_stars(t.conf[... | t.read("my_switch#") |
Based on the snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | t.read("my_switch#") |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | def get_prompt(self): |
Next line prediction: <|code_start|> if not ip_owner:
self.port.add_ip(new_ip)
else:
if ip_owner == self.port:
for ip in self.port.ips:
if new_ip.ip == ip.ip:
self.write_line("IP/Port: Errno(6)... | .format(self.port.vlan_id)) |
Given the code snippet: <|code_start|>
class RoutingEngineTest(unittest.TestCase):
def test_2_ssh(self):
conf = TEST_SWITCHES["brocade"]
tester1 = SshTester("ssh-1", "127.0.0.1", conf["ssh"], u'root', u'root')
tester2 = SshTester("ssh-2", "127.0.0.1", conf["ssh"], u'root', u'root')
... | tester1.read("Password:") |
Next line prediction: <|code_start|>
assert_interface_configuration(t, "Vlan4000", [
"interface ve 4000",
"!"])
configuring(t, do="no interface ve 4000")
configuring(t, do="no vlan 4000")
@with_protocol
def test_extreme_vlan_ranges(self, t):
enable(t)
... | t.read("SSH@my_switch(config-vlan-4090)#") |
Using the snippet: <|code_start|> t.read("SSH@my_switch(config)#")
t.write("no interface ethe 1/65")
t.readln("Invalid input -> 1/65")
t.readln("Type ? for a list")
t.read("SSH@my_switch(config)#")
t.write("no interface ethe 1/99")
t.readln("Invalid input -> 1/99... | t.readln("Error - invalid interface 1/64") |
Predict the next line for this snippet: <|code_start|> def test_show_vlan_has_tagged_untagged_ports(self, t):
enable(t)
create_vlan(t, "1600")
set_interface_untagged_on_vlan(t, "ethernet 1/2", "1600")
t.write("show vlan 1600")
t.readln("")
t.readln("PORT-VLAN 1600, Na... | t.readln("Statically tagged Ports : ethe 1/4") |
Based on the snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | test_switch = "dell10g" |
Given the code snippet: <|code_start|> def test_entering_enable_mode_requires_a_password(self, t):
t.write("enable")
t.read("Password:")
t.write_stars(t.conf["extra"]["password"])
t.read("\r\n")
t.read("my_switch#")
@with_protocol
def test_wrong_password(self, t):
... | t.write("quit") |
Given snippet: <|code_start|>
tester_class = SshTester
test_switch = "dell10g"
@with_protocol
def test_entering_enable_mode_requires_a_password(self, t):
t.write("enable")
t.read("Password:")
t.write_stars(t.conf["extra"]["password"])
t.read("\r\n")
t.read("my_sw... | t.write("exit") |
Continue the code snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | t.read("my_switch#") |
Given the following code snippet before the placeholder: <|code_start|># You may obtain a copy of the License at
#
# 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 WARRAN... | else: |
Predict the next line after this 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... | def do_backdoor(self, *args): |
Here is a snippet: <|code_start|>
class CiscoCoreTest(unittest.TestCase):
def test_cisco_2960_24TT_L_has_right_ports(self):
ports = cisco_core.Cisco2960_24TT_L_SwitchCore.get_default_ports()
fast_ethernet_ports = [p for p in ports if p.name.startswith('FastEthernet')]
<|code_end|>
. Write the nex... | gigabit_ethernet_ports = [p for p in ports if p.name.startswith('GigabitEthernet')] |
Using the snippet: <|code_start|>
class TransportsTests(unittest.TestCase):
def test_http_service_has_default_port(self):
http_service = SwitchHttpService()
assert_that(http_service.port, equal_to(80))
def test_ssh_service_has_default_port(self):
ssh_service = SwitchSshService()
... | def test_telnet_service_has_default_port(self): |
Predict the next line after this snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License ... | logging.info("{} (TELNET): Registered on {} tcp/{}".format( |
Here is a snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | def hook_to_reactor(self, reactor): |
Predict the next line after this snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | self.write_line(" VLAN Error") |
Predict the next line after this snippet: <|code_start|> self.switch_configuration.name, self.port.vlan_id, self.vrrp.group_id)
def do_backup(self, *args):
if "priority".startswith(args[0]) and "track-priority".startswith(args[2]):
self.vrrp.priority = args[1]
if len(self... | self.vrrp.timers_hello = args[0] |
Here is a snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | processed = self.sub_processor.process_command(line) |
Based on the snippet: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | return self.switch_configuration.name + "(config-vrf)#" |
Using the snippet: <|code_start|>
class TestCiscoAutoEnabledSwitchProtocol(ProtocolTest):
__test__ = False
test_switch = "cisco-auto-enabled"
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
<|code_end|>
, determine the next li... | t.write("terminal length 0") |
Predict the next line for this snippet: <|code_start|>
class TestCiscoAutoEnabledSwitchProtocol(ProtocolTest):
__test__ = False
test_switch = "cisco-auto-enabled"
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
<|code_end|>
with the help of current file ... | t.read("my_switch#") |
Using the snippet: <|code_start|>
class TestCiscoAutoEnabledSwitchProtocol(ProtocolTest):
__test__ = False
test_switch = "cisco-auto-enabled"
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
t.write("terminal length 0")... | t.read("my_switch(config)#") |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | if self.sub_processor.is_done: |
Next line prediction: <|code_start|>
class SwitchFactoryTest(unittest.TestCase):
def test_switch_model_does_not_exist(self):
factory = switch_factory.SwitchFactory(mapping={})
with self.assertRaises(switch_factory.InvalidSwitchModel) as e:
factory.get('invalid_model')
assert_t... | name='my_hostname', |
Next line prediction: <|code_start|>
class SwitchFactoryTest(unittest.TestCase):
def test_switch_model_does_not_exist(self):
factory = switch_factory.SwitchFactory(mapping={})
with self.assertRaises(switch_factory.InvalidSwitchModel) as e:
factory.get('invalid_model')
assert_t... | def test_switch_model_exists(self): |
Using the snippet: <|code_start|> self.channelLookup.update({b'session': session.SSHSession})
netconf_protocol = switch_core.get_netconf_protocol()
if netconf_protocol:
self.subsystemLookup.update({b'netconf': netconf_protocol})
def openShell(self, protocol):
server_prot... | self.switch_core = switch_core |
Continue the code snippet: <|code_start|>@implementer(conchinterfaces.ISession)
class SSHDemoAvatar(avatar.ConchUser):
def __init__(self, username, switch_core):
avatar.ConchUser.__init__(self)
self.username = username
self.switch_core = switch_core
self.channelLookup.update({b'sessi... | pass |
Here is a snippet: <|code_start|># Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | def test_write_memory(self, t): |
Predict the next line for this snippet: <|code_start|># Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | start_time = time.time() |
Using the snippet: <|code_start|># Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | t.write("write memory") |
Next line prediction: <|code_start|># Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | t.read("SSH@my_switch#") |
Here is a snippet: <|code_start|># Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | t.read("SSH@my_switch#") |
Given the code snippet: <|code_start|>logger = logging.getLogger()
# NOTE(mmitchell): This is necessary because some imports will initialize the root logger.
logger.setLevel('DEBUG')
def main():
parser = argparse.ArgumentParser(description='Fake-switch simulator launcher',
fo... | logger.info('Starting reactor') |
Here is a snippet: <|code_start|>
@attrs.define(kw_only=True, eq=False)
class JSONSerializer(Serializer):
magic_key: str = '_apscheduler_json'
dump_options: dict[str, Any] = attrs.field(factory=dict)
load_options: dict[str, Any] = attrs.field(factory=dict)
def __attrs_post_init__(self):
self.... | return dumps(obj, ensure_ascii=False, **self.dump_options).encode('utf-8') |
Continue the code snippet: <|code_start|>
def __attrs_post_init__(self):
self.dump_options['default'] = self._default_hook
self.load_options['object_hook'] = self._object_hook
def _default_hook(self, obj):
if hasattr(obj, '__getstate__'):
cls_ref, state = marshal_object(obj)... | def deserialize_from_unicode(self, serialized: str): |
Given the following code snippet before the placeholder: <|code_start|> magic_key: str = '_apscheduler_json'
dump_options: dict[str, Any] = attrs.field(factory=dict)
load_options: dict[str, Any] = attrs.field(factory=dict)
def __attrs_post_init__(self):
self.dump_options['default'] = self._defau... | def serialize_to_unicode(self, obj) -> str: |
Next line prediction: <|code_start|>from __future__ import annotations
@attrs.define(kw_only=True, eq=False)
class JSONSerializer(Serializer):
magic_key: str = '_apscheduler_json'
dump_options: dict[str, Any] = attrs.field(factory=dict)
load_options: dict[str, Any] = attrs.field(factory=dict)
<|code_e... | def __attrs_post_init__(self): |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
@attrs.define
class BaseCombiningTrigger(Trigger):
triggers: list[Trigger]
_next_fire_times: list[datetime | None] = attrs.field(init=False, eq=False, factory=list)
def __getstate__(self) -> dict[str, Any]:
... | 'version': 1, |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
@attrs.define
class BaseCombiningTrigger(Trigger):
triggers: list[Trigger]
<|code_end|>
using the current file's imports:
from abc import abstractmethod
from datetime import datetime, timedelta
from typing import Any
f... | _next_fire_times: list[datetime | None] = attrs.field(init=False, eq=False, factory=list) |
Using the snippet: <|code_start|>from __future__ import annotations
@attrs.define
class BaseCombiningTrigger(Trigger):
triggers: list[Trigger]
_next_fire_times: list[datetime | None] = attrs.field(init=False, eq=False, factory=list)
def __getstate__(self) -> dict[str, Any]:
return {
... | self._next_fire_times = state['next_fire_times'] |
Given the code snippet: <|code_start|>from __future__ import annotations
@attrs.define
class BaseCombiningTrigger(Trigger):
triggers: list[Trigger]
_next_fire_times: list[datetime | None] = attrs.field(init=False, eq=False, factory=list)
def __getstate__(self) -> dict[str, Any]:
return {
... | @abstractmethod |
Next line prediction: <|code_start|>from __future__ import annotations
@attrs.define
class BaseCombiningTrigger(Trigger):
triggers: list[Trigger]
_next_fire_times: list[datetime | None] = attrs.field(init=False, eq=False, factory=list)
def __getstate__(self) -> dict[str, Any]:
return {
<|code_... | 'version': 1, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.