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 == 'POST': form = ProfileForm(request.POST, instance=request.user.profile) if form.is_valid(): form.save() messages.success(request, "Profile updated successfully") return redirect('profile:edit') else: form = ProfileForm(instance=request.user.profile) return render(request, 'profile/edit/view.html', { 'form': form, }) @login_required def edit_account(request): <|code_end|> with the help of current file imports: from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from librement.utils.ajax import ajax from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm from .utils import get_rss_feed and context from other files: # Path: src/librement/profile/forms.py # class ProfileForm(forms.ModelForm): # class Meta: # model = Profile # fields = ( # 'display_name', # 'biography', # 'rss_url', # ) # # class AccountForm(dict): # def __init__(self, user, *args, **kwargs): # self.user = user # # for key, klass, fn in ( # ('user', AccountUserForm, lambda x: x), # ('profile', AccountProfileForm, lambda x: x.profile), # ): # self[key] = klass(instance=fn(user), *args, **kwargs) # # def save(self): # return [x.save() for x in self.values()] # # def is_valid(self): # return all(x.is_valid() for x in self.values()) # # class URLForm(forms.ModelForm): # username = forms.RegexField(regex=r'^[\w-]+$') # # class Meta: # model = User # fields = ( # 'username', # ) # # class PictureForm(forms.Form): # picture = forms.ImageField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(PictureForm, self).__init__(*args, **kwargs) # # def save(self): # self.user.profile.picture.save( # self.cleaned_data['picture'] # ) # self.user.profile.save() # # class PasswordForm(forms.Form): # password_old = forms.CharField() # password = forms.CharField() # password_confirm = forms.CharField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(PasswordForm, self).__init__(*args, **kwargs) # # def save(self): # self.user.set_password(self.cleaned_data['password']) # self.user.save() # # def clean_password_old(self): # val = self.cleaned_data['password_old'] # # if not self.user.check_password(val): # raise forms.ValidationError( # "Password is not correct." # ) # # return val # # def clean_password_confirm(self): # password = self.cleaned_data.get('password', '') # password_confirm = self.cleaned_data['password_confirm'] # # if password != password_confirm: # raise forms.ValidationError("Passwords do not match.") # # if len(password) < 8: # raise forms.ValidationError( # "Password must be at least 8 characters" # ) # # return password # # Path: src/librement/profile/utils.py # def get_rss_feed(url): # if not url: # return None # # key = 'feed:%s' % hashlib.sha1(url).hexdigest() # feed = cache.get(key) # # if feed is None: # feed = feedparser.parse(url) # cache.set(key, feed, 3600) # # return feed , which may contain function names, class names, or code. Output only the next line.
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(':', 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) == pk: return r user = User.objects.get(pk=pk) except (ValueError, User.DoesNotExist): return r <|code_end|> . Use current file imports: from django.shortcuts import redirect from django.utils.cache import add_never_cache_headers from django.core.signing import TimestampSigner, BadSignature from django.contrib.auth.models import User from . import app_settings from .utils import login, strip_token, get_user_salt and context (classes, functions, or code) from other files: # Path: src/contrib/django_autologin/utils.py # def login(request, user): # user.backend = settings.AUTHENTICATION_BACKENDS[0] # auth.login(request, user) # # def strip_token(url): # bits = urlparse.urlparse(url) # original_query = urlparse.parse_qsl(bits.query) # # query = {} # for k, v in original_query: # if k != app_settings.KEY: # query[k] = v # # query = urllib.urlencode(query) # # return urlparse.urlunparse( # (bits[0], bits[1], bits[2], bits[3], query, bits[5]), # ) # # def get_user_salt(user): # return "".join(str(getattr(user, x)) for x in app_settings.SALT_FIELDS) . Output only the next line.
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(':', 1)[0]) # Only change user if necessary. We strip the token in any case. # The AnonymousUser class has no 'pk' attribute (#18093) <|code_end|> . Use current file imports: from django.shortcuts import redirect from django.utils.cache import add_never_cache_headers from django.core.signing import TimestampSigner, BadSignature from django.contrib.auth.models import User from . import app_settings from .utils import login, strip_token, get_user_salt and context (classes, functions, or code) from other files: # Path: src/contrib/django_autologin/utils.py # def login(request, user): # user.backend = settings.AUTHENTICATION_BACKENDS[0] # auth.login(request, user) # # def strip_token(url): # bits = urlparse.urlparse(url) # original_query = urlparse.parse_qsl(bits.query) # # query = {} # for k, v in original_query: # if k != app_settings.KEY: # query[k] = v # # query = urllib.urlencode(query) # # return urlparse.urlunparse( # (bits[0], bits[1], bits[2], bits[3], query, bits[5]), # ) # # def get_user_salt(user): # return "".join(str(getattr(user, x)) for x in app_settings.SALT_FIELDS) . Output only the next line.
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) == pk: return r user = User.objects.get(pk=pk) except (ValueError, User.DoesNotExist): return r try: TimestampSigner(salt=get_user_salt(user)).unsign( token, max_age=app_settings.MAX_AGE, ) except BadSignature: return r response = self.render( request, user, token, strip_token(request.get_full_path()), ) add_never_cache_headers(response) return response <|code_end|> using the current file's imports: from django.shortcuts import redirect from django.utils.cache import add_never_cache_headers from django.core.signing import TimestampSigner, BadSignature from django.contrib.auth.models import User from . import app_settings from .utils import login, strip_token, get_user_salt and any relevant context from other files: # Path: src/contrib/django_autologin/utils.py # def login(request, user): # user.backend = settings.AUTHENTICATION_BACKENDS[0] # auth.login(request, user) # # def strip_token(url): # bits = urlparse.urlparse(url) # original_query = urlparse.parse_qsl(bits.query) # # query = {} # for k, v in original_query: # if k != app_settings.KEY: # query[k] = v # # query = urllib.urlencode(query) # # return urlparse.urlunparse( # (bits[0], bits[1], bits[2], bits[3], query, bits[5]), # ) # # def get_user_salt(user): # return "".join(str(getattr(user, x)) for x in app_settings.SALT_FIELDS) . Output only the next line.
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'], username=username, ) user.set_password(self.cleaned_data['password']) user.save() # Store the user's email address; we don't use User.email as we support # multiple email addresses. email = user.emails.create(email=self.cleaned_data['email']) # Update Profile model rather than create a new one. profile = super(RegistrationForm, self).save(commit=False) profile.user = user if profile.account_type == AccountEnum.INDIVIDUAL: profile.display_name = u"%s %s" % (user.first_name, user.last_name) else: profile.display_name = profile.organisation profile.save() # Send confirmation email send_mail((email.email,), 'registration/confirm.email', { <|code_end|> using the current file's imports: from email_from_template import send_mail from django import forms from django.contrib.auth.models import User from librement.profile.enums import AccountEnum from librement.account.models import Email from librement.profile.models import Profile from .utils import invent_username and any relevant context from other files: # Path: src/librement/registration/utils.py # def invent_username(first_name, last_name): # counter = itertools.count(random.randrange(1000000)) # # base = slugify(u'%s%s' % (first_name, last_name)) # # username = base or 'user' # # while User.objects.filter(username=username).exists(): # # We must ensure that our username suggestions are under 30 # # characters or we'll simply fail later when we try and create a # # User (hence the [:30]), but we also need space for the variable # # suffix (hence the [:25]) or we run the risk of entering into # # infinite loop trying the same combination again and again. # username = '%s%d' % (base[:25], counter.next()) # username = username[:30] # # return username . Output only the next line.
'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, field.attname)) ) return render_to_response('debug_toolbar_user_panel/content.html', { 'form': UserForm(), 'next': request.GET.get('next'), 'users': User.objects.order_by('-last_login')[:10], 'current': current, }, context_instance=RequestContext(request)) <|code_end|> . Use current file imports: (from django.http import HttpResponseRedirect, HttpResponseBadRequest from django.conf import settings from django.contrib import auth from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .forms import UserForm from .decorators import debug_required) and context including class names, function names, or small code snippets from other files: # Path: src/contrib/debug_toolbar_user_panel/forms.py # class UserForm(forms.Form): # val = forms.CharField(label='User.{id,username,email}') # # def get_lookup(self): # val = self.cleaned_data['val'] # # if '@' in val: # return {'email': val} # # try: # return {'pk': int(val)} # except: # return {'username': val} # # Path: src/contrib/debug_toolbar_user_panel/decorators.py # def debug_required(fn): # @functools.wraps(fn) # def wrapper(*args, **kwargs): # if not getattr(settings, 'DEBUG_TOOLBAR_USER_DEBUG', settings.DEBUG): # return HttpResponseForbidden() # return fn(*args, **kwargs) # return wrapper . Output only the next line.
@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 django.conf import settings from django.contrib import auth from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .forms import UserForm from .decorators import debug_required and context including class names, function names, and sometimes code from other files: # Path: src/contrib/debug_toolbar_user_panel/forms.py # class UserForm(forms.Form): # val = forms.CharField(label='User.{id,username,email}') # # def get_lookup(self): # val = self.cleaned_data['val'] # # if '@' in val: # return {'email': val} # # try: # return {'pk': int(val)} # except: # return {'username': val} # # Path: src/contrib/debug_toolbar_user_panel/decorators.py # def debug_required(fn): # @functools.wraps(fn) # def wrapper(*args, **kwargs): # if not getattr(settings, 'DEBUG_TOOLBAR_USER_DEBUG', settings.DEBUG): # return HttpResponseForbidden() # return fn(*args, **kwargs) # return wrapper . Output only the next line.
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 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 inbox to confirm your email address.", ) return redirect('profile:emails:view') else: form = EmailForm(request.user) return render(request, 'profile/emails/add.html', { 'form': form, <|code_end|> with the help of current file imports: from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from .forms import EmailForm, ConfirmForm and context from other files: # Path: src/librement/profile/emails/forms.py # class EmailForm(forms.Form): # email = forms.EmailField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(EmailForm, self).__init__(*args, **kwargs) # # def clean_email(self): # val = self.cleaned_data['email'] # # if Email.objects.filter(email=val).exists(): # raise forms.ValidationError("Email address already in use.") # # return val # # def send_email(self): # email = self.cleaned_data['email'] # # send_mail( # (email,), # 'profile/emails/confirm.email', { # 'user': self.user, # 'signed': Signer().sign(email), # }, # ) # # class ConfirmForm(forms.Form): # signed = forms.CharField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(ConfirmForm, self).__init__(*args, **kwargs) # # def clean_signed(self): # val = self.cleaned_data['signed'] # # try: # email = Signer().unsign(val) # except BadSignature: # raise forms.ValidationError("") # # if Email.objects.filter(email=email).exists(): # # Race condition or linked clicked twice # raise forms.ValidationError("") # # self.cleaned_data['email'] = email # # return val # # def save(self): # self.user.emails.create( # email=self.cleaned_data['email'], # ) , which may contain function names, class names, or code. Output only the next line.
})
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 inbox to confirm your email address.", ) return redirect('profile:emails:view') else: form = EmailForm(request.user) return render(request, 'profile/emails/add.html', { 'form': form, }) @require_POST @login_required def delete(request, email_id): email = get_object_or_404(request.user.emails, pk=email_id) if request.user.emails.count() > 1: email.delete() messages.success(request, "Email address deleted.") else: <|code_end|> using the current file's imports: from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from .forms import EmailForm, ConfirmForm and any relevant context from other files: # Path: src/librement/profile/emails/forms.py # class EmailForm(forms.Form): # email = forms.EmailField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(EmailForm, self).__init__(*args, **kwargs) # # def clean_email(self): # val = self.cleaned_data['email'] # # if Email.objects.filter(email=val).exists(): # raise forms.ValidationError("Email address already in use.") # # return val # # def send_email(self): # email = self.cleaned_data['email'] # # send_mail( # (email,), # 'profile/emails/confirm.email', { # 'user': self.user, # 'signed': Signer().sign(email), # }, # ) # # class ConfirmForm(forms.Form): # signed = forms.CharField() # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(ConfirmForm, self).__init__(*args, **kwargs) # # def clean_signed(self): # val = self.cleaned_data['signed'] # # try: # email = Signer().unsign(val) # except BadSignature: # raise forms.ValidationError("") # # if Email.objects.filter(email=email).exists(): # # Race condition or linked clicked twice # raise forms.ValidationError("") # # self.cleaned_data['email'] = email # # return val # # def save(self): # self.user.emails.create( # email=self.cleaned_data['email'], # ) . Output only the next line.
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 distribution # and at http://librement.net/license/. No part of Librement, including # this file, may be copied, modified, propagated, or distributed except # according to the terms contained in the LICENSE file. 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 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) <|code_end|> , continue by predicting the next line. Consider current file imports: from django_yadt import YADTImageField from django_enumfield import EnumField from django.db import models from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum and context: # Path: src/librement/profile/enums.py which might include code, classes, or functions. Output only the next line.
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 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum, default=CountryEnum.US) picture = YADTImageField(variants={ 'thumbnail': { 'width': 150, 'height': 150, 'format': 'jpeg', 'crop': True, }, }, cachebust=True) rss_url = models.CharField(max_length=200, blank=True) def __unicode__(self): <|code_end|> , predict the immediate next line with the help of imports: from django_yadt import YADTImageField from django_enumfield import EnumField from django.db import models from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum and context (classes, functions, sometimes code) from other files: # Path: src/librement/profile/enums.py . Output only the next line.
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-profit accounts" ) return val class AccountForm(dict): def __init__(self, user, *args, **kwargs): self.user = user for key, klass, fn in ( ('user', AccountUserForm, lambda x: x), ('profile', AccountProfileForm, lambda x: x.profile), ): self[key] = klass(instance=fn(user), *args, **kwargs) def save(self): return [x.save() for x in self.values()] def is_valid(self): return all(x.is_valid() for x in self.values()) class URLForm(forms.ModelForm): <|code_end|> . Use current file imports: (from django import forms from django.contrib.auth.models import User from .enums import AccountEnum from .models import Profile) and context including class names, function names, or small code snippets from other files: # Path: src/librement/profile/enums.py # # Path: src/librement/profile/models.py # 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 = models.CharField(max_length=150, blank=True) # address_2 = models.CharField(max_length=150, blank=True) # city = models.CharField(max_length=100, blank=True) # region = models.CharField(max_length=100, blank=True) # zipcode = models.CharField(max_length=100, blank=True) # # country = EnumField(CountryEnum, default=CountryEnum.US) # # picture = YADTImageField(variants={ # 'thumbnail': { # 'width': 150, # 'height': 150, # 'format': 'jpeg', # 'crop': True, # }, # }, cachebust=True) # # rss_url = models.CharField(max_length=200, blank=True) # # def __unicode__(self): # return self.display_name . Output only the next line.
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 distribution # and at http://librement.net/license/. No part of Librement, including # this file, may be copied, modified, propagated, or distributed except # according to the terms contained in the LICENSE file. class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'display_name', 'biography', <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from django.contrib.auth.models import User from .enums import AccountEnum from .models import Profile and context: # Path: src/librement/profile/enums.py # # Path: src/librement/profile/models.py # 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 = models.CharField(max_length=150, blank=True) # address_2 = models.CharField(max_length=150, blank=True) # city = models.CharField(max_length=100, blank=True) # region = models.CharField(max_length=100, blank=True) # zipcode = models.CharField(max_length=100, blank=True) # # country = EnumField(CountryEnum, default=CountryEnum.US) # # picture = YADTImageField(variants={ # 'thumbnail': { # 'width': 150, # 'height': 150, # 'format': 'jpeg', # 'crop': True, # }, # }, cachebust=True) # # rss_url = models.CharField(max_length=200, blank=True) # # def __unicode__(self): # return self.display_name which might include code, classes, or functions. Output only the next line.
'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 distribution # and at http://librement.net/license/. No part of Librement, including # this file, may be copied, modified, propagated, or distributed except # according to the terms contained in the LICENSE file. class LibrementBackend(ModelBackend): def authenticate(self, email=None, password=None): try: email = Email.objects.get(email__iexact=email) for candidate in ( password, password.swapcase(), password[0:1].lower() + password[1:], <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.auth.backends import ModelBackend from .models import Email and context: # Path: src/librement/account/models.py # class Email(models.Model): # user = models.ForeignKey('auth.User', related_name='emails') # # email = models.EmailField(unique=True) # # def __unicode__(self): # return u"%s" % self.email which might include code, classes, or functions. Output only the next line.
):
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/forgot_password.html', { 'form': form, }) def forgot_password_done(request): return render(request, 'passwords/forgot_password_done.html') @login_required def reset_password(request): if request.method == 'POST': form = ResetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() return redirect('passwords:reset-password-done') print form.errors <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ForgotPasswordForm, ResetPasswordForm and context (class names, function names, or code) available: # Path: src/librement/passwords/forms.py # class ForgotPasswordForm(forms.Form): # email = forms.EmailField() # # def clean_email(self): # val = self.cleaned_data['email'] # # try: # return Email.objects.get( # email=val, # user__is_active=True, # ) # except Email.DoesNotExist: # raise forms.ValidationError( # "That email address does not exist." # ) # # def save(self): # email = self.cleaned_data['email'] # # send_mail( # (email.email,), # 'passwords/forgot_password.email', # {'user': email.user}, # ) # # class ResetPasswordForm(forms.Form): # password = forms.CharField(required=False) # password_confirm = forms.CharField(required=False) # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(ResetPasswordForm, self).__init__(*args, **kwargs) # # def clean_password_confirm(self): # password = self.cleaned_data.get('password', '') # password_confirm = self.cleaned_data['password_confirm'] # # if password != password_confirm: # raise forms.ValidationError("Passwords do not match.") # # if len(password) < 8: # raise forms.ValidationError( # "Password must be at least 8 characters" # ) # # return password # # def save(self): # self.user.set_password(self.cleaned_data['password']) # self.user.save() . Output only the next line.
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_password_done.html') @login_required def reset_password(request): if request.method == 'POST': form = ResetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() return redirect('passwords:reset-password-done') print form.errors else: form = ResetPasswordForm(request.user) return render(request, 'passwords/reset_password.html', { 'form': form, <|code_end|> , predict the immediate next line with the help of imports: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ForgotPasswordForm, ResetPasswordForm and context (classes, functions, sometimes code) from other files: # Path: src/librement/passwords/forms.py # class ForgotPasswordForm(forms.Form): # email = forms.EmailField() # # def clean_email(self): # val = self.cleaned_data['email'] # # try: # return Email.objects.get( # email=val, # user__is_active=True, # ) # except Email.DoesNotExist: # raise forms.ValidationError( # "That email address does not exist." # ) # # def save(self): # email = self.cleaned_data['email'] # # send_mail( # (email.email,), # 'passwords/forgot_password.email', # {'user': email.user}, # ) # # class ResetPasswordForm(forms.Form): # password = forms.CharField(required=False) # password_confirm = forms.CharField(required=False) # # def __init__(self, user, *args, **kwargs): # self.user = user # # super(ResetPasswordForm, self).__init__(*args, **kwargs) # # def clean_password_confirm(self): # password = self.cleaned_data.get('password', '') # password_confirm = self.cleaned_data['password_confirm'] # # if password != password_confirm: # raise forms.ValidationError("Passwords do not match.") # # if len(password) < 8: # raise forms.ValidationError( # "Password must be at least 8 characters" # ) # # return password # # def save(self): # self.user.set_password(self.cleaned_data['password']) # self.user.save() . Output only the next line.
})
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(): link = form.save(commit=False) link.user = request.user link.save() if link: messages.success(request, "Link updated successfully.") else: messages.success(request, "Link added successfully.") return redirect('profile:links:view') else: form = LinkForm(instance=link) return render(request, 'profile/links/add_edit.html', { 'link': link, 'form': form, }) @require_POST <|code_end|> with the help of current file imports: from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from .forms import LinkForm and context from other files: # Path: src/librement/profile/links/forms.py # class LinkForm(forms.ModelForm): # class Meta: # model = Link # fields = ( # 'url', # 'title', # ) , which may contain function names, class names, or code. Output only the next line.
@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 of this distribution # and at http://librement.net/license/. No part of Librement, including # this file, may be copied, modified, propagated, or distributed except # according to the terms contained in the LICENSE file. def login(request): if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) if request.method == 'POST': form = LoginForm(request.POST) <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.contrib import auth from django.shortcuts import render, redirect from django.contrib.auth import logout as django_logout from .forms import LoginForm and context (functions, classes, or occasionally code) from other files: # Path: src/librement/account/forms.py # class LoginForm(forms.Form): # email = forms.EmailField(max_length=30) # password = forms.CharField() # # def clean(self): # user = None # email = self.cleaned_data.get('email') # password = self.cleaned_data.get('password') # # if email and password: # user = authenticate(email=email, password=password) # # if user is None: # raise forms.ValidationError( # "Please enter a correct username and password." # ) # # if not user.is_active: # raise forms.ValidationError("This account is not active.") # # self.cleaned_data['user'] = user # # return self.cleaned_data . Output only the next line.
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( "Item value %d has been used more than once (%s)" % \ (item.value, item) ) used_values.add(item.value) if item.slug in used_slugs: raise ValueError( "Item slug %r has been used more than once" % item.slug ) used_slugs.add(item.slug) items.append((n, item)) items.sort(key=lambda i: i[1].creation_counter) item_objects = [i[1] for i in items] by_val = dict((i.value, i) for i in item_objects) by_slug = dict((i.slug, i) for i in item_objects) specials = { 'items': dict(items), 'sorted_items': items, 'items_by_val': by_val, 'items_by_slug': by_slug, <|code_end|> using the current file's imports: from .item import Item and any relevant context from other files: # Path: src/contrib/django_enumfield/item.py # class Item(object): # __metaclass__ = ItemMeta # # def __init__(self, value, slug, display=None): # if not isinstance(value, int): # raise TypeError("item value should be an integer, not %r" \ # % type(value)) # # if not isinstance(slug, str): # raise TypeError("item slug should be a string, not %r" \ # % type(slug)) # # if display != None and not isinstance(display, (basestring)): # raise TypeError("item display name should be a basestring, not %r" \ # % type(display)) # # super(Item, self).__init__() # # self.value = value # self.slug = slug # # if display is None: # self.display = slug.capitalize() # else: # self.display = display # # self.creation_counter = Item.creation_counter # Item.creation_counter += 1 # # def __str__(self): # return self.__unicode__() # # def __unicode__(self): # # This is not pretty, but it makes the Django admin work right when it # # renders a select box # return self.slug # # def __repr__(self): # return u"<enum.Item: %d %s %r>" % (self.value, self.slug, self.display) # # def __hash__(self): # return self.value # # def __eq__(self, other): # if isinstance(other, Item): # return self.value == other.value # if isinstance(other, (int, str, long, unicode)): # try: # return self.value == int(other) # except ValueError: # return unicode(self.slug) == unicode(other) # return False # # def __ne__(self, other): # return not self.__eq__(other) . Output only the next line.
}
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 this distribution # and at http://librement.net/license/. No part of Librement, including # this file, may be copied, modified, propagated, or distributed except # according to the terms contained in the LICENSE file. class LinkForm(forms.ModelForm): class Meta: model = Link fields = ( 'url', 'title', <|code_end|> , determine the next line of code. You have imports: from django import forms from .models import Link and context (class names, function names, or code) available: # Path: src/librement/profile/links/models.py # class Link(models.Model): # user = models.ForeignKey('auth.User', related_name='links') # # url = models.URLField() # title = models.CharField(max_length=100) # # def __unicode__(self): # return u"%s <%s>" % (self.title, self.url) . Output only the next line.
)
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 <|code_end|> . Use current file imports: (import os import ctypes import shutil from PyQt4 import QtGui, QtCore, QtXml from Extensions import Global from Extensions.Projects.ProjectManager.ProjectView.ProgressWidget import ProgressWidget) and context including class names, function names, or small code snippets from other files: # Path: Extensions/Global.py # def getDefaultFont(): # def iconFromPath(path): . Output only the next line.
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 == 0) for i in range(self.projectWindowStack.count() - 1): editorTabWidget = self.projectWindowStack.widget(i).editorTabWidget if isCustom: editorTabWidget.adjustToStyleSheet(True) else: editorTabWidget.adjustToStyleSheet(False) def exportSettings(self): options = QtGui.QFileDialog.Options() savepath = os.path.join(self.useData.getLastOpenedDir(), "Pcode_Settings" + '_' + QtCore.QDateTime().currentDateTime().toString().replace(' ', '_').replace(':', '-')) savepath = os.path.normpath(savepath) fileName = QtGui.QFileDialog.getSaveFileName(self, "Choose Folder", savepath, "Pcode Settings (*)", options) if fileName: try: QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.useData.saveLastOpenedDir(os.path.split(fileName)[0]) shutil.make_archive(fileName, "zip", self.useData.appPathDict["settingsdir"]) except Exception as err: QtGui.QApplication.restoreOverrideCursor() <|code_end|> using the current file's imports: import os import shutil from PyQt4 import QtCore, QtGui from PyQt4.Qsci import QsciScintilla from Extensions import StyleSheet and any relevant context from other files: # Path: Extensions/StyleSheet.py . Output only the next line.
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.addButton(QtGui.QIcon( os.path.join("Resources", "images", "links_selected")), "Unified Diff") self.addButton(QtGui.QIcon( os.path.join("Resources", "images", "links")), "Context Diff") def setCurrentView(self): index = self.editorTabWidget.currentWidget().currentIndex() self.setIndex(None, index) def viewChanged(self, button): index = self.buttonGroup.id(button) self.setIndex(button, index) if index == 2: self.editorTabWidget.getUnifiedDiff().generateUnifiedDiff() elif index == 3: self.editorTabWidget.getContextDiff().generateContextDiff() def addButton(self, icon, toolTip): button = QtGui.QToolButton() button.setToolTip(toolTip) button.setCheckable(True) button.setIcon(icon) self.buttonGroup.addButton(button) <|code_end|> . Write the next line using the current file imports: import os from PyQt4 import QtGui from Extensions import StyleSheet and context from other files: # Path: Extensions/StyleSheet.py , which may include functions, classes, or code. Output only the next line.
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 file imports: (from django.conf import settings from django.conf.urls import url, include from censusreporter.config.base.urls import urlpatterns, handler500 from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views import static from django.http import Http404 import os, os.path) and context including class names, function names, or small code snippets from other files: # Path: censusreporter/config/base/urls.py . Output only the next line.
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,'16000US1714000') self.assertEqual(slug,'chicago-il') def test_parse_geoid(self): (geoid,slug) = self.view.parse_fragment('16000US1714000') self.assertEqual(geoid,'16000US1714000') self.assertEqual(slug,None) def test_parse_census_geoid(self): (geoid,slug) = self.view.parse_fragment('1600000US1714000') self.assertEqual(geoid,'16000US1714000') self.assertEqual(slug,None) def test_parse_vermont(self): (geoid,slug) = self.view.parse_fragment('61000US50ADD-addison-state-senate-district-vt') self.assertEqual(geoid,'61000US50ADD') self.assertEqual(slug,'addison-state-senate-district-vt') def test_parse_problem_geoid(self): <|code_end|> , predict the next line using imports from the current file: from django.test import TestCase from .views import GeographyDetailView and context including class names, function names, and sometimes code from other files: # Path: censusreporter/apps/census/views.py # class GeographyDetailView(TemplateView): # template_name = 'profile/profile_detail.html' # # def parse_fragment(self, fragment): # """Given a URL, return a (geoid,slug) tuple. slug may be None. # GeoIDs are not tested for structure, but are simply the part of the URL # before any '-' character, also allowing for the curiosity of Vermont # legislative districts. # (see https://github.com/censusreporter/censusreporter/issues/50) # """ # # def handle_long_geoid(geo_id): # """Census API uses seven characters for the 'sumlevel' part. # See https://www.census.gov/programs-surveys/geography/guidance/geo-identifiers.html for more info # Legislative district geoIDs sometimes have a strange bit in the first two characters # after the sumlevel which we can't make sense of. Also, we only support component # '00' so we just force to that. # # If we don't seem to have one of those, just pass back what we got unchanged. # """ # parts = geo_id.split('US') # # if len(parts) == 2 and len(parts[0]) == 7: # American Fact Finder style GeoID. # sumlevel = parts[0][:3] # identifier = parts[1] # return "{}00US{}".format(sumlevel, identifier) # return geo_id # # parts = fragment.split('-', 1) # if len(parts) == 1: # return (handle_long_geoid(fragment), None) # # geoid, slug = parts # geoid = handle_long_geoid(geoid) # if len(slug) == 1: # geoid = '{}-{}'.format(geoid, slug) # slug = None # else: # parts = slug.split('-') # if len(parts) > 1 and len(parts[0]) == 1: # geoid = '{}-{}'.format(geoid, parts[0]) # slug = '-'.join(parts[1:]) # # return (geoid, slug) # # def dispatch(self, *args, **kwargs): # # self.geo_id, self.slug = self.parse_fragment(kwargs.get('fragment')) # # # checking geoid # geography_info = self.get_geography(self.geo_id) # if geography_info is None: # raise Http404 # # # checking slug # calculated_slug = self.make_slug(geography_info) # if self.slug != calculated_slug: # fragment = '{}-{}'.format(self.geo_id, calculated_slug) # path = reverse('geography_detail', args=(fragment,)) # self.canonical_url = self.request.build_absolute_uri(path) # return HttpResponseRedirect(path) # # self.canonical_url = self.request.build_absolute_uri() # return super(GeographyDetailView, self).dispatch(*args, **kwargs) # # def make_slug(self, geo): # if geo: # try: # # get slug from geo # return slugify(geo['properties']['display_name']) # except Exception as e: # # if we have a strange situation where there's no # # display name attached to the geography, we should # # go ahead and display the profile page # logger.warn(e) # logger.warn("Geography {} has no display_name".format(self.geo_id)) # pass # else: # pass # # def make_canonical_url(self, geo_id): # pass # # def get_geography(self, geo_id): # endpoint = f"{settings.API_URL}/1.0/geo/tiger2019/{self.geo_id}" # r = r_session.get(endpoint) # status_code = r.status_code # # if status_code == 200: # geo_data = r.json(object_pairs_hook=OrderedDict) # return geo_data # return None # # def get_context_data(self, *args, **kwargs): # geography_id = self.geo_id # profile_data = geo_profile(geography_id) # # if profile_data: # profile_data = enhance_api_data(profile_data) # # profile_data_json = SafeString(json.dumps(profile_data)) # # else: # raise Http404 # # page_context = { # 'profile_data_json': profile_data_json, # 'canonical_url': self.canonical_url # } # page_context.update(profile_data) # return page_context . Output only the next line.
(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), unique=True) username = db.Column(db.String(50), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean(), default=False) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) def set_password(self, password): self.password = encrypt_password(password) def check_password(self, password): return verify_password(password, self.password) def check_mail_for_uniqueness(self, new_email): if self.query.filter_by(email=new_email).first() is None: result = True else: result = False return result def check_unique_username(self, new_username): if self.query.filter_by(username=new_username).first() is None: <|code_end|> . Write the next line using the current file imports: from flask.ext.security import UserMixin, RoleMixin from flask.ext.sqlalchemy import SQLAlchemy from savalidation import ValidationMixin from flask.ext.security.utils import encrypt_password, verify_password from datetime import datetime from .errors_handlers import CheckError and context from other files: # Path: server/errors_handlers.py # class CheckError(ValueError): # pass , which may include functions, classes, or code. Output only the next line.
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=[user.email]) msg.body = render_template( "email/confirmation_email.txt", 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': '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']) <|code_end|> , determine the next line of code. You have imports: from datetime import datetime from flask import ( render_template, flash, url_for, request, Blueprint, jsonify, current_app as app ) from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer from .errors_handlers import CheckError from .extensions import datastore from .models import db, User and context (class names, function names, or code) available: # Path: server/errors_handlers.py # class CheckError(ValueError): # pass # # Path: server/extensions.py # class CheckError(ValueError): # def custom_authentication_handler(username, password): # def custom_identity_handler(payload): # def custom_auth_response_callback(access_token, identity): # def custom_jwt_payload_handler(identity): # # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): . Output only the next line.
@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': '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']) @users_bp.route('/confirm/<token>') def confirm_email(token): email = confirm_token(token) user = User.query.filter_by(email=email).first_or_404() if user.email == email: user.active = True user.confirmed_at = datetime.utcnow() db.session.add(user) db.session.commit() <|code_end|> . Use current file imports: (from datetime import datetime from flask import ( render_template, flash, url_for, request, Blueprint, jsonify, current_app as app ) from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer from .errors_handlers import CheckError from .extensions import datastore from .models import db, User) and context including class names, function names, or small code snippets from other files: # Path: server/errors_handlers.py # class CheckError(ValueError): # pass # # Path: server/extensions.py # class CheckError(ValueError): # def custom_authentication_handler(username, password): # def custom_identity_handler(payload): # def custom_auth_response_callback(access_token, identity): # def custom_jwt_payload_handler(identity): # # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): . Output only the next line.
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']) @users_bp.route('/confirm/<token>') def confirm_email(token): email = confirm_token(token) user = User.query.filter_by(email=email).first_or_404() if user.email == email: user.active = True user.confirmed_at = datetime.utcnow() db.session.add(user) db.session.commit() flash('You have confirmed your account. Thanks!', 'success') else: flash('The confirmation link is invalid or has expired.', 'danger') return render_template("email/confirm.html") def confirm_token(token, expiration=4800): serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) try: email = serializer.loads( token, salt=app.config['SECURITY_PASSWORD_SALT'], <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from flask import ( render_template, flash, url_for, request, Blueprint, jsonify, current_app as app ) from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer from .errors_handlers import CheckError from .extensions import datastore from .models import db, User and context: # Path: server/errors_handlers.py # class CheckError(ValueError): # pass # # Path: server/extensions.py # class CheckError(ValueError): # def custom_authentication_handler(username, password): # def custom_identity_handler(payload): # def custom_auth_response_callback(access_token, identity): # def custom_jwt_payload_handler(identity): # # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): which might include code, classes, or functions. Output only the next line.
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 imports in this file: from datetime import datetime from flask import ( render_template, flash, url_for, request, Blueprint, jsonify, current_app as app ) from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer from .errors_handlers import CheckError from .extensions import datastore from .models import db, User and context (functions, classes, or occasionally code) from other files: # Path: server/errors_handlers.py # class CheckError(ValueError): # pass # # Path: server/extensions.py # class CheckError(ValueError): # def custom_authentication_handler(username, password): # def custom_identity_handler(payload): # def custom_auth_response_callback(access_token, identity): # def custom_jwt_payload_handler(identity): # # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): . Output only the next line.
'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() @jwt.authentication_handler def custom_authentication_handler(username, password): user = datastore.find_user(email=username) <|code_end|> , predict the next line using imports from the current file: from flask.ext.mail import Mail from flask.ext.cors import CORS from flask.ext.security import Security, SQLAlchemyUserDatastore from .models import User, Role, db from flask_jwt import JWT from flask import abort, jsonify, current_app from datetime import datetime and context including class names, function names, and sometimes code from other files: # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): . Output only the next line.
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): return user return None @jwt.identity_handler def custom_identity_handler(payload): user = datastore.find_user(id=payload['user_id']) return user @jwt.auth_response_handler def custom_auth_response_callback(access_token, identity): del identity return jsonify({'token': access_token.decode('utf-8')}) @jwt.jwt_payload_handler def custom_jwt_payload_handler(identity): iat = datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') <|code_end|> . Use current file imports: from flask.ext.mail import Mail from flask.ext.cors import CORS from flask.ext.security import Security, SQLAlchemyUserDatastore from .models import User, Role, db from flask_jwt import JWT from flask import abort, jsonify, current_app from datetime import datetime and context (classes, functions, or code) from other files: # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): . Output only the next line.
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('shell', Shell(make_context=make_context)) manager.add_command('db', MigrateCommand) manager.add_command('create_user', CreateUserCommand()) manager.add_command('create_role', CreateRoleCommand()) manager.add_command('add_role', AddRoleCommand()) manager.add_command('remove_role', RemoveRoleCommand()) manager.add_command('deactivate_user', DeactivateUserCommand()) manager.add_command('activate_user', ActivateUserCommand()) <|code_end|> . Write the next line using the current file imports: from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Shell, Server from flask.ext.security.script import ( CreateUserCommand, CreateRoleCommand, AddRoleCommand, RemoveRoleCommand, ActivateUserCommand, DeactivateUserCommand, ) from server.models import db from run import app and context from other files: # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): # # Path: run.py , which may include functions, classes, or code. Output only the next line.
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 from flask.ext.script import Manager, Shell, Server from flask.ext.security.script import ( CreateUserCommand, CreateRoleCommand, AddRoleCommand, RemoveRoleCommand, ActivateUserCommand, DeactivateUserCommand, ) from server.models import db from run import app and context from other files: # Path: server/models.py # class Role(db.Model, RoleMixin): # class User(db.Model, UserMixin, ValidationMixin): # class Article(db.Model): # def set_password(self, password): # def check_password(self, password): # def check_mail_for_uniqueness(self, new_email): # def check_unique_username(self, new_username): # def import_data(self, data): # def __init__(self, title, text, author): # def author_username(self): # def __repr__(self): # # Path: run.py , which may include functions, classes, or code. Output only the next line.
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_manager = APIManager() api_manager.create_api( User, methods=['GET', 'PUT'], url_prefix=REST_API_PREFIX, preprocessors=dict(GET_SINGLE=[auth_user_func], GET_MANY=[auth_admin_func]), collection_name='user', include_columns=['id', 'username', 'roles']) api_manager.create_api( Article, # results_per_page=5, methods=['GET', 'POST', 'DELETE', 'PUT'], url_prefix=REST_API_PREFIX, preprocessors=dict(GET_SINGLE=[auth_without_jwt], GET_MANY=[auth_without_jwt]), collection_name='article', <|code_end|> , generate the next line using the imports in this file: import os import logging from flask.ext.restless import APIManager from flask.ext.restless import ProcessingException from flask_jwt import jwt_required, current_identity from .models import User, Article and context (functions, classes, or occasionally code) from other files: # Path: server/models.py # class User(db.Model, UserMixin, ValidationMixin): # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(255), unique=True) # username = db.Column(db.String(50), unique=True) # password = db.Column(db.String(255)) # active = db.Column(db.Boolean(), default=False) # confirmed_at = db.Column(db.DateTime()) # roles = db.relationship('Role', secondary=roles_users, # backref=db.backref('users', lazy='dynamic')) # # def set_password(self, password): # self.password = encrypt_password(password) # # def check_password(self, password): # return verify_password(password, self.password) # # def check_mail_for_uniqueness(self, new_email): # if self.query.filter_by(email=new_email).first() is None: # result = True # else: # result = False # return result # # def check_unique_username(self, new_username): # if self.query.filter_by(username=new_username).first() is None: # result = True # else: # result = False # return result # # def import_data(self, data): # try: # self.email = data['email'] # except KeyError as key_err: # raise CheckError('Invalid user: missing ' + key_err.args[0]) # try: # self.username = data['username'] # except KeyError as key_err: # raise CheckError('Invalid username: missing ' + key_err.args[0]) # try: # self.password = data['password'] # except KeyError as key_err: # raise CheckError('Invalid password: missing ' + key_err.args[0]) # return self # # class Article(db.Model): # __tablename__ = 'article' # id = db.Column(db.Integer, primary_key=True) # title = db.Column(db.String(120), nullable=False) # slug = db.Column(db.String(120)) # text = db.Column(db.Text, nullable=False) # author = db.Column(db.Integer, db.ForeignKey('user.id')) # created_at = db.Column(db.DateTime, default=db.func.now()) # # def __init__(self, title, text, author): # self.title = title # self.text = text # self.author = author # self.created_at = datetime.utcnow() # # def author_username(self): # return unicode(User.query.filter_by(id=self.author).first().username) # # def __repr__(self): # return '<Article {}>'.format(self.title) . Output only the next line.
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_object} import REST_API_PREFIX'.format(configuration_object=configuration_object)) except Exception as e: logger.debug('Couldn\'t load REST_API_PREFIX from `%s`!\nDetails: %s', configuration_object, e) REST_API_PREFIX = REST_API_PREFIX or '/api/v1' <|code_end|> , predict the next line using imports from the current file: import os import logging from flask.ext.restless import APIManager from flask.ext.restless import ProcessingException from flask_jwt import jwt_required, current_identity from .models import User, Article and context including class names, function names, and sometimes code from other files: # Path: server/models.py # class User(db.Model, UserMixin, ValidationMixin): # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(255), unique=True) # username = db.Column(db.String(50), unique=True) # password = db.Column(db.String(255)) # active = db.Column(db.Boolean(), default=False) # confirmed_at = db.Column(db.DateTime()) # roles = db.relationship('Role', secondary=roles_users, # backref=db.backref('users', lazy='dynamic')) # # def set_password(self, password): # self.password = encrypt_password(password) # # def check_password(self, password): # return verify_password(password, self.password) # # def check_mail_for_uniqueness(self, new_email): # if self.query.filter_by(email=new_email).first() is None: # result = True # else: # result = False # return result # # def check_unique_username(self, new_username): # if self.query.filter_by(username=new_username).first() is None: # result = True # else: # result = False # return result # # def import_data(self, data): # try: # self.email = data['email'] # except KeyError as key_err: # raise CheckError('Invalid user: missing ' + key_err.args[0]) # try: # self.username = data['username'] # except KeyError as key_err: # raise CheckError('Invalid username: missing ' + key_err.args[0]) # try: # self.password = data['password'] # except KeyError as key_err: # raise CheckError('Invalid password: missing ' + key_err.args[0]) # return self # # class Article(db.Model): # __tablename__ = 'article' # id = db.Column(db.Integer, primary_key=True) # title = db.Column(db.String(120), nullable=False) # slug = db.Column(db.String(120)) # text = db.Column(db.Text, nullable=False) # author = db.Column(db.Integer, db.ForeignKey('user.id')) # created_at = db.Column(db.DateTime, default=db.func.now()) # # def __init__(self, title, text, author): # self.title = title # self.text = text # self.author = author # self.created_at = datetime.utcnow() # # def author_username(self): # return unicode(User.query.filter_by(id=self.author).first().username) # # def __repr__(self): # return '<Article {}>'.format(self.title) . Output only the next line.
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, Tuple, Union from ..util.misc import randn_c and context (classes, functions, sometimes code) from other files: # Path: pyphysim/util/misc.py # def randn_c(*args: int) -> np.ndarray: # """ # Generates a random circularly complex gaussian matrix. # # Parameters # ---------- # *args : any # Variable number of arguments (int values) specifying the # dimensions of the returned array. This is directly passed to the # numpy.random.randn function. # # Returns # ------- # result : np.ndarray # A random N-dimensional numpy array (complex dtype) where the `N` is # equal to the number of parameters passed to `randn_c`. # # Examples # -------- # >>> a = randn_c(4,3) # >>> a.shape # (4, 3) # >>> a.dtype # dtype('complex128') # # """ # # noinspection PyArgumentList # return (1.0 / math.sqrt(2.0)) * (np.random.randn(*args) + # (1j * np.random.randn(*args))) . Output only the next line.
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 containing the string below spec = """[Scenario] SNR=real_numpy_array(default=15) modulator=option('PSK', 'QAM', 'BPSK', default="PSK") <|code_end|> . Write the next line using the current file imports: from configobj import ConfigObj, flatten_errors from validate import Validator from pyphysim.simulations.configobjvalidation import real_numpy_array_check and context from other files: # Path: pyphysim/simulations/configobjvalidation.py # def real_numpy_array_check(value: Union[str, List[str]], # min: Optional[float] = None, # max: Optional[float] = None) -> List[float]: # """ # Parse and validate `value` as a numpy array (of floats). # # Value can be either a single number, a range expression in the form of # min:max or min:step:max, or even a list containing numbers and range # expressions. # # Parameters # ---------- # value : str, List[str] # The string to be converted (of a list of strings to ve converted). This # can be either a single number, a range expression in the form of min:max # or min:step:max, or even a list containing numbers and range # expressions. # min : float # The minimum allowed value. If the converted value is (or have) # lower than `min` then the VdtValueTooSmallError exception will be # raised. # max : float # The maximum allowed value. If the converted value is (or have) # greater than `man` then the VdtValueTooSmallError exception will be # raised. # # Returns # ------- # List[float] # The parsed numpy array. # # Notes # ----- # You can either separate the values with commas or spaces (any comma # will have the same effect as a space). However, if you separate with # spaces the values should be in brackets, while if you separate with # commands there should be no brackets. # # >> SNR = 0,5,10:20 # >> SNR = [0 5 10:20] # """ # if isinstance(value, str): # # Remove '[' and ']' if they exist. # if value[0] == '[' and value[-1] == ']': # value = value[1:-1].strip() # value = value.replace(',', ' ') # Replace commas with spaces # value = value.split() # Split based on spaces # # Notice that at this point value is a list of strings # # # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # # Test if it is a list or not # if isinstance(value, list): # # If it is a list, each element can be either a number of a 'range # # expression' that can be parsed with _parse_float_range_expr. We # # simple apply real_numpy_array_check on each element in the list # # to do the work and stack horizontally all the results. # out = np.hstack([real_numpy_array_check(a, min, max) for a in value]) # # else: # # It its not a list, it can be either a single number of a 'range # # expression' that can be parsed with _parse_float_range_expr # try: # out = np.array([validate.is_float(value)]) # except validate.VdtTypeError: # out = _parse_float_range_expr(value) # # # xxxxxxxxxx Validate if minimum and maximum allowed values xxxxxxxxxxx # if min is not None: # # maybe "min" was passed as a string and thus we need to convert it # # to a float # min = float(min) # if out.min() < min: # raise validate.VdtValueTooSmallError(out.min()) # # if max is not None: # # maybe "min" was passed as a string and thus we need to convert it # # to a float # max = float(max) # if out.max() > max: # raise validate.VdtValueTooBigError(out.max()) # # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # # return cast(List[float], out.tolist()) , which may include functions, classes, or code. Output only the next line.
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 : int Size of the cyclic prefix (in samples). num_used_subcarriers : int, optional Number of used subcarriers. Must be greater than or equal to 2 and lower than or equal to fft_size. If not provided, fft_size will be used Returns ------- OFDM Raises ------ ValueError If the any of the parameters are invalid.""" self.fft_size: int = 0 self.cp_size: int = 0 self.num_used_subcarriers: int = 0 self.set_parameters(fft_size, cp_size, num_used_subcarriers) <|code_end|> , determine the next line of code. You have imports: import math import numpy as np from typing import Optional, Tuple from ..channels import fading and context (class names, function names, or code) available: # Path: pyphysim/channels/fading.py # _MATPLOTLIB_AVAILABLE = True # _MATPLOTLIB_AVAILABLE = False # class TdlChannelProfile: # class TdlImpulseResponse: # class TdlChannel: # class TdlMimoChannel(TdlChannel): # def __init__(self, # tap_powers_dB: Optional[np.ndarray] = None, # tap_delays: Optional[np.ndarray] = None, # name: str = 'custom') -> None: # def mean_excess_delay(self) -> float: # def rms_delay_spread(self) -> float: # def name(self) -> str: # def tap_powers_dB(self) -> np.ndarray: # def tap_powers_linear(self) -> np.ndarray: # def tap_delays(self) -> np.ndarray: # def num_taps(self) -> int: # def num_taps_with_padding(self) -> int: # def Ts(self) -> Optional[float]: # def is_discretized(self) -> bool: # def get_discretize_profile(self, Ts: float) -> "TdlChannelProfile": # def _calc_discretized_tap_powers_and_delays( # self, Ts: float) -> Tuple[np.ndarray, np.ndarray]: # def __repr__(self) -> str: # pragma: no cover # def __init__(self, tap_values: np.ndarray, # channel_profile: TdlChannelProfile) -> None: # def tap_values_sparse(self) -> np.ndarray: # def tap_indexes_sparse(self) -> np.ndarray: # def Ts(self) -> Optional[float]: # def tap_delays_sparse(self) -> np.ndarray: # def tap_values(self) -> np.ndarray: # def num_samples(self) -> int: # def channel_profile(self) -> TdlChannelProfile: # def _get_samples_including_the_extra_zeros(self) -> np.ndarray: # def get_freq_response(self, fft_size: int) -> np.ndarray: # def __mul__(self, value: float) -> "TdlImpulseResponse": # def __rmul__(self, value: float) -> "TdlImpulseResponse": # def plot_impulse_response(self) -> None: # pragma: no cover # def plot_frequency_response(self, # fft_size: int) -> None: # pragma: no cover # def concatenate_samples( # impulse_responses: List["TdlImpulseResponse"] # ) -> "TdlImpulseResponse": # def __init__(self, # fading_generator: FadingGenerator, # channel_profile: Optional[TdlChannelProfile] = None, # tap_powers_dB: Optional[np.ndarray] = None, # tap_delays: Optional[np.ndarray] = None, # Ts: Optional[float] = None) -> None: # def switched_direction(self) -> bool: # def switched_direction(self, value: bool) -> None: # def set_num_antennas(self, num_rx_antennas: int, # num_tx_antennas: int) -> None: # def _set_fading_generator_shape(self, new_shape: Optional[Shape]) -> None: # def channel_profile(self) -> TdlChannelProfile: # def num_taps(self) -> int: # def num_taps_with_padding(self) -> int: # def generate_impulse_response(self, num_samples: int = 1) -> None: # def num_tx_antennas(self) -> int: # def num_rx_antennas(self) -> int: # def get_last_impulse_response(self) -> TdlImpulseResponse: # def __prepare_transmit_signal_shape(self, # signal: np.ndarray) -> np.ndarray: # def corrupt_data(self, signal: np.ndarray) -> np.ndarray: # def corrupt_data_in_freq_domain( # self, # signal: np.ndarray, # fft_size: int, # carrier_indexes: Optional[Indexes] = None) -> np.ndarray: # def __init__(self, # fading_generator: FadingGenerator, # channel_profile: Optional[TdlChannelProfile] = None, # tap_powers_dB: Optional[np.ndarray] = None, # tap_delays: Optional[np.ndarray] = None, # Ts: Optional[float] = None) -> None: . Output only the next line.
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} }} \\draw[-latex,shorten <=-3mm] (origem) -- (0,\\YMax) node[left]{{$\\frac{{N_0}}{{|H_n|^2}}$}}; \\draw[-latex,shorten <=-3mm,shorten >=-1mm] (origem) -- (\\XMax,0) node[below] {{Channel}}; %% Desenha nivel de agual \\def\\waterLevelCoord{{ {WaterLevelCoord} }} \\def\\waterLevelLabel{{ {WaterLevelLabel:.4f} }} \\begin{{pgfonlayer}}{{background}} \\fill[gray!30!white] (origem) rectangle (\\XMax,\\waterLevelCoord); \\end{{pgfonlayer}} \\begin{{pgfonlayer}}{{foreground}} \\draw[dashed] (0,\\waterLevelCoord) node[left] {{ \\waterLevelLabel }} -- ++(\\XMax,0); \\end{{pgfonlayer}} %% Desenha os canais \\def\\channelLength{{8mm}} \\draw[fill=white] (0,0) \\foreach \\ind/\\value in {{ {Points} }} {{ % Store coordinates P0,P1,... -| (\\ind*\\channelLength,\\value) coordinate (P\\ind) <|code_end|> . Use current file imports: import numpy as np import os from pyphysim.comm import waterfilling and context (classes, functions, or code) from other files: # Path: pyphysim/comm/waterfilling.py # def doWF(vtChannels: np.ndarray, # dPt: float, # noiseVar: float = 1.0, # Es: float = 1.0) -> Tuple[np.ndarray, float]: . Output only the next line.
}}
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 method in their __init__ method, as well as implement the calcTheoreticalSER and calcTheoreticalBER methods. """ <|code_end|> , predict the immediate next line with the help of imports: import matplotlib.pyplot as plt import math import numpy as np from typing import Optional, TypeVar, Union from pyphysim.util.conversion import binary2gray, dB2Linear, gray2binary from pyphysim.util.misc import level2bits, qfunc and context (classes, functions, sometimes code) from other files: # Path: pyphysim/util/conversion.py # def binary2gray(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number (in decimal format) to the corresponding Gray code # (still in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in decimal encoding # # Returns # ------- # num_gray : int | np.ndarray # Corresponding gray code (in decimal format) of `num`. # # Examples # -------- # >>> binary2gray(np.arange(0, 8)) # array([0, 1, 3, 2, 6, 7, 5, 4]) # """ # return xor((num >> 1), num) # # def dB2Linear(valueIndB: NumberOrArray) -> NumberOrArray: # """ # Convert input from dB to linear scale. # # Parameters # ---------- # valueIndB : int | float | np.ndarray # Value in dB # # Returns # ------- # valueInLinear : int | float | np.ndarray # Value in Linear scale. # # Examples # -------- # >>> dB2Linear(30) # 1000.0 # """ # return pow(10, valueIndB / 10.0) # # def gray2binary(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number in Gray code (in decimal format) to its original # value (in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in gray coding # # Returns # ------- # num_orig : int | np.ndarray # The original number (in decimal format) whose Gray code # correspondent is `num`. # # Examples # -------- # >>> gray2binary(binary2gray(np.arange(0,10))) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # # """ # temp = xor(num, (num >> 8)) # temp = xor(temp, (temp >> 4)) # temp = xor(temp, (temp >> 2)) # temp = xor(temp, (temp >> 1)) # # return temp # # Path: pyphysim/util/misc.py # def level2bits(n: int) -> int: # """ # Calculates the number of bits needed to represent n different # values. # # Parameters # ---------- # n : int # Number of different levels. # # Returns # ------- # num_bits : int # Number of bits required to represent `n` levels. # # Examples # -------- # >>> list(map(level2bits,range(1,20))) # [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5] # """ # if n < 1: # raise ValueError("level2bits: n must be greater then one") # return int2bits(n - 1) # # def qfunc(x: float) -> float: # """ # Calculates the 'q' function of x. # # Parameters # ---------- # x : float # The value to apply the Q function. # # Returns # ------- # result : float # Qfunc(x) # # Examples # -------- # >>> qfunc(0.0) # 0.5 # >>> round(qfunc(1.0), 9) # 0.158655254 # >>> round(qfunc(3.0), 9) # 0.001349898 # """ # return cast(float, 0.5 * erfc(x / math.sqrt(2))) . Output only the next line.
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__ method, as well as implement the calcTheoreticalSER and calcTheoreticalBER methods. """ try: # noinspection PyUnresolvedReferences _MATPLOTLIB_AVAILABLE = True except ImportError: # pragma: no cover _MATPLOTLIB_AVAILABLE = False PI = np.pi NumberOrArray = TypeVar("NumberOrArray", np.ndarray, float) __all__ = ['Modulator', 'PSK', 'QPSK', 'BPSK', 'QAM'] # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Modulator Class xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx <|code_end|> , determine the next line of code. You have imports: import matplotlib.pyplot as plt import math import numpy as np from typing import Optional, TypeVar, Union from pyphysim.util.conversion import binary2gray, dB2Linear, gray2binary from pyphysim.util.misc import level2bits, qfunc and context (class names, function names, or code) available: # Path: pyphysim/util/conversion.py # def binary2gray(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number (in decimal format) to the corresponding Gray code # (still in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in decimal encoding # # Returns # ------- # num_gray : int | np.ndarray # Corresponding gray code (in decimal format) of `num`. # # Examples # -------- # >>> binary2gray(np.arange(0, 8)) # array([0, 1, 3, 2, 6, 7, 5, 4]) # """ # return xor((num >> 1), num) # # def dB2Linear(valueIndB: NumberOrArray) -> NumberOrArray: # """ # Convert input from dB to linear scale. # # Parameters # ---------- # valueIndB : int | float | np.ndarray # Value in dB # # Returns # ------- # valueInLinear : int | float | np.ndarray # Value in Linear scale. # # Examples # -------- # >>> dB2Linear(30) # 1000.0 # """ # return pow(10, valueIndB / 10.0) # # def gray2binary(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number in Gray code (in decimal format) to its original # value (in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in gray coding # # Returns # ------- # num_orig : int | np.ndarray # The original number (in decimal format) whose Gray code # correspondent is `num`. # # Examples # -------- # >>> gray2binary(binary2gray(np.arange(0,10))) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # # """ # temp = xor(num, (num >> 8)) # temp = xor(temp, (temp >> 4)) # temp = xor(temp, (temp >> 2)) # temp = xor(temp, (temp >> 1)) # # return temp # # Path: pyphysim/util/misc.py # def level2bits(n: int) -> int: # """ # Calculates the number of bits needed to represent n different # values. # # Parameters # ---------- # n : int # Number of different levels. # # Returns # ------- # num_bits : int # Number of bits required to represent `n` levels. # # Examples # -------- # >>> list(map(level2bits,range(1,20))) # [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5] # """ # if n < 1: # raise ValueError("level2bits: n must be greater then one") # return int2bits(n - 1) # # def qfunc(x: float) -> float: # """ # Calculates the 'q' function of x. # # Parameters # ---------- # x : float # The value to apply the Q function. # # Returns # ------- # result : float # Qfunc(x) # # Examples # -------- # >>> qfunc(0.0) # 0.5 # >>> round(qfunc(1.0), 9) # 0.158655254 # >>> round(qfunc(3.0), 9) # 0.001349898 # """ # return cast(float, 0.5 * erfc(x / math.sqrt(2))) . Output only the next line.
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 method in their __init__ method, as well as implement the calcTheoreticalSER and calcTheoreticalBER methods. """ try: # noinspection PyUnresolvedReferences _MATPLOTLIB_AVAILABLE = True except ImportError: # pragma: no cover _MATPLOTLIB_AVAILABLE = False PI = np.pi NumberOrArray = TypeVar("NumberOrArray", np.ndarray, float) <|code_end|> , predict the immediate next line with the help of imports: import matplotlib.pyplot as plt import math import numpy as np from typing import Optional, TypeVar, Union from pyphysim.util.conversion import binary2gray, dB2Linear, gray2binary from pyphysim.util.misc import level2bits, qfunc and context (classes, functions, sometimes code) from other files: # Path: pyphysim/util/conversion.py # def binary2gray(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number (in decimal format) to the corresponding Gray code # (still in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in decimal encoding # # Returns # ------- # num_gray : int | np.ndarray # Corresponding gray code (in decimal format) of `num`. # # Examples # -------- # >>> binary2gray(np.arange(0, 8)) # array([0, 1, 3, 2, 6, 7, 5, 4]) # """ # return xor((num >> 1), num) # # def dB2Linear(valueIndB: NumberOrArray) -> NumberOrArray: # """ # Convert input from dB to linear scale. # # Parameters # ---------- # valueIndB : int | float | np.ndarray # Value in dB # # Returns # ------- # valueInLinear : int | float | np.ndarray # Value in Linear scale. # # Examples # -------- # >>> dB2Linear(30) # 1000.0 # """ # return pow(10, valueIndB / 10.0) # # def gray2binary(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number in Gray code (in decimal format) to its original # value (in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in gray coding # # Returns # ------- # num_orig : int | np.ndarray # The original number (in decimal format) whose Gray code # correspondent is `num`. # # Examples # -------- # >>> gray2binary(binary2gray(np.arange(0,10))) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # # """ # temp = xor(num, (num >> 8)) # temp = xor(temp, (temp >> 4)) # temp = xor(temp, (temp >> 2)) # temp = xor(temp, (temp >> 1)) # # return temp # # Path: pyphysim/util/misc.py # def level2bits(n: int) -> int: # """ # Calculates the number of bits needed to represent n different # values. # # Parameters # ---------- # n : int # Number of different levels. # # Returns # ------- # num_bits : int # Number of bits required to represent `n` levels. # # Examples # -------- # >>> list(map(level2bits,range(1,20))) # [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5] # """ # if n < 1: # raise ValueError("level2bits: n must be greater then one") # return int2bits(n - 1) # # def qfunc(x: float) -> float: # """ # Calculates the 'q' function of x. # # Parameters # ---------- # x : float # The value to apply the Q function. # # Returns # ------- # result : float # Qfunc(x) # # Examples # -------- # >>> qfunc(0.0) # 0.5 # >>> round(qfunc(1.0), 9) # 0.158655254 # >>> round(qfunc(3.0), 9) # 0.001349898 # """ # return cast(float, 0.5 * erfc(x / math.sqrt(2))) . Output only the next line.
__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 self.setConstellation method in their __init__ method, as well as implement the calcTheoreticalSER and calcTheoreticalBER methods. """ try: # noinspection PyUnresolvedReferences _MATPLOTLIB_AVAILABLE = True except ImportError: # pragma: no cover <|code_end|> with the help of current file imports: import matplotlib.pyplot as plt import math import numpy as np from typing import Optional, TypeVar, Union from pyphysim.util.conversion import binary2gray, dB2Linear, gray2binary from pyphysim.util.misc import level2bits, qfunc and context from other files: # Path: pyphysim/util/conversion.py # def binary2gray(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number (in decimal format) to the corresponding Gray code # (still in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in decimal encoding # # Returns # ------- # num_gray : int | np.ndarray # Corresponding gray code (in decimal format) of `num`. # # Examples # -------- # >>> binary2gray(np.arange(0, 8)) # array([0, 1, 3, 2, 6, 7, 5, 4]) # """ # return xor((num >> 1), num) # # def dB2Linear(valueIndB: NumberOrArray) -> NumberOrArray: # """ # Convert input from dB to linear scale. # # Parameters # ---------- # valueIndB : int | float | np.ndarray # Value in dB # # Returns # ------- # valueInLinear : int | float | np.ndarray # Value in Linear scale. # # Examples # -------- # >>> dB2Linear(30) # 1000.0 # """ # return pow(10, valueIndB / 10.0) # # def gray2binary(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number in Gray code (in decimal format) to its original # value (in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in gray coding # # Returns # ------- # num_orig : int | np.ndarray # The original number (in decimal format) whose Gray code # correspondent is `num`. # # Examples # -------- # >>> gray2binary(binary2gray(np.arange(0,10))) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # # """ # temp = xor(num, (num >> 8)) # temp = xor(temp, (temp >> 4)) # temp = xor(temp, (temp >> 2)) # temp = xor(temp, (temp >> 1)) # # return temp # # Path: pyphysim/util/misc.py # def level2bits(n: int) -> int: # """ # Calculates the number of bits needed to represent n different # values. # # Parameters # ---------- # n : int # Number of different levels. # # Returns # ------- # num_bits : int # Number of bits required to represent `n` levels. # # Examples # -------- # >>> list(map(level2bits,range(1,20))) # [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5] # """ # if n < 1: # raise ValueError("level2bits: n must be greater then one") # return int2bits(n - 1) # # def qfunc(x: float) -> float: # """ # Calculates the 'q' function of x. # # Parameters # ---------- # x : float # The value to apply the Q function. # # Returns # ------- # result : float # Qfunc(x) # # Examples # -------- # >>> qfunc(0.0) # 0.5 # >>> round(qfunc(1.0), 9) # 0.158655254 # >>> round(qfunc(3.0), 9) # 0.001349898 # """ # return cast(float, 0.5 * erfc(x / math.sqrt(2))) , which may contain function names, class names, or code. Output only the next line.
_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 in their __init__ method, as well as implement the calcTheoreticalSER and calcTheoreticalBER methods. """ try: # noinspection PyUnresolvedReferences _MATPLOTLIB_AVAILABLE = True except ImportError: # pragma: no cover _MATPLOTLIB_AVAILABLE = False <|code_end|> , continue by predicting the next line. Consider current file imports: import matplotlib.pyplot as plt import math import numpy as np from typing import Optional, TypeVar, Union from pyphysim.util.conversion import binary2gray, dB2Linear, gray2binary from pyphysim.util.misc import level2bits, qfunc and context: # Path: pyphysim/util/conversion.py # def binary2gray(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number (in decimal format) to the corresponding Gray code # (still in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in decimal encoding # # Returns # ------- # num_gray : int | np.ndarray # Corresponding gray code (in decimal format) of `num`. # # Examples # -------- # >>> binary2gray(np.arange(0, 8)) # array([0, 1, 3, 2, 6, 7, 5, 4]) # """ # return xor((num >> 1), num) # # def dB2Linear(valueIndB: NumberOrArray) -> NumberOrArray: # """ # Convert input from dB to linear scale. # # Parameters # ---------- # valueIndB : int | float | np.ndarray # Value in dB # # Returns # ------- # valueInLinear : int | float | np.ndarray # Value in Linear scale. # # Examples # -------- # >>> dB2Linear(30) # 1000.0 # """ # return pow(10, valueIndB / 10.0) # # def gray2binary(num: IntOrIntArray) -> IntOrIntArray: # """ # Convert a number in Gray code (in decimal format) to its original # value (in decimal format). # # Parameters # ---------- # num : int | np.ndarray # The number in gray coding # # Returns # ------- # num_orig : int | np.ndarray # The original number (in decimal format) whose Gray code # correspondent is `num`. # # Examples # -------- # >>> gray2binary(binary2gray(np.arange(0,10))) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # # """ # temp = xor(num, (num >> 8)) # temp = xor(temp, (temp >> 4)) # temp = xor(temp, (temp >> 2)) # temp = xor(temp, (temp >> 1)) # # return temp # # Path: pyphysim/util/misc.py # def level2bits(n: int) -> int: # """ # Calculates the number of bits needed to represent n different # values. # # Parameters # ---------- # n : int # Number of different levels. # # Returns # ------- # num_bits : int # Number of bits required to represent `n` levels. # # Examples # -------- # >>> list(map(level2bits,range(1,20))) # [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5] # """ # if n < 1: # raise ValueError("level2bits: n must be greater then one") # return int2bits(n - 1) # # def qfunc(x: float) -> float: # """ # Calculates the 'q' function of x. # # Parameters # ---------- # x : float # The value to apply the Q function. # # Returns # ------- # result : float # Qfunc(x) # # Examples # -------- # >>> qfunc(0.0) # 0.5 # >>> round(qfunc(1.0), 9) # 0.158655254 # >>> round(qfunc(3.0), 9) # 0.001349898 # """ # return cast(float, 0.5 * erfc(x / math.sqrt(2))) which might include code, classes, or functions. Output only the next line.
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_size', 'batch_size', 'max_step', 'model_dir', 'lr_rate', 'clip_gradient_norm', 'burn_in_step', 'increment_step', 'train_steps']) def config_word2pos(): # load vocab src_vocab = build_vocab('data/vocab.word', 256, ' ') trg_vocab = build_vocab('data/vocab.tag', 32, ' ') params = {'encoder': {'rnn_cell': {'state_size': 512, 'cell_name': 'BasicLSTMCell', 'num_layers': 1, 'input_keep_prob': 1.0, 'output_keep_prob': 1.0}, 'attention_key_size': 256}, 'decoder': {'rnn_cell': {'cell_name': 'BasicLSTMCell', <|code_end|> . Use current file imports: (from collections import namedtuple from build_inputs import build_vocab) and context including class names, function names, or small code snippets from other files: # Path: build_inputs.py # def build_vocab(vocab_file, embedding_dim, delimiter=' '): # # construct vocab # with open(vocab_file, 'r') as f: # symbols = [s[:-1] for s in f.readlines()] # vocab = sq.Vocab(symbols, embedding_dim, delimiter) # return vocab . Output only the next line.
'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() my_layer = MyLayer() assert my_layer.name == 'my_layer' def test_graph(): MyLayer('graph') graph = Graph() assert len(graph.layers) == 2 try: my_layer = MyLayer() graph.add_layers(my_layer) except ValueError: graph.clear_layers() return assert False if __name__ == '__main__': <|code_end|> , determine the next line of code. You have imports: from sequencing_np.nn.base import Layer, Graph and context (class names, function names, or code) available: # Path: sequencing_np/nn/base.py # class Layer(object): # """Base layer class.""" # # def __init__(self, params_keys, base_name=None, name=None, # dtype=DTYPE, **kwargs): # """ # Base class of all layers. # # :param params_keys: name of params # :param base_name: similar to scope # :param name: Layer name # :param dtype: # :param kwargs: # """ # # if not name: # name = self.to_snake_case(self.__class__.__name__) # # # to match the trained params from tensorflow # self.name = '{}/{}'.format(base_name, name) if base_name else name # self.dtype = dtype # # self.params = dict.fromkeys(params_keys) # graph = Graph() # graph.add_layers(self) # # def initialize(self, trained_params): # """ # Initialize this layer by the params from tensorflow. # TODO: Try to match the convention in tensorflow # # :param trained_params: dict of trained params # :return: # """ # # for k in self.params: # key = '{}/{}'.format(self.name, k) # self.params[k] = trained_params[key] # # @staticmethod # def to_snake_case(name): # intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) # insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() # # If the class is private the name starts with "_" which is not secure # # for creating scopes. We prefix the name with "private" in this case. # if insecure[0] != '_': # return insecure # return 'private' + insecure # # class Graph(metaclass=Singleton): # """ # Graph should be a singleton. # """ # def __init__(self): # self.layers = {} # # def add_layers(self, layer): # # collect layers # if layer.name in self.layers: # raise ValueError('Duplicated layer: {}'.format(layer.name)) # self.layers[layer.name] = layer # # def clear_layers(self): # self.layers = {} # # def print_vars(self): # # for debug # for k in self.layers: # print(self.layers[k].params) # # def initialize(self, trained_params): # """ # Use tensorflow trained params to initialize np model # # :param trained_params: dict # :return: # """ # for k in self.layers: # layer = self.layers[k] # layer.initialize(trained_params) . Output only the next line.
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_name, name, dtype, **kwargs) def test_base(): graph = Graph() graph.clear_layers() my_layer = MyLayer() assert my_layer.name == 'my_layer' def test_graph(): MyLayer('graph') graph = Graph() assert len(graph.layers) == 2 try: my_layer = MyLayer() graph.add_layers(my_layer) except ValueError: <|code_end|> , determine the next line of code. You have imports: from sequencing_np.nn.base import Layer, Graph and context (class names, function names, or code) available: # Path: sequencing_np/nn/base.py # class Layer(object): # """Base layer class.""" # # def __init__(self, params_keys, base_name=None, name=None, # dtype=DTYPE, **kwargs): # """ # Base class of all layers. # # :param params_keys: name of params # :param base_name: similar to scope # :param name: Layer name # :param dtype: # :param kwargs: # """ # # if not name: # name = self.to_snake_case(self.__class__.__name__) # # # to match the trained params from tensorflow # self.name = '{}/{}'.format(base_name, name) if base_name else name # self.dtype = dtype # # self.params = dict.fromkeys(params_keys) # graph = Graph() # graph.add_layers(self) # # def initialize(self, trained_params): # """ # Initialize this layer by the params from tensorflow. # TODO: Try to match the convention in tensorflow # # :param trained_params: dict of trained params # :return: # """ # # for k in self.params: # key = '{}/{}'.format(self.name, k) # self.params[k] = trained_params[key] # # @staticmethod # def to_snake_case(name): # intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) # insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() # # If the class is private the name starts with "_" which is not secure # # for creating scopes. We prefix the name with "private" in this case. # if insecure[0] != '_': # return insecure # return 'private' + insecure # # class Graph(metaclass=Singleton): # """ # Graph should be a singleton. # """ # def __init__(self): # self.layers = {} # # def add_layers(self, layer): # # collect layers # if layer.name in self.layers: # raise ValueError('Duplicated layer: {}'.format(layer.name)) # self.layers[layer.name] = layer # # def clear_layers(self): # self.layers = {} # # def print_vars(self): # # for debug # for k in self.layers: # print(self.layers[k].params) # # def initialize(self, trained_params): # """ # Use tensorflow trained params to initialize np model # # :param trained_params: dict # :return: # """ # for k in self.layers: # layer = self.layers[k] # layer.initialize(trained_params) . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class ConfigVlanCommandProcessor(BaseCommandProcessor): def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): super(ConfigVlanCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) <|code_end|> , generate the next line using the imports in this file: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and context (functions, classes, or occasionally code) from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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): self.child.send(data.encode()) class SshTester(ProtocolTester): CONF_KEY = "ssh" def get_ssh_connect_command(self): return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ % (self.username, self.host, self.port) def login(self): self.wait_for('[pP]assword: ', regex=True) self.write_invisible(self.password) self.wait_for('[>#]$', regex=True) class TelnetTester(ProtocolTester): CONF_KEY = "telnet" def get_ssh_connect_command(self): <|code_end|> with the help of current file imports: import logging import re import unittest import pexpect from functools import wraps from flexmock import flexmock_teardown from hamcrest import assert_that, equal_to from tests.util.global_reactor import TEST_SWITCHES and context from other files: # Path: tests/util/global_reactor.py # TEST_SWITCHES = { # "arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "http": _unique_port(), # "extra": {}, # }, # "brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "password": "Br0cad3" # }, # }, # "cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "CiSc000" # }, # }, # "cisco-auto-enabled": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "auto_enabled": True # }, # }, # "cisco6500": { # "model": "cisco_6500", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": {}, # }, # "dell": { # "model": "dell_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL10G" # }, # }, # "dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL" # }, # }, # "juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_qfx": { # "model": "juniper_qfx_copper_generic", # "hostname": "ju_ju_ju_juniper_qfx_copper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_mx": { # "model": "juniper_mx_generic", # "hostname": "super_juniper_mx", # "ssh": _unique_port(), # "extra": {}, # }, # "commit-delayed-arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell": { # "model": "dell_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # } # } , which may contain function names, class names, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class Dell10GConfigureVlanCommandProcessor(BaseCommandProcessor): def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): super(Dell10GConfigureVlanCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) self.vlan = args[0] <|code_end|> , predict the immediate next line with the help of imports: from fake_switches.command_processing.base_command_processor import \ BaseCommandProcessor and context (classes, functions, sometimes code) from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class SwitchTftpParser(object): def __init__(self, configuration, reader=None): self.configuration = configuration self.reader = reader if reader else tftp_reader self.logger = logging.getLogger("fake_switches.%s.tftp" % self.configuration.name) def parse(self, url, filename, command_processor): self.logger.info("Reading : %s/%s" % (url, filename)) data = self.reader.read_tftp(url, filename).split("\n") command_processor.init( self.configuration, NoopTerminalController(), self.logger, NotPipingProcessor()) <|code_end|> , predict the immediate next line with the help of imports: import logging from fake_switches.adapters import tftp_reader from fake_switches.command_processing.piping_processor_base import NotPipingProcessor from fake_switches.terminal import NoopTerminalController and context (classes, functions, sometimes code) from other files: # Path: fake_switches/adapters/tftp_reader.py # def read_tftp(server, remote_filename, port=69): # def __init__(self): # def write(self, data): # class FakeFile(object): . Output only the next line.
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_([ { 'vlans': {}, 'sourceDetail': '', 'errors': ['VLAN 999 not found in current VLAN database'] } ])) def test_execute_show_vlan_invalid_input(self): with self.assertRaises(CommandError) as expect: self.connection.execute("show vlan shizzle") assert_that(str(expect.exception), is_( "Error [1002]: CLI command 1 of 1 'show vlan shizzle' failed: invalid command " "[Invalid input]" )) def test_add_and_remove_vlan(self): result = Vlans(self.node).configure_vlan("737", ["name wwaaat!"]) assert_that(result, is_(True)) result = Vlans(self.node).delete("737") assert_that(result, is_(True)) <|code_end|> , generate the next line using the imports in this file: import unittest import pyeapi from hamcrest import assert_that, is_ from pyeapi.api.vlans import Vlans from pyeapi.eapilib import CommandError from tests.util.global_reactor import TEST_SWITCHES and context (functions, classes, or occasionally code) from other files: # Path: tests/util/global_reactor.py # TEST_SWITCHES = { # "arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "http": _unique_port(), # "extra": {}, # }, # "brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "password": "Br0cad3" # }, # }, # "cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "CiSc000" # }, # }, # "cisco-auto-enabled": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "auto_enabled": True # }, # }, # "cisco6500": { # "model": "cisco_6500", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": {}, # }, # "dell": { # "model": "dell_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL10G" # }, # }, # "dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL" # }, # }, # "juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_qfx": { # "model": "juniper_qfx_copper_generic", # "hostname": "ju_ju_ju_juniper_qfx_copper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_mx": { # "model": "juniper_mx_generic", # "hostname": "super_juniper_mx", # "ssh": _unique_port(), # "extra": {}, # }, # "commit-delayed-arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell": { # "model": "dell_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # } # } . Output only the next line.
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(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["extra"]["password"]) t.read("\r\n") t.read("my_switch#") @with_protocol def test_wrong_password(self, t): t.write("enable") t.read("Password:") t.write_stars("hello_world") t.readln("Incorrect Password!") t.read("my_switch>") @with_protocol <|code_end|> , predict the immediate next line with the help of imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context (classes, functions, sometimes code) from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class DellUnprivilegedTest(ProtocolTest): __test__ = False tester_class = SshTester test_switch = "dell" @with_protocol <|code_end|> . Write the next line using the current file imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) , which may include functions, classes, or code. Output only the next line.
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["extra"]["password"]) t.read("\r\n") t.read("my_switch#") @with_protocol def test_wrong_password(self, t): t.write("enable") t.read("Password:") t.write_stars("hello_world") t.readln("Incorrect Password!") t.read("my_switch>") @with_protocol def test_no_password_works_for_legacy_reasons(self, t): t.write("enable") t.read("Password:") t.write_stars("") t.read("\r\n") <|code_end|> . Write the next line using the current file imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) , which may include functions, classes, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. 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["extra"]["password"]) t.read("\r\n") <|code_end|> , predict the immediate next line with the help of imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context (classes, functions, sometimes code) from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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/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 for the specific language governing permissions and # limitations under the License. class ConfigVrfCommandProcessor(BaseCommandProcessor): def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): super(ConfigVrfCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) self.vrf = args[0] <|code_end|> , predict the next line using imports from the current file: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and context including class names, function names, and sometimes code from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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) Duplicate ip address") break else: if new_ip.ip in ip: if len(args) > 2 and "secondary".startswith(args[2]): if not next((ip for ip in self.port.secondary_ips if ip.ip == new_ip.ip), False): self.port.add_secondary_ip(new_ip) else: self.write_line("IP/Port: Errno(6) Duplicate ip address") break else: self.write_line( "IP/Port: Errno(15) Can only assign one primary ip address per subnet") break else: self.write_line("IP/Port: Errno(11) ip subnet overlap with another interface") if "access-group".startswith(args[0]): if "in".startswith(args[2]): self.port.access_group_in = args[1] elif "out".startswith(args[2]): self.port.access_group_out = args[1] self.write_line("Warning: An undefined or zero length ACL has been applied. " "Filtering will not occur for the specified interface VE {} (outbound)." <|code_end|> . Use current file imports: (from netaddr import IPNetwork from netaddr.ip import IPAddress from fake_switches.brocade.command_processor.config_interface import ConfigInterfaceCommandProcessor) and context including class names, function names, or small code snippets from other files: # Path: fake_switches/brocade/command_processor/config_interface.py # class ConfigInterfaceCommandProcessor(BaseCommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # super(ConfigInterfaceCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) # self.port = args[0] # # def get_prompt(self): # return "SSH@%s(config-if-e1000-%s)#" % (self.switch_configuration.name, split_port_name(self.port.name)[1]) # # def do_enable(self, *_): # self.port.shutdown = False # # def do_disable(self, *_): # self.port.shutdown = None # # def do_vrf(self, *args): # if "forwarding".startswith(args[0]): # if len(args) > 1: # if isinstance(self.port, VlanPort): # for ip in self.port.ips[:]: # self.port.remove_ip(ip) # vrf = self.switch_configuration.get_vrf(args[1]) # if vrf is None: # self.write_line("Error - VRF({}) does not exist or Route-Distinguisher not specified or Address Family not configured".format( # args[1])) # else: # self.port.vrf = vrf # self.write_line("Warning: All IPv4 and IPv6 addresses (including link-local) on this interface have been removed") # # def do_no_vrf(self, *args): # if "forwarding".startswith(args[0]): # if len(args) == 1: # self.write_line("Incomplete command.") # elif self.port.vrf.name != args[1]: # self.write_line("Error - VRF({}) does not exist or Route-Distinguisher not specified or Address Family not configured".format( # args[1])) # else: # if isinstance(self.port, VlanPort): # for ip in self.port.ips[:]: # self.port.remove_ip(ip) # self.port.vrf = None # self.write_line("Warning: All IPv4 and IPv6 addresses (including link-local) on this interface have been removed") # # def do_exit(self): # self.is_done = True # # def do_port_name(self, *args): # self.port.description = " ".join(args) # # def do_no_port_name(self, *_): # self.port.description = None . Output only the next line.
.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.connect() tester1.write("enable") <|code_end|> , generate the next line using the imports in this file: import unittest from tests.util.global_reactor import TEST_SWITCHES from tests.util.protocol_util import SshTester, TelnetTester and context (functions, classes, or occasionally code) from other files: # Path: tests/util/global_reactor.py # TEST_SWITCHES = { # "arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "http": _unique_port(), # "extra": {}, # }, # "brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "password": "Br0cad3" # }, # }, # "cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "CiSc000" # }, # }, # "cisco-auto-enabled": { # "model": "cisco_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "auto_enabled": True # }, # }, # "cisco6500": { # "model": "cisco_6500", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": {}, # }, # "dell": { # "model": "dell_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL10G" # }, # }, # "dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "telnet": _unique_port(), # "ssh": _unique_port(), # "extra": { # "password": "DeLL" # }, # }, # "juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_qfx": { # "model": "juniper_qfx_copper_generic", # "hostname": "ju_ju_ju_juniper_qfx_copper", # "ssh": _unique_port(), # "extra": { # "ports": _juniper_ports_with_less_ae() # }, # }, # "juniper_mx": { # "model": "juniper_mx_generic", # "hostname": "super_juniper_mx", # "ssh": _unique_port(), # "extra": {}, # }, # "commit-delayed-arista": { # "model": "arista_generic", # "hostname": "my_arista", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-brocade": { # "model": "brocade_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-cisco": { # "model": "cisco_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell": { # "model": "dell_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-dell10g": { # "model": "dell10g_generic", # "hostname": "my_switch", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # }, # "commit-delayed-juniper": { # "model": "juniper_generic", # "hostname": "ju_ju_ju_juniper", # "ssh": _unique_port(), # "extra": { # "commit_delay": COMMIT_DELAY # }, # } # } # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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.write("configure terminal") t.read("SSH@my_switch(config)#") t.write("vlan -1") t.readln("Invalid input -> -1") t.readln("Type ? for a list") t.read("SSH@my_switch(config)#") t.write("vlan 0") t.readln("Error: vlan ID value 0 not allowed.") t.read("SSH@my_switch(config)#") t.write("vlan 1") t.read("SSH@my_switch(config-vlan-1)#") t.write("exit") t.read("SSH@my_switch(config)#") t.write("vlan 4090") <|code_end|> . Use current file imports: (import mock from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest) and context including class names, function names, or small code snippets from other files: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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("Type ? for a list") t.read("SSH@my_switch(config)#") t.write("no interface ethe 2/1") t.readln("Error - interface 2/1 is not an ETHERNET interface") t.read("SSH@my_switch(config)#") t.write("exit") t.read("SSH@my_switch#") @with_protocol def test_command_interface_invalid_interface_name(self, t): enable(t) t.write("configure terminal") t.read("SSH@my_switch(config)#") t.write("interface ethe 1/25") t.readln("Error - invalid interface 1/25") t.read("SSH@my_switch(config)#") t.write("interface ethe 1/64") <|code_end|> , determine the next line of code. You have imports: import mock from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context (class names, function names, or code) available: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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, Name [None], Priority Level -, Priority Force 0, Creation Type STATIC") t.readln("Topo HW idx : 81 Topo SW idx: 257 Topo next vlan: 0") t.readln("L2 protocols : STP") t.readln("Untagged Ports : ethe 1/2") t.readln("Associated Virtual Interface Id: NONE") t.readln("----------------------------------------------------------") t.readln("Port Type Tag-Mode Protocol State") t.readln("1/2 PHYSICAL UNTAGGED STP DISABLED") t.readln("Arp Inspection: 0") t.readln("DHCP Snooping: 0") t.readln("IPv4 Multicast Snooping: Disabled") t.readln("IPv6 Multicast Snooping: Disabled") t.readln("") t.readln("No Virtual Interfaces configured for this vlan") t.read("SSH@my_switch#") set_interface_tagged_on_vlan(t, "ethernet 1/4", "1600") t.write("show vlan 1600") t.readln("") t.readln("PORT-VLAN 1600, Name [None], Priority Level -, Priority Force 0, Creation Type STATIC") t.readln("Topo HW idx : 81 Topo SW idx: 257 Topo next vlan: 0") t.readln("L2 protocols : STP") <|code_end|> with the help of current file imports: import mock from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context from other files: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() , which may contain function names, class names, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class Dell10GUnprivilegedTest(ProtocolTest): __test__ = False tester_class = SshTester <|code_end|> , predict the immediate next line with the help of imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context (classes, functions, sometimes code) from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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("enable") t.read("Password:") t.write_stars("hello_world") t.readln("Incorrect Password!") t.read("my_switch>") @with_protocol def test_no_password_works_for_legacy_reasons(self, t): t.write("enable") t.read("Password:") t.write_stars("") t.read("\r\n") t.read("my_switch#") @with_protocol def test_exit_disconnects(self, t): t.write("exit") t.read_eof() @with_protocol def test_quit_disconnects(self, t): <|code_end|> , generate the next line using the imports in this file: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context (functions, classes, or occasionally code) from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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_switch#") @with_protocol def test_wrong_password(self, t): t.write("enable") t.read("Password:") t.write_stars("hello_world") t.readln("Incorrect Password!") t.read("my_switch>") @with_protocol def test_no_password_works_for_legacy_reasons(self, t): t.write("enable") t.read("Password:") t.write_stars("") t.read("\r\n") t.read("my_switch#") @with_protocol def test_exit_disconnects(self, t): <|code_end|> , continue by predicting the next line. Consider current file imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) which might include code, classes, or functions. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class Dell10GUnprivilegedTest(ProtocolTest): __test__ = False 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") <|code_end|> . Use current file imports: from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester and context (classes, functions, or code) from other files: # Path: tests/util/protocol_util.py # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() # # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) . Output only the next line.
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 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 DellDefaultCommandProcessor(BaseCommandProcessor): def __init__(self, enabled): super(DellDefaultCommandProcessor, self).__init__() self.enabled_processor = enabled def get_prompt(self): return "\n" + "%s>" % self.switch_configuration.name def do_enable(self): self.write("Password:") self.replace_input = '*' self.continue_to(self.continue_enabling) def continue_enabling(self, line): self.replace_input = False if line == "" or line in self.switch_configuration.privileged_passwords: self.write_line("") self.move_to(self.enabled_processor) <|code_end|> , predict the next line using imports from the current file: from fake_switches.command_processing.base_command_processor import \ BaseCommandProcessor and context including class names, function names, and sometimes code from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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. # See the License for the specific language governing permissions and # limitations under the License. class DellConfigCommandProcessor(ConfigCommandProcessor): interface_separator = ' ' def get_prompt(self): return "\n" + self.switch_configuration.name + "(config)#" def do_vlan(self, *args): if "database".startswith(args[0]): self.move_to(self.config_vlan_processor) def do_interface(self, *args): if 'vlan'.startswith(args[0]): vlan_id = int(args[1]) vlan = self.switch_configuration.get_vlan(vlan_id) if vlan is None: self.write_line("VLAN ID not found.") return self.write_line("") super(DellConfigCommandProcessor, self).do_interface(*args) <|code_end|> using the current file's imports: from fake_switches.cisco.command_processor.config import \ ConfigCommandProcessor and any relevant context from other files: # Path: fake_switches/cisco/command_processor/config.py # class ConfigCommandProcessor(BaseCommandProcessor): # interface_separator = "" # # def __init__(self, config_vlan, config_vrf, config_interface): # super(ConfigCommandProcessor, self).__init__() # self.config_vlan_processor = config_vlan # self.config_vrf_processor = config_vrf # self.config_interface_processor = config_interface # # def get_prompt(self): # return self.switch_configuration.name + "(config)#" # # def do_vlan(self, raw_number, *_): # number = int(raw_number) # if number < 0: # self.write_line("Command rejected: Bad VLAN list - character #1 ('-') delimits a VLAN number") # self.write_line(" which is out of the range 1..4094.") # elif number < 1 or number > 4094: # self.write_line("Command rejected: Bad VLAN list - character #X (EOL) delimits a VLAN") # self.write_line("number which is out of the range 1..4094.") # else: # vlan = self.switch_configuration.get_vlan(number) # if not vlan: # vlan = self.switch_configuration.new("Vlan", number) # self.switch_configuration.add_vlan(vlan) # self.move_to(self.config_vlan_processor, vlan) # # def do_no_vlan(self, *args): # vlan = self.switch_configuration.get_vlan(int(args[0])) # if vlan: # self.switch_configuration.remove_vlan(vlan) # # def do_no_ip(self, cmd, *args): # if "vrf".startswith(cmd): # self.switch_configuration.remove_vrf(args[0]) # elif "route".startswith(cmd): # self.switch_configuration.remove_static_route(args[0], args[1]) # # def do_ip(self, cmd, *args): # if "vrf".startswith(cmd): # vrf = self.switch_configuration.new("VRF", args[0]) # self.switch_configuration.add_vrf(vrf) # self.move_to(self.config_vrf_processor, vrf) # elif "route".startswith(cmd): # static_route = self.switch_configuration.new("Route", *args) # self.switch_configuration.add_static_route(static_route) # # def do_interface(self, *args): # interface_name = self.interface_separator.join(args) # port = self.switch_configuration.get_port_by_partial_name(interface_name) # if port: # self.move_to(self.config_interface_processor, port) # else: # m = re.match("vlan{separator}(\d+)".format(separator=self.interface_separator), interface_name.lower()) # if m: # vlan_id = int(m.groups()[0]) # new_vlan_interface = self.make_vlan_port(vlan_id, interface_name) # self.switch_configuration.add_port(new_vlan_interface) # self.move_to(self.config_interface_processor, new_vlan_interface) # elif interface_name.lower().startswith('port-channel'): # new_int = self.make_aggregated_port(interface_name) # self.switch_configuration.add_port(new_int) # self.move_to(self.config_interface_processor, new_int) # else: # self.show_unknown_interface_error_message() # # def do_no_interface(self, *args): # port = self.switch_configuration.get_port_by_partial_name("".join(args)) # if isinstance(port, VlanPort) or isinstance(port, AggregatedPort): # self.switch_configuration.remove_port(port) # # def do_default(self, cmd, *args): # if 'interface'.startswith(cmd): # interface_name = self.interface_separator.join(args) # port = self.switch_configuration.get_port_by_partial_name(interface_name) # if port: # port.reset() # else: # self.show_unknown_interface_error_message() # # def do_exit(self): # self.is_done = True # # def show_unknown_interface_error_message(self): # self.write_line(" ^") # self.write_line("% Invalid input detected at '^' marker (not such interface)") # self.write_line("") # # def make_vlan_port(self, vlan_id, interface_name): # return self.switch_configuration.new("VlanPort", vlan_id, interface_name.capitalize()) # # def make_aggregated_port(self, interface_name): # return self.switch_configuration.new("AggregatedPort", interface_name.capitalize()) . Output only the next line.
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 next line using the current file imports: import unittest from fake_switches.cisco import cisco_core from hamcrest import assert_that, has_length, has_property and context from other files: # Path: fake_switches/cisco/cisco_core.py # class BaseCiscoSwitchCore(switch_core.SwitchCore): # class Cisco2960SwitchCore(BaseCiscoSwitchCore): # class CiscoShellSession(ShellSession): # class Cisco2960_24TT_L_SwitchCore(CiscoSwitchCore): # class Cisco2960_48TT_L_SwitchCore(CiscoSwitchCore): # def __init__(self, switch_configuration): # def launch(self, protocol, terminal_controller): # def new_command_processor(self): # def get_netconf_protocol(self): # def get_default_ports(): # def new_command_processor(self): # def handle_unknown_command(self, line): # def get_default_ports(): # def get_default_ports(): , which may include functions, classes, or code. Output only the next line.
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() assert_that(ssh_service.port, equal_to(22)) <|code_end|> , determine the next line of code. You have imports: import unittest from hamcrest import assert_that, equal_to from fake_switches.transports import SwitchSshService, SwitchTelnetService, SwitchHttpService and context (class names, function names, or code) available: # Path: fake_switches/transports/ssh_service.py # class SwitchSshService(BaseTransport): # def __init__(self, ip=None, port=22, switch_core=None, users=None): # super(SwitchSshService, self).__init__(ip, port, switch_core, users) # # def hook_to_reactor(self, reactor): # ssh_factory = factory.SSHFactory() # ssh_factory.portal = portal.Portal(SSHDemoRealm(self.switch_core)) # if not self.users: # self.users = {'root': b'root'} # ssh_factory.portal.registerChecker( # checkers.InMemoryUsernamePasswordDatabaseDontUse(**self.users)) # # host_public_key, host_private_key = getRSAKeys() # ssh_factory.publicKeys = { # b'ssh-rsa': keys.Key.fromString(data=host_public_key.encode())} # ssh_factory.privateKeys = { # b'ssh-rsa': keys.Key.fromString(data=host_private_key.encode())} # # lport = reactor.listenTCP(port=self.port, factory=ssh_factory, interface=self.ip) # logging.info(lport) # logging.info( # "%s (SSH): Registered on %s tcp/%s" % (self.switch_core.switch_configuration.name, self.ip, self.port)) # return lport # # Path: fake_switches/transports/telnet_service.py # class SwitchTelnetService(BaseTransport): # def __init__(self, ip=None, port=23, switch_core=None, users=None): # super(SwitchTelnetService, self).__init__(ip, port, switch_core, users) # # def hook_to_reactor(self, reactor): # factory = SwitchTelnetFactory(self.switch_core) # port = reactor.listenTCP(port=self.port, factory=factory, interface=self.ip) # logging.info("{} (TELNET): Registered on {} tcp/{}".format( # self.switch_core.switch_configuration.name, self.ip, self.port)) # return port # # Path: fake_switches/transports/http_service.py # class SwitchHttpService(BaseTransport): # def __init__(self, ip=None, port=80, switch_core=None, users=None): # super(SwitchHttpService, self).__init__(ip, port, switch_core, users) # # def hook_to_reactor(self, reactor): # site = Site(self.switch_core.get_http_resource()) # # lport = reactor.listenTCP(port=self.port, factory=site, interface=self.ip) # logging.info(lport) # logging.info("{} (HTTP): Registered on {} tcp/{}" # .format(self.switch_core.switch_configuration.name, self.ip, self.port)) . Output only the next line.
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 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 SwitchTelnetFactory(Factory): def __init__(self, switch_core): self.switch_core = switch_core def protocol(self): return SwitchTelnetShell(self.switch_core) class SwitchTelnetService(BaseTransport): def __init__(self, ip=None, port=23, switch_core=None, users=None): super(SwitchTelnetService, self).__init__(ip, port, switch_core, users) def hook_to_reactor(self, reactor): factory = SwitchTelnetFactory(self.switch_core) port = reactor.listenTCP(port=self.port, factory=factory, interface=self.ip) <|code_end|> using the current file's imports: import logging from twisted.internet.protocol import Factory from fake_switches.terminal.telnet import SwitchTelnetShell from fake_switches.transports.base_transport import BaseTransport and any relevant context from other files: # Path: fake_switches/terminal/telnet.py # class SwitchTelnetShell(StatefulTelnet): # count = 0 # # def __init__(self, switch_core): # super(SwitchTelnetShell, self).__init__() # self.switch_core = switch_core # self.session = None # self.awaiting_keystroke = None # # def connectionMade(self): # super(SwitchTelnetShell, self).connectionMade() # self.write('Username: ') # self.handler = self.validate_username # # def validate_username(self, _): # self.write('Password: ') # self.enable_input_replacement("") # self.handler = self.validate_password # # def validate_password(self, _): # self.disable_input_replacement() # self.session = self.switch_core.launch( # "telnet", TelnetTerminalController(shell=self)) # self.handler = self.command # # def command(self, line): # keep_going = self.session.receive(line) # # if self.session.command_processor.replace_input is False: # self.disable_input_replacement() # else: # self.enable_input_replacement(self.session.command_processor.replace_input) # # if not keep_going: # self.transport.loseConnection() # # def applicationDataReceived(self, data): # data_string = data.decode() # if data_string in self._printable_chars: # if self.awaiting_keystroke is not None: # args = self.awaiting_keystroke[1] + [data_string] # cmd = self.awaiting_keystroke[0] # cmd(*args) # return # # super(SwitchTelnetShell, self).applicationDataReceived(data) # # def get_actual_processor(self): # if not self.session: # return None # command_processor = self.session.command_processor # while command_processor.sub_processor is not None: # command_processor = command_processor.sub_processor # return command_processor # # def handle_keystroke(self, data): # command_processor = self.get_actual_processor() # return command_processor is not None and command_processor.keystroke(data) # # Path: fake_switches/transports/base_transport.py # class BaseTransport(object): # def __init__(self, ip=None, port=None, switch_core=None, users=None): # self.ip = ip # self.port = port # self.switch_core = switch_core # self.users = users # # def hook_to_reactor(self, reactor): # raise NotImplementedError() . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class SwitchTelnetFactory(Factory): def __init__(self, switch_core): self.switch_core = switch_core def protocol(self): return SwitchTelnetShell(self.switch_core) class SwitchTelnetService(BaseTransport): def __init__(self, ip=None, port=23, switch_core=None, users=None): super(SwitchTelnetService, self).__init__(ip, port, switch_core, users) <|code_end|> . Write the next line using the current file imports: import logging from twisted.internet.protocol import Factory from fake_switches.terminal.telnet import SwitchTelnetShell from fake_switches.transports.base_transport import BaseTransport and context from other files: # Path: fake_switches/terminal/telnet.py # class SwitchTelnetShell(StatefulTelnet): # count = 0 # # def __init__(self, switch_core): # super(SwitchTelnetShell, self).__init__() # self.switch_core = switch_core # self.session = None # self.awaiting_keystroke = None # # def connectionMade(self): # super(SwitchTelnetShell, self).connectionMade() # self.write('Username: ') # self.handler = self.validate_username # # def validate_username(self, _): # self.write('Password: ') # self.enable_input_replacement("") # self.handler = self.validate_password # # def validate_password(self, _): # self.disable_input_replacement() # self.session = self.switch_core.launch( # "telnet", TelnetTerminalController(shell=self)) # self.handler = self.command # # def command(self, line): # keep_going = self.session.receive(line) # # if self.session.command_processor.replace_input is False: # self.disable_input_replacement() # else: # self.enable_input_replacement(self.session.command_processor.replace_input) # # if not keep_going: # self.transport.loseConnection() # # def applicationDataReceived(self, data): # data_string = data.decode() # if data_string in self._printable_chars: # if self.awaiting_keystroke is not None: # args = self.awaiting_keystroke[1] + [data_string] # cmd = self.awaiting_keystroke[0] # cmd(*args) # return # # super(SwitchTelnetShell, self).applicationDataReceived(data) # # def get_actual_processor(self): # if not self.session: # return None # command_processor = self.session.command_processor # while command_processor.sub_processor is not None: # command_processor = command_processor.sub_processor # return command_processor # # def handle_keystroke(self, data): # command_processor = self.get_actual_processor() # return command_processor is not None and command_processor.keystroke(data) # # Path: fake_switches/transports/base_transport.py # class BaseTransport(object): # def __init__(self, ip=None, port=None, switch_core=None, users=None): # self.ip = ip # self.port = port # self.switch_core = switch_core # self.users = users # # def hook_to_reactor(self, reactor): # raise NotImplementedError() , which may include functions, classes, or code. Output only the next line.
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 # # 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 for the specific language governing permissions and # limitations under the License. class Dell10GConfigCommandProcessor(DellConfigCommandProcessor): def do_vlan(self, raw_number, *_): number = int(raw_number) if number < 1 or number > 4094: self.write_line("") self.write_line("") self.write_line(" Failure Information") self.write_line("---------------------------------------") self.write_line(" VLANs failed to be configured : 1") self.write_line("---------------------------------------") <|code_end|> using the current file's imports: from fake_switches.dell.command_processor.config import DellConfigCommandProcessor and any relevant context from other files: # Path: fake_switches/dell/command_processor/config.py # class DellConfigCommandProcessor(ConfigCommandProcessor): # interface_separator = ' ' # # def get_prompt(self): # return "\n" + self.switch_configuration.name + "(config)#" # # def do_vlan(self, *args): # if "database".startswith(args[0]): # self.move_to(self.config_vlan_processor) # # def do_interface(self, *args): # if 'vlan'.startswith(args[0]): # vlan_id = int(args[1]) # vlan = self.switch_configuration.get_vlan(vlan_id) # if vlan is None: # self.write_line("VLAN ID not found.") # return # self.write_line("") # super(DellConfigCommandProcessor, self).do_interface(*args) # # def do_backdoor(self, *args): # if 'remove'.startswith(args[0]) and 'port-channel'.startswith(args[1]): # self.switch_configuration.remove_port( # self.switch_configuration.get_port_by_partial_name(" ".join(args[1:3]))) # # def do_exit(self): # self.write_line("") # self.is_done = True # # def make_vlan_port(self, vlan_id, interface_name): # return self.switch_configuration.new("VlanPort", vlan_id, interface_name) # # def make_aggregated_port(self, interface_name): # return self.switch_configuration.new("AggregatedPort", interface_name) . Output only the next line.
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.vrrp.track) > 0: track_port = list(self.vrrp.track.keys())[0] else: track_port = None self.vrrp.track.update({track_port: args[3]}) def do_no_backup(self, *_): self.vrrp.priority = None if len(self.vrrp.track) > 0: track_port = list(self.vrrp.track.keys())[0] else: track_port = None self.vrrp.track.update({track_port: None}) def do_ip_address(self, *args): if self.vrrp.ip_addresses is not None: self.vrrp.ip_addresses.append(args[0]) else: self.vrrp.ip_addresses = [args[0]] def do_no_ip_address(self, *args): if args[0] in self.vrrp.ip_addresses: self.vrrp.ip_addresses.remove(args[0]) def do_hello_interval(self, *args): <|code_end|> using the current file's imports: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and any relevant context from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class DefaultCommandProcessor(BaseCommandProcessor): def __init__(self, enabled): super(DefaultCommandProcessor, self).__init__() self.enabled_processor = enabled def get_prompt(self): return self.switch_configuration.name + ">" def delegate_to_sub_processor(self, line): <|code_end|> . Write the next line using the current file imports: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and context from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True , which may include functions, classes, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class ConfigVRFCommandProcessor(BaseCommandProcessor): def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): super(ConfigVRFCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) self.vrf = args[0] def get_prompt(self): <|code_end|> , predict the immediate next line with the help of imports: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and context (classes, functions, sometimes code) from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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 line of code. You have imports: from tests.util.protocol_util import SshTester, TelnetTester, with_protocol, ProtocolTest and context (class names, function names, or code) available: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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 imports: from tests.util.protocol_util import SshTester, TelnetTester, with_protocol, ProtocolTest and context from other files: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() , which may contain function names, class names, or code. Output only the next line.
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#") t.write("terminal width 0") t.read("my_switch#") t.write("configure terminal") t.readln("Enter configuration commands, one per line. End with CNTL/Z.") <|code_end|> , determine the next line of code. You have imports: from tests.util.protocol_util import SshTester, TelnetTester, with_protocol, ProtocolTest and context (class names, function names, or code) available: # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # class TelnetTester(ProtocolTester): # CONF_KEY = "telnet" # # def get_ssh_connect_command(self): # return 'telnet %s %s' \ # % (self.host, self.port) # # def login(self): # self.wait_for("Username: ") # self.write(self.username) # self.wait_for("[pP]assword: ", True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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/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 for the specific language governing permissions and # limitations under the License. class DefaultCommandProcessor(BaseCommandProcessor): def __init__(self, enabled): super(DefaultCommandProcessor, self).__init__() self.enabled_processor = enabled def get_prompt(self): return "SSH@%s>" % self.switch_configuration.name def delegate_to_sub_processor(self, line): processed = self.sub_processor.process_command(line) <|code_end|> , predict the next line using imports from the current file: from fake_switches.command_processing.base_command_processor import BaseCommandProcessor and context including class names, function names, and sometimes code from other files: # Path: fake_switches/command_processing/base_command_processor.py # class BaseCommandProcessor(CommandProcessor): # def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): # """ # :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration # :type terminal_controller: fake_switches.terminal.TerminalController # :type logger: logging.Logger # :type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase # """ # # self.switch_configuration = switch_configuration # self.terminal_controller = terminal_controller # self.logger = logger # self.piping_processor = piping_processor # self.sub_processor = None # self.continuing_to = None # self.is_done = False # self.replace_input = False # self.awaiting_keystroke = False # # def process_command(self, line): # if " | " in line: # line, piping_command = line.split(" | ", 1) # piping_started = self.activate_piping(piping_command) # if not piping_started: # return False # # processed = False # # if self.sub_processor: # processed = self.delegate_to_sub_processor(line) # # if not processed: # if self.continuing_to: # processed = self.continue_command(line) # else: # processed = self.parse_and_execute_command(line) # # if not self.continuing_to and not self.awaiting_keystroke and not self.is_done and processed and not self.sub_processor: # self.finish_piping() # self.show_prompt() # # return processed # # def parse_and_execute_command(self, line): # if line.strip(): # func, args = self.get_command_func(line) # if not func: # self.logger.debug("%s can't process : %s, falling back to parent" % (self.__class__.__name__, line)) # return False # else: # func(*args) # return True # # def continue_command(self, line): # func = self.continuing_to # self.continue_to(None) # func(line) # return True # # def delegate_to_sub_processor(self, line): # processed = self.sub_processor.process_command(line) # if self.sub_processor.is_done: # self.sub_processor = None # self.show_prompt() # return processed # # def move_to(self, new_processor, *args): # new_processor.init(self.switch_configuration, # self.terminal_controller, # self.logger, # self.piping_processor, # *args) # self.sub_processor = new_processor # self.logger.info("new subprocessor = {}".format(self.sub_processor.__class__.__name__)) # self.sub_processor.show_prompt() # # def continue_to(self, continuing_action): # self.continuing_to = continuing_action # # def get_continue_command_func(self, cmd): # return getattr(self, 'continue_' + cmd, None) # # def write(self, data): # filtered = self.pipe(data) # if filtered is not False: # self.terminal_controller.write(filtered) # # def write_line(self, data): # self.write(data + u"\n") # # def show_prompt(self): # if self.sub_processor is not None: # self.sub_processor.show_prompt() # else: # self.write(self.get_prompt()) # # def get_prompt(self): # pass # # def activate_piping(self, piping_command): # return self.piping_processor.start_listening(piping_command) # # def pipe(self, data): # if self.piping_processor.is_listening(): # return self.piping_processor.pipe(data) # else: # return data # # def finish_piping(self): # if self.piping_processor.is_listening(): # self.piping_processor.stop_listening() # # def on_keystroke(self, callback, *args): # def on_keystroke_handler(key): # self.awaiting_keystroke = False # self.terminal_controller.remove_any_key_handler() # callback(*(args + (key,))) # # self.terminal_controller.add_any_key_handler(on_keystroke_handler) # self.awaiting_keystroke = True . Output only the next line.
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_that(str(e.exception), contains_string('invalid_model')) def test_switch_model_exists(self): core_mock = mock.create_autospec(switch_core.SwitchCore) core_mock.get_default_ports.return_value = mock.sentinel.port_list with mock.patch('fake_switches.switch_factory.switch_configuration') as switch_conf_module: switch_conf_instance = mock.Mock() switch_conf_class = mock.Mock() switch_conf_class.return_value = switch_conf_instance switch_conf_module.SwitchConfiguration = switch_conf_class factory = switch_factory.SwitchFactory(mapping={'a': core_mock}) switch = factory.get('a', 'my_hostname') assert_that(switch, is_(instance_of(switch_core.SwitchCore))) switch_conf_class.assert_called_with('127.0.0.1', <|code_end|> . Use current file imports: (import unittest import mock from fake_switches import switch_core from fake_switches import switch_factory from hamcrest import assert_that, contains_string, is_, instance_of) and context including class names, function names, or small code snippets from other files: # Path: fake_switches/switch_core.py # class SwitchCore(object): # def __init__(self, switch_configuration): # def launch(self, protocol, terminal_controller): # def get_default_ports(): # def get_netconf_protocol(self): # def get_http_resource(self): # # Path: fake_switches/switch_factory.py # DEFAULT_MAPPING = { # 'arista_generic': arista_core.AristaSwitchCore, # 'brocade_generic': brocade_core.BrocadeSwitchCore, # 'cisco_generic': cisco_core.CiscoSwitchCore, # 'cisco_6500': cisco6500_core.Cisco6500SwitchCore, # 'cisco_2960_24TT_L': cisco_core.Cisco2960_24TT_L_SwitchCore, # 'cisco_2960_48TT_L': cisco_core.Cisco2960_48TT_L_SwitchCore, # 'dell_generic': dell_core.DellSwitchCore, # 'dell10g_generic': dell10g_core.Dell10GSwitchCore, # 'juniper_generic': juniper_core.JuniperSwitchCore, # 'juniper_qfx_copper_generic': juniper_qfx_copper_core.JuniperQfxCopperSwitchCore, # 'juniper_mx_generic': juniper_mx_core.JuniperMXSwitchCore # } # class SwitchFactory(object): # class SwitchFactoryException(Exception): # class InvalidSwitchModel(SwitchFactoryException): # def __init__(self, mapping=None): # def get(self, switch_model, hostname='switch_hostname', password='root', ports=None, **kwargs): . Output only the next line.
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_that(str(e.exception), contains_string('invalid_model')) <|code_end|> . Use current file imports: (import unittest import mock from fake_switches import switch_core from fake_switches import switch_factory from hamcrest import assert_that, contains_string, is_, instance_of) and context including class names, function names, or small code snippets from other files: # Path: fake_switches/switch_core.py # class SwitchCore(object): # def __init__(self, switch_configuration): # def launch(self, protocol, terminal_controller): # def get_default_ports(): # def get_netconf_protocol(self): # def get_http_resource(self): # # Path: fake_switches/switch_factory.py # DEFAULT_MAPPING = { # 'arista_generic': arista_core.AristaSwitchCore, # 'brocade_generic': brocade_core.BrocadeSwitchCore, # 'cisco_generic': cisco_core.CiscoSwitchCore, # 'cisco_6500': cisco6500_core.Cisco6500SwitchCore, # 'cisco_2960_24TT_L': cisco_core.Cisco2960_24TT_L_SwitchCore, # 'cisco_2960_48TT_L': cisco_core.Cisco2960_48TT_L_SwitchCore, # 'dell_generic': dell_core.DellSwitchCore, # 'dell10g_generic': dell10g_core.Dell10GSwitchCore, # 'juniper_generic': juniper_core.JuniperSwitchCore, # 'juniper_qfx_copper_generic': juniper_qfx_copper_core.JuniperQfxCopperSwitchCore, # 'juniper_mx_generic': juniper_mx_core.JuniperMXSwitchCore # } # class SwitchFactory(object): # class SwitchFactoryException(Exception): # class InvalidSwitchModel(SwitchFactoryException): # def __init__(self, mapping=None): # def get(self, switch_model, hostname='switch_hostname', password='root', ports=None, **kwargs): . Output only the next line.
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_protocol = insults.ServerProtocol(SwitchSSHShell, self, switch_core=self.switch_core) server_protocol.makeConnection(protocol) protocol.makeConnection(session.wrapProtocol(server_protocol)) def getPty(self, terminal, windowSize, attrs): return None def execCommand(self, protocol, cmd): raise NotImplementedError() def closed(self): pass def windowChanged(self, newWindowSize): pass def eofReceived(self): pass @implementer(portal.IRealm) class SSHDemoRealm: def __init__(self, switch_core): <|code_end|> , determine the next line of code. You have imports: import logging from twisted.conch import avatar, interfaces as conchinterfaces from twisted.conch.insults import insults from twisted.conch.ssh import factory, keys, session from twisted.cred import portal, checkers from zope.interface import implementer from fake_switches.terminal.ssh import SwitchSSHShell from fake_switches.transports.base_transport import BaseTransport and context (class names, function names, or code) available: # Path: fake_switches/terminal/ssh.py # class SwitchSSHShell(recvline.HistoricRecvLine): # def __init__(self, user, switch_core): # self.user = user # self.switch_core = switch_core # self.session = None # self.awaiting_keystroke = None # # # Hack to get rid of magical characters that reset the screen / clear / goto position 0, 0 # def initializeScreen(self): # self.mode = 'insert' # # def connectionMade(self): # recvline.HistoricRecvLine.connectionMade(self) # self.session = self.switch_core.launch("ssh", SshTerminalController( # shell=self # )) # # def lineReceived(self, line): # line = line.decode() # still_listening = self.session.receive(line) # if not still_listening: # self.terminal.loseConnection() # # def keystrokeReceived(self, keyID, modifier): # if keyID in self._printableChars: # if self.awaiting_keystroke is not None: # args = self.awaiting_keystroke[1] + [keyID.decode()] # cmd = self.awaiting_keystroke[0] # cmd(*args) # return # # super(SwitchSSHShell, self).keystrokeReceived(keyID, modifier) # # # replacing behavior of twisted/conch/recvline.py:205 # def characterReceived(self, ch, moreCharactersComing): # command_processor = self.get_actual_processor() # # if command_processor.replace_input is False: # self.terminal.write(ch) # else: # self.terminal.write((len(ch) * command_processor.replace_input).encode()) # # if self.mode == 'insert': # self.lineBuffer.insert(self.lineBufferIndex, ch) # else: # self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch] # self.lineBufferIndex += 1 # # def get_actual_processor(self): # proc = self.session.command_processor # while proc.sub_processor is not None: # proc = proc.sub_processor # return proc # # Path: fake_switches/transports/base_transport.py # class BaseTransport(object): # def __init__(self, ip=None, port=None, switch_core=None, users=None): # self.ip = ip # self.port = port # self.switch_core = switch_core # self.users = users # # def hook_to_reactor(self, reactor): # raise NotImplementedError() . Output only the next line.
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'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_protocol = insults.ServerProtocol(SwitchSSHShell, self, switch_core=self.switch_core) server_protocol.makeConnection(protocol) protocol.makeConnection(session.wrapProtocol(server_protocol)) def getPty(self, terminal, windowSize, attrs): return None def execCommand(self, protocol, cmd): raise NotImplementedError() def closed(self): pass def windowChanged(self, newWindowSize): pass def eofReceived(self): <|code_end|> . Use current file imports: import logging from twisted.conch import avatar, interfaces as conchinterfaces from twisted.conch.insults import insults from twisted.conch.ssh import factory, keys, session from twisted.cred import portal, checkers from zope.interface import implementer from fake_switches.terminal.ssh import SwitchSSHShell from fake_switches.transports.base_transport import BaseTransport and context (classes, functions, or code) from other files: # Path: fake_switches/terminal/ssh.py # class SwitchSSHShell(recvline.HistoricRecvLine): # def __init__(self, user, switch_core): # self.user = user # self.switch_core = switch_core # self.session = None # self.awaiting_keystroke = None # # # Hack to get rid of magical characters that reset the screen / clear / goto position 0, 0 # def initializeScreen(self): # self.mode = 'insert' # # def connectionMade(self): # recvline.HistoricRecvLine.connectionMade(self) # self.session = self.switch_core.launch("ssh", SshTerminalController( # shell=self # )) # # def lineReceived(self, line): # line = line.decode() # still_listening = self.session.receive(line) # if not still_listening: # self.terminal.loseConnection() # # def keystrokeReceived(self, keyID, modifier): # if keyID in self._printableChars: # if self.awaiting_keystroke is not None: # args = self.awaiting_keystroke[1] + [keyID.decode()] # cmd = self.awaiting_keystroke[0] # cmd(*args) # return # # super(SwitchSSHShell, self).keystrokeReceived(keyID, modifier) # # # replacing behavior of twisted/conch/recvline.py:205 # def characterReceived(self, ch, moreCharactersComing): # command_processor = self.get_actual_processor() # # if command_processor.replace_input is False: # self.terminal.write(ch) # else: # self.terminal.write((len(ch) * command_processor.replace_input).encode()) # # if self.mode == 'insert': # self.lineBuffer.insert(self.lineBufferIndex, ch) # else: # self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch] # self.lineBufferIndex += 1 # # def get_actual_processor(self): # proc = self.session.command_processor # while proc.sub_processor is not None: # proc = proc.sub_processor # return proc # # Path: fake_switches/transports/base_transport.py # class BaseTransport(object): # def __init__(self, ip=None, port=None, switch_core=None, users=None): # self.ip = ip # self.port = port # self.switch_core = switch_core # self.users = users # # def hook_to_reactor(self, reactor): # raise NotImplementedError() . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class TestBrocadeSwitchProtocolWithCommitDelay(ProtocolTest): tester_class = SshTester test_switch = "commit-delayed-brocade" @with_protocol <|code_end|> . Write the next line using the current file imports: import time from hamcrest import assert_that, greater_than from tests.brocade.test_brocade_switch_protocol import enable from tests.util.global_reactor import COMMIT_DELAY from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context from other files: # Path: tests/brocade/test_brocade_switch_protocol.py # def enable(t): # t.write("enable") # t.read("Password:") # t.write_invisible(t.conf["extra"].get("password", "root")) # t.read("SSH@my_switch#") # # Path: tests/util/global_reactor.py # COMMIT_DELAY = 1 # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() , which may include functions, classes, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class TestBrocadeSwitchProtocolWithCommitDelay(ProtocolTest): tester_class = SshTester test_switch = "commit-delayed-brocade" @with_protocol def test_write_memory(self, t): enable(t) t.child.timeout = 10 <|code_end|> with the help of current file imports: import time from hamcrest import assert_that, greater_than from tests.brocade.test_brocade_switch_protocol import enable from tests.util.global_reactor import COMMIT_DELAY from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context from other files: # Path: tests/brocade/test_brocade_switch_protocol.py # def enable(t): # t.write("enable") # t.read("Password:") # t.write_invisible(t.conf["extra"].get("password", "root")) # t.read("SSH@my_switch#") # # Path: tests/util/global_reactor.py # COMMIT_DELAY = 1 # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() , which may contain function names, class names, or code. Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class TestBrocadeSwitchProtocolWithCommitDelay(ProtocolTest): tester_class = SshTester test_switch = "commit-delayed-brocade" @with_protocol def test_write_memory(self, t): enable(t) t.child.timeout = 10 start_time = time.time() <|code_end|> , determine the next line of code. You have imports: import time from hamcrest import assert_that, greater_than from tests.brocade.test_brocade_switch_protocol import enable from tests.util.global_reactor import COMMIT_DELAY from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context (class names, function names, or code) available: # Path: tests/brocade/test_brocade_switch_protocol.py # def enable(t): # t.write("enable") # t.read("Password:") # t.write_invisible(t.conf["extra"].get("password", "root")) # t.read("SSH@my_switch#") # # Path: tests/util/global_reactor.py # COMMIT_DELAY = 1 # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class TestBrocadeSwitchProtocolWithCommitDelay(ProtocolTest): tester_class = SshTester test_switch = "commit-delayed-brocade" @with_protocol def test_write_memory(self, t): enable(t) t.child.timeout = 10 start_time = time.time() t.write("write memory") <|code_end|> . Use current file imports: (import time from hamcrest import assert_that, greater_than from tests.brocade.test_brocade_switch_protocol import enable from tests.util.global_reactor import COMMIT_DELAY from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest) and context including class names, function names, or small code snippets from other files: # Path: tests/brocade/test_brocade_switch_protocol.py # def enable(t): # t.write("enable") # t.read("Password:") # t.write_invisible(t.conf["extra"].get("password", "root")) # t.read("SSH@my_switch#") # # Path: tests/util/global_reactor.py # COMMIT_DELAY = 1 # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() . Output only the next line.
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 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 for the specific language governing permissions and # limitations under the License. class TestBrocadeSwitchProtocolWithCommitDelay(ProtocolTest): tester_class = SshTester test_switch = "commit-delayed-brocade" @with_protocol def test_write_memory(self, t): enable(t) t.child.timeout = 10 start_time = time.time() t.write("write memory") <|code_end|> . Write the next line using the current file imports: import time from hamcrest import assert_that, greater_than from tests.brocade.test_brocade_switch_protocol import enable from tests.util.global_reactor import COMMIT_DELAY from tests.util.protocol_util import SshTester, with_protocol, ProtocolTest and context from other files: # Path: tests/brocade/test_brocade_switch_protocol.py # def enable(t): # t.write("enable") # t.read("Password:") # t.write_invisible(t.conf["extra"].get("password", "root")) # t.read("SSH@my_switch#") # # Path: tests/util/global_reactor.py # COMMIT_DELAY = 1 # # Path: tests/util/protocol_util.py # class SshTester(ProtocolTester): # CONF_KEY = "ssh" # # def get_ssh_connect_command(self): # return 'ssh %s@%s -p %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' \ # % (self.username, self.host, self.port) # # def login(self): # self.wait_for('[pP]assword: ', regex=True) # self.write_invisible(self.password) # self.wait_for('[>#]$', regex=True) # # def with_protocol(test): # @wraps(test) # def wrapper(self): # try: # logging.info(">>>> CONNECTING [%s]" % self.protocol.name) # self.protocol.connect() # logging.info(">>>> START") # test(self, self.protocol) # logging.info(">>>> SUCCESS") # finally: # self.protocol.disconnect() # # return wrapper # # class ProtocolTest(unittest.TestCase): # tester_class = SshTester # test_switch = None # # def setUp(self): # conf = TEST_SWITCHES[self.test_switch] # self.protocol = self.tester_class(self.tester_class.CONF_KEY, # "127.0.0.1", # conf[self.tester_class.CONF_KEY], # u'root', # u'root', # conf) # # def tearDown(self): # flexmock_teardown() , which may include functions, classes, or code. Output only the next line.
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', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--model', type=str, default='cisco_generic', help='Switch model, allowed values are ' + ', '.join(switch_factory.DEFAULT_MAPPING.keys())) parser.add_argument('--hostname', type=str, default='switch', help='Switch hostname') parser.add_argument('--username', type=str, default='root', help='Switch username') parser.add_argument('--password', type=str, default='root', help='Switch password') parser.add_argument('--listen-host', type=str, default='0.0.0.0', help='Listen host') parser.add_argument('--listen-port', type=int, default=2222, help='Listen port') args = parser.parse_args() args.password = args.password.encode() factory = switch_factory.SwitchFactory() switch_core = factory.get(args.model, args.hostname, args.password) ssh_service = SwitchSshService( ip=args.listen_host, port=args.listen_port, switch_core=switch_core, users={args.username: args.password}) ssh_service.hook_to_reactor(reactor) <|code_end|> , generate the next line using the imports in this file: import argparse import logging from fake_switches import switch_factory from fake_switches.transports.ssh_service import SwitchSshService from twisted.internet import reactor and context (functions, classes, or occasionally code) from other files: # Path: fake_switches/switch_factory.py # DEFAULT_MAPPING = { # 'arista_generic': arista_core.AristaSwitchCore, # 'brocade_generic': brocade_core.BrocadeSwitchCore, # 'cisco_generic': cisco_core.CiscoSwitchCore, # 'cisco_6500': cisco6500_core.Cisco6500SwitchCore, # 'cisco_2960_24TT_L': cisco_core.Cisco2960_24TT_L_SwitchCore, # 'cisco_2960_48TT_L': cisco_core.Cisco2960_48TT_L_SwitchCore, # 'dell_generic': dell_core.DellSwitchCore, # 'dell10g_generic': dell10g_core.Dell10GSwitchCore, # 'juniper_generic': juniper_core.JuniperSwitchCore, # 'juniper_qfx_copper_generic': juniper_qfx_copper_core.JuniperQfxCopperSwitchCore, # 'juniper_mx_generic': juniper_mx_core.JuniperMXSwitchCore # } # class SwitchFactory(object): # class SwitchFactoryException(Exception): # class InvalidSwitchModel(SwitchFactoryException): # def __init__(self, mapping=None): # def get(self, switch_model, hostname='switch_hostname', password='root', ports=None, **kwargs): # # Path: fake_switches/transports/ssh_service.py # class SwitchSshService(BaseTransport): # def __init__(self, ip=None, port=22, switch_core=None, users=None): # super(SwitchSshService, self).__init__(ip, port, switch_core, users) # # def hook_to_reactor(self, reactor): # ssh_factory = factory.SSHFactory() # ssh_factory.portal = portal.Portal(SSHDemoRealm(self.switch_core)) # if not self.users: # self.users = {'root': b'root'} # ssh_factory.portal.registerChecker( # checkers.InMemoryUsernamePasswordDatabaseDontUse(**self.users)) # # host_public_key, host_private_key = getRSAKeys() # ssh_factory.publicKeys = { # b'ssh-rsa': keys.Key.fromString(data=host_public_key.encode())} # ssh_factory.privateKeys = { # b'ssh-rsa': keys.Key.fromString(data=host_private_key.encode())} # # lport = reactor.listenTCP(port=self.port, factory=ssh_factory, interface=self.ip) # logging.info(lport) # logging.info( # "%s (SSH): Registered on %s tcp/%s" % (self.switch_core.switch_configuration.name, self.ip, self.port)) # return lport . Output only the next line.
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.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) return {self.magic_key: [cls_ref, state]} elif isinstance(obj, datetime): return marshal_date(obj) raise TypeError(f'Object of type {obj.__class__.__name__!r} is not JSON serializable') def _object_hook(self, obj_state: dict[str, Any]): if self.magic_key in obj_state: ref, *rest = obj_state[self.magic_key] return unmarshal_object(ref, *rest) return obj_state def serialize(self, obj) -> bytes: <|code_end|> . Write the next line using the current file imports: from datetime import datetime from json import dumps, loads from typing import Any from ..abc import Serializer from ..marshalling import marshal_date, marshal_object, unmarshal_object import attrs and context from other files: # Path: src/apscheduler/abc.py # class Serializer(metaclass=ABCMeta): # __slots__ = () # # @abstractmethod # def serialize(self, obj) -> bytes: # pass # # def serialize_to_unicode(self, obj) -> str: # return b64encode(self.serialize(obj)).decode('ascii') # # @abstractmethod # def deserialize(self, serialized: bytes): # pass # # def deserialize_from_unicode(self, serialized: str): # return self.deserialize(b64decode(serialized)) # # Path: src/apscheduler/marshalling.py # @overload # def marshal_date(value: None) -> None: # ... # # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance , which may include functions, classes, or code. Output only the next line.
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) return {self.magic_key: [cls_ref, state]} elif isinstance(obj, datetime): return marshal_date(obj) raise TypeError(f'Object of type {obj.__class__.__name__!r} is not JSON serializable') def _object_hook(self, obj_state: dict[str, Any]): if self.magic_key in obj_state: ref, *rest = obj_state[self.magic_key] return unmarshal_object(ref, *rest) return obj_state def serialize(self, obj) -> bytes: return dumps(obj, ensure_ascii=False, **self.dump_options).encode('utf-8') def deserialize(self, serialized: bytes): return loads(serialized, **self.load_options) def serialize_to_unicode(self, obj) -> str: return dumps(obj, ensure_ascii=False, **self.dump_options) <|code_end|> . Use current file imports: from datetime import datetime from json import dumps, loads from typing import Any from ..abc import Serializer from ..marshalling import marshal_date, marshal_object, unmarshal_object import attrs and context (classes, functions, or code) from other files: # Path: src/apscheduler/abc.py # class Serializer(metaclass=ABCMeta): # __slots__ = () # # @abstractmethod # def serialize(self, obj) -> bytes: # pass # # def serialize_to_unicode(self, obj) -> str: # return b64encode(self.serialize(obj)).decode('ascii') # # @abstractmethod # def deserialize(self, serialized: bytes): # pass # # def deserialize_from_unicode(self, serialized: str): # return self.deserialize(b64decode(serialized)) # # Path: src/apscheduler/marshalling.py # @overload # def marshal_date(value: None) -> None: # ... # # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance . Output only the next line.
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._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) return {self.magic_key: [cls_ref, state]} elif isinstance(obj, datetime): return marshal_date(obj) raise TypeError(f'Object of type {obj.__class__.__name__!r} is not JSON serializable') def _object_hook(self, obj_state: dict[str, Any]): if self.magic_key in obj_state: ref, *rest = obj_state[self.magic_key] return unmarshal_object(ref, *rest) return obj_state def serialize(self, obj) -> bytes: return dumps(obj, ensure_ascii=False, **self.dump_options).encode('utf-8') def deserialize(self, serialized: bytes): return loads(serialized, **self.load_options) <|code_end|> , predict the next line using imports from the current file: from datetime import datetime from json import dumps, loads from typing import Any from ..abc import Serializer from ..marshalling import marshal_date, marshal_object, unmarshal_object import attrs and context including class names, function names, and sometimes code from other files: # Path: src/apscheduler/abc.py # class Serializer(metaclass=ABCMeta): # __slots__ = () # # @abstractmethod # def serialize(self, obj) -> bytes: # pass # # def serialize_to_unicode(self, obj) -> str: # return b64encode(self.serialize(obj)).decode('ascii') # # @abstractmethod # def deserialize(self, serialized: bytes): # pass # # def deserialize_from_unicode(self, serialized: str): # return self.deserialize(b64decode(serialized)) # # Path: src/apscheduler/marshalling.py # @overload # def marshal_date(value: None) -> None: # ... # # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance . Output only the next line.
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_end|> . Use current file imports: (from datetime import datetime from json import dumps, loads from typing import Any from ..abc import Serializer from ..marshalling import marshal_date, marshal_object, unmarshal_object import attrs) and context including class names, function names, or small code snippets from other files: # Path: src/apscheduler/abc.py # class Serializer(metaclass=ABCMeta): # __slots__ = () # # @abstractmethod # def serialize(self, obj) -> bytes: # pass # # def serialize_to_unicode(self, obj) -> str: # return b64encode(self.serialize(obj)).decode('ascii') # # @abstractmethod # def deserialize(self, serialized: bytes): # pass # # def deserialize_from_unicode(self, serialized: str): # return self.deserialize(b64decode(serialized)) # # Path: src/apscheduler/marshalling.py # @overload # def marshal_date(value: None) -> None: # ... # # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance . Output only the next line.
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]: return { <|code_end|> using the current file's imports: from abc import abstractmethod from datetime import datetime, timedelta from typing import Any from ..abc import Trigger from ..exceptions import MaxIterationsReached from ..marshalling import marshal_object, unmarshal_object from ..validators import as_timedelta, require_state_version import attrs and any relevant context from other files: # Path: src/apscheduler/abc.py # class Trigger(Iterator[datetime], metaclass=ABCMeta): # """Abstract base class that defines the interface that every trigger must implement.""" # # __slots__ = () # # @abstractmethod # def next(self) -> datetime | None: # """ # Return the next datetime to fire on. # # If no such datetime can be calculated, ``None`` is returned. # :raises apscheduler.exceptions.MaxIterationsReached: # """ # # @abstractmethod # def __getstate__(self): # """Return the (JSON compatible) serializable state of the trigger.""" # # @abstractmethod # def __setstate__(self, state): # """Initialize an empty instance from an existing state.""" # # def __iter__(self): # return self # # def __next__(self) -> datetime: # dateval = self.next() # if dateval is None: # raise StopIteration # else: # return dateval # # Path: src/apscheduler/exceptions.py # class MaxIterationsReached(Exception): # """ # Raised when a trigger has reached its maximum number of allowed computation iterations when # trying to calculate the next fire time. # """ # # Path: src/apscheduler/marshalling.py # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance # # Path: src/apscheduler/validators.py # def as_timedelta(value: timedelta | float) -> timedelta: # if isinstance(value, (int, float)): # return timedelta(seconds=value) # elif isinstance(value, timedelta): # return value # # # raise TypeError(f'{attribute.name} must be a timedelta or number of seconds, got ' # # f'{value.__class__.__name__} instead') # # def require_state_version(trigger: Trigger, state: dict[str, Any], max_version: int) -> None: # try: # if state['version'] > max_version: # raise DeserializationError( # f'{trigger.__class__.__name__} received a serialized state with version ' # f'{state["version"]}, but it only supports up to version {max_version}. ' # f'This can happen when an older version of APScheduler is being used with a data ' # f'store that was previously used with a newer APScheduler version.' # ) # except KeyError as exc: # raise DeserializationError('Missing "version" key in the serialized state') from exc . Output only the next line.
'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 from ..abc import Trigger from ..exceptions import MaxIterationsReached from ..marshalling import marshal_object, unmarshal_object from ..validators import as_timedelta, require_state_version import attrs and any relevant context from other files: # Path: src/apscheduler/abc.py # class Trigger(Iterator[datetime], metaclass=ABCMeta): # """Abstract base class that defines the interface that every trigger must implement.""" # # __slots__ = () # # @abstractmethod # def next(self) -> datetime | None: # """ # Return the next datetime to fire on. # # If no such datetime can be calculated, ``None`` is returned. # :raises apscheduler.exceptions.MaxIterationsReached: # """ # # @abstractmethod # def __getstate__(self): # """Return the (JSON compatible) serializable state of the trigger.""" # # @abstractmethod # def __setstate__(self, state): # """Initialize an empty instance from an existing state.""" # # def __iter__(self): # return self # # def __next__(self) -> datetime: # dateval = self.next() # if dateval is None: # raise StopIteration # else: # return dateval # # Path: src/apscheduler/exceptions.py # class MaxIterationsReached(Exception): # """ # Raised when a trigger has reached its maximum number of allowed computation iterations when # trying to calculate the next fire time. # """ # # Path: src/apscheduler/marshalling.py # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance # # Path: src/apscheduler/validators.py # def as_timedelta(value: timedelta | float) -> timedelta: # if isinstance(value, (int, float)): # return timedelta(seconds=value) # elif isinstance(value, timedelta): # return value # # # raise TypeError(f'{attribute.name} must be a timedelta or number of seconds, got ' # # f'{value.__class__.__name__} instead') # # def require_state_version(trigger: Trigger, state: dict[str, Any], max_version: int) -> None: # try: # if state['version'] > max_version: # raise DeserializationError( # f'{trigger.__class__.__name__} received a serialized state with version ' # f'{state["version"]}, but it only supports up to version {max_version}. ' # f'This can happen when an older version of APScheduler is being used with a data ' # f'store that was previously used with a newer APScheduler version.' # ) # except KeyError as exc: # raise DeserializationError('Missing "version" key in the serialized state') from exc . Output only the next line.
_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 { 'version': 1, 'triggers': [marshal_object(trigger) for trigger in self.triggers], 'next_fire_times': self._next_fire_times } @abstractmethod def __setstate__(self, state: dict[str, Any]) -> None: self.triggers = [unmarshal_object(*trigger_state) for trigger_state in state['triggers']] <|code_end|> , determine the next line of code. You have imports: from abc import abstractmethod from datetime import datetime, timedelta from typing import Any from ..abc import Trigger from ..exceptions import MaxIterationsReached from ..marshalling import marshal_object, unmarshal_object from ..validators import as_timedelta, require_state_version import attrs and context (class names, function names, or code) available: # Path: src/apscheduler/abc.py # class Trigger(Iterator[datetime], metaclass=ABCMeta): # """Abstract base class that defines the interface that every trigger must implement.""" # # __slots__ = () # # @abstractmethod # def next(self) -> datetime | None: # """ # Return the next datetime to fire on. # # If no such datetime can be calculated, ``None`` is returned. # :raises apscheduler.exceptions.MaxIterationsReached: # """ # # @abstractmethod # def __getstate__(self): # """Return the (JSON compatible) serializable state of the trigger.""" # # @abstractmethod # def __setstate__(self, state): # """Initialize an empty instance from an existing state.""" # # def __iter__(self): # return self # # def __next__(self) -> datetime: # dateval = self.next() # if dateval is None: # raise StopIteration # else: # return dateval # # Path: src/apscheduler/exceptions.py # class MaxIterationsReached(Exception): # """ # Raised when a trigger has reached its maximum number of allowed computation iterations when # trying to calculate the next fire time. # """ # # Path: src/apscheduler/marshalling.py # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance # # Path: src/apscheduler/validators.py # def as_timedelta(value: timedelta | float) -> timedelta: # if isinstance(value, (int, float)): # return timedelta(seconds=value) # elif isinstance(value, timedelta): # return value # # # raise TypeError(f'{attribute.name} must be a timedelta or number of seconds, got ' # # f'{value.__class__.__name__} instead') # # def require_state_version(trigger: Trigger, state: dict[str, Any], max_version: int) -> None: # try: # if state['version'] > max_version: # raise DeserializationError( # f'{trigger.__class__.__name__} received a serialized state with version ' # f'{state["version"]}, but it only supports up to version {max_version}. ' # f'This can happen when an older version of APScheduler is being used with a data ' # f'store that was previously used with a newer APScheduler version.' # ) # except KeyError as exc: # raise DeserializationError('Missing "version" key in the serialized state') from exc . Output only the next line.
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 { 'version': 1, 'triggers': [marshal_object(trigger) for trigger in self.triggers], 'next_fire_times': self._next_fire_times } <|code_end|> , generate the next line using the imports in this file: from abc import abstractmethod from datetime import datetime, timedelta from typing import Any from ..abc import Trigger from ..exceptions import MaxIterationsReached from ..marshalling import marshal_object, unmarshal_object from ..validators import as_timedelta, require_state_version import attrs and context (functions, classes, or occasionally code) from other files: # Path: src/apscheduler/abc.py # class Trigger(Iterator[datetime], metaclass=ABCMeta): # """Abstract base class that defines the interface that every trigger must implement.""" # # __slots__ = () # # @abstractmethod # def next(self) -> datetime | None: # """ # Return the next datetime to fire on. # # If no such datetime can be calculated, ``None`` is returned. # :raises apscheduler.exceptions.MaxIterationsReached: # """ # # @abstractmethod # def __getstate__(self): # """Return the (JSON compatible) serializable state of the trigger.""" # # @abstractmethod # def __setstate__(self, state): # """Initialize an empty instance from an existing state.""" # # def __iter__(self): # return self # # def __next__(self) -> datetime: # dateval = self.next() # if dateval is None: # raise StopIteration # else: # return dateval # # Path: src/apscheduler/exceptions.py # class MaxIterationsReached(Exception): # """ # Raised when a trigger has reached its maximum number of allowed computation iterations when # trying to calculate the next fire time. # """ # # Path: src/apscheduler/marshalling.py # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance # # Path: src/apscheduler/validators.py # def as_timedelta(value: timedelta | float) -> timedelta: # if isinstance(value, (int, float)): # return timedelta(seconds=value) # elif isinstance(value, timedelta): # return value # # # raise TypeError(f'{attribute.name} must be a timedelta or number of seconds, got ' # # f'{value.__class__.__name__} instead') # # def require_state_version(trigger: Trigger, state: dict[str, Any], max_version: int) -> None: # try: # if state['version'] > max_version: # raise DeserializationError( # f'{trigger.__class__.__name__} received a serialized state with version ' # f'{state["version"]}, but it only supports up to version {max_version}. ' # f'This can happen when an older version of APScheduler is being used with a data ' # f'store that was previously used with a newer APScheduler version.' # ) # except KeyError as exc: # raise DeserializationError('Missing "version" key in the serialized state') from exc . Output only the next line.
@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_end|> . Use current file imports: (from abc import abstractmethod from datetime import datetime, timedelta from typing import Any from ..abc import Trigger from ..exceptions import MaxIterationsReached from ..marshalling import marshal_object, unmarshal_object from ..validators import as_timedelta, require_state_version import attrs) and context including class names, function names, or small code snippets from other files: # Path: src/apscheduler/abc.py # class Trigger(Iterator[datetime], metaclass=ABCMeta): # """Abstract base class that defines the interface that every trigger must implement.""" # # __slots__ = () # # @abstractmethod # def next(self) -> datetime | None: # """ # Return the next datetime to fire on. # # If no such datetime can be calculated, ``None`` is returned. # :raises apscheduler.exceptions.MaxIterationsReached: # """ # # @abstractmethod # def __getstate__(self): # """Return the (JSON compatible) serializable state of the trigger.""" # # @abstractmethod # def __setstate__(self, state): # """Initialize an empty instance from an existing state.""" # # def __iter__(self): # return self # # def __next__(self) -> datetime: # dateval = self.next() # if dateval is None: # raise StopIteration # else: # return dateval # # Path: src/apscheduler/exceptions.py # class MaxIterationsReached(Exception): # """ # Raised when a trigger has reached its maximum number of allowed computation iterations when # trying to calculate the next fire time. # """ # # Path: src/apscheduler/marshalling.py # def marshal_object(obj) -> tuple[str, Any]: # return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() # # def unmarshal_object(ref: str, state): # cls = callable_from_ref(ref) # instance = cls.__new__(cls) # instance.__setstate__(state) # return instance # # Path: src/apscheduler/validators.py # def as_timedelta(value: timedelta | float) -> timedelta: # if isinstance(value, (int, float)): # return timedelta(seconds=value) # elif isinstance(value, timedelta): # return value # # # raise TypeError(f'{attribute.name} must be a timedelta or number of seconds, got ' # # f'{value.__class__.__name__} instead') # # def require_state_version(trigger: Trigger, state: dict[str, Any], max_version: int) -> None: # try: # if state['version'] > max_version: # raise DeserializationError( # f'{trigger.__class__.__name__} received a serialized state with version ' # f'{state["version"]}, but it only supports up to version {max_version}. ' # f'This can happen when an older version of APScheduler is being used with a data ' # f'store that was previously used with a newer APScheduler version.' # ) # except KeyError as exc: # raise DeserializationError('Missing "version" key in the serialized state') from exc . Output only the next line.
'version': 1,