Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|> def get_months_transactions(user): today = timezone.now() first_day_of_a_month = datetime(today.year, today.month, 1, tzinfo=today.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_a_month, user=user, active=True) return qs def get_last_months_transactions(user): first_day_of_a_month = timezone.now().replace(day=1) last_month = first_day_of_a_month - timedelta(days=1) first_day_of_last_month = datetime(last_month.year, last_month.month, 1, tzinfo=last_month.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_last_month, user=user, active=True) <|code_end|> using the current file's imports: from datetime import datetime from datetime import timedelta from django.utils import timezone from books.models import Transaction and any relevant context from other files: # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() . Output only the next line.
return qs
Continue the code snippet: <|code_start|> class TransactionFactory(factory.DjangoModelFactory): title = factory.Sequence(lambda n: 'transaction_%d' % n) amount = 10 category = models.Transaction.EXPENSE user = factory.SubFactory(UserFactory) class Meta: model = models.Transaction class DebtLoanFactory(factory.DjangoModelFactory): with_who = "ACME co." title = factory.Sequence(lambda n: 'debt_loan_%d' % n) <|code_end|> . Use current file imports: import factory from accounts.factories import UserFactory from books import models and context (classes, functions, or code) from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/models.py # class Transaction(models.Model): # class DebtLoan(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # def __str__(self): # def deactivate(self): # def __str__(self): # def deactivate(self): . Output only the next line.
amount = 42
Based on the snippet: <|code_start|> 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone from accounts.factories import UserFactory from books.factories import DebtLoanFactory from books.factories import TransactionFactory from books.models import DebtLoan from books.models import Transaction import random import factory import pytz and context (classes, functions, sometimes code) from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/factories.py # class DebtLoanFactory(factory.DjangoModelFactory): # with_who = "ACME co." # title = factory.Sequence(lambda n: 'debt_loan_%d' % n) # amount = 42 # category = models.DebtLoan.DEBT # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.DebtLoan # # Path: books/factories.py # class TransactionFactory(factory.DjangoModelFactory): # title = factory.Sequence(lambda n: 'transaction_%d' % n) # amount = 10 # category = models.Transaction.EXPENSE # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.Transaction # # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() . Output only the next line.
created=factory.Sequence(lambda n: self._get_all_time()),
Here is a snippet: <|code_start|> category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) <|code_end|> . Write the next line using the current file imports: from datetime import datetime from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone from accounts.factories import UserFactory from books.factories import DebtLoanFactory from books.factories import TransactionFactory from books.models import DebtLoan from books.models import Transaction import random import factory import pytz and context from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/factories.py # class DebtLoanFactory(factory.DjangoModelFactory): # with_who = "ACME co." # title = factory.Sequence(lambda n: 'debt_loan_%d' % n) # amount = 42 # category = models.DebtLoan.DEBT # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.DebtLoan # # Path: books/factories.py # class TransactionFactory(factory.DjangoModelFactory): # title = factory.Sequence(lambda n: 'transaction_%d' % n) # amount = 10 # category = models.Transaction.EXPENSE # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.Transaction # # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() , which may include functions, classes, or code. Output only the next line.
print("DebtLoans for admin created")
Given the following code snippet before the placeholder: <|code_start|> ) # create for this year TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("Transactions for admin created") def create_debt_loans(self): categories = [DebtLoan.DEBT, DebtLoan.LOAN] # create now DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, <|code_end|> , predict the next line using imports from the current file: from datetime import datetime from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone from accounts.factories import UserFactory from books.factories import DebtLoanFactory from books.factories import TransactionFactory from books.models import DebtLoan from books.models import Transaction import random import factory import pytz and context including class names, function names, and sometimes code from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/factories.py # class DebtLoanFactory(factory.DjangoModelFactory): # with_who = "ACME co." # title = factory.Sequence(lambda n: 'debt_loan_%d' % n) # amount = 42 # category = models.DebtLoan.DEBT # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.DebtLoan # # Path: books/factories.py # class TransactionFactory(factory.DjangoModelFactory): # title = factory.Sequence(lambda n: 'transaction_%d' % n) # amount = 10 # category = models.Transaction.EXPENSE # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.Transaction # # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() . Output only the next line.
)
Given snippet: <|code_start|> ) # create for last month TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("Transactions for admin created") <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone from accounts.factories import UserFactory from books.factories import DebtLoanFactory from books.factories import TransactionFactory from books.models import DebtLoan from books.models import Transaction import random import factory import pytz and context: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/factories.py # class DebtLoanFactory(factory.DjangoModelFactory): # with_who = "ACME co." # title = factory.Sequence(lambda n: 'debt_loan_%d' % n) # amount = 42 # category = models.DebtLoan.DEBT # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.DebtLoan # # Path: books/factories.py # class TransactionFactory(factory.DjangoModelFactory): # title = factory.Sequence(lambda n: 'transaction_%d' % n) # amount = 10 # category = models.Transaction.EXPENSE # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.Transaction # # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() which might include code, classes, or functions. Output only the next line.
def create_debt_loans(self):
Continue the code snippet: <|code_start|> category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) <|code_end|> . Use current file imports: from datetime import datetime from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone from accounts.factories import UserFactory from books.factories import DebtLoanFactory from books.factories import TransactionFactory from books.models import DebtLoan from books.models import Transaction import random import factory import pytz and context (classes, functions, or code) from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/factories.py # class DebtLoanFactory(factory.DjangoModelFactory): # with_who = "ACME co." # title = factory.Sequence(lambda n: 'debt_loan_%d' % n) # amount = 42 # category = models.DebtLoan.DEBT # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.DebtLoan # # Path: books/factories.py # class TransactionFactory(factory.DjangoModelFactory): # title = factory.Sequence(lambda n: 'transaction_%d' % n) # amount = 10 # category = models.Transaction.EXPENSE # user = factory.SubFactory(UserFactory) # # class Meta: # model = models.Transaction # # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() . Output only the next line.
print("Transactions for admin created")
Here is a snippet: <|code_start|> class HomePageTests(TestCase): def setUp(self): self.user = UserFactory() def test_home_not_logged_in(self): c = Client() response = c.get(reverse('home')) self.assertRedirects(response, reverse('login')) <|code_end|> . Write the next line using the current file imports: from django.contrib.auth.models import User from django.core.management import call_command from django.core.urlresolvers import reverse from django.test import Client from django.test import TestCase from accounts.factories import UserFactory from books.models import Transaction and context from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() , which may include functions, classes, or code. Output only the next line.
def test_home_logged_in(self):
Given snippet: <|code_start|> class HomePageTests(TestCase): def setUp(self): self.user = UserFactory() def test_home_not_logged_in(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.auth.models import User from django.core.management import call_command from django.core.urlresolvers import reverse from django.test import Client from django.test import TestCase from accounts.factories import UserFactory from books.models import Transaction and context: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() which might include code, classes, or functions. Output only the next line.
c = Client()
Next line prediction: <|code_start|> urlpatterns = [ # login/logout url(r'^logout/$', auth_logout, name='logout'), url(r'^login/$', views.login, name='login'), url(r'^login_redirect/$', views.login_redirect, name='login_redirect'), # password reset url(r'^password-reset/$', password_reset, {'template_name': 'password_reset.html'}, name='password_reset'), url(r'^password-reset-done/$', password_reset_done, {'template_name': 'password_reset_done.html'}, name='password_reset_done'), url(r'^password-reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', <|code_end|> . Use current file imports: (from django.conf.urls import include, url from django.contrib.auth.views import logout as auth_logout from django.contrib.auth.views import password_reset from django.contrib.auth.views import password_reset_done from django.contrib.auth.views import password_reset_confirm from django.contrib.auth.views import password_reset_complete from accounts import views) and context including class names, function names, or small code snippets from other files: # Path: accounts/views.py # def login(request, *args, **kwargs): # def login_redirect(request): . Output only the next line.
password_reset_confirm,
Continue the code snippet: <|code_start|> ctx = {} user_id = request.user.id user = User.objects.get(id=user_id) user_debt_loans = DebtLoan.objects.filter(user=user, active=True) user_debt_loans = user_debt_loans.order_by('-created') ctx['user'] = user ctx['debt_loans'] = user_debt_loans ctx['debt_sum'] = user_debt_loans \ .filter(category=DebtLoan.DEBT) \ .aggregate(Sum('amount')).get('amount__sum') ctx['loan_sum'] = user_debt_loans \ .filter(category=DebtLoan.LOAN) \ .aggregate(Sum('amount')).get('amount__sum') ctx['list'] = 'debts_loans' return render(request, 'debt_loan_list.html', context=ctx) @login_required def debt_loan_create(request): form = forms.DebtLoanForm(request.POST or None) if form.is_valid(): form.instance.user = request.user form.save() return redirect(reverse('debt_loan_list')) <|code_end|> . Use current file imports: from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.urls import reverse from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from books.models import DebtLoan from books.models import Transaction from books import forms from books import services and context (classes, functions, or code) from other files: # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/forms.py # class TransactionForm(forms.ModelForm): # class Meta: # class DebtLoanForm(forms.ModelForm): # class Meta: # # Path: books/services.py # def get_months_transactions(user): # def get_last_months_transactions(user): # def get_this_years_transactions(user): . Output only the next line.
return render(request, 'debt_loan_create.html', {'form': form})
Predict the next line for this snippet: <|code_start|>@login_required def transaction_list_filter(request): fltr = request.GET.get('filter', None) request.session['filter:transaction_list'] = fltr return redirect(reverse('transaction_list')) @login_required def transaction_create(request): form = forms.TransactionForm(request.POST or None) if form.is_valid(): form.instance.user = request.user form.save() return redirect(reverse('transaction_list')) return render(request, 'transaction_create.html', {'form': form}) @login_required def transaction_delete(request, pk): Transaction.objects.get(pk=pk).deactivate() return redirect(reverse('transaction_list')) @login_required def transaction_update(request, pk): instance = get_object_or_404(Transaction, pk=pk) form = forms.TransactionForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect(reverse('transaction_list')) <|code_end|> with the help of current file imports: from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.urls import reverse from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from books.models import DebtLoan from books.models import Transaction from books import forms from books import services and context from other files: # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/forms.py # class TransactionForm(forms.ModelForm): # class Meta: # class DebtLoanForm(forms.ModelForm): # class Meta: # # Path: books/services.py # def get_months_transactions(user): # def get_last_months_transactions(user): # def get_this_years_transactions(user): , which may contain function names, class names, or code. Output only the next line.
return render(request, 'transaction_create.html', {'form': form})
Given the code snippet: <|code_start|> @login_required def transaction_list(request): ctx = {} user_id = request.user.id <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.urls import reverse from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from books.models import DebtLoan from books.models import Transaction from books import forms from books import services and context (functions, classes, or occasionally code) from other files: # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/forms.py # class TransactionForm(forms.ModelForm): # class Meta: # class DebtLoanForm(forms.ModelForm): # class Meta: # # Path: books/services.py # def get_months_transactions(user): # def get_last_months_transactions(user): # def get_this_years_transactions(user): . Output only the next line.
user = User.objects.get(id=user_id)
Given snippet: <|code_start|> ctx['fltr'] = fltr else: # make 'this_month' filter default user_transactions = services.get_months_transactions(user) ctx['fltr'] = 'this_month' user_transactions = user_transactions.order_by('-created') ctx['user'] = user ctx['transactions'] = user_transactions ctx['negative_transaction_sum'] = user_transactions \ .filter(category=Transaction.EXPENSE) \ .aggregate(Sum('amount')).get('amount__sum') ctx['positive_transaction_sum'] = user_transactions \ .filter(category=Transaction.INCOME) \ .aggregate(Sum('amount')).get('amount__sum') ctx['list'] = 'transactions' return render(request, 'transaction_list.html', context=ctx) @login_required def transaction_list_filter(request): fltr = request.GET.get('filter', None) request.session['filter:transaction_list'] = fltr return redirect(reverse('transaction_list')) @login_required <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.urls import reverse from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from books.models import DebtLoan from books.models import Transaction from books import forms from books import services and context: # Path: books/models.py # class DebtLoan(models.Model): # DEBT = 0 # LOAN = 1 # CATEGORY_CHOICES = ( # (DEBT, 'debt'), # (LOAN, 'loan'), # ) # # with_who = fields.CharField(max_length=255) # title = fields.CharField(max_length=255, null=True, blank=True) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # if self.title: # return "{}: {}".format(self.with_who, self.title) # else: # return "{}".format(self.with_who) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/models.py # class Transaction(models.Model): # EXPENSE = 'exp' # INCOME = 'inc' # CATEGORY_CHOICES = ( # (EXPENSE, 'expense'), # (INCOME, 'income'), # ) # # title = fields.CharField(max_length=255) # amount = fields.DecimalField(max_digits=10, decimal_places=2) # category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES) # created = fields.DateTimeField(default=timezone.now, editable=False) # modified = fields.DateTimeField(default=timezone.now) # active = fields.BooleanField(default=True) # user = models.ForeignKey(User, on_delete=models.CASCADE) # # def __str__(self): # return "{}".format(self.title) # # def deactivate(self): # if self.active: # self.active = False # self.save() # # Path: books/forms.py # class TransactionForm(forms.ModelForm): # class Meta: # class DebtLoanForm(forms.ModelForm): # class Meta: # # Path: books/services.py # def get_months_transactions(user): # def get_last_months_transactions(user): # def get_this_years_transactions(user): which might include code, classes, or functions. Output only the next line.
def transaction_create(request):
Given the following code snippet before the placeholder: <|code_start|> class LoginTests(TestCase): def setUp(self): self.user = UserFactory() def test_login_get(self): c = Client() response = c.get(reverse('login')) self.assertEqual(200, response.status_code) def test_login_post(self): c = Client() response = c.post( reverse('login'), {'username': self.user.username, 'password': 'secret'}, follow=True ) self.assertRedirects(response, reverse('transaction_list')) def test_login_and_remember_post(self): c = Client() response = c.post( reverse('login'), {'username': self.user.username, 'password': 'secret', 'remember_me': 'on'}, <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import Client from django.test import TestCase from accounts.factories import UserFactory and context including class names, function names, and sometimes code from other files: # Path: accounts/factories.py # class UserFactory(factory.DjangoModelFactory): # username = factory.Sequence(lambda n: 'admin%d' % n) # password = 'secret' # email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) # # class Meta: # model = User # # @classmethod # def _create(cls, model_class, *args, **kwargs): # manager = cls._get_manager(model_class) # return manager.create_user(*args, **kwargs) . Output only the next line.
follow=True
Predict the next line for this snippet: <|code_start|> urlpatterns = [ # Examples: url(r'^$', finance_views_home, name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include(accounts_urls)), url(r'^books/', include(books_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: <|code_end|> with the help of current file imports: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from accounts import urls as accounts_urls from books import urls as books_urls from finance.views import home as finance_views_home import debug_toolbar and context from other files: # Path: accounts/urls.py # # Path: books/urls.py # # Path: finance/views.py # def home(request): # if request.user.is_authenticated(): # return redirect(reverse('transaction_list')) # return redirect(reverse('login')) , which may contain function names, class names, or code. Output only the next line.
urlpatterns.append(
Predict the next line after this snippet: <|code_start|> urlpatterns = [ # Examples: url(r'^$', finance_views_home, name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include(accounts_urls)), url(r'^books/', include(books_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns.append( <|code_end|> using the current file's imports: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from accounts import urls as accounts_urls from books import urls as books_urls from finance.views import home as finance_views_home import debug_toolbar and any relevant context from other files: # Path: accounts/urls.py # # Path: books/urls.py # # Path: finance/views.py # def home(request): # if request.user.is_authenticated(): # return redirect(reverse('transaction_list')) # return redirect(reverse('login')) . Output only the next line.
url(r'^__debug__/', include(debug_toolbar.urls)),
Given the code snippet: <|code_start|> urlpatterns = [ # Examples: url(r'^$', finance_views_home, name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include(accounts_urls)), url(r'^books/', include(books_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns.append( <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from accounts import urls as accounts_urls from books import urls as books_urls from finance.views import home as finance_views_home import debug_toolbar and context (functions, classes, or occasionally code) from other files: # Path: accounts/urls.py # # Path: books/urls.py # # Path: finance/views.py # def home(request): # if request.user.is_authenticated(): # return redirect(reverse('transaction_list')) # return redirect(reverse('login')) . Output only the next line.
url(r'^__debug__/', include(debug_toolbar.urls)),
Next line prediction: <|code_start|> # Three sources: a <- b <-c # simply test the structure of resulting connectivity measures b0 = np.array([[0, 0.9, 0], [0, 0, 0.9], [0, 0, 0]]) identity = np.eye(3) nfft = 5 c = connectivity.Connectivity(b=b0, c=identity, nfft=nfft) k = lambda x: np.sum(np.abs(x), 2) l = lambda x: np.sum(x, 2) # a should have the same structure as b assert_zerostructure(k(c.A()), b0 + identity) self.assertFalse(np.all(k(c.A()) == k(c.A()).T)) # H should be upper triangular self.assertTrue(np.allclose(np.tril(k(c.H()), -1), 0)) self.assertFalse(np.all(k(c.H()) == k(c.H()).T)) # S should be a full matrix and symmetric self.assertTrue(np.all(k(c.S()) > 0)) self.assertTrue(np.all(k(c.S()) == k(c.S()).T)) # g should be nonzero for direct connections only and symmetric in # magnitude self.assertEqual(k(c.G())[0, 2], 0) self.assertTrue(np.all(k(c.G()) == k(c.G()).T)) # Phase should be zero along the diagonal self.assertTrue(np.allclose(k(c.PHI()).diagonal(), 0)) # Phase should be antisymmetric self.assertTrue(np.allclose(l(c.PHI()), -l(c.PHI()).T)) # Coherence should be 1 over all frequencies along the diagonal self.assertTrue(np.all(k(c.COH()).diagonal() == nfft)) self.assertLessEqual(np.max(np.abs(c.COH())), 1) # pCOH should be nonzero for direct connections only and symmetric in # magnitude <|code_end|> . Use current file imports: (import unittest import numpy as np from scot import connectivity from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal) and context including class names, function names, or small code snippets from other files: # Path: scot/connectivity.py # def connectivity(measure_names, b, c=None, nfft=512): # """Calculate connectivity measures. # # Parameters # ---------- # measure_names : str or list of str # Name(s) of the connectivity measure(s) to calculate. See # :class:`Connectivity` for supported measures. # b : array, shape (n_channels, n_channels * model_order) # VAR model coefficients. See :ref:`var-model-coefficients` for details # about the arrangement of coefficients. # c : array, shape (n_channels, n_channels), optional # Covariance matrix of the driving noise process. Identity matrix is used # if set to None (default). # nfft : int, optional # Number of frequency bins to calculate. Note that these points cover the # range between 0 and half the sampling rate. # # Returns # ------- # result : array, shape (n_channels, n_channels, `nfft`) # An array of shape (m, m, nfft) is returned if measures is a string. If # measures is a list of strings, a dictionary is returned, where each key # is the name of the measure, and the corresponding values are arrays of # shape (m, m, nfft). # # Notes # ----- # When using this function, it is more efficient to get several measures at # once than calling the function multiple times. # # Examples # -------- # >>> c = connectivity(['DTF', 'PDC'], [[0.3, 0.6], [0.0, 0.9]]) # """ # con = Connectivity(b, c, nfft) # try: # return getattr(con, measure_names)() # except TypeError: # return dict((m, getattr(con, m)()) for m in measure_names) . Output only the next line.
self.assertEqual(k(c.pCOH())[0, 2], 0)
Next line prediction: <|code_start|> self.assertRaises(AttributeError, csp, np.random.randn(3,10), [1,1,0,0] ) # number of class labels does not match number of trials self.assertRaises(AttributeError, csp, np.random.randn(5,3,10), [1,1,0,0] ) def testInputSafety(self): # function must not change input variables self.assertTrue((self.X == self.Y).all()) self.assertEqual(self.C, self.D) def testOutputSizes(self): # output matrices must have the correct size self.assertTrue(self.W.shape == (self.M, self.M)) self.assertTrue(self.V.shape == (self.M, self.M)) def testInverse(self): # V should be the inverse of W I = np.abs(self.V.dot(self.W)) self.assertTrue(np.abs(np.mean(I.diagonal())) - 1 < epsilon) self.assertTrue(np.abs(np.sum(I) - I.trace()) < epsilon) class TestDimensionalityReduction(unittest.TestCase): def setUp(self): self.n_comps = 5 self.X = np.random.rand(10,6,100) self.C = np.asarray([0,0,0,0,0,1,1,1,1,1]) self.X[self.C == 0, 0, :] *= 10 <|code_end|> . Use current file imports: (import unittest import numpy as np from numpy.testing.utils import assert_allclose from scot.datatools import dot_special from scot.csp import csp from generate_testdata import generate_covsig from .generate_testdata import generate_covsig) and context including class names, function names, or small code snippets from other files: # Path: scot/csp.py # def csp(x, cl, numcomp=None): # """Calculate common spatial patterns (CSP). # # Parameters # ---------- # x : array, shape (trials, channels, samples) or (channels, samples) # EEG data set. # cl : list of valid dict keys # Class labels associated with each trial. Currently, only two classes # are supported. # numcomp : int, optional # Number of patterns to keep after applying CSP. If `numcomp` is greater # than channels or None, all patterns are returned. # # Returns # ------- # w : array, shape (channels, components) # CSP weight matrix. # v : array, shape (components, channels) # CSP projection matrix. # """ # # x = np.asarray(x) # cl = np.asarray(cl).ravel() # # if x.ndim != 3 or x.shape[0] < 2: # raise AttributeError('CSP requires at least two trials.') # # t, m, n = x.shape # # if t != cl.size: # raise AttributeError('CSP only works with multiple classes. Number of ' # 'elements in cl ({}) must equal the first ' # 'dimension of x ({})'.format(cl.size, t)) # # labels = np.unique(cl) # # if labels.size != 2: # raise AttributeError('CSP is currently implemented for two classes ' # 'only (got {}).'.format(labels.size)) # # x1 = x[cl == labels[0], :, :] # x2 = x[cl == labels[1], :, :] # # sigma1 = np.zeros((m, m)) # for t in range(x1.shape[0]): # sigma1 += np.cov(x1[t, :, :]) / x1.shape[0] # sigma1 /= sigma1.trace() # # sigma2 = np.zeros((m, m)) # for t in range(x2.shape[0]): # sigma2 += np.cov(x2[t, :, :]) / x2.shape[0] # sigma2 /= sigma2.trace() # # e, w = eigh(sigma1, sigma1 + sigma2, overwrite_a=True, overwrite_b=True, # check_finite=False) # # order = np.argsort(e)[::-1] # w = w[:, order] # v = np.linalg.inv(w) # # # subsequently remove unwanted components from the middle of w and v # if numcomp is None: # numcomp = w.shape[1] # while w.shape[1] > numcomp: # i = int(np.floor(w.shape[1]/2)) # w = np.delete(w, i, 1) # v = np.delete(v, i, 0) # # return w, v . Output only the next line.
self.X[self.C == 0, 2, :] *= 5
Given the following code snippet before the placeholder: <|code_start|># Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2014 SCoT Development Team eeglocs = [p.list for p in _eeglocs] class TestWarpLocations(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_interface(self): self.assertRaises(TypeError, warp_locations) <|code_end|> , predict the next line using imports from the current file: import unittest import numpy as np from numpy.testing.utils import assert_allclose from scot.eegtopo.warp_layout import warp_locations from scot.eegtopo.eegpos3d import positions as _eeglocs and context including class names, function names, and sometimes code from other files: # Path: scot/eegtopo/eegpos3d.py # def intersection(a, b, expr=lambda c: c.vector.z >= 0): # def construct_1020_easycap(variant=0): . Output only the next line.
self.assertEqual(warp_locations(np.eye(3)).shape, (3, 3)) # returns array
Here is a snippet: <|code_start|> cls.register = Library('test') def test_register_function1(self): @self.register.register def test(): pass self.assertIs(self.register.get('test'), test) def test_register_function2(self): @self.register.register() def test(): pass self.assertIs(self.register.get('test'), test) def test_register_unknown_item(self): self.assertRaises(KeyError, self.register.get, 'unknown_item') def test_register_unknown_item_global(self): self.assertRaises(KeyError, Library.get_global, 'test:unknown_item') def test_register_get_global(self): @self.register.register def test(): pass self.assertIs(Library.get_global('test:test'), test) def test_register_namespaces(self): <|code_end|> . Write the next line using the current file imports: from django.test import TestCase from achilles.common import (BaseLibrary, achilles_plugins, achilles_renders) and context from other files: # Path: achilles/common.py # class BaseLibrary(object): # """ # Base register library, provides decorator functions to register # items of any type. # # All items are registered using a name to uniquely identify them # # This register library is namespaced, so every new instance of it # gets registered under the given namespace. This will avoid # collisions between apps # """ # namespace_separator = ':' # # def __init__(self, namespace): # # global namespaced register # if not hasattr(type(self), 'registers'): # type(self).registers = {} # # # Register the instanced library # if namespace in type(self).registers: # library = type(self).registers[namespace] # raise ValueError("An namespace with name " # "'%s' is already registered in '%s'" % # (namespace, library.__module__)) # # type(self).registers[namespace] = self # self.namespace = namespace # self.items = {} # # def get(self, name): # if name not in self.items: # raise KeyError("'%s' item doesn't exists" % name) # return self.items[name] # # @classmethod # def get_global(cls, name): # if cls.namespace_separator in name: # namespace, name = name.split(cls.namespace_separator, 1) # else: # namespace = None # if namespace not in cls.registers: # raise KeyError("'%s' namespace doesn't exists. " # "Avaible namespaces are: %s" # % (namespace, cls.registers.keys())) # register = cls.registers[namespace] # try: # return register.get(name) # except KeyError: # raise KeyError("'%s' doesn't exists" % name) # # def register(self, name=None): # if name is None: # return self._register # elif callable(name): # func = name # name = getattr(name, '_decorated_function', name).__name__ # return self._register(func, name) # else: # def dec(func): # return self._register(func, name) # return dec # # def _register(self, func, name=None): # name = name or getattr(func, '_decorated_function', func).__name__ # func.register_name = ':'.join([self.namespace or '', name]) # self.items[name] = func # return func # # def achilles_plugins(): # """ # Return a dict of the enabled plugins with achilles namespace as keys # """ # return getattr(settings, 'ACHILLES_PLUGINS', # { # 'blocks': 'achilles.blocks', # 'actions': 'achilles.actions', # 'console': 'achilles.console', # 'redirect': 'achilles.redirect', # 'messages': 'achilles.messages', # }) # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} , which may include functions, classes, or code. Output only the next line.
register = Library('namespace')
Next line prediction: <|code_start|> self.assertEqual(set(plugins.keys()), set(renders.keys())) class LibraryTests(TestCase): @classmethod def setUpClass(cls): cls.register = Library('test') def test_register_function1(self): @self.register.register def test(): pass self.assertIs(self.register.get('test'), test) def test_register_function2(self): @self.register.register() def test(): pass self.assertIs(self.register.get('test'), test) def test_register_unknown_item(self): self.assertRaises(KeyError, self.register.get, 'unknown_item') def test_register_unknown_item_global(self): self.assertRaises(KeyError, Library.get_global, 'test:unknown_item') <|code_end|> . Use current file imports: (from django.test import TestCase from achilles.common import (BaseLibrary, achilles_plugins, achilles_renders)) and context including class names, function names, or small code snippets from other files: # Path: achilles/common.py # class BaseLibrary(object): # """ # Base register library, provides decorator functions to register # items of any type. # # All items are registered using a name to uniquely identify them # # This register library is namespaced, so every new instance of it # gets registered under the given namespace. This will avoid # collisions between apps # """ # namespace_separator = ':' # # def __init__(self, namespace): # # global namespaced register # if not hasattr(type(self), 'registers'): # type(self).registers = {} # # # Register the instanced library # if namespace in type(self).registers: # library = type(self).registers[namespace] # raise ValueError("An namespace with name " # "'%s' is already registered in '%s'" % # (namespace, library.__module__)) # # type(self).registers[namespace] = self # self.namespace = namespace # self.items = {} # # def get(self, name): # if name not in self.items: # raise KeyError("'%s' item doesn't exists" % name) # return self.items[name] # # @classmethod # def get_global(cls, name): # if cls.namespace_separator in name: # namespace, name = name.split(cls.namespace_separator, 1) # else: # namespace = None # if namespace not in cls.registers: # raise KeyError("'%s' namespace doesn't exists. " # "Avaible namespaces are: %s" # % (namespace, cls.registers.keys())) # register = cls.registers[namespace] # try: # return register.get(name) # except KeyError: # raise KeyError("'%s' doesn't exists" % name) # # def register(self, name=None): # if name is None: # return self._register # elif callable(name): # func = name # name = getattr(name, '_decorated_function', name).__name__ # return self._register(func, name) # else: # def dec(func): # return self._register(func, name) # return dec # # def _register(self, func, name=None): # name = name or getattr(func, '_decorated_function', func).__name__ # func.register_name = ':'.join([self.namespace or '', name]) # self.items[name] = func # return func # # def achilles_plugins(): # """ # Return a dict of the enabled plugins with achilles namespace as keys # """ # return getattr(settings, 'ACHILLES_PLUGINS', # { # 'blocks': 'achilles.blocks', # 'actions': 'achilles.actions', # 'console': 'achilles.console', # 'redirect': 'achilles.redirect', # 'messages': 'achilles.messages', # }) # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} . Output only the next line.
def test_register_get_global(self):
Continue the code snippet: <|code_start|> class Library(BaseLibrary): pass class AchillesRendersTests(TestCase): def test_achilles_renders(self): plugins = achilles_plugins() renders = achilles_renders() self.assertEqual(set(plugins.keys()), set(renders.keys())) class LibraryTests(TestCase): <|code_end|> . Use current file imports: from django.test import TestCase from achilles.common import (BaseLibrary, achilles_plugins, achilles_renders) and context (classes, functions, or code) from other files: # Path: achilles/common.py # class BaseLibrary(object): # """ # Base register library, provides decorator functions to register # items of any type. # # All items are registered using a name to uniquely identify them # # This register library is namespaced, so every new instance of it # gets registered under the given namespace. This will avoid # collisions between apps # """ # namespace_separator = ':' # # def __init__(self, namespace): # # global namespaced register # if not hasattr(type(self), 'registers'): # type(self).registers = {} # # # Register the instanced library # if namespace in type(self).registers: # library = type(self).registers[namespace] # raise ValueError("An namespace with name " # "'%s' is already registered in '%s'" % # (namespace, library.__module__)) # # type(self).registers[namespace] = self # self.namespace = namespace # self.items = {} # # def get(self, name): # if name not in self.items: # raise KeyError("'%s' item doesn't exists" % name) # return self.items[name] # # @classmethod # def get_global(cls, name): # if cls.namespace_separator in name: # namespace, name = name.split(cls.namespace_separator, 1) # else: # namespace = None # if namespace not in cls.registers: # raise KeyError("'%s' namespace doesn't exists. " # "Avaible namespaces are: %s" # % (namespace, cls.registers.keys())) # register = cls.registers[namespace] # try: # return register.get(name) # except KeyError: # raise KeyError("'%s' doesn't exists" % name) # # def register(self, name=None): # if name is None: # return self._register # elif callable(name): # func = name # name = getattr(name, '_decorated_function', name).__name__ # return self._register(func, name) # else: # def dec(func): # return self._register(func, name) # return dec # # def _register(self, func, name=None): # name = name or getattr(func, '_decorated_function', func).__name__ # func.register_name = ':'.join([self.namespace or '', name]) # self.items[name] = func # return func # # def achilles_plugins(): # """ # Return a dict of the enabled plugins with achilles namespace as keys # """ # return getattr(settings, 'ACHILLES_PLUGINS', # { # 'blocks': 'achilles.blocks', # 'actions': 'achilles.actions', # 'console': 'achilles.console', # 'redirect': 'achilles.redirect', # 'messages': 'achilles.messages', # }) # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} . Output only the next line.
@classmethod
Next line prediction: <|code_start|> out = Template( "{% load achilles %}" "{% ablock 'message' %}").render(Context()) self.assertEqual(out, '<div data-ablock="message">foo\n</div>') def test_render_function_block_returning_same_context(self): @self.register.block(template_name='block_template.html', takes_context=True) def message(context): context['message'] = 'foo' return context out = Template( "{% load achilles %}" "{% ablock 'message' %}").render(Context()) self.assertEqual(out, '<div data-ablock="message">foo\n</div>') def test_render_class_block(self): @self.register.block('message') class Message(blocks.Block): template_name = 'block_template.html' def get_context_data(self, *args, **kwargs): context = super(Message, self).get_context_data(*args, **kwargs) context.update({'message': 'foo'}) return context out = Template( "{% load achilles %}" <|code_end|> . Use current file imports: (import os from django.test import TestCase from django.test.utils import override_settings from django.template import Template, Context from achilles import blocks) and context including class names, function names, or small code snippets from other files: # Path: achilles/blocks.py # class Library(BaseLibrary): # class B(Block): # class Block(object): # def __init__(self, namespace=None): # def register(self, name=None): # def block(self, name=None, template_name=None, takes_context=False): # def dec(name): # def _create_class(self, func): # def get_context_data(self, *args, **kwargs): # def get(name, context=None): # def __init__(self, context): # def render(self, *args, **kwargs): # def get_context_data(self, *args, **kwargs): # def update(self, transport, *args, **kwargs): # def update(transport, name, *args, **kwargs): # def render(transport): . Output only the next line.
"{% ablock 'message' %}").render(Context())
Predict the next line for this snippet: <|code_start|> 'id': '2', 'args': [2], }, { 'name': 'action', 'id': '3', 'kwargs': {'param': 33}, }, ]) data = actions.render(self.transport) self.assertEqual(data["1"]["value"], 13) self.assertEqual(data["2"]["value"], 2) self.assertEqual(data["3"]["value"], 33) def test_run_actions_error(self): @self.register.action def action(request): raise ValueError('foo') actions.run_actions(self.transport, [ { 'name': 'action', 'id': '1', }, ]) data = actions.render(self.transport) <|code_end|> with the help of current file imports: from django.test import RequestFactory from django.test import TestCase from achilles.common import AchillesTransport from achilles import actions and context from other files: # Path: achilles/common.py # class AchillesTransport(object): # """ # Transport object, holds information context for some user requests # and response # """ # def __init__(self, request): # """ # Achilles Transport init for Django requests, it gets a request object # and fills its fields from it # """ # # plugin's data # self._data = {} # # # common properties # self.encoding = request.encoding # # # backend specific properties # self.request = request # # def data(self, key=None, default=None): # """ # Return achilles response dict. Achilles stores here data related # to the request, in order to prepare a reply. # # If key value is given, this function will return that key (if exists) # from achilles response dict. # # If default is given it will be asigned and returned if it doesn't exist # """ # if key not in self._data and default is not None: # self._data[key] = default # # return self._data[key] # # Path: achilles/actions.py # class Library(BaseLibrary): # def __init__(self, namespace=None): # def _register(self, func, name=None): # def wrapper(transport, *args, **kwargs): # def get(name): # def run_actions(transport, actions): # def render(transport): , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(data["1"]["error"], 'ValueError')
Predict the next line for this snippet: <|code_start|> class ActionsTests(TestCase): @classmethod def setupClass(cls): cls.register = actions.Library() def setUp(self): <|code_end|> with the help of current file imports: from django.test import RequestFactory from django.test import TestCase from achilles.common import AchillesTransport from achilles import actions and context from other files: # Path: achilles/common.py # class AchillesTransport(object): # """ # Transport object, holds information context for some user requests # and response # """ # def __init__(self, request): # """ # Achilles Transport init for Django requests, it gets a request object # and fills its fields from it # """ # # plugin's data # self._data = {} # # # common properties # self.encoding = request.encoding # # # backend specific properties # self.request = request # # def data(self, key=None, default=None): # """ # Return achilles response dict. Achilles stores here data related # to the request, in order to prepare a reply. # # If key value is given, this function will return that key (if exists) # from achilles response dict. # # If default is given it will be asigned and returned if it doesn't exist # """ # if key not in self._data and default is not None: # self._data[key] = default # # return self._data[key] # # Path: achilles/actions.py # class Library(BaseLibrary): # def __init__(self, namespace=None): # def _register(self, func, name=None): # def wrapper(transport, *args, **kwargs): # def get(name): # def run_actions(transport, actions): # def render(transport): , which may contain function names, class names, or code. Output only the next line.
request = RequestFactory().get('/path')
Given snippet: <|code_start|> class ActionsTests(TestCase): @classmethod def setupClass(cls): cls.request_factory = RequestFactory() def setUp(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import RequestFactory, TestCase from django.conf import settings from achilles.common import achilles_plugins from achilles.views import endpoint import json and context: # Path: achilles/common.py # def achilles_plugins(): # """ # Return a dict of the enabled plugins with achilles namespace as keys # """ # return getattr(settings, 'ACHILLES_PLUGINS', # { # 'blocks': 'achilles.blocks', # 'actions': 'achilles.actions', # 'console': 'achilles.console', # 'redirect': 'achilles.redirect', # 'messages': 'achilles.messages', # }) # # Path: achilles/views.py # def endpoint(request): # if request.method != 'POST': # return HttpResponseBadRequest() # # match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE']) # if match: # charset = match.group(1) # else: # charset = settings.DEFAULT_CHARSET # # transport = AchillesTransport(request) # data = json.loads(request.body.decode(charset)) # run_actions(transport, data) # # result = {} # for (namespace, render) in achilles_renders().items(): # result[namespace] = render(transport) # # return HttpResponse(json.dumps(result), content_type="application/json") which might include code, classes, or functions. Output only the next line.
self.request = self.request_factory.post(
Predict the next line for this snippet: <|code_start|> register = blocks.Library('messages') def render(request): return [ { 'level': message.level, 'message': message.message, 'tags': message.tags, 'extra_tags': message.extra_tags, <|code_end|> with the help of current file imports: from django.contrib.messages import get_messages from achilles import blocks and context from other files: # Path: achilles/blocks.py # class Library(BaseLibrary): # class B(Block): # class Block(object): # def __init__(self, namespace=None): # def register(self, name=None): # def block(self, name=None, template_name=None, takes_context=False): # def dec(name): # def _create_class(self, func): # def get_context_data(self, *args, **kwargs): # def get(name, context=None): # def __init__(self, context): # def render(self, *args, **kwargs): # def get_context_data(self, *args, **kwargs): # def update(self, transport, *args, **kwargs): # def update(transport, name, *args, **kwargs): # def render(transport): , which may contain function names, class names, or code. Output only the next line.
}
Based on the snippet: <|code_start|> register = actions.Library('example') @register.action def multiply(transport, a, b): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import messages from achilles import actions, blocks, console and context (classes, functions, sometimes code) from other files: # Path: achilles/actions.py # class Library(BaseLibrary): # def __init__(self, namespace=None): # def _register(self, func, name=None): # def wrapper(transport, *args, **kwargs): # def get(name): # def run_actions(transport, actions): # def render(transport): # # Path: achilles/blocks.py # class Library(BaseLibrary): # class B(Block): # class Block(object): # def __init__(self, namespace=None): # def register(self, name=None): # def block(self, name=None, template_name=None, takes_context=False): # def dec(name): # def _create_class(self, func): # def get_context_data(self, *args, **kwargs): # def get(name, context=None): # def __init__(self, context): # def render(self, *args, **kwargs): # def get_context_data(self, *args, **kwargs): # def update(self, transport, *args, **kwargs): # def update(transport, name, *args, **kwargs): # def render(transport): # # Path: achilles/console.py # def log(transport, msg): # def render(transport): . Output only the next line.
messages.info(request, 'Multiplication done')
Using the snippet: <|code_start|> register = actions.Library('example') @register.action def multiply(transport, a, b): messages.info(request, 'Multiplication done') return float(a) * float(b) @register.action def divide(transport, a, b): messages.info(request, 'Division done') return float(a) / float(b) @register.action <|code_end|> , determine the next line of code. You have imports: from django.contrib import messages from achilles import actions, blocks, console and context (class names, function names, or code) available: # Path: achilles/actions.py # class Library(BaseLibrary): # def __init__(self, namespace=None): # def _register(self, func, name=None): # def wrapper(transport, *args, **kwargs): # def get(name): # def run_actions(transport, actions): # def render(transport): # # Path: achilles/blocks.py # class Library(BaseLibrary): # class B(Block): # class Block(object): # def __init__(self, namespace=None): # def register(self, name=None): # def block(self, name=None, template_name=None, takes_context=False): # def dec(name): # def _create_class(self, func): # def get_context_data(self, *args, **kwargs): # def get(name, context=None): # def __init__(self, context): # def render(self, *args, **kwargs): # def get_context_data(self, *args, **kwargs): # def update(self, transport, *args, **kwargs): # def update(transport, name, *args, **kwargs): # def render(transport): # # Path: achilles/console.py # def log(transport, msg): # def render(transport): . Output only the next line.
def log(transport):
Here is a snippet: <|code_start|> def endpoint(request): if request.method != 'POST': return HttpResponseBadRequest() <|code_end|> . Write the next line using the current file imports: from django.http import HttpResponseBadRequest, HttpResponse from django.conf import settings from django.test.client import CONTENT_TYPE_RE from achilles.common import AchillesTransport, achilles_renders from achilles.actions import run_actions import json and context from other files: # Path: achilles/common.py # class AchillesTransport(object): # """ # Transport object, holds information context for some user requests # and response # """ # def __init__(self, request): # """ # Achilles Transport init for Django requests, it gets a request object # and fills its fields from it # """ # # plugin's data # self._data = {} # # # common properties # self.encoding = request.encoding # # # backend specific properties # self.request = request # # def data(self, key=None, default=None): # """ # Return achilles response dict. Achilles stores here data related # to the request, in order to prepare a reply. # # If key value is given, this function will return that key (if exists) # from achilles response dict. # # If default is given it will be asigned and returned if it doesn't exist # """ # if key not in self._data and default is not None: # self._data[key] = default # # return self._data[key] # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} # # Path: achilles/actions.py # def run_actions(transport, actions): # """ # Run the given list of actions sent by the client # """ # pre_actions_call.send(transport, transport=transport) # # data = transport.data('actions', {}) # for a in actions: # name = a['name'] # action = get(name) # # # run and save return value # try: # result = action(transport, # *a.get('args', []), # **a.get('kwargs', {})) # # data[a['id']] = { # 'value': result # } # except Exception as e: # # Mark as error # data[a['id']] = { # 'error': e.__class__.__name__, # 'message': str(e), # } # if settings.DEBUG: # data[a['id']]['trace'] = traceback.format_exc() # # logger.exception("Error on %s action" % name) # # post_actions_call.send(transport, transport=transport) , which may include functions, classes, or code. Output only the next line.
match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
Predict the next line for this snippet: <|code_start|> def endpoint(request): if request.method != 'POST': return HttpResponseBadRequest() match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE']) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET transport = AchillesTransport(request) data = json.loads(request.body.decode(charset)) run_actions(transport, data) result = {} for (namespace, render) in achilles_renders().items(): <|code_end|> with the help of current file imports: from django.http import HttpResponseBadRequest, HttpResponse from django.conf import settings from django.test.client import CONTENT_TYPE_RE from achilles.common import AchillesTransport, achilles_renders from achilles.actions import run_actions import json and context from other files: # Path: achilles/common.py # class AchillesTransport(object): # """ # Transport object, holds information context for some user requests # and response # """ # def __init__(self, request): # """ # Achilles Transport init for Django requests, it gets a request object # and fills its fields from it # """ # # plugin's data # self._data = {} # # # common properties # self.encoding = request.encoding # # # backend specific properties # self.request = request # # def data(self, key=None, default=None): # """ # Return achilles response dict. Achilles stores here data related # to the request, in order to prepare a reply. # # If key value is given, this function will return that key (if exists) # from achilles response dict. # # If default is given it will be asigned and returned if it doesn't exist # """ # if key not in self._data and default is not None: # self._data[key] = default # # return self._data[key] # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} # # Path: achilles/actions.py # def run_actions(transport, actions): # """ # Run the given list of actions sent by the client # """ # pre_actions_call.send(transport, transport=transport) # # data = transport.data('actions', {}) # for a in actions: # name = a['name'] # action = get(name) # # # run and save return value # try: # result = action(transport, # *a.get('args', []), # **a.get('kwargs', {})) # # data[a['id']] = { # 'value': result # } # except Exception as e: # # Mark as error # data[a['id']] = { # 'error': e.__class__.__name__, # 'message': str(e), # } # if settings.DEBUG: # data[a['id']]['trace'] = traceback.format_exc() # # logger.exception("Error on %s action" % name) # # post_actions_call.send(transport, transport=transport) , which may contain function names, class names, or code. Output only the next line.
result[namespace] = render(transport)
Predict the next line for this snippet: <|code_start|> def endpoint(request): if request.method != 'POST': return HttpResponseBadRequest() match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE']) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET transport = AchillesTransport(request) <|code_end|> with the help of current file imports: from django.http import HttpResponseBadRequest, HttpResponse from django.conf import settings from django.test.client import CONTENT_TYPE_RE from achilles.common import AchillesTransport, achilles_renders from achilles.actions import run_actions import json and context from other files: # Path: achilles/common.py # class AchillesTransport(object): # """ # Transport object, holds information context for some user requests # and response # """ # def __init__(self, request): # """ # Achilles Transport init for Django requests, it gets a request object # and fills its fields from it # """ # # plugin's data # self._data = {} # # # common properties # self.encoding = request.encoding # # # backend specific properties # self.request = request # # def data(self, key=None, default=None): # """ # Return achilles response dict. Achilles stores here data related # to the request, in order to prepare a reply. # # If key value is given, this function will return that key (if exists) # from achilles response dict. # # If default is given it will be asigned and returned if it doesn't exist # """ # if key not in self._data and default is not None: # self._data[key] = default # # return self._data[key] # # def achilles_renders(): # """ # Return a dict of enabled plugin' render functions # """ # return {k: import_by_path('%s.render' % p) # for k, p in achilles_plugins().items()} # # Path: achilles/actions.py # def run_actions(transport, actions): # """ # Run the given list of actions sent by the client # """ # pre_actions_call.send(transport, transport=transport) # # data = transport.data('actions', {}) # for a in actions: # name = a['name'] # action = get(name) # # # run and save return value # try: # result = action(transport, # *a.get('args', []), # **a.get('kwargs', {})) # # data[a['id']] = { # 'value': result # } # except Exception as e: # # Mark as error # data[a['id']] = { # 'error': e.__class__.__name__, # 'message': str(e), # } # if settings.DEBUG: # data[a['id']]['trace'] = traceback.format_exc() # # logger.exception("Error on %s action" % name) # # post_actions_call.send(transport, transport=transport) , which may contain function names, class names, or code. Output only the next line.
data = json.loads(request.body.decode(charset))
Here is a snippet: <|code_start|> class NMapParser(Parser): type = "parsers.NMap" def __init__(self, collector): super(NMapParser, self).__init__(collector) if os.name == 'nt': self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "nmap_parser.bat") else: <|code_end|> . Write the next line using the current file imports: import os import subprocess import definitions from engine.parser import Parser and context from other files: # Path: engine/parser.py # class Parser(object): # # def __init__(self, collector): # self.post_conditions = [] # self.collector = collector # self.file_or_dir = collector.output_dir # self.parsed_folder = os.path.join(collector.base_dir, "parsed") # self.parserInputs = [] # self.status = "pending" # # def parse(self): # self.pb = ProgressBarDetails() # self.pb.set_title(self.collector.name + " Parser Output") # self.pb.appendText("Starting parser for " + self.collector.name + "...\n") # # self.text_buffer = self.pb.text_buffer # if os.name == 'nt': # subprocess.Popen( # self.parserInputs, # cwd=os.path.dirname(os.path.realpath(__file__)), # stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) # self.status = "running" # else: # self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) # self.status = "running" # gobject.timeout_add(100, self.update_textbuffer) # # # # def non_block_read(self, output): # ''' even in a thread, a normal read with block until the buffer is full ''' # fd = output.fileno() # fl = fcntl.fcntl(fd, fcntl.F_GETFL) # fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # try: # return output.read() # except: # return '' # # def update_textbuffer(self): # self.text_buffer.insert_at_cursor(self.non_block_read(self.sub_proc.stdout)) # res = self.sub_proc.poll() is None # if res == False: # self.status = "complete" # self.text_buffer.insert_at_cursor("Finished. Please close this window.") # if not self.pb.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): # self.pb.destroy() # return res # #### # # # def do_file(self, file_path): # print "" # # def __parse_file(self, file_path): # if self.__meets_post_conditions(file_path): # self.do_file(file_path) # # def __parse_directory(self, dir): # for file in os.listdir(dir): # self.__parse_file(os.path.join(dir, file)) # # def __meets_post_conditions(self, file_path): # for post_condition in self.post_conditions: # if not post_condition.assert_true(file_path): # return False # return True # # def dump_to_file(self, lines): # with open(self.pfolder, 'w') as outfile: # outfile.writelines(lines) , which may include functions, classes, or code. Output only the next line.
self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "nmap_parser.sh")
Using the snippet: <|code_start|> def select_folder(self, event): dialog_select_folder = gtk.FileChooserDialog() dialog_select_folder.set_title("Export To") dialog_select_folder.set_transient_for(self) dialog_select_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) dialog_select_folder.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK) dialog_select_folder.set_current_folder(self.entry_selected_folder.get_text()) response = dialog_select_folder.run() if response == gtk.RESPONSE_OK: self.entry_selected_folder.set_text(dialog_select_folder.get_filename()) dialog_select_folder.destroy() def close_export_dialog(self, event): self.hide_all() def export(self, event): export_base_dir = self.entry_selected_folder.get_text() export_raw = self.checkbutton_export_raw.get_active() export_compressed = self.checkbutton_export_compressed.get_active() export_parsed = self.checkbutton_export_parsed.get_active() if not export_base_dir: utils.gui.show_error_message(self, "Please select a directory to export to.") return if not os.path.isdir(export_base_dir): utils.gui.show_error_message(self, "Please select a valid directory to export to.") return <|code_end|> , determine the next line of code. You have imports: import gtk import os import shutil import time import definitions import utils.gui from os.path import expanduser from engine.archiver.zip_format import zip from engine.archiver.tar_format import tar from gui.progress_bar import ProgressBar and context (class names, function names, or code) available: # Path: engine/archiver/zip_format.py # def zip(source, dest): # """Compresses a file/dir, given a source path, to the zip format # The resulting file will be created in the given dest path. """ # # dest_directory = os.path.dirname(dest) # # if not os.path.exists(dest_directory): # print("Created zip destination folder. %s" % dest_directory) # os.makedirs(dest_directory) # # if os.path.exists(source): # epoch_time = str(int(time.time())) # # moved the creation of the zip file inside each case below in order to create the zip only if necessary. # # if os.path.isfile(source): # # printDebugInfo(" inside zip, the source is a file ") # # zOut = zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + epoch_time + ZIP_EXT, mode='w') # zOut.write(source, compress_type=zipfile.ZIP_DEFLATED, arcname=os.path.basename( # source)) # This fixes the bug where the compressed file in the zip did not have the correct file extension # zOut.close() # print (" Compressed: %s into %s" % (source, dest)) # elif os.path.isdir(source): # printDebugInfo(" inside zip, the source is a directory ") # # with zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + str(epoch_time) + ZIP_EXT, mode='w') as myzip: # rootlen = len(source) # use the sub-part of path which you want to keep in your zip file # for base, dirs, files in os.walk(source): # for ifile in files: # fn = os.path.join(base, ifile) # myzip.write(fn, fn[rootlen:], compress_type=zipfile.ZIP_DEFLATED) # # else: # print("File: " + source + " Doesn't exist! zip function aborted.") # # Path: engine/archiver/tar_format.py # def tar(source, dest): # """Compresses a file/dir, given a source path, using tar archiving # with bzip2 compression. The resulting file will be created in # the given dest path. """ # # if os.path.exists(source): # if os.listdir(source): # Compress files, not an empty directory # epochTime = str(int(time.time())) # # with tarfile.open(dest + SEPARATOR + epochTime + EXT, "w:bz2") as tarBall: # tarBall.add(source, arcname=os.path.basename(source)) # tarBall.close() # else: # print(" File: " + source + " Doesn't exist! tar function aborted.") # # Path: gui/progress_bar.py # class ProgressBar(gtk.Window): # # # Clean up allocated memory and remove the timer # def destroy_progress(self, widget, data=None): # self.destroy() # # # Update the value of the progress bar so that we get # # some movement # def setValue(self, pvalue): # # Set the new value # self.pbar.set_fraction(pvalue) # # def __init__(self): # super(ProgressBar, self).__init__() # # #Configure the Window # self.set_resizable(False) # self.connect("destroy", self.destroy_progress) # self.set_title("Progress Bar") # self.set_position(gtk.WIN_POS_CENTER) # self.set_size_request(460, 50) # self.set_border_width(0) # # #Create the VBox in case we want to add additional items later # vbox = gtk.VBox(False, 5) # vbox.set_border_width(10) # self.add(vbox) # vbox.show() # # # Create the ProgressBar # self.pbar = gtk.ProgressBar() # self.pbar.set_fraction(0.0) # self.pbar.set_text("Starting") # vbox.add(self.pbar) # self.pbar.show() # # #Display the Window # self.show() . Output only the next line.
if not export_raw and not export_compressed and not export_parsed:
Given snippet: <|code_start|> hbox_okcancel.pack_start(button_export) frame_exporttype.add(vbox_exporttype) frame_exportoptions.add(vbox_exportoptions) frame_exportto.add(hbox_exportto) vbox.pack_start(frame_exporttype) vbox.pack_start(frame_exportoptions) vbox.pack_start(frame_exportto) vbox.pack_start(hbox_okcancel) self.add(vbox) self.show_all() def on_key_release(self, widget, event): keyname = gtk.gdk.keyval_name(event.keyval) if keyname == "KP_Enter" or keyname == "Return": self.export(event) def checkbutton_compress_export_toggled(self, event): if self.checkbutton_compress_export.get_active(): self.radiobutton_compress_export_format_zip.set_sensitive(True) self.radiobutton_compress_export_format_tar.set_sensitive(True) else: self.radiobutton_compress_export_format_zip.set_sensitive(False) self.radiobutton_compress_export_format_tar.set_sensitive(False) def select_folder(self, event): dialog_select_folder = gtk.FileChooserDialog() dialog_select_folder.set_title("Export To") dialog_select_folder.set_transient_for(self) <|code_end|> , continue by predicting the next line. Consider current file imports: import gtk import os import shutil import time import definitions import utils.gui from os.path import expanduser from engine.archiver.zip_format import zip from engine.archiver.tar_format import tar from gui.progress_bar import ProgressBar and context: # Path: engine/archiver/zip_format.py # def zip(source, dest): # """Compresses a file/dir, given a source path, to the zip format # The resulting file will be created in the given dest path. """ # # dest_directory = os.path.dirname(dest) # # if not os.path.exists(dest_directory): # print("Created zip destination folder. %s" % dest_directory) # os.makedirs(dest_directory) # # if os.path.exists(source): # epoch_time = str(int(time.time())) # # moved the creation of the zip file inside each case below in order to create the zip only if necessary. # # if os.path.isfile(source): # # printDebugInfo(" inside zip, the source is a file ") # # zOut = zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + epoch_time + ZIP_EXT, mode='w') # zOut.write(source, compress_type=zipfile.ZIP_DEFLATED, arcname=os.path.basename( # source)) # This fixes the bug where the compressed file in the zip did not have the correct file extension # zOut.close() # print (" Compressed: %s into %s" % (source, dest)) # elif os.path.isdir(source): # printDebugInfo(" inside zip, the source is a directory ") # # with zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + str(epoch_time) + ZIP_EXT, mode='w') as myzip: # rootlen = len(source) # use the sub-part of path which you want to keep in your zip file # for base, dirs, files in os.walk(source): # for ifile in files: # fn = os.path.join(base, ifile) # myzip.write(fn, fn[rootlen:], compress_type=zipfile.ZIP_DEFLATED) # # else: # print("File: " + source + " Doesn't exist! zip function aborted.") # # Path: engine/archiver/tar_format.py # def tar(source, dest): # """Compresses a file/dir, given a source path, using tar archiving # with bzip2 compression. The resulting file will be created in # the given dest path. """ # # if os.path.exists(source): # if os.listdir(source): # Compress files, not an empty directory # epochTime = str(int(time.time())) # # with tarfile.open(dest + SEPARATOR + epochTime + EXT, "w:bz2") as tarBall: # tarBall.add(source, arcname=os.path.basename(source)) # tarBall.close() # else: # print(" File: " + source + " Doesn't exist! tar function aborted.") # # Path: gui/progress_bar.py # class ProgressBar(gtk.Window): # # # Clean up allocated memory and remove the timer # def destroy_progress(self, widget, data=None): # self.destroy() # # # Update the value of the progress bar so that we get # # some movement # def setValue(self, pvalue): # # Set the new value # self.pbar.set_fraction(pvalue) # # def __init__(self): # super(ProgressBar, self).__init__() # # #Configure the Window # self.set_resizable(False) # self.connect("destroy", self.destroy_progress) # self.set_title("Progress Bar") # self.set_position(gtk.WIN_POS_CENTER) # self.set_size_request(460, 50) # self.set_border_width(0) # # #Create the VBox in case we want to add additional items later # vbox = gtk.VBox(False, 5) # vbox.set_border_width(10) # self.add(vbox) # vbox.show() # # # Create the ProgressBar # self.pbar = gtk.ProgressBar() # self.pbar.set_fraction(0.0) # self.pbar.set_text("Starting") # vbox.add(self.pbar) # self.pbar.show() # # #Display the Window # self.show() which might include code, classes, or functions. Output only the next line.
dialog_select_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
Next line prediction: <|code_start|> if self.checkbutton_compress_export.get_active(): self.radiobutton_compress_export_format_zip.set_sensitive(True) self.radiobutton_compress_export_format_tar.set_sensitive(True) else: self.radiobutton_compress_export_format_zip.set_sensitive(False) self.radiobutton_compress_export_format_tar.set_sensitive(False) def select_folder(self, event): dialog_select_folder = gtk.FileChooserDialog() dialog_select_folder.set_title("Export To") dialog_select_folder.set_transient_for(self) dialog_select_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) dialog_select_folder.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK) dialog_select_folder.set_current_folder(self.entry_selected_folder.get_text()) response = dialog_select_folder.run() if response == gtk.RESPONSE_OK: self.entry_selected_folder.set_text(dialog_select_folder.get_filename()) dialog_select_folder.destroy() def close_export_dialog(self, event): self.hide_all() def export(self, event): export_base_dir = self.entry_selected_folder.get_text() export_raw = self.checkbutton_export_raw.get_active() export_compressed = self.checkbutton_export_compressed.get_active() export_parsed = self.checkbutton_export_parsed.get_active() <|code_end|> . Use current file imports: (import gtk import os import shutil import time import definitions import utils.gui from os.path import expanduser from engine.archiver.zip_format import zip from engine.archiver.tar_format import tar from gui.progress_bar import ProgressBar) and context including class names, function names, or small code snippets from other files: # Path: engine/archiver/zip_format.py # def zip(source, dest): # """Compresses a file/dir, given a source path, to the zip format # The resulting file will be created in the given dest path. """ # # dest_directory = os.path.dirname(dest) # # if not os.path.exists(dest_directory): # print("Created zip destination folder. %s" % dest_directory) # os.makedirs(dest_directory) # # if os.path.exists(source): # epoch_time = str(int(time.time())) # # moved the creation of the zip file inside each case below in order to create the zip only if necessary. # # if os.path.isfile(source): # # printDebugInfo(" inside zip, the source is a file ") # # zOut = zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + epoch_time + ZIP_EXT, mode='w') # zOut.write(source, compress_type=zipfile.ZIP_DEFLATED, arcname=os.path.basename( # source)) # This fixes the bug where the compressed file in the zip did not have the correct file extension # zOut.close() # print (" Compressed: %s into %s" % (source, dest)) # elif os.path.isdir(source): # printDebugInfo(" inside zip, the source is a directory ") # # with zipfile.ZipFile(dest + FILE_NAME_SEPARATOR + str(epoch_time) + ZIP_EXT, mode='w') as myzip: # rootlen = len(source) # use the sub-part of path which you want to keep in your zip file # for base, dirs, files in os.walk(source): # for ifile in files: # fn = os.path.join(base, ifile) # myzip.write(fn, fn[rootlen:], compress_type=zipfile.ZIP_DEFLATED) # # else: # print("File: " + source + " Doesn't exist! zip function aborted.") # # Path: engine/archiver/tar_format.py # def tar(source, dest): # """Compresses a file/dir, given a source path, using tar archiving # with bzip2 compression. The resulting file will be created in # the given dest path. """ # # if os.path.exists(source): # if os.listdir(source): # Compress files, not an empty directory # epochTime = str(int(time.time())) # # with tarfile.open(dest + SEPARATOR + epochTime + EXT, "w:bz2") as tarBall: # tarBall.add(source, arcname=os.path.basename(source)) # tarBall.close() # else: # print(" File: " + source + " Doesn't exist! tar function aborted.") # # Path: gui/progress_bar.py # class ProgressBar(gtk.Window): # # # Clean up allocated memory and remove the timer # def destroy_progress(self, widget, data=None): # self.destroy() # # # Update the value of the progress bar so that we get # # some movement # def setValue(self, pvalue): # # Set the new value # self.pbar.set_fraction(pvalue) # # def __init__(self): # super(ProgressBar, self).__init__() # # #Configure the Window # self.set_resizable(False) # self.connect("destroy", self.destroy_progress) # self.set_title("Progress Bar") # self.set_position(gtk.WIN_POS_CENTER) # self.set_size_request(460, 50) # self.set_border_width(0) # # #Create the VBox in case we want to add additional items later # vbox = gtk.VBox(False, 5) # vbox.set_border_width(10) # self.add(vbox) # vbox.show() # # # Create the ProgressBar # self.pbar = gtk.ProgressBar() # self.pbar.set_fraction(0.0) # self.pbar.set_text("Starting") # vbox.add(self.pbar) # self.pbar.show() # # #Display the Window # self.show() . Output only the next line.
if not export_base_dir:
Given the following code snippet before the placeholder: <|code_start|> class ManualScreenShotParser(Parser): type = "parsers.ManualScreenShot" def __init__(self, collector): super(ManualScreenShotParser, self).__init__(collector) if os.name == 'nt': <|code_end|> , predict the next line using imports from the current file: import os import subprocess from engine.parser import Parser and context including class names, function names, and sometimes code from other files: # Path: engine/parser.py # class Parser(object): # # def __init__(self, collector): # self.post_conditions = [] # self.collector = collector # self.file_or_dir = collector.output_dir # self.parsed_folder = os.path.join(collector.base_dir, "parsed") # self.parserInputs = [] # self.status = "pending" # # def parse(self): # self.pb = ProgressBarDetails() # self.pb.set_title(self.collector.name + " Parser Output") # self.pb.appendText("Starting parser for " + self.collector.name + "...\n") # # self.text_buffer = self.pb.text_buffer # if os.name == 'nt': # subprocess.Popen( # self.parserInputs, # cwd=os.path.dirname(os.path.realpath(__file__)), # stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) # self.status = "running" # else: # self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) # self.status = "running" # gobject.timeout_add(100, self.update_textbuffer) # # # # def non_block_read(self, output): # ''' even in a thread, a normal read with block until the buffer is full ''' # fd = output.fileno() # fl = fcntl.fcntl(fd, fcntl.F_GETFL) # fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # try: # return output.read() # except: # return '' # # def update_textbuffer(self): # self.text_buffer.insert_at_cursor(self.non_block_read(self.sub_proc.stdout)) # res = self.sub_proc.poll() is None # if res == False: # self.status = "complete" # self.text_buffer.insert_at_cursor("Finished. Please close this window.") # if not self.pb.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): # self.pb.destroy() # return res # #### # # # def do_file(self, file_path): # print "" # # def __parse_file(self, file_path): # if self.__meets_post_conditions(file_path): # self.do_file(file_path) # # def __parse_directory(self, dir): # for file in os.listdir(dir): # self.__parse_file(os.path.join(dir, file)) # # def __meets_post_conditions(self, file_path): # for post_condition in self.post_conditions: # if not post_condition.assert_true(file_path): # return False # return True # # def dump_to_file(self, lines): # with open(self.pfolder, 'w') as outfile: # outfile.writelines(lines) . Output only the next line.
self.script_file = os.path.join(
Given the code snippet: <|code_start|> self.file_re = file_re def assert_true(self, file): return re.match(self.file_re, file) class Parser(object): def __init__(self, collector): self.post_conditions = [] self.collector = collector self.file_or_dir = collector.output_dir self.parsed_folder = os.path.join(collector.base_dir, "parsed") self.parserInputs = [] self.status = "pending" def parse(self): self.pb = ProgressBarDetails() self.pb.set_title(self.collector.name + " Parser Output") self.pb.appendText("Starting parser for " + self.collector.name + "...\n") self.text_buffer = self.pb.text_buffer if os.name == 'nt': subprocess.Popen( self.parserInputs, cwd=os.path.dirname(os.path.realpath(__file__)), stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) self.status = "running" else: self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) <|code_end|> , generate the next line using the imports in this file: import os import subprocess import re import gobject import fcntl import gtk from gui.progress_bar_details import ProgressBarDetails and context (functions, classes, or occasionally code) from other files: # Path: gui/progress_bar_details.py # class ProgressBarDetails(gtk.Window): # # # Clean up allocated memory and remove the timer # def destroy_progress(self, widget, data=None): # self.destroy() # # # Update the value of the progress bar so that we get # # some movement # def setValue(self, pvalue): # # Set the new value # self.pbar.set_fraction(pvalue) # # def appendText(self, text): # if text.strip() != "": # self.msg_i += 1 # i = self.text_buffer.get_end_iter() # self.text_buffer.insert(i, str(text), -1) # return True # # def __init__(self): # super(ProgressBarDetails, self).__init__() # # #Configure the Window # self.set_resizable(False) # self.connect("destroy", self.destroy_progress) # self.set_title("Progress Bar") # self.set_position(gtk.WIN_POS_CENTER) # self.set_size_request(460, 150) # self.set_border_width(0) # # #Create the VBox in case we want to add additional items later # self.vbox = gtk.VBox(False, 5) # self.vbox.set_border_width(10) # self.add(self.vbox) # self.vbox.show() # # #create the scrolled window # self.scrolled_window =gtk.ScrolledWindow() # self.scrolled_window.set_usize(460, 100) # self.vbox.add(self.scrolled_window) # self.scrolled_window.show() # # self.text_view = gtk.TextView() # self.msg_i = 0 # self.text_buffer = self.text_view.get_buffer() # self.scrolled_window.add_with_viewport(self.text_view) # self.text_view.connect("size-allocate", self.autoscroll) # self.text_view.show() # # # Create the ProgressBar # self.pbar = gtk.ProgressBar() # #self.pbar.set_usize(460, 40) # self.pbar.set_fraction(0.0) # self.vbox.add(self.pbar) # self.pbar.show() # # #Display the Window # self.show() # # def autoscroll(self, *args): # """The actual scrolling method""" # adj = self.scrolled_window.get_vadjustment() # adj.set_value(adj.get_upper() - adj.get_page_size()) . Output only the next line.
self.status = "running"
Here is a snippet: <|code_start|> class TSharkParser(Parser): type = "parsers.TShark" def __init__(self, collector): super(TSharkParser, self).__init__(collector) if os.name == 'nt': <|code_end|> . Write the next line using the current file imports: import os import subprocess import gobject import fcntl import definitions from engine.parser import Parser and context from other files: # Path: engine/parser.py # class Parser(object): # # def __init__(self, collector): # self.post_conditions = [] # self.collector = collector # self.file_or_dir = collector.output_dir # self.parsed_folder = os.path.join(collector.base_dir, "parsed") # self.parserInputs = [] # self.status = "pending" # # def parse(self): # self.pb = ProgressBarDetails() # self.pb.set_title(self.collector.name + " Parser Output") # self.pb.appendText("Starting parser for " + self.collector.name + "...\n") # # self.text_buffer = self.pb.text_buffer # if os.name == 'nt': # subprocess.Popen( # self.parserInputs, # cwd=os.path.dirname(os.path.realpath(__file__)), # stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) # self.status = "running" # else: # self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) # self.status = "running" # gobject.timeout_add(100, self.update_textbuffer) # # # # def non_block_read(self, output): # ''' even in a thread, a normal read with block until the buffer is full ''' # fd = output.fileno() # fl = fcntl.fcntl(fd, fcntl.F_GETFL) # fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # try: # return output.read() # except: # return '' # # def update_textbuffer(self): # self.text_buffer.insert_at_cursor(self.non_block_read(self.sub_proc.stdout)) # res = self.sub_proc.poll() is None # if res == False: # self.status = "complete" # self.text_buffer.insert_at_cursor("Finished. Please close this window.") # if not self.pb.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): # self.pb.destroy() # return res # #### # # # def do_file(self, file_path): # print "" # # def __parse_file(self, file_path): # if self.__meets_post_conditions(file_path): # self.do_file(file_path) # # def __parse_directory(self, dir): # for file in os.listdir(dir): # self.__parse_file(os.path.join(dir, file)) # # def __meets_post_conditions(self, file_path): # for post_condition in self.post_conditions: # if not post_condition.assert_true(file_path): # return False # return True # # def dump_to_file(self, lines): # with open(self.pfolder, 'w') as outfile: # outfile.writelines(lines) , which may include functions, classes, or code. Output only the next line.
self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tshark_parser.bat")
Here is a snippet: <|code_start|> class SnoopyParser(Parser): type = "parsers.Snoopy" def __init__(self, collector): super(SnoopyParser, self).__init__(collector) if os.name == 'nt': self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "snoopy_parser.bat") <|code_end|> . Write the next line using the current file imports: import os import subprocess from engine.parser import Parser and context from other files: # Path: engine/parser.py # class Parser(object): # # def __init__(self, collector): # self.post_conditions = [] # self.collector = collector # self.file_or_dir = collector.output_dir # self.parsed_folder = os.path.join(collector.base_dir, "parsed") # self.parserInputs = [] # self.status = "pending" # # def parse(self): # self.pb = ProgressBarDetails() # self.pb.set_title(self.collector.name + " Parser Output") # self.pb.appendText("Starting parser for " + self.collector.name + "...\n") # # self.text_buffer = self.pb.text_buffer # if os.name == 'nt': # subprocess.Popen( # self.parserInputs, # cwd=os.path.dirname(os.path.realpath(__file__)), # stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) # self.status = "running" # else: # self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) # self.status = "running" # gobject.timeout_add(100, self.update_textbuffer) # # # # def non_block_read(self, output): # ''' even in a thread, a normal read with block until the buffer is full ''' # fd = output.fileno() # fl = fcntl.fcntl(fd, fcntl.F_GETFL) # fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # try: # return output.read() # except: # return '' # # def update_textbuffer(self): # self.text_buffer.insert_at_cursor(self.non_block_read(self.sub_proc.stdout)) # res = self.sub_proc.poll() is None # if res == False: # self.status = "complete" # self.text_buffer.insert_at_cursor("Finished. Please close this window.") # if not self.pb.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): # self.pb.destroy() # return res # #### # # # def do_file(self, file_path): # print "" # # def __parse_file(self, file_path): # if self.__meets_post_conditions(file_path): # self.do_file(file_path) # # def __parse_directory(self, dir): # for file in os.listdir(dir): # self.__parse_file(os.path.join(dir, file)) # # def __meets_post_conditions(self, file_path): # for post_condition in self.post_conditions: # if not post_condition.assert_true(file_path): # return False # return True # # def dump_to_file(self, lines): # with open(self.pfolder, 'w') as outfile: # outfile.writelines(lines) , which may include functions, classes, or code. Output only the next line.
else:
Given snippet: <|code_start|> class manualscreenshot(ManualCollector): def __init__(self, collector_config): super(manualscreenshot, self).__init__(collector_config) self.command_description = "Take Screenshot" def build_commands(self): self.commands.append("python takeshoot.py") def run(self): #TODO: Need to fix the base collector class to not act like an automatic collector <|code_end|> , continue by predicting the next line. Consider current file imports: from engine.collector import ManualCollector from plugins.collectors.manualscreenshot import takeshoot import os import time and context: # Path: engine/collector.py # class ManualCollector(Collector): # def __init__(self, collector_config): # super(ManualCollector, self).__init__(collector_config) # # self.command_description = "" # Needs to be overridden # # Path: plugins/collectors/manualscreenshot/takeshoot.py # class CaptureScreen(): # def __init__(self): # def save_shot(self): which might include code, classes, or functions. Output only the next line.
if not os.path.exists(self.output_dir):
Given the following code snippet before the placeholder: <|code_start|> menu.append(main_application_menu_item) main_application_menu_item.connect('activate', self.show_main_gui, gui) #separator sep0 = gtk.SeparatorMenuItem() sep0.show() menu.append(sep0) for collector in app_engine.collectors: if isinstance(collector, engine.collector.ManualCollector): menu_item_collector = gtk.MenuItem(collector.command_description) menu.append(menu_item_collector) menu_item_collector.connect('activate', self.run_collector, collector) #separator sep1 = gtk.SeparatorMenuItem() sep1.show() menu.append(sep1) # show about_menu_item dialog self.startall_menu_item = gtk.MenuItem("Start All Collectors") self.startall_menu_item.show() menu.append(self.startall_menu_item) self.startall_menu_item.connect('activate', gui.startall_collectors) # show about_menu_item dialog self.stopall_menu_item = gtk.MenuItem("Stop All Collectors") self.stopall_menu_item.show() menu.append(self.stopall_menu_item) self.stopall_menu_item.connect('activate', gui.stopall_collectors) <|code_end|> , predict the next line using imports from the current file: import gtk import os import appindicator import engine.collector from _version import __version__ and context including class names, function names, and sometimes code from other files: # Path: _version.py . Output only the next line.
self.stopall_menu_item.set_sensitive(False)
Next line prediction: <|code_start|> class PyKeyloggerParser(Parser): def __init__(self, collector): super(PyKeyloggerParser, self).__init__(collector) self.click_dir = os.path.join(self.file_or_dir, "click_images") self.timed_dir = os.path.join(self.file_or_dir, "timed_screenshots") self.file_or_dir = os.path.join(self.file_or_dir, "detailed_log", "logfile.txt") if os.name == 'nt': self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "keylogger_parser.bat") <|code_end|> . Use current file imports: (import os import subprocess from engine.parser import Parser) and context including class names, function names, or small code snippets from other files: # Path: engine/parser.py # class Parser(object): # # def __init__(self, collector): # self.post_conditions = [] # self.collector = collector # self.file_or_dir = collector.output_dir # self.parsed_folder = os.path.join(collector.base_dir, "parsed") # self.parserInputs = [] # self.status = "pending" # # def parse(self): # self.pb = ProgressBarDetails() # self.pb.set_title(self.collector.name + " Parser Output") # self.pb.appendText("Starting parser for " + self.collector.name + "...\n") # # self.text_buffer = self.pb.text_buffer # if os.name == 'nt': # subprocess.Popen( # self.parserInputs, # cwd=os.path.dirname(os.path.realpath(__file__)), # stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE) # self.status = "running" # else: # self.sub_proc = subprocess.Popen(self.parserInputs, stdout=subprocess.PIPE, shell=False) # self.status = "running" # gobject.timeout_add(100, self.update_textbuffer) # # # # def non_block_read(self, output): # ''' even in a thread, a normal read with block until the buffer is full ''' # fd = output.fileno() # fl = fcntl.fcntl(fd, fcntl.F_GETFL) # fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # try: # return output.read() # except: # return '' # # def update_textbuffer(self): # self.text_buffer.insert_at_cursor(self.non_block_read(self.sub_proc.stdout)) # res = self.sub_proc.poll() is None # if res == False: # self.status = "complete" # self.text_buffer.insert_at_cursor("Finished. Please close this window.") # if not self.pb.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): # self.pb.destroy() # return res # #### # # # def do_file(self, file_path): # print "" # # def __parse_file(self, file_path): # if self.__meets_post_conditions(file_path): # self.do_file(file_path) # # def __parse_directory(self, dir): # for file in os.listdir(dir): # self.__parse_file(os.path.join(dir, file)) # # def __meets_post_conditions(self, file_path): # for post_condition in self.post_conditions: # if not post_condition.assert_true(file_path): # return False # return True # # def dump_to_file(self, lines): # with open(self.pfolder, 'w') as outfile: # outfile.writelines(lines) . Output only the next line.
else:
Given the code snippet: <|code_start|> class nmap(AutomaticCollector): def build_commands(self): option = self.config.get_collector_custom_data()["interfaces"]["additional options"] network = self.config.get_collector_custom_data()["interfaces"]["ip range"] out_file_name = "nmap_" + definitions.TIMESTAMP_PLACEHOLDER <|code_end|> , generate the next line using the imports in this file: import os import definitions from engine.collector import AutomaticCollector and context (functions, classes, or occasionally code) from other files: # Path: engine/collector.py # class AutomaticCollector(Collector): # def __init__(self, collector_config): # super(AutomaticCollector, self).__init__(collector_config) # # self.compressed_dir = os.path.join(self.base_dir, definitions.PLUGIN_COLLECTORS_COMPRESSED_DIRNAME) # # self.commands = [] # self.output_filenames = [] # self.processes = [] # self.pid_commands = {} # # self.archiver = None # # def refresh_data(self): # super(AutomaticCollector, self).refresh_data() # # if self.config.collector_has_archiver(): # self.archiver = Archiver(self) # # def run(self): # if self.is_running(): # return # # print (" --> Running %s" % self.name) # # self.build_commands() # self.start_time = str(int(time.time())) # self.create_metafile() # # if not os.path.exists(self.output_dir): # os.mkdir(self.output_dir) # # for command in self.commands: # self.output_filenames.append(definitions.TIMESTAMP_PLACEHOLDER) # self.run_command(command) # # if self.config.get_collector_auto_restart_enabled(): # self.stopFlag = Event() # ar_thread = self.AutoRestart(self, self.stopFlag) # ar_thread.start() # # def run_command(self, command): # runcmds = shlex.split(command.replace(definitions.TIMESTAMP_PLACEHOLDER, self.start_time)) # # try: # process = subprocess.Popen(runcmds, # shell=False, # cwd=self.base_dir, # stdout=self.devnull, # stderr=self.devnull) # # except OSError as err: # print "Error attempting to run command in collector: %s | command: %s\n" % (self.name, command) # print "System Error:", err # else: # self.processes.append(process) # self.pid_commands[process.pid] = command # print("[x] Started: %s -pID(s): %s" % (self.name,str(process.pid))) # # # def terminate(self): # if not self.is_running(): # print (" ...%s processes already dead" % self.name) # return # # tps = [] # for process in self.processes: # if process: # parent_pid = process.pid # parent = psutil.Process(parent_pid) # try: # for child in parent.children(recursive=True): # child.kill() # parent.kill() # except Exception as e: # print (" !! %s: %s" % (self.name, e)) # else: # tps.append(process.pid) # print (" [x] Terminated: %s - pId(s): %s" % (self.name, ', '.join(str(p) for p in tps))) # # self.commands = [] # self.output_filenames = [] # self.processes = [] # self.pid_commands.clear() # # def is_running(self): #TODO: Is this best way to test this? # if self.processes: # return True # return False # # class AutoRestart(Thread): #TODO: Review this # def __init__(self, outer, event): # Thread.__init__(self) # self.outer = outer # self.stopped = event # self.auto_restart_enabled = self.outer.config.get_collector_auto_restart_enabled() # self.time_interval = self.outer.config.get_collector_auto_restart_time_interval() # # def run(self): # while not self.stopped.wait(self.time_interval): # procs = list(self.outer.processes) # for process in procs: # poll_res = process.poll() # if poll_res is not None: # self.restart_process(process) # # def restart_process(self, dead_process): # command = self.outer.pid_commands[dead_process.pid] # self.outer.processes.remove(dead_process) # del self.outer.pid_commands[dead_process.pid] # if(self.auto_restart_enabled): # print("Auto restart enabled for: " + self.outer.name) # print("Auto restart interval: " + str(self.time_interval)) # print("Attempting to restart...") # #print(" --> process %s died, attempting to restart..." % (dead_process.pid)) # #In the case of tshark, process restarts, but dies if interface is down; can't tell if it continues runningd # self.outer.run_command(command) . Output only the next line.
self.output_filenames.append(out_file_name)
Given the code snippet: <|code_start|> class tshark(AutomaticCollector): #TODO: need plugin type in configs? #TODO: Use self.output_filepath? def build_commands(self): # get additional options from the config file mode = self.config.get_collector_custom_data()["interfaces"]["mode"] ifaces = self.config.get_collector_custom_data()["interfaces"]["interfaces"] if mode == "inclusive": self.interfaces = ifaces else: self.interfaces = [iface for iface in netifaces.interfaces() if iface not in ifaces] # build commands for iface in self.interfaces: out_file_name = definitions.TIMESTAMP_PLACEHOLDER + "_" + iface self.output_filenames.append(out_file_name) out_file_path = os.path.join(self.output_dir, out_file_name + ".pcap") cmd = "dumpcap " \ + "-i " + str(iface) + " " \ <|code_end|> , generate the next line using the imports in this file: import os import netifaces import definitions from engine.collector import AutomaticCollector and context (functions, classes, or occasionally code) from other files: # Path: engine/collector.py # class AutomaticCollector(Collector): # def __init__(self, collector_config): # super(AutomaticCollector, self).__init__(collector_config) # # self.compressed_dir = os.path.join(self.base_dir, definitions.PLUGIN_COLLECTORS_COMPRESSED_DIRNAME) # # self.commands = [] # self.output_filenames = [] # self.processes = [] # self.pid_commands = {} # # self.archiver = None # # def refresh_data(self): # super(AutomaticCollector, self).refresh_data() # # if self.config.collector_has_archiver(): # self.archiver = Archiver(self) # # def run(self): # if self.is_running(): # return # # print (" --> Running %s" % self.name) # # self.build_commands() # self.start_time = str(int(time.time())) # self.create_metafile() # # if not os.path.exists(self.output_dir): # os.mkdir(self.output_dir) # # for command in self.commands: # self.output_filenames.append(definitions.TIMESTAMP_PLACEHOLDER) # self.run_command(command) # # if self.config.get_collector_auto_restart_enabled(): # self.stopFlag = Event() # ar_thread = self.AutoRestart(self, self.stopFlag) # ar_thread.start() # # def run_command(self, command): # runcmds = shlex.split(command.replace(definitions.TIMESTAMP_PLACEHOLDER, self.start_time)) # # try: # process = subprocess.Popen(runcmds, # shell=False, # cwd=self.base_dir, # stdout=self.devnull, # stderr=self.devnull) # # except OSError as err: # print "Error attempting to run command in collector: %s | command: %s\n" % (self.name, command) # print "System Error:", err # else: # self.processes.append(process) # self.pid_commands[process.pid] = command # print("[x] Started: %s -pID(s): %s" % (self.name,str(process.pid))) # # # def terminate(self): # if not self.is_running(): # print (" ...%s processes already dead" % self.name) # return # # tps = [] # for process in self.processes: # if process: # parent_pid = process.pid # parent = psutil.Process(parent_pid) # try: # for child in parent.children(recursive=True): # child.kill() # parent.kill() # except Exception as e: # print (" !! %s: %s" % (self.name, e)) # else: # tps.append(process.pid) # print (" [x] Terminated: %s - pId(s): %s" % (self.name, ', '.join(str(p) for p in tps))) # # self.commands = [] # self.output_filenames = [] # self.processes = [] # self.pid_commands.clear() # # def is_running(self): #TODO: Is this best way to test this? # if self.processes: # return True # return False # # class AutoRestart(Thread): #TODO: Review this # def __init__(self, outer, event): # Thread.__init__(self) # self.outer = outer # self.stopped = event # self.auto_restart_enabled = self.outer.config.get_collector_auto_restart_enabled() # self.time_interval = self.outer.config.get_collector_auto_restart_time_interval() # # def run(self): # while not self.stopped.wait(self.time_interval): # procs = list(self.outer.processes) # for process in procs: # poll_res = process.poll() # if poll_res is not None: # self.restart_process(process) # # def restart_process(self, dead_process): # command = self.outer.pid_commands[dead_process.pid] # self.outer.processes.remove(dead_process) # del self.outer.pid_commands[dead_process.pid] # if(self.auto_restart_enabled): # print("Auto restart enabled for: " + self.outer.name) # print("Auto restart interval: " + str(self.time_interval)) # print("Attempting to restart...") # #print(" --> process %s died, attempting to restart..." % (dead_process.pid)) # #In the case of tshark, process restarts, but dies if interface is down; can't tell if it continues runningd # self.outer.run_command(command) . Output only the next line.
+ "-w " + str(out_file_path)
Given the following code snippet before the placeholder: <|code_start|> class SetEnqueueResetReverseDns(BaseReverseDns): def __init__(self, *args, **kwargs): try: self.IPs = kwargs.pop('IPs') except KeyError: # IPs parameter is not filled <|code_end|> , predict the next line using imports from the current file: from ._BaseReverseDns import BaseReverseDns and context including class names, function names, and sometimes code from other files: # Path: ArubaCloud/ReverseDns/Requests/_BaseReverseDns.py # class BaseReverseDns(Request): # def __init__(self, *args, **kwargs): # super(BaseReverseDns, self).__init__(*args, **kwargs) # # noinspection PyPep8Naming # # def commit(self): # pass . Output only the next line.
self.IPs = []
Using the snippet: <|code_start|>#!/usr/bin/env python3 sys.path.insert(1,"..") ############################################ #utilites ############################################ def is_networkfilesystem(dir): return gmeutils.helpers.is_networkfs(dir) <|code_end|> , determine the next line of code. You have imports: import unittest,sys,tempfile import gpgmailencrypt import gmeutils.helpers import gmeutils.archivemanagers import gmeutils.virusscanners import gmeutils.spamscanners import gmeutils.gpgmailserver import email import filecmp import glob import os import os.path import shutil import time import sqlite3 import sqlite3 from gmeutils.dkim import mydkim from multiprocessing import Process and context (class names, function names, or code) available: # Path: gmeutils/dkim.py # class mydkim(_gmechild): # # def __init__(self,parent,selector,domain,privkey): # _gmechild.__init__(self,parent,filename=__file__) # self.selector=selector # self.domain=domain # self.privkey=None # # try: # with open(os.path.expanduser(privkey),"rb") as f: # self.privkey=f.read() # except: # self.log("Could not read DKIM key","e") # self.log_traceback() # # def sign_mail(self,mail): # origmail=email.message_from_string(mail) # # if "DKIM-Signature" in origmail: # del origmail["DKIM-Signature"] # # try: # _res=dkim.sign( mail.encode("UTF-8",unicodeerror), # self.selector.encode("UTF-8",unicodeerror), # self.domain.encode("UTF-8",unicodeerror), # self.privkey).decode("UTF-8",unicodeerror) # msg=_res.split(":",1)[1] # origmail["DKIM-Signature"]=msg # return origmail.as_string() # except: # self.log("Error executing dkim.sign_mail","e") # self.log_traceback() # return mail . Output only the next line.
def has_app(appname):
Here is a snippet: <|code_start|> ####### #_alert ####### def _alert(self): if self.alarmfunc: self.alarmfunc(*self.alarmfuncargs,**self.kwalarmfuncargs) self.running=False ############## #_create_timer ############## def _create_timer(self): self.alarm=threading.Timer( self.timer, self._action) self.running=True self.alarm.start() ########### #is_running ########### def is_running(self): """returns True if the timer is running, returns False after the timer expired""" <|code_end|> . Write the next line using the current file imports: from .child import _gmechild import threading and context from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass , which may include functions, classes, or code. Output only the next line.
return self.running
Based on the snippet: <|code_start|> #unpackingformats ################# def unpackingformats(self): return ["SHAR"] ################## #uncompresscommand ################## @_dbg def uncompresscommand( self, sourcefile, directory, password=None): cmd=[ self.cmd, "\"%s\""%sourcefile, ">/dev/null"] return cmd ############ #_snappytest ############ _snappytest=""" txt="testtext" try: import snappy x=snappy.compress(txt) y=snappy.uncompress(x) <|code_end|> , predict the immediate next line with the help of imports: import os import shutil import subprocess import tempfile from .child import _gmechild from .version import * from ._dbg import _dbg and context (classes, functions, sometimes code) from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
if y!=txt:
Using the snippet: <|code_start|> def __init__(self,parent): _baseunpacker.__init__(self,parent,chdir=True) self.cmd=shutil.which("kgb") ################# #unpackingformats ################# def unpackingformats(self): return ["KGB"] ################## #uncompresscommand ################## @_dbg def uncompresscommand( self, sourcefile, directory, password=None): cmd=[ self.cmd, "\"%s\""%sourcefile, ">/dev/null"] return cmd ##### #_LHA ##### <|code_end|> , determine the next line of code. You have imports: import os import shutil import subprocess import tempfile from .child import _gmechild from .version import * from ._dbg import _dbg and context (class names, function names, or code) available: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
class _LHA(_baseunpacker):
Given the code snippet: <|code_start|> "SOPHOS" ] ################# #get_virusscanner ################# def get_virusscanner(scanner,parent): scanner=scanner.upper().strip() try: if scanner=="AVAST": s= _AVAST(parent=parent) if s.cmd and len(s.cmd)>0: return s if scanner=="AVG": s= _AVG(parent=parent) if s.cmd and len(s.cmd)>0: return s if scanner=="CLAMAV" and _clamavscan_available: return _CLAMAV(parent=parent) if scanner=="COMODO": s= _COMODO(parent=parent) if s.cmd and len(s.cmd)>0: <|code_end|> , generate the next line using the imports in this file: import os import re import shutil import subprocess import pyclamd from .child import _gmechild from ._dbg import _dbg from .version import * and context (functions, classes, or occasionally code) from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
return s
Next line prediction: <|code_start|> raise NotImplementedError ####### #_AVAST ####### class _AVAST(_basevirusscanner): def __init__(self,parent): self.cmd=shutil.which("scan") _basevirusscanner.__init__(self,parent) @_dbg def has_virus(self,directory): cmd=[self.cmd,"-u",directory] result=False information=[] try: p = subprocess.Popen( cmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) p.wait() for line in p.stdout.readlines(): _l=line.decode("UTF-8",unicodeerror) if _l.startswith("/"): found=_l.split("\t",1) <|code_end|> . Use current file imports: (import os import re import shutil import subprocess import pyclamd from .child import _gmechild from ._dbg import _dbg from .version import *) and context including class names, function names, or small code snippets from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
virusinfo=found[1][:-1]
Next line prediction: <|code_start|> "-in",self._filename, "-out", sourcefile, "-inkey" , _recipient[2] ] return cmd ############ #_opensslcmd ############ @_dbg def _opensslcmd(self,cmd): result="" p = subprocess.Popen( cmd.split(" "), stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) result=p.stdout.read() return result, p.returncode ####################### #get_certemailaddresses ####################### @_dbg def get_certemailaddresses(self,certfile): """returns a list of all e-mail addresses the 'certfile' for which is valid.""" cmd=[ self.parent._SMIMECMD, "x509", "-in",certfile, <|code_end|> . Use current file imports: (import email import email.utils import os import re import subprocess import tempfile from .child import _gmechild from .version import * from ._dbg import _dbg) and context including class names, function names, or small code snippets from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
"-text",
Based on the snippet: <|code_start|> @_dbg def get_certemailaddresses(self,certfile): """returns a list of all e-mail addresses the 'certfile' for which is valid.""" cmd=[ self.parent._SMIMECMD, "x509", "-in",certfile, "-text", "-noout"] cert,returncode=self._opensslcmd(" ".join(cmd)) cert=cert.decode("utf-8",unicodeerror) email=[] found=re.search("(?<=emailAddress=)(.*)",cert) if found != None: try: email.append(cert[found.start():found.end()]) except: pass found=re.search("(?<=email:)(.*)",cert) # get alias names if found != None: try: n=cert[found.start():found.end()] if n not in email: email.append(n) except: <|code_end|> , predict the immediate next line with the help of imports: import email import email.utils import os import re import subprocess import tempfile from .child import _gmechild from .version import * from ._dbg import _dbg and context (classes, functions, sometimes code) from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
pass
Using the snippet: <|code_start|> "timezone":"часовои пояс", "_date":"0:%d.%m.%Y", "_time":"%H:%M", }, "SE":{ "appointment":"möte", "file":"fil", "content":"innehåll", "attachment":"bilaga", "passwordfor":"Lösenord för", "_date":"0:%Y-%m-%d", "_time":"%H:%M", }, "US":{ "_date":"0:%m/%d/%Y", "_time":"%I:%M %p", }, } ######### #localedb ######### def localedb(parent,value): if not parent: return value error=0 try: value=_LOCALEDB[parent._LOCALE][value] <|code_end|> , determine the next line of code. You have imports: import base64 import binascii import email import email.utils import hashlib import html import html.parser import os import mimetypes import random import re import quopri import subprocess import sys import urllib import uu from email import header from io import BytesIO from .child import _gmechild from .version import * and context (class names, function names, or code) available: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass . Output only the next line.
except:
Continue the code snippet: <|code_start|> self.push("454 TLS not available due to temporary reason") self.parent.log("STARTTLS called, but is not active","w",filename=__file__,lineno=inspect.currentframe().f_lineno) return if arg: self.push("501 Syntax error: no arguments allowed") return self.push("220 Go ahead") conn=self.smtp_server.create_sslconnection(self.conn) self.conn=conn self.set_socket(conn) self.reset_values() self.tls_active=True #ADMIN functions ########### #smtp_DEBUG ########### def smtp_DEBUG(self,arg): syntaxerror="501 Syntax error: DEBUG TRUE|FALSE or ON|OFF or YES|NO" if not arg: self.push(syntaxerror) return command=arg.upper() <|code_end|> . Use current file imports: import asynchat import asyncore import binascii import datetime import inspect import os import select import smtpd import socket import ssl import sys from .version import * from .password import pw_verify,_deprecated_get_hash and context (classes, functions, or code) from other files: # Path: gmeutils/password.py # def pw_verify(password,pwhash,parent=None): # """ # compares the password with an already hashed password # returns True if password is correct, else False # """ # result=False # # try: # result=pwd_context.verify(password,pwhash) # except: # # if parent: # parent.log("pw_verify error","e") # parent.log_traceback() # # return result # # def _deprecated_get_hash(txt): # i=0 # r=txt # # while i<=1000: # r=hashlib.sha512(r.encode("UTF-8",unicodeerror)).hexdigest() # i+=1 # # return r . Output only the next line.
if command in ["TRUE","ON","YES"] :
Given the following code snippet before the placeholder: <|code_start|> "error decode base64 '%s'"% sys.exc_info()[1],filename=__file__,lineno=inspect.currentframe().f_lineno) d=[] if len(d)<2: self.push("454 Temporary authentication failure.") return while len(d)>2: del d[0] user=d[0] password=d[1] if (self.smtp_server.authenticate(user,password)): self.push("235 Authentication successful.") self.is_authenticated=True self.is_admin=self.parent.is_admin(user) self.user=user if self.is_admin: self.parent.log("admin user '%s' logged in"%user,filename=__file__,lineno=inspect.currentframe().f_lineno) else: self.parent.log("User '%s' successfully logged in"%user,filename=__file__,lineno=inspect.currentframe().f_lineno) else: self.push("454 Temporary authentication failure.") self.parent.log("User '%s' failed to login"%user,"w",filename=__file__,lineno=inspect.currentframe().f_lineno) else: <|code_end|> , predict the next line using imports from the current file: import asynchat import asyncore import binascii import datetime import inspect import os import select import smtpd import socket import ssl import sys from .version import * from .password import pw_verify,_deprecated_get_hash and context including class names, function names, and sometimes code from other files: # Path: gmeutils/password.py # def pw_verify(password,pwhash,parent=None): # """ # compares the password with an already hashed password # returns True if password is correct, else False # """ # result=False # # try: # result=pwd_context.verify(password,pwhash) # except: # # if parent: # parent.log("pw_verify error","e") # parent.log_traceback() # # return result # # def _deprecated_get_hash(txt): # i=0 # r=txt # # while i<=1000: # r=hashlib.sha512(r.encode("UTF-8",unicodeerror)).hexdigest() # i+=1 # # return r . Output only the next line.
self.push("454 Temporary authentication failure.")
Predict the next line for this snippet: <|code_start|> self._tabledefinition["encryptionmapindex"]=( "create unique index eindex" " on encryptionmap (\"user\");") self._tabledefinition["pgpencryptsubject"]=("create table \"pgpencryptsubject\" (" "\"user\" varchar (255) not null ," "\"encryptsubject\" tinyint);") self._tabledefinition["pgpencryptsubjectindex"]=("create unique index esindex" " on pgpencryptsubject (\"user\");") self._tabledefinition["pdfpasswords"]=("create table \"pdfpasswords\" (" "\"user\" varchar (255) not null ," "\"password\" varchar(255)," "\"starttime\" float);") self._tabledefinition["pdfpasswordsindex"]=("create unique index pindex" " on pdfpasswords (\"user\");") self._tabledefinition["smimeusers"]=("create table \"smimeuser\"(" "\"user\" varchar (255) not null, " "\"privatekey\" varchar (255), " "\"publickey\" varchar(255) not null, " "\"cipher\" varchar (255));") self._tabledefinition["smimeusersindex"]=("create unique index sindex" " on smimeuser (\"user\");") self._tabledefinition["gpgencryptionkeys"]=("create table " "\"gpgencryptionkeys\" (" "\"user\" varchar (255) not null, " "\"encryptionkey\" varchar (255) not null);") self._tabledefinition["gpgencryptionkeysindex"]=( "create unique index gencindex on gpgencryptionkeys (\"user\"," <|code_end|> with the help of current file imports: from gmeutils.child import _gmechild from gmeutils.helpers import * from gmeutils.password import * from gmeutils.version import * from gmeutils._dbg import _dbg from mysql.connector import errorcode import email.utils import os.path import re import time import sqlite3 import mysql.connector as mysql import pydodbc as odbc import psycopg2 as pg import pymssql and context from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper , which may contain function names, class names, or code. Output only the next line.
"\"encryptionkey\");")
Given the code snippet: <|code_start|> result=list() for user in self._smimeuser: result.append(user) return result ################## #smimeprivate_keys ################## @_dbg def smimeprivate_keys(self): "returns a list of all available private keys" result=list() for user in self._smimeuser: user=user.lower() if self._smimeuser[user][2]!=None: result.append(user) return result ################ #set_pdfpassword ################ @_dbg <|code_end|> , generate the next line using the imports in this file: from gmeutils.child import _gmechild from gmeutils.helpers import * from gmeutils.password import * from gmeutils.version import * from gmeutils._dbg import _dbg from mysql.connector import errorcode import email.utils import os.path import re import time import sqlite3 import mysql.connector as mysql import pydodbc as odbc import psycopg2 as pg import pymssql and context (functions, classes, or occasionally code) from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
def set_pdfpassword(self,user,password,autodelete=True):
Next line prediction: <|code_start|> self._prepare_syslog() elif logmode=="stderr": self._LOGGING=self.l_stderr else: self._LOGGING=self.l_none ############ #get_logging ############ @_dbg def get_logging( self): if self._LOGGING==self.l_syslog: return "syslog" elif self._LOGGING==self.l_stderr: return "stderr" else: return "none" ############# #_set_logmode ############# @_dbg def _set_logmode(self): try: if self._LOGGING==self.l_file and len(self._LOGFILE)>0: self._logfile = open(self._LOGFILE, <|code_end|> . Use current file imports: (import os import inspect import time import sys import logging import logging.handlers import syslog from .child import _gmechild from .version import * from ._dbg import _dbg from gmeutils.helpers import *) and context including class names, function names, or small code snippets from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
mode='a',
Using the snippet: <|code_start|> elif l=='stderr': self._LOGGING=self.l_stderr else: self._LOGGING=self.l_none except: pass try: self._LOGFILE=cfg.get('logging','file') except: pass try: self._DEBUG=cfg.getboolean('logging','debug') except: pass try: s=cfg.get('logging','debugsearchtext') if len(s)>0: self._DEBUGSEARCHTEXT=s.split(",") except: pass try: e=cfg.get('logging','debugexcludetext') <|code_end|> , determine the next line of code. You have imports: import os import inspect import time import sys import logging import logging.handlers import syslog from .child import _gmechild from .version import * from ._dbg import _dbg from gmeutils.helpers import * and context (class names, function names, or code) available: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper . Output only the next line.
if len(e)>0:
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3 #License GPL v3 #Author Horst Knorr <gpgmailencrypt@gmx.de> host="localhost" port=10025 cl=sys.argv[1:] try: host=cl[0] port=int(cl[1]) <|code_end|> , predict the next line using imports from the current file: import sys from gmeutils import adminconsole and context including class names, function names, and sometimes code from other files: # Path: gmeutils/adminconsole.py # def start_adminconsole(host,port): # def __init__(self,parent=None): # def _sendcmd(self, cmd,arg=""): # def getreply(self): # def start(self,host="localhost",port=0): # def print_help(self): # def __init__(self, options): # def complete( self, # text, # state): # def display_matches( self, # substitution, # matches, # longest_match_length): # class gmeadmin(_gmechild): # class MyCompleter(object): # Custom completer . Output only the next line.
except:
Given snippet: <|code_start|> ################# #_basespamchecker ################# class _basespamchecker(_gmechild): def __init__(self,parent,leveldict): _gmechild.__init__(self,parent=parent,filename=__file__) self.cmd=None @_dbg def set_leveldict(self,leveldict): raise NotImplementedError @_dbg def is_spam(self,mail): raise NotImplementedError def is_available(self): if self.cmd!= None and len(self.cmd)>0: return True else: return False ############## #_SPAMASSASSIN ############## <|code_end|> , continue by predicting the next line. Consider current file imports: import shutil import subprocess from .child import _gmechild from ._dbg import _dbg from .version import * and context: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper which might include code, classes, or functions. Output only the next line.
class _SPAMASSASSIN(_basespamchecker):
Here is a snippet: <|code_start|> except: self.log("Could not convert score to float","e") if level =="S": spamlevel=S_SPAM elif level == "U": spamlevel=S_MAYBESPAM return spamlevel,score ################################################################################ #################### #get_spamscannerlist #################### def get_spamscannerlist(): return ["BOGOFILTER","SPAMASSASSIN"] ################ #get_spamscanner ################ def get_spamscanner(scanner,parent,leveldict): scanner=scanner.upper().strip() if scanner=="BOGOFILTER": _s=_BOGOFILTER(parent,leveldict) <|code_end|> . Write the next line using the current file imports: import shutil import subprocess from .child import _gmechild from ._dbg import _dbg from .version import * and context from other files: # Path: gmeutils/child.py # class _gmechild: # "base class of all classes that will be used from class gme" # # ######### # #__init__ # ######### # # def __init__(self,parent,filename): # self.parent=parent # self._level=1 # self.filename=filename # # #### # #log # #### # # def log(self, # msg, # infotype="m", # lineno=-1, # filename="", # force=False): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.log( msg=msg, # infotype=infotype, # lineno=lineno, # filename=filename, # force=force) # self.parent._logger._level-=self._level # except: # sys.stderr.write("%s\n"%(msg)) # # ############## # #log_traceback # ############## # # def log_traceback(self): # # try: # self.parent.log_traceback() # except: # pass # # # ###### # #error # ###### # # def error( self, # msg, # lineno=0, # filename=""): # """logs as error message. When logging is disabled, # this will log to stderr""" # self.log(msg,infotype="e",lineno=lineno,filename=filename,force=True) # # ######## # #warning # ######## # # def warning(self, # msg, # lineno=0, # filename=""): # """logs as warning message.""" # self.log(msg,infotype="w",lineno=lineno,filename=filename,force=False) # # ###### # #debug # ###### # # def debug( self, # msg, # lineno=0, # filename=""): # # if filename=="": # filename=self.filename # # try: # self.parent._logger._level+=self._level # self.parent.debug(msg=msg,lineno=lineno,filename=filename) # self.parent._logger._level-=self._level # except: # pass # # Path: gmeutils/_dbg.py # def _dbg(func): # # @wraps(func) # def wrapper(*args, **kwargs): # parent=None # # lineno=0 # endlineno=0 # filename=inspect.getfile(func) # # if args: # # if isinstance(args[0],child._gmechild): # parent=args[0] # elif hasattr(args[0],"send_mails"): # parent=args[0] # elif hasattr(args[0],"parent"): # parent=args[0].parent # # if not parent: # print(">> START %s"%func.__name__,lineno) # result=func(*args,**kwargs) # print(">> END %s"%func.__name__,lineno) # return result # # # try: # source=inspect.getsourcelines(func) # lineno=source[1] # endlineno=lineno+len(source[0]) # except: # pass # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level+=1 # # parent.debug("START %s"%func.__name__,lineno,filename) # result=func(*args,**kwargs) # parent.debug("END %s"%func.__name__,endlineno,filename) # # if (hasattr(parent,"_logger") and # hasattr(parent._logger,"_level")): # parent._logger._level-=1 # # if parent._logger._level<0: # parent._logger._level=0 # # return result # # return wrapper , which may include functions, classes, or code. Output only the next line.
if _s.is_available():
Predict the next line after this snippet: <|code_start|>cookies = cookielib.LWPCookieJar() handlers = [ urllib2.HTTPHandler(), urllib2.HTTPCookieProcessor(cookies) ] opener = urllib2.build_opener(*handlers) def fetch_raw(url, data=None, content_type='application/json'): if not data: req = urllib2.Request(url) else: data_bytes = json.dumps(data) req = urllib2.Request(url, data_bytes, {'Content-Type': content_type}) return opener.open(req) def fetch_url(url, data=None, act=None, **kw): su_to = kw.get('su_to') if su_to: url_su_to = urllib.quote_plus(su_to.encode('utf8')) if '?' in url: url += '&su_to=' + url_su_to else: url += '?su_to=' + url_su_to if act: act['url'] = url <|code_end|> using the current file's imports: import sys import json import os.path import urllib import urllib2 import urlparse import argparse import cookielib import pdb;pdb.set_trace() import pdb;pdb.set_trace() import pdb;pdb.set_trace() import pdb;pdb.set_trace() from pprint import pprint from lithoxyl import DEBUG, INFO from montage import utils from montage.log import script_log and any relevant context from other files: # Path: montage/utils.py # CUR_PATH = os.path.dirname(os.path.abspath(__file__)) # PROJ_PATH = os.path.dirname(CUR_PATH) # USER_ENV_MAP = {'tools.montage-dev': 'devlabs', # 'tools.montage': 'prod', # 'tools.montage-beta': 'beta'} # DEFAULT_ENV_NAME = 'dev' # DEFAULT_SERIES = {'name': 'Unofficial', # 'description': 'For unofficial campaigns, whether for testing or just for fun!', # 'url': 'TODO add docs url'} # TODO: status is always active # DEVTEST_CONFIG = {'oauth_consumer_token': None, # 'oauth_secret_token': None, # 'cookie_secret': 'supertotallyrandomsecretcookiesecret8675309', # 'api_log_path': 'montage_api.log', # 'replay_log_path': 'montage_replay.log', # 'feel_log_path': 'montage_feel.log', # 'db_url': "sqlite:///tmp_montage.db", # 'db_echo': False, # 'debug': True, # 'superusers': ['Slaporte', 'MahmoudHashemi'], # 'dev_local_cookie_value': '"W7XGXxmUjl4kbkE0TWaFo4Oth50=?userid=NjAyNDQ3NA==&username=IlNsYXBvcnRlIg=="', # '__file__': 'devtest-builtin', # '__env__': 'devtest', # } # class MontageError(Exception): # class PermissionDenied(MontageError, Forbidden): # class DoesNotExist(MontageError, NotFound): # class InvalidAction(MontageError, BadRequest): # class NotImplementedResponse(MontageError, BadRequest, NotImplementedError): # def to_unicode(obj): # def encode_dict_to_bytes(query): # def encode_value_to_bytes(value): # def get_mw_userid(username): # def get_threshold_map(ratings_map): # def get_env_name(): # def load_env_config(env_name=None): # def load_default_series(): # def check_schema(db_url, base_type, echo=False, autoexit=False): # def format_date(date): # def js_isoparse(date_str): # def json_serial(obj): # def parse_date(date): # def weighted_choice(weighted_choices): # def process_weighted_choices(wcp): # def fast_weighted_choice(nsw, values): # # Path: montage/log.py . Output only the next line.
try:
Here is a snippet: <|code_start|> urllib2.HTTPHandler(), urllib2.HTTPCookieProcessor(cookies) ] opener = urllib2.build_opener(*handlers) def fetch_raw(url, data=None, content_type='application/json'): if not data: req = urllib2.Request(url) else: data_bytes = json.dumps(data) req = urllib2.Request(url, data_bytes, {'Content-Type': content_type}) return opener.open(req) def fetch_url(url, data=None, act=None, **kw): su_to = kw.get('su_to') if su_to: url_su_to = urllib.quote_plus(su_to.encode('utf8')) if '?' in url: url += '&su_to=' + url_su_to else: url += '?su_to=' + url_su_to if act: act['url'] = url try: res = fetch_raw(url, data=data, content_type=kw.get('content_type', 'application/json')) <|code_end|> . Write the next line using the current file imports: import sys import json import os.path import urllib import urllib2 import urlparse import argparse import cookielib import pdb;pdb.set_trace() import pdb;pdb.set_trace() import pdb;pdb.set_trace() import pdb;pdb.set_trace() from pprint import pprint from lithoxyl import DEBUG, INFO from montage import utils from montage.log import script_log and context from other files: # Path: montage/utils.py # CUR_PATH = os.path.dirname(os.path.abspath(__file__)) # PROJ_PATH = os.path.dirname(CUR_PATH) # USER_ENV_MAP = {'tools.montage-dev': 'devlabs', # 'tools.montage': 'prod', # 'tools.montage-beta': 'beta'} # DEFAULT_ENV_NAME = 'dev' # DEFAULT_SERIES = {'name': 'Unofficial', # 'description': 'For unofficial campaigns, whether for testing or just for fun!', # 'url': 'TODO add docs url'} # TODO: status is always active # DEVTEST_CONFIG = {'oauth_consumer_token': None, # 'oauth_secret_token': None, # 'cookie_secret': 'supertotallyrandomsecretcookiesecret8675309', # 'api_log_path': 'montage_api.log', # 'replay_log_path': 'montage_replay.log', # 'feel_log_path': 'montage_feel.log', # 'db_url': "sqlite:///tmp_montage.db", # 'db_echo': False, # 'debug': True, # 'superusers': ['Slaporte', 'MahmoudHashemi'], # 'dev_local_cookie_value': '"W7XGXxmUjl4kbkE0TWaFo4Oth50=?userid=NjAyNDQ3NA==&username=IlNsYXBvcnRlIg=="', # '__file__': 'devtest-builtin', # '__env__': 'devtest', # } # class MontageError(Exception): # class PermissionDenied(MontageError, Forbidden): # class DoesNotExist(MontageError, NotFound): # class InvalidAction(MontageError, BadRequest): # class NotImplementedResponse(MontageError, BadRequest, NotImplementedError): # def to_unicode(obj): # def encode_dict_to_bytes(query): # def encode_value_to_bytes(value): # def get_mw_userid(username): # def get_threshold_map(ratings_map): # def get_env_name(): # def load_env_config(env_name=None): # def load_default_series(): # def check_schema(db_url, base_type, echo=False, autoexit=False): # def format_date(date): # def js_isoparse(date_str): # def json_serial(obj): # def parse_date(date): # def weighted_choice(weighted_choices): # def process_weighted_choices(wcp): # def fast_weighted_choice(nsw, values): # # Path: montage/log.py , which may include functions, classes, or code. Output only the next line.
except urllib2.HTTPError as he:
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division try: # pragma: nocoverage except ImportError: # pragma: nocoverage class CommandTest: def setup(self): self.app = Flask('alchemist') self.app.config['COMPONENTS'] = ['alchemist'] alchemist.configure(self.app) def _run(self, command, patch=None): if patch is None: patch = self.patch target = mock.MagicMock() with mock.patch(patch, target): <|code_end|> . Write the next line using the current file imports: from alchemist import test from flask import Flask from . import utils from unittest import mock from alchemist import management from alchemist.commands import Shell import alchemist import sys import io import py import mock and context from other files: # Path: alchemist/test.py # def settings(app, **kwargs): # def setup_class(cls): # def teardown(self): # def request(self, path='', url=None, data=None, format='json', # *args, **kwargs): # def head(self, *args, **kwargs): # def options(self, *args, **kwargs): # def get(self, *args, **kwargs): # def post(self, *args, **kwargs): # def put(self, *args, **kwargs): # def patch(self, *args, **kwargs): # def delete(self, *args, **kwargs): # class TestBase: , which may include functions, classes, or code. Output only the next line.
manager = management.Manager(self.app)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class TestSettings: def test_project(self): self.app = Flask('alchemist.tests.a') with settings(self.app): alchemist.configure(self.app) <|code_end|> using the current file's imports: from alchemist.test import settings from flask import Flask from os import path from alchemist import app from .a.example import application from .a.b.example import application from alchemist.app import application import os import sys import alchemist and any relevant context from other files: # Path: alchemist/test.py # @contextmanager # def settings(app, **kwargs): # """Save current application config and restore after block. # # Allows override with the keyword arguments. # """ # # # Save the current application config to restore. # _config = dict(app.config) # # # Make requested changes for this scope. # app.config.update(kwargs) # # yield # # # Restore the previous application config. # app.config = _config . Output only the next line.
assert self.app.config.get('A_SETTING', 1)
Given snippet: <|code_start|> with raises(exceptions.ImproperlyConfigured): db.engine['default'] def test_usage(self): uri = 'sqlite:///:memory:' with settings(self.app, DATABASES={'default': uri}): with contextlib.closing(db.engine.connect()) as connection: result = connection.execute("BEGIN") assert isinstance(result, ResultProxy) def test_lookup(self): uri = 'sqlite:///:memory:' with settings(self.app, DATABASES={'default': uri}): assert 'connect' in dir(db.engine) def test_expanded(self): config = { 'engine': 'sqlite', 'name': 'name', } with settings(self.app, DATABASES={'default': config}): <|code_end|> , continue by predicting the next line. Consider current file imports: import alchemist import contextlib import py import mock from alchemist.test import settings from flask import Flask from pytest import raises from sqlalchemy.engine.result import ResultProxy from sqlalchemy.exc import OperationalError from . import utils from unittest import mock from alchemist.db._engine import Engine from alchemist import db from alchemist import db from alchemist import db from alchemist import db, exceptions from alchemist import db, exceptions from alchemist import db from alchemist import db from alchemist import db from alchemist import db from alchemist import db, exceptions from alchemist import db from alchemist import db from alchemist import db from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from .a.models import Entity from alchemist import db from alchemist import db from .a.models import Entity from alchemist import db from alchemist.db._engine import Engine from alchemist import db from alchemist import db from alchemist import db and context: # Path: alchemist/test.py # @contextmanager # def settings(app, **kwargs): # """Save current application config and restore after block. # # Allows override with the keyword arguments. # """ # # # Save the current application config to restore. # _config = dict(app.config) # # # Make requested changes for this scope. # app.config.update(kwargs) # # yield # # # Restore the previous application config. # app.config = _config which might include code, classes, or functions. Output only the next line.
assert db.engine.url.drivername == 'sqlite'
Given snippet: <|code_start|> self.fail('Set your SHIPPO_API_KEY in your os.environ') except Exception as inst: self.fail("Test failed with exception %s" % inst) def test_list_accessors(self): try: address = shippo.Address.create(**DUMMY_ADDRESS) except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') self.assertEqual(address['object_created'], address.object_created) address['foo'] = 'bar' self.assertEqual(address.foo, 'bar') def test_unicode(self): # Make sure unicode requests can be sent self.assertRaises(shippo.error.APIError, shippo.Address.retrieve, '☃') def test_get_rates(self): try: shipment = create_mock_shipment() rates = shippo.Shipment.get_rates( shipment.object_id, asynchronous=False) except shippo.error.InvalidRequestError: pass except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') except Exception as inst: <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest2 import shippo from mock import patch from shippo.test.helper import ( create_mock_shipment, DUMMY_ADDRESS, INVALID_ADDRESS, ShippoTestCase, ) and context: # Path: shippo/test/helper.py # def create_mock_shipment(asynchronous=False, api_key=None): # to_address = shippo.Address.create(api_key=api_key, **TO_ADDRESS) # from_address = shippo.Address.create(api_key=api_key, **FROM_ADDRESS) # parcel = shippo.Parcel.create(api_key=api_key, **DUMMY_PARCEL) # SHIPMENT = DUMMY_SHIPMENT.copy() # SHIPMENT['address_from'] = from_address.object_id # SHIPMENT['address_to'] = to_address.object_id # SHIPMENT['parcels'] = [parcel.object_id] # SHIPMENT['asynchronous'] = asynchronous # shipment = shippo.Shipment.create(api_key=api_key, **SHIPMENT) # return shipment # # DUMMY_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street1": "Clayton St.", # "street_no": "215", # "street2": "", # "city": "San Francisco", # "state": "CA", # "zip": "94117", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # INVALID_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street2": "", # "city": "San Francisco", # "state": "CA", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # class ShippoTestCase(TestCase): # RESTORE_ATTRIBUTES = ('api_version', 'api_key') # # def setUp(self): # super(ShippoTestCase, self).setUp() # # self._shippo_original_attributes = {} # # for attr in self.RESTORE_ATTRIBUTES: # self._shippo_original_attributes[attr] = getattr( # shippo.config, attr) # # api_base = os.environ.get('SHIPPO_API_BASE') # if api_base: # shippo.config.api_base = api_base # # shippo.config.api_key = os.environ.get( # 'SHIPPO_API_KEY', '51895b669caa45038110fd4074e61e0d') # shippo.config.api_version = os.environ.get( # 'SHIPPO_API_VERSION', '2018-02-08') # # def tearDown(self): # super(ShippoTestCase, self).tearDown() # # for attr in self.RESTORE_ATTRIBUTES: # setattr(shippo.config, attr, # self._shippo_original_attributes[attr]) # # # Python < 2.7 compatibility # def assertRaisesRegexp(self, exception, regexp, callable, *args, **kwargs): # try: # callable(*args, **kwargs) # except exception as err: # if regexp is None: # return True # # if isinstance(regexp, str): # regexp = re.compile(regexp) # if not regexp.search(str(err)): # raise self.failureException('"%s" does not match "%s"' % # (regexp.pattern, str(err))) # else: # raise self.failureException( # '%s was not raised' % (exception.__name__,)) which might include code, classes, or functions. Output only the next line.
self.fail("Test failed with exception %s" % inst)
Based on the snippet: <|code_start|> self.assertRaises(shippo.error.APIConnectionError, shippo.Address.create) finally: shippo.config.api_base = api_base def test_run(self): try: address = shippo.Address.create(**DUMMY_ADDRESS) self.assertEqual(address.is_complete, True) address_validated = shippo.Address.validate(address.object_id) self.assertEqual(address_validated.is_complete, True) except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') except Exception as inst: self.fail("Test failed with exception %s" % inst) def test_list_accessors(self): try: address = shippo.Address.create(**DUMMY_ADDRESS) except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') self.assertEqual(address['object_created'], address.object_created) address['foo'] = 'bar' self.assertEqual(address.foo, 'bar') def test_unicode(self): # Make sure unicode requests can be sent self.assertRaises(shippo.error.APIError, shippo.Address.retrieve, <|code_end|> , predict the immediate next line with the help of imports: import unittest2 import shippo from mock import patch from shippo.test.helper import ( create_mock_shipment, DUMMY_ADDRESS, INVALID_ADDRESS, ShippoTestCase, ) and context (classes, functions, sometimes code) from other files: # Path: shippo/test/helper.py # def create_mock_shipment(asynchronous=False, api_key=None): # to_address = shippo.Address.create(api_key=api_key, **TO_ADDRESS) # from_address = shippo.Address.create(api_key=api_key, **FROM_ADDRESS) # parcel = shippo.Parcel.create(api_key=api_key, **DUMMY_PARCEL) # SHIPMENT = DUMMY_SHIPMENT.copy() # SHIPMENT['address_from'] = from_address.object_id # SHIPMENT['address_to'] = to_address.object_id # SHIPMENT['parcels'] = [parcel.object_id] # SHIPMENT['asynchronous'] = asynchronous # shipment = shippo.Shipment.create(api_key=api_key, **SHIPMENT) # return shipment # # DUMMY_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street1": "Clayton St.", # "street_no": "215", # "street2": "", # "city": "San Francisco", # "state": "CA", # "zip": "94117", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # INVALID_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street2": "", # "city": "San Francisco", # "state": "CA", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # class ShippoTestCase(TestCase): # RESTORE_ATTRIBUTES = ('api_version', 'api_key') # # def setUp(self): # super(ShippoTestCase, self).setUp() # # self._shippo_original_attributes = {} # # for attr in self.RESTORE_ATTRIBUTES: # self._shippo_original_attributes[attr] = getattr( # shippo.config, attr) # # api_base = os.environ.get('SHIPPO_API_BASE') # if api_base: # shippo.config.api_base = api_base # # shippo.config.api_key = os.environ.get( # 'SHIPPO_API_KEY', '51895b669caa45038110fd4074e61e0d') # shippo.config.api_version = os.environ.get( # 'SHIPPO_API_VERSION', '2018-02-08') # # def tearDown(self): # super(ShippoTestCase, self).tearDown() # # for attr in self.RESTORE_ATTRIBUTES: # setattr(shippo.config, attr, # self._shippo_original_attributes[attr]) # # # Python < 2.7 compatibility # def assertRaisesRegexp(self, exception, regexp, callable, *args, **kwargs): # try: # callable(*args, **kwargs) # except exception as err: # if regexp is None: # return True # # if isinstance(regexp, str): # regexp = re.compile(regexp) # if not regexp.search(str(err)): # raise self.failureException('"%s" does not match "%s"' % # (regexp.pattern, str(err))) # else: # raise self.failureException( # '%s was not raised' % (exception.__name__,)) . Output only the next line.
'☃')
Based on the snippet: <|code_start|> def test_dns_failure(self): api_base = shippo.config.api_base try: shippo.config.api_base = 'https://my-invalid-domain.ireallywontresolve/v1' self.assertRaises(shippo.error.APIConnectionError, shippo.Address.create) finally: shippo.config.api_base = api_base def test_run(self): try: address = shippo.Address.create(**DUMMY_ADDRESS) self.assertEqual(address.is_complete, True) address_validated = shippo.Address.validate(address.object_id) self.assertEqual(address_validated.is_complete, True) except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') except Exception as inst: self.fail("Test failed with exception %s" % inst) def test_list_accessors(self): try: address = shippo.Address.create(**DUMMY_ADDRESS) except shippo.error.AuthenticationError: self.fail('Set your SHIPPO_API_KEY in your os.environ') self.assertEqual(address['object_created'], address.object_created) address['foo'] = 'bar' self.assertEqual(address.foo, 'bar') <|code_end|> , predict the immediate next line with the help of imports: import unittest2 import shippo from mock import patch from shippo.test.helper import ( create_mock_shipment, DUMMY_ADDRESS, INVALID_ADDRESS, ShippoTestCase, ) and context (classes, functions, sometimes code) from other files: # Path: shippo/test/helper.py # def create_mock_shipment(asynchronous=False, api_key=None): # to_address = shippo.Address.create(api_key=api_key, **TO_ADDRESS) # from_address = shippo.Address.create(api_key=api_key, **FROM_ADDRESS) # parcel = shippo.Parcel.create(api_key=api_key, **DUMMY_PARCEL) # SHIPMENT = DUMMY_SHIPMENT.copy() # SHIPMENT['address_from'] = from_address.object_id # SHIPMENT['address_to'] = to_address.object_id # SHIPMENT['parcels'] = [parcel.object_id] # SHIPMENT['asynchronous'] = asynchronous # shipment = shippo.Shipment.create(api_key=api_key, **SHIPMENT) # return shipment # # DUMMY_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street1": "Clayton St.", # "street_no": "215", # "street2": "", # "city": "San Francisco", # "state": "CA", # "zip": "94117", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # INVALID_ADDRESS = { # "name": "Laura Behrens Wu", # "company": "Shippo", # "street2": "", # "city": "San Francisco", # "state": "CA", # "country": "US", # "phone": "+1 555 341 9393", # "metadata": "Customer ID 123456" # } # # class ShippoTestCase(TestCase): # RESTORE_ATTRIBUTES = ('api_version', 'api_key') # # def setUp(self): # super(ShippoTestCase, self).setUp() # # self._shippo_original_attributes = {} # # for attr in self.RESTORE_ATTRIBUTES: # self._shippo_original_attributes[attr] = getattr( # shippo.config, attr) # # api_base = os.environ.get('SHIPPO_API_BASE') # if api_base: # shippo.config.api_base = api_base # # shippo.config.api_key = os.environ.get( # 'SHIPPO_API_KEY', '51895b669caa45038110fd4074e61e0d') # shippo.config.api_version = os.environ.get( # 'SHIPPO_API_VERSION', '2018-02-08') # # def tearDown(self): # super(ShippoTestCase, self).tearDown() # # for attr in self.RESTORE_ATTRIBUTES: # setattr(shippo.config, attr, # self._shippo_original_attributes[attr]) # # # Python < 2.7 compatibility # def assertRaisesRegexp(self, exception, regexp, callable, *args, **kwargs): # try: # callable(*args, **kwargs) # except exception as err: # if regexp is None: # return True # # if isinstance(regexp, str): # regexp = re.compile(regexp) # if not regexp.search(str(err)): # raise self.failureException('"%s" does not match "%s"' % # (regexp.pattern, str(err))) # else: # raise self.failureException( # '%s was not raised' % (exception.__name__,)) . Output only the next line.
def test_unicode(self):
Given snippet: <|code_start|> yield (key, value) def _build_api_url(url, query): scheme, netloc, path, base_query, fragment = urllib.parse.urlsplit(url) if base_query: query = '%s&%s' % (base_query, query) return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment)) class APIRequestor(object): _CERTIFICATE_VERIFIED = False def __init__(self, key=None, client=None): self.api_key = key self._client = client or http_client.new_default_http_client( verify_ssl_certs=verify_ssl_certs) def request(self, method, url, params=None): self._check_ssl_cert()\ if params is not None and isinstance(params, dict): params = {('async' if k == 'asynchronous' else k): v for k, v in params.items()} rbody, rcode, my_api_key = self.request_raw( <|code_end|> , continue by predicting the next line. Consider current file imports: import calendar import datetime import os import platform import socket import ssl import time import urllib.parse import warnings import shippo from shippo import error, http_client, util, certificate_blacklist from shippo.version import VERSION from shippo.config import verify_ssl_certs from shippo.config import api_version from shippo.config import api_key from shippo.config import verify_ssl_certs and context: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/http_client.py # def new_default_http_client(*args, **kwargs): # def __init__(self, verify_ssl_certs=True): # def request(self, method, url, headers, post_data=None): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e, url): # class HTTPClient(object): # class RequestsClient(HTTPClient): # class UrlFetchClient(HTTPClient): # # Path: shippo/util.py # # Path: shippo/certificate_blacklist.py # BLACKLISTED_DIGESTS = { # } # def verify(hostname, certificate): # # Path: shippo/version.py # VERSION = '2.1.2' which might include code, classes, or functions. Output only the next line.
method.lower(), url, params)
Given the following code snippet before the placeholder: <|code_start|> Unfortunately the interface to OpenSSL doesn't make it easy to check the certificate before sending potentially sensitive data on the wire. This approach raises the bar for an attacker significantly.""" if verify_ssl_certs and not self._CERTIFICATE_VERIFIED: uri = urllib.parse.urlparse(shippo.config.api_base) try: certificate = ssl.get_server_certificate( (uri.hostname, uri.port or 443)) der_cert = ssl.PEM_cert_to_DER_cert(certificate) except socket.error as e: raise error.APIConnectionError(e) except TypeError: # The Google App Engine development server blocks the C socket # module which causes a type error when using the SSL library if ('APPENGINE_RUNTIME' in os.environ and 'Dev' in os.environ.get('SERVER_SOFTWARE', '')): self._CERTIFICATE_VERIFIED = True warnings.warn( 'We were unable to verify Shippo\'s SSL certificate ' 'due to a bug in the Google App Engine development ' 'server. Please alert us immediately at ' 'suppgoshippo.compo.com if this message appears in your ' 'production logs.') return else: raise self._CERTIFICATE_VERIFIED = certificate_blacklist.verify( <|code_end|> , predict the next line using imports from the current file: import calendar import datetime import os import platform import socket import ssl import time import urllib.parse import warnings import shippo from shippo import error, http_client, util, certificate_blacklist from shippo.version import VERSION from shippo.config import verify_ssl_certs from shippo.config import api_version from shippo.config import api_key from shippo.config import verify_ssl_certs and context including class names, function names, and sometimes code from other files: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/http_client.py # def new_default_http_client(*args, **kwargs): # def __init__(self, verify_ssl_certs=True): # def request(self, method, url, headers, post_data=None): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e, url): # class HTTPClient(object): # class RequestsClient(HTTPClient): # class UrlFetchClient(HTTPClient): # # Path: shippo/util.py # # Path: shippo/certificate_blacklist.py # BLACKLISTED_DIGESTS = { # } # def verify(hostname, certificate): # # Path: shippo/version.py # VERSION = '2.1.2' . Output only the next line.
uri.hostname, der_cert)
Predict the next line for this snippet: <|code_start|> def interpret_response(self, rbody, rcode): try: if hasattr(rbody, 'decode'): rbody = rbody.decode('utf-8') if rbody == '': rbody = '{"msg": "empty_response"}' resp = util.json.loads(rbody) except Exception: raise error.APIError( "Invalid response body from API: %s " "(HTTP response code was %d)" % (rbody, rcode), rbody, rcode) if not (200 <= rcode < 300): self.handle_api_error(rbody, rcode, resp) return resp def _check_ssl_cert(self): """Preflight the SSL certificate presented by the backend. This isn't 100% bulletproof, in that we're not actually validating the transport used to communicate with Shippo, merely that the first attempt to does not use a revoked certificate. Unfortunately the interface to OpenSSL doesn't make it easy to check the certificate before sending potentially sensitive data on the wire. This approach raises the bar for an attacker significantly.""" if verify_ssl_certs and not self._CERTIFICATE_VERIFIED: <|code_end|> with the help of current file imports: import calendar import datetime import os import platform import socket import ssl import time import urllib.parse import warnings import shippo from shippo import error, http_client, util, certificate_blacklist from shippo.version import VERSION from shippo.config import verify_ssl_certs from shippo.config import api_version from shippo.config import api_key from shippo.config import verify_ssl_certs and context from other files: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/http_client.py # def new_default_http_client(*args, **kwargs): # def __init__(self, verify_ssl_certs=True): # def request(self, method, url, headers, post_data=None): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e, url): # class HTTPClient(object): # class RequestsClient(HTTPClient): # class UrlFetchClient(HTTPClient): # # Path: shippo/util.py # # Path: shippo/certificate_blacklist.py # BLACKLISTED_DIGESTS = { # } # def verify(hostname, certificate): # # Path: shippo/version.py # VERSION = '2.1.2' , which may contain function names, class names, or code. Output only the next line.
uri = urllib.parse.urlparse(shippo.config.api_base)
Given snippet: <|code_start|> def _build_api_url(url, query): scheme, netloc, path, base_query, fragment = urllib.parse.urlsplit(url) if base_query: query = '%s&%s' % (base_query, query) return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment)) class APIRequestor(object): _CERTIFICATE_VERIFIED = False def __init__(self, key=None, client=None): self.api_key = key self._client = client or http_client.new_default_http_client( verify_ssl_certs=verify_ssl_certs) def request(self, method, url, params=None): self._check_ssl_cert()\ if params is not None and isinstance(params, dict): params = {('async' if k == 'asynchronous' else k): v for k, v in params.items()} rbody, rcode, my_api_key = self.request_raw( method.lower(), url, params) <|code_end|> , continue by predicting the next line. Consider current file imports: import calendar import datetime import os import platform import socket import ssl import time import urllib.parse import warnings import shippo from shippo import error, http_client, util, certificate_blacklist from shippo.version import VERSION from shippo.config import verify_ssl_certs from shippo.config import api_version from shippo.config import api_key from shippo.config import verify_ssl_certs and context: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/http_client.py # def new_default_http_client(*args, **kwargs): # def __init__(self, verify_ssl_certs=True): # def request(self, method, url, headers, post_data=None): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e, url): # class HTTPClient(object): # class RequestsClient(HTTPClient): # class UrlFetchClient(HTTPClient): # # Path: shippo/util.py # # Path: shippo/certificate_blacklist.py # BLACKLISTED_DIGESTS = { # } # def verify(hostname, certificate): # # Path: shippo/version.py # VERSION = '2.1.2' which might include code, classes, or functions. Output only the next line.
resp = self.interpret_response(rbody, rcode)
Here is a snippet: <|code_start|> def _encode_datetime(dttime): if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime) is not None: utc_timestamp = calendar.timegm(dttime.utctimetuple()) else: utc_timestamp = time.mktime(dttime.timetuple()) return int(utc_timestamp) def _api_encode(data): for key, value in list(data.items()): key = key if value is None: continue elif hasattr(value, 'shippo_id'): yield (key, value.shippo_id) elif isinstance(value, list) or isinstance(value, tuple): for subvalue in value: <|code_end|> . Write the next line using the current file imports: import calendar import datetime import os import platform import socket import ssl import time import urllib.parse import warnings import shippo from shippo import error, http_client, util, certificate_blacklist from shippo.version import VERSION from shippo.config import verify_ssl_certs from shippo.config import api_version from shippo.config import api_key from shippo.config import verify_ssl_certs and context from other files: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/http_client.py # def new_default_http_client(*args, **kwargs): # def __init__(self, verify_ssl_certs=True): # def request(self, method, url, headers, post_data=None): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e): # def request(self, method, url, headers, post_data=None): # def _handle_request_error(self, e, url): # class HTTPClient(object): # class RequestsClient(HTTPClient): # class UrlFetchClient(HTTPClient): # # Path: shippo/util.py # # Path: shippo/certificate_blacklist.py # BLACKLISTED_DIGESTS = { # } # def verify(hostname, certificate): # # Path: shippo/version.py # VERSION = '2.1.2' , which may include functions, classes, or code. Output only the next line.
yield ("%s[]" % (key,), subvalue)
Predict the next line after this snippet: <|code_start|> # are succeptible to the same and should be updated. content = result.content status_code = result.status_code except Exception as e: # Would catch just requests.exceptions.RequestException, but can # also raise ValueError, RuntimeError, etc. self._handle_request_error(e) return content, status_code def _handle_request_error(self, e): if isinstance(e, requests.exceptions.RequestException): msg = ("Unexpected error communicating with Shippo. " "If this problem persists, let us know at " "support@goshippo.com.") err = "%s: %s" % (type(e).__name__, str(e)) else: msg = ("Unexpected error communicating with Shippo. " "It looks like there's probably a configuration " "issue locally. If this problem persists, let us " "know at support@goshippo.com.") err = "A %s was raised" % (type(e).__name__,) if str(e): err += " with error message %s" % (str(e),) else: err += " with no error message" msg = textwrap.fill(msg) + "\n\n(Network error: %s)" % (err,) raise error.APIConnectionError(msg) <|code_end|> using the current file's imports: import os import sys import textwrap import requests from shippo import error from google.appengine.api import urlfetch and any relevant context from other files: # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): . Output only the next line.
class UrlFetchClient(HTTPClient):
Using the snippet: <|code_start|> if id: self['object_id'] = id def __setattr__(self, k, v): if k[0] == '_' or k in self.__dict__: return super(ShippoObject, self).__setattr__(k, v) else: self[k] = v def __getattr__(self, k): if k[0] == '_': raise AttributeError(k) try: return self[k] except KeyError as err: raise AttributeError(*err.args) def __setitem__(self, k, v): if v == "": raise ValueError( "You cannot set %s to an empty string. " "We interpret empty strings as None in requests." "You may set %s.%s = None to delete the property" % ( k, str(self), k)) super(ShippoObject, self).__setitem__(k, v) # Allows for unpickling in Python 3.x <|code_end|> , determine the next line of code. You have imports: import urllib.parse import sys import time import warnings import shippo.config as config from shippo import api_requestor, error, util from shippo.config import rates_req_timeout and context (class names, function names, or code) available: # Path: shippo/api_requestor.py # def _encode_datetime(dttime): # def _api_encode(data): # def _build_api_url(url, query): # def __init__(self, key=None, client=None): # def request(self, method, url, params=None): # def handle_api_error(self, rbody, rcode, resp): # def request_raw(self, method, url, params=None): # def interpret_response(self, rbody, rcode): # def _check_ssl_cert(self): # class APIRequestor(object): # _CERTIFICATE_VERIFIED = False # # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/util.py # # Path: shippo/config.py . Output only the next line.
if not hasattr(self, '_unsaved_values'):
Here is a snippet: <|code_start|> def __init__(self, id=None, api_key=None, **params): super(ShippoObject, self).__init__() self._unsaved_values = set() self._transient_values = set() self._retrieve_params = params self._previous_metadata = None object.__setattr__(self, 'api_key', api_key) if id: self['object_id'] = id def __setattr__(self, k, v): if k[0] == '_' or k in self.__dict__: return super(ShippoObject, self).__setattr__(k, v) else: self[k] = v def __getattr__(self, k): if k[0] == '_': raise AttributeError(k) try: return self[k] except KeyError as err: raise AttributeError(*err.args) <|code_end|> . Write the next line using the current file imports: import urllib.parse import sys import time import warnings import shippo.config as config from shippo import api_requestor, error, util from shippo.config import rates_req_timeout and context from other files: # Path: shippo/api_requestor.py # def _encode_datetime(dttime): # def _api_encode(data): # def _build_api_url(url, query): # def __init__(self, key=None, client=None): # def request(self, method, url, params=None): # def handle_api_error(self, rbody, rcode, resp): # def request_raw(self, method, url, params=None): # def interpret_response(self, rbody, rcode): # def _check_ssl_cert(self): # class APIRequestor(object): # _CERTIFICATE_VERIFIED = False # # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/util.py # # Path: shippo/config.py , which may include functions, classes, or code. Output only the next line.
def __setitem__(self, k, v):
Here is a snippet: <|code_start|> super(ShippoObject, self).__setitem__(k, v) # Allows for unpickling in Python 3.x if not hasattr(self, '_unsaved_values'): self._unsaved_values = set() self._unsaved_values.add(k) def __getitem__(self, k): try: return super(ShippoObject, self).__getitem__(k) except KeyError as err: if k in self._transient_values: raise KeyError( "%r. HINT: The %r attribute was set in the past." "It was then wiped when refreshing the object with " "the result returned by Shippo's API, probably as a " "result of a save(). The attributes currently " "available on this object are: %s" % (k, k, ', '.join(list(self.keys())))) else: raise err def __delitem__(self, k): raise TypeError( "You cannot delete attributes on a ShippoObject. " "To unset a property, set it to None.") @classmethod <|code_end|> . Write the next line using the current file imports: import urllib.parse import sys import time import warnings import shippo.config as config from shippo import api_requestor, error, util from shippo.config import rates_req_timeout and context from other files: # Path: shippo/api_requestor.py # def _encode_datetime(dttime): # def _api_encode(data): # def _build_api_url(url, query): # def __init__(self, key=None, client=None): # def request(self, method, url, params=None): # def handle_api_error(self, rbody, rcode, resp): # def request_raw(self, method, url, params=None): # def interpret_response(self, rbody, rcode): # def _check_ssl_cert(self): # class APIRequestor(object): # _CERTIFICATE_VERIFIED = False # # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/util.py # # Path: shippo/config.py , which may include functions, classes, or code. Output only the next line.
def construct_from(cls, values, api_key):
Here is a snippet: <|code_start|> def class_name(cls): if cls == APIResource: raise NotImplementedError( 'APIResource is an abstract class. You should perform ' 'actions on its subclasses (e.g. Address, Parcel)') return str(urllib.parse.quote_plus(cls.__name__.lower())) @classmethod def class_url(cls): cls_name = cls.class_name() return "/v1/%ss" % (cls_name,) def instance_url(self): object_id = self.get('object_id') if not object_id: raise error.InvalidRequestError( 'Could not determine which URL to request: %s instance ' 'has invalid ID: %r' % (type(self).__name__, object_id), 'object_id') object_id = object_id base = self.class_url() extn = urllib.parse.quote_plus(object_id) return "%s/%s" % (base, extn) class CreateableAPIResource(APIResource): @classmethod def create(cls, api_key=None, **params): requestor = api_requestor.APIRequestor(api_key) url = cls.class_url() <|code_end|> . Write the next line using the current file imports: import urllib.parse import sys import time import warnings import shippo.config as config from shippo import api_requestor, error, util from shippo.config import rates_req_timeout and context from other files: # Path: shippo/api_requestor.py # def _encode_datetime(dttime): # def _api_encode(data): # def _build_api_url(url, query): # def __init__(self, key=None, client=None): # def request(self, method, url, params=None): # def handle_api_error(self, rbody, rcode, resp): # def request_raw(self, method, url, params=None): # def interpret_response(self, rbody, rcode): # def _check_ssl_cert(self): # class APIRequestor(object): # _CERTIFICATE_VERIFIED = False # # Path: shippo/error.py # class ShippoError(Exception): # class APIError(ShippoError): # class APIConnectionError(ShippoError): # class AddressError(ShippoError): # class InvalidRequestError(ShippoError): # class AuthenticationError(ShippoError): # def __init__(self, message=None, http_body=None, http_status=None, # json_body=None): # def __init__(self, message, param, code, http_body=None, # http_status=None, json_body=None): # def __init__(self, message, param, http_body=None, # http_status=None, json_body=None): # # Path: shippo/util.py # # Path: shippo/config.py , which may include functions, classes, or code. Output only the next line.
response, api_key = requestor.request('post', url, params)
Based on the snippet: <|code_start|> return client.request(method, url, headers, post_data) def mock_response(self, body, code): raise NotImplementedError( 'You must implement this in your test subclass') def mock_error(self, error): raise NotImplementedError( 'You must implement this in your test subclass') def check_call(self, meth, abs_url, headers, params): raise NotImplementedError( 'You must implement this in your test subclass') def test_request(self): self.mock_response(self.request_mock, '{"status": "ok"}', 200) for meth in VALID_API_METHODS: abs_url = self.valid_url data = '' if meth != 'post': data = None headers = {'my-header': 'header val'} body, code = self.make_request( meth, abs_url, headers, data) self.assertEqual(200, code) <|code_end|> , predict the immediate next line with the help of imports: import warnings import unittest2 import shippo from mock import Mock from shippo.test.helper import ShippoUnitTestCase and context (classes, functions, sometimes code) from other files: # Path: shippo/test/helper.py # class ShippoUnitTestCase(ShippoTestCase): # REQUEST_LIBRARIES = ['urlfetch', 'requests'] # # def setUp(self): # super(ShippoUnitTestCase, self).setUp() # # self.request_patchers = {} # self.request_mocks = {} # for lib in self.REQUEST_LIBRARIES: # patcher = patch("shippo.http_client.%s" % (lib,)) # # self.request_mocks[lib] = patcher.start() # self.request_patchers[lib] = patcher # # def tearDown(self): # super(ShippoUnitTestCase, self).tearDown() # # for patcher in list(self.request_patchers.values()): # patcher.stop() . Output only the next line.
self.assertEqual('{"status": "ok"}', body)
Continue the code snippet: <|code_start|> class APIRequestorTests(TestCase): def test_oauth_token_auth(self): mock_client = Mock() mock_client.name = 'mock_client' mock_client.request.return_value = ('{"status": "ok"}', 200) requestor = api_requestor.APIRequestor( key='oauth.mocktoken.mocksig', client=mock_client) requestor.request('GET', '/v1/echo') args, kwargs = mock_client.request.call_args method, url, headers, data = args self.assertDictContainsSubset( {'Authorization': 'Bearer oauth.mocktoken.mocksig'}, headers, "Expect correct token type to used for authorization with oauth token" <|code_end|> . Use current file imports: from shippo import api_requestor from mock import patch, Mock from unittest2 import TestCase import unittest2 and context (classes, functions, or code) from other files: # Path: shippo/api_requestor.py # def _encode_datetime(dttime): # def _api_encode(data): # def _build_api_url(url, query): # def __init__(self, key=None, client=None): # def request(self, method, url, params=None): # def handle_api_error(self, rbody, rcode, resp): # def request_raw(self, method, url, params=None): # def interpret_response(self, rbody, rcode): # def _check_ssl_cert(self): # class APIRequestor(object): # _CERTIFICATE_VERIFIED = False . Output only the next line.
)
Predict the next line for this snippet: <|code_start|># coding=utf-8 register_standard_logs('output', __file__) mod = Model() country = Country(mod, 'CO') Household(country, 'HH') gov = ConsolidatedGovernment(country, 'GOV') FixedMarginBusiness(country, 'BUS') Market(country, 'GOOD') <|code_end|> with the help of current file imports: from sfc_models.objects import * from sfc_models.examples.Quick2DPlot import Quick2DPlot and context from other files: # Path: sfc_models/examples/Quick2DPlot.py # class Quick2DPlot(object): # def __init__(self, x, y, title='', run_now=True, output_directory=None, filename=None): # self.X = x # self.Y = y # self.Title = title # self.XLabel = None # self.YLabel = None # self.Legend = None # self.FileName = filename # self.LegendPos = 'best' # self.OutputDirectory = output_directory # if run_now: # self.DoPlot() # # def DoPlot(self): # pragma: no cover # if plt is None: # pprint('Attempted to plot the following data; cannot to do because cannot import matplotlib') # if type(self.X[0]) == list: # pprint('Series 1') # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X[0])): # pprint('%f %20f' % (self.X[0][i], self.Y[0][i])) # pprint('Series 2') # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X[1])): # pprint('%f %20f' % (self.X[1][i], self.Y[1][i])) # else: # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X)): # pprint('%f %20f' % (self.X[i], self.Y[i])) # return # if type(self.X[0]) == list: # fig, ax = plt.subplots() # ax.plot(self.X[0], self.Y[0], marker='o', markersize=4) # ax.plot(self.X[1], self.Y[1], marker='^', markersize=4.5) # # plt.plot(self.X[0], self.Y[0], self.X[1], self.Y[1], marker='o') # else: # plt.plot(self.X, self.Y, marker='o') # params = Quick2DPlotParams() # params.ReadFile() # plt.rcParams.update({'font.size': params.FontSize}) # figure = plt.gcf() # figure.set_size_inches(4.5, 3) # if len(self.Title) > 0: # plt.title(self.Title) # plt.grid() # if self.XLabel is not None: # plt.xlabel(self.XLabel) # if self.YLabel is not None: # plt.ylabel(self.YLabel) # if self.Legend is not None: # plt.legend(self.Legend, loc=self.LegendPos) # # if params.OutputDirectory is not None: # self.OutputDirectory = params.OutputDirectory # if (self.OutputDirectory is not None) and (self.FileName is not None): # fullname = os.path.join(self.OutputDirectory, self.FileName) # pprint('Saving File: {0} dpi={1}'.format(fullname, params.dpi)) # plt.savefig(fullname, dpi=params.dpi) # plt.show() , which may contain function names, class names, or code. Output only the next line.
Market(country, 'LAB')
Given the following code snippet before the placeholder: <|code_start|> License/Disclaimer ------------------ Copyright 2017 Brian Romanchuk 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. """ from __future__ import print_function if sys.version_info[0] < 3: # pragma: no cover (Do coverage test in 3.x) # import Tkinter as tk # from Tkinter import * else: validate_str = """ This command will install sfc_models to a directory that you specify. It will also create a sub-directory named "output" (which is where log files are directed). <|code_end|> , predict the next line using imports from the current file: import sys import tkMessageBox as mbox import tkFileDialog as fdog import tkinter as tk import tkinter.messagebox as mbox import tkinter.filedialog as fdog from tkinter import * from sfc_models.examples import install_example_scripts and context including class names, function names, and sometimes code from other files: # Path: sfc_models/examples/install_example_scripts.py # def install(target_dir): # pragma: no cover . Output only the next line.
It will not overwrite existing files; it is recommended that you clear out your local copy of the examples directory before installing an updated examples set.
Predict the next line after this snippet: <|code_start|> Household(country, 'HH') ConsolidatedGovernment(country, 'GOV') FixedMarginBusiness(country, 'BUS') Market(country, 'GOOD') Market(country, 'LAB') TaxFlow(country, 'TAX', taxrate=.2) mod.AddExogenous('GOV', 'DEM_GOOD', [15.,]*5 + [government_consumption,]* 50) mod.AddGlobalEquation('DEBT_GDP', 'DEBT-TO-GDP RATIO', '-100.*GOV__F/BUS__SUP_GOOD') mod.AddGlobalEquation('DEFICIT', 'DEFICIT-TO-GDP RATIO', '-100.*GOV__INC/BUS__SUP_GOOD') mod.EquationSolver.MaxTime = 40 print(mod.EquationSolver.ParameterErrorTolerance) # mod.EquationSolver.ParameterErrorTolerance = 1e-8 mod.EquationSolver.ParameterSolveInitialSteadyState = True return mod mod20 = build_model(government_consumption=20.0) mod20.main() mod25 = build_model(government_consumption=25.0) mod25.main() k = mod20.GetTimeSeries('k') Y20 = mod20.GetTimeSeries('BUS__SUP_GOOD') Rat20 = mod20.GetTimeSeries('DEBT_GDP') Def20 = mod20.GetTimeSeries('GOV__INC') Y30 = mod25.GetTimeSeries('BUS__SUP_GOOD') Rat30 = mod25.GetTimeSeries('DEBT_GDP') Def30 = mod25.GetTimeSeries('GOV__INC') p = Quick2DPlot([k,k], [Y20, Y30], title='Output in Simulations', filename='intro_X_XX_sim_fiscal.png', run_now=False) p.Legend = ['Scenario #1', 'Scenario #2'] <|code_end|> using the current file's imports: from sfc_models.objects import * from sfc_models.examples.Quick2DPlot import Quick2DPlot and any relevant context from other files: # Path: sfc_models/examples/Quick2DPlot.py # class Quick2DPlot(object): # def __init__(self, x, y, title='', run_now=True, output_directory=None, filename=None): # self.X = x # self.Y = y # self.Title = title # self.XLabel = None # self.YLabel = None # self.Legend = None # self.FileName = filename # self.LegendPos = 'best' # self.OutputDirectory = output_directory # if run_now: # self.DoPlot() # # def DoPlot(self): # pragma: no cover # if plt is None: # pprint('Attempted to plot the following data; cannot to do because cannot import matplotlib') # if type(self.X[0]) == list: # pprint('Series 1') # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X[0])): # pprint('%f %20f' % (self.X[0][i], self.Y[0][i])) # pprint('Series 2') # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X[1])): # pprint('%f %20f' % (self.X[1][i], self.Y[1][i])) # else: # pprint('%s %20s' % ('X', 'Y')) # for i in range(0, len(self.X)): # pprint('%f %20f' % (self.X[i], self.Y[i])) # return # if type(self.X[0]) == list: # fig, ax = plt.subplots() # ax.plot(self.X[0], self.Y[0], marker='o', markersize=4) # ax.plot(self.X[1], self.Y[1], marker='^', markersize=4.5) # # plt.plot(self.X[0], self.Y[0], self.X[1], self.Y[1], marker='o') # else: # plt.plot(self.X, self.Y, marker='o') # params = Quick2DPlotParams() # params.ReadFile() # plt.rcParams.update({'font.size': params.FontSize}) # figure = plt.gcf() # figure.set_size_inches(4.5, 3) # if len(self.Title) > 0: # plt.title(self.Title) # plt.grid() # if self.XLabel is not None: # plt.xlabel(self.XLabel) # if self.YLabel is not None: # plt.ylabel(self.YLabel) # if self.Legend is not None: # plt.legend(self.Legend, loc=self.LegendPos) # # if params.OutputDirectory is not None: # self.OutputDirectory = params.OutputDirectory # if (self.OutputDirectory is not None) and (self.FileName is not None): # fullname = os.path.join(self.OutputDirectory, self.FileName) # pprint('Saving File: {0} dpi={1}'.format(fullname, params.dpi)) # plt.savefig(fullname, dpi=params.dpi) # plt.show() . Output only the next line.
p.DoPlot()
Predict the next line for this snippet: <|code_start|> class TestBaseSolver(TestCase): def test_CsvString(self): obj = BaseSolver(['x', 'y', 't']) <|code_end|> with the help of current file imports: from unittest import TestCase from sfc_models.base_solver import BaseSolver and context from other files: # Path: sfc_models/base_solver.py # class BaseSolver(object): # def __init__(self, variable_list): # self.VariableList = variable_list # # def WriteCSV(self, f_name): # pragma: no cover # out = self.CreateCsvString() # with open(f_name, 'w') as f: # f.write(out) # # def CreateCsvString(self): # varlist = self.VariableList # if 't' in varlist: # varlist.remove('t') # varlist = ['t', ] + varlist # out = '\t'.join(varlist) + '\n' # for i in range(0, len(getattr(self, varlist[0]))): # txt = [] # for v in varlist: # txt.append(str(getattr(self, v)[i])) # out += '\t'.join(txt) + '\n' # return out , which may contain function names, class names, or code. Output only the next line.
obj.x = [1., 1., 1.]
Here is a snippet: <|code_start|>0.498641604188 >>> best_options['c1'] 1 >>> best_options['c2'] 1 """ # Import from __future__ from __future__ import absolute_import, print_function, with_statement # Import standard library # Import from pyswarms # Import from package class GridSearch(SearchBase): """Exhaustive search of optimal performance on selected objective function over all combinations of specified hyperparameter values.""" def __init__( self, optimizer, n_particles, dimensions, options, objective_func, iters, bounds=None, velocity_clamp=(0, 1), <|code_end|> . Write the next line using the current file imports: import itertools from pyswarms.utils.search.base_search import SearchBase and context from other files: # Path: pyswarms/utils/search/base_search.py # class SearchBase(object): # def assertions(self): # """Assertion method to check :code:`optimizer` input # # Raises # ------ # TypeError # When :code:`optimizer` does not have an `'optimize'` attribute. # """ # # Check type of optimizer object # if not hasattr(self.optimizer, "optimize"): # raise TypeError( # "Parameter `optimizer` must have an " "`'optimize'` attribute." # ) # # def __init__( # self, # optimizer, # n_particles, # dimensions, # options, # objective_func, # iters, # bounds=None, # velocity_clamp=(0, 1), # ): # """Initialize the Search # # Attributes # ---------- # optimizer: pyswarms.single # either LocalBestPSO or GlobalBestPSO # n_particles : int # number of particles in the swarm. # dimensions : int # number of dimensions in the space. # options : dict with keys :code:`{'c1', 'c2', 'w', 'k', 'p'}` # a dictionary containing the parameters for the specific # optimization technique # # * c1 : float # cognitive parameter # * c2 : float # social parameter # * w : float # inertia parameter # * k : int # number of neighbors to be considered. Must be a # positive integer less than :code:`n_particles` # * p: int {1,2} # the Minkowski p-norm to use. 1 is the # sum-of-absolute values (or L1 distance) while 2 is # the Euclidean (or L2) distance. # # objective_func: function # objective function to be evaluated # iters: int # number of iterations # bounds : tuple of np.ndarray, optional (default is None) # a tuple of size 2 where the first entry is the minimum bound # while the second entry is the maximum bound. Each array must # be of shape :code:`(dimensions,)`. # velocity_clamp : tuple (default is :code:`None`) # a tuple of size 2 where the first entry is the minimum velocity # and the second entry is the maximum velocity. It # sets the limits for velocity clamping. # """ # # # Assign attributes # self.optimizer = optimizer # self.n_particles = n_particles # self.dims = dimensions # self.options = options # self.bounds = bounds # self.vclamp = velocity_clamp # self.objective_func = objective_func # self.iters = iters # # Invoke assertions # self.assertions() # # def generate_score(self, options): # """Generate score for optimizer's performance on objective function # # Parameters # ---------- # # options: dict # a dict with the following keys: {'c1', 'c2', 'w', 'k', 'p'} # """ # # # Intialize optimizer # f = self.optimizer( # self.n_particles, # self.dims, # options, # self.bounds, # velocity_clamp=self.vclamp, # ) # # # Return score # return f.optimize(self.objective_func, self.iters)[0] # # def search(self, maximum=False): # """Compare optimizer's objective function performance scores # for all combinations of provided parameters # # Parameters # ---------- # # maximum: bool # a bool defaulting to False, returning the minimum value for the # objective function. If set to True, will return the maximum value # for the objective function. # """ # # # Generate the grid of all hyperparameter value combinations # grid = self.generate_grid() # # # Calculate scores for all hyperparameter combinations # scores = [self.generate_score(i) for i in grid] # # # Default behavior # idx, self.best_score = min(enumerate(scores), key=op.itemgetter(1)) # # # Catches the maximum bool flag # if maximum: # idx, self.best_score = max(enumerate(scores), key=op.itemgetter(1)) # # # Return optimum hyperparameter value property from grid using index # self.best_options = op.itemgetter(idx)(grid) # return self.best_score, self.best_options , which may include functions, classes, or code. Output only the next line.
):
Given snippet: <|code_start|>>>> options = {'c1': [1, 5], 'c2': [6, 10], 'w' : [2, 5], 'k' : [11, 15], 'p' : 1} >>> g = RandomSearch(LocalBestPSO, n_particles=40, dimensions=20, options=options, objective_func=sphere, iters=10) >>> best_score, best_options = g.search() >>> best_score 1.41978545901 >>> best_options['c1'] 1.543556887693 >>> best_options['c2'] 9.504769054771 """ # Import from __future__ from __future__ import absolute_import, print_function, with_statement # Import modules # Import from pyswarms # Import from package class RandomSearch(SearchBase): """Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from past.builtins import xrange from pyswarms.utils.search.base_search import SearchBase and context: # Path: pyswarms/utils/search/base_search.py # class SearchBase(object): # def assertions(self): # """Assertion method to check :code:`optimizer` input # # Raises # ------ # TypeError # When :code:`optimizer` does not have an `'optimize'` attribute. # """ # # Check type of optimizer object # if not hasattr(self.optimizer, "optimize"): # raise TypeError( # "Parameter `optimizer` must have an " "`'optimize'` attribute." # ) # # def __init__( # self, # optimizer, # n_particles, # dimensions, # options, # objective_func, # iters, # bounds=None, # velocity_clamp=(0, 1), # ): # """Initialize the Search # # Attributes # ---------- # optimizer: pyswarms.single # either LocalBestPSO or GlobalBestPSO # n_particles : int # number of particles in the swarm. # dimensions : int # number of dimensions in the space. # options : dict with keys :code:`{'c1', 'c2', 'w', 'k', 'p'}` # a dictionary containing the parameters for the specific # optimization technique # # * c1 : float # cognitive parameter # * c2 : float # social parameter # * w : float # inertia parameter # * k : int # number of neighbors to be considered. Must be a # positive integer less than :code:`n_particles` # * p: int {1,2} # the Minkowski p-norm to use. 1 is the # sum-of-absolute values (or L1 distance) while 2 is # the Euclidean (or L2) distance. # # objective_func: function # objective function to be evaluated # iters: int # number of iterations # bounds : tuple of np.ndarray, optional (default is None) # a tuple of size 2 where the first entry is the minimum bound # while the second entry is the maximum bound. Each array must # be of shape :code:`(dimensions,)`. # velocity_clamp : tuple (default is :code:`None`) # a tuple of size 2 where the first entry is the minimum velocity # and the second entry is the maximum velocity. It # sets the limits for velocity clamping. # """ # # # Assign attributes # self.optimizer = optimizer # self.n_particles = n_particles # self.dims = dimensions # self.options = options # self.bounds = bounds # self.vclamp = velocity_clamp # self.objective_func = objective_func # self.iters = iters # # Invoke assertions # self.assertions() # # def generate_score(self, options): # """Generate score for optimizer's performance on objective function # # Parameters # ---------- # # options: dict # a dict with the following keys: {'c1', 'c2', 'w', 'k', 'p'} # """ # # # Intialize optimizer # f = self.optimizer( # self.n_particles, # self.dims, # options, # self.bounds, # velocity_clamp=self.vclamp, # ) # # # Return score # return f.optimize(self.objective_func, self.iters)[0] # # def search(self, maximum=False): # """Compare optimizer's objective function performance scores # for all combinations of provided parameters # # Parameters # ---------- # # maximum: bool # a bool defaulting to False, returning the minimum value for the # objective function. If set to True, will return the maximum value # for the objective function. # """ # # # Generate the grid of all hyperparameter value combinations # grid = self.generate_grid() # # # Calculate scores for all hyperparameter combinations # scores = [self.generate_score(i) for i in grid] # # # Default behavior # idx, self.best_score = min(enumerate(scores), key=op.itemgetter(1)) # # # Catches the maximum bool flag # if maximum: # idx, self.best_score = max(enumerate(scores), key=op.itemgetter(1)) # # # Return optimum hyperparameter value property from grid using index # self.best_options = op.itemgetter(idx)(grid) # return self.best_score, self.best_options which might include code, classes, or functions. Output only the next line.
def assertions(self):
Here is a snippet: <|code_start|> return obj_with_args_ @pytest.fixture def obj_without_args(self): """Objective function without arguments""" return rosenbrock @pytest.mark.parametrize( "history, expected_shape", [ ("cost_history", (1000,)), ("mean_pbest_history", (1000,)), ("mean_neighbor_history", (1000,)), ("pos_history", (1000, 10, 2)), ("velocity_history", (1000, 10, 2)), ], ) def test_train_history(self, optimizer_history, history, expected_shape): """Test if training histories are of expected shape""" opt = vars(optimizer_history) assert np.array(opt[history]).shape == expected_shape def test_reset_default_values(self, optimizer_reset): """Test if best cost and best pos are set properly when the reset() method is called""" assert optimizer_reset.swarm.best_cost == np.inf assert set(optimizer_reset.swarm.best_pos) == set(np.array([])) @pytest.mark.skip(reason="The Ring topology converges too slowly") <|code_end|> . Write the next line using the current file imports: import abc import numpy as np import pytest import multiprocessing from pyswarms.utils.functions.single_obj import rosenbrock, sphere and context from other files: # Path: pyswarms/utils/functions/single_obj.py # def rosenbrock(x): # """Rosenbrock objective function. # # Also known as the Rosenbrock's valley or Rosenbrock's banana # function. Has a global minimum of :code:`np.ones(dimensions)` where # :code:`dimensions` is :code:`x.shape[1]`. The search domain is # :code:`[-inf, inf]`. # # Parameters # ---------- # x : numpy.ndarray # set of inputs of shape :code:`(n_particles, dimensions)` # # Returns # ------- # numpy.ndarray # computed cost of size :code:`(n_particles, )` # """ # # r = np.sum( # 100 * (x.T[1:] - x.T[:-1] ** 2.0) ** 2 + (1 - x.T[:-1]) ** 2.0, axis=0 # ) # # return r # # def sphere(x): # """Sphere objective function. # # Has a global minimum at :code:`0` and with a search domain of # :code:`[-inf, inf]` # # Parameters # ---------- # x : numpy.ndarray # set of inputs of shape :code:`(n_particles, dimensions)` # # Returns # ------- # numpy.ndarray # computed cost of size :code:`(n_particles, )` # """ # j = (x ** 2.0).sum(axis=1) # # return j , which may include functions, classes, or code. Output only the next line.
def test_ftol_effect(self, options, optimizer):
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Import modules # Import from pyswarms np.random.seed(4135157) class TestVonNeumannTopology(ABCTestTopology): @pytest.fixture def topology(self): return VonNeumann @pytest.fixture <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import pytest from pyswarms.backend.topology import VonNeumann from .abc_test_topology import ABCTestTopology and context: # Path: pyswarms/backend/topology/von_neumann.py # class VonNeumann(Ring): # def __init__(self, static=None): # # static = None is just an artifact to make the API consistent # # Setting it will not change swarm behavior # super(VonNeumann, self).__init__(static=True) # self.rep = Reporter(logger=logging.getLogger(__name__)) # # def compute_gbest(self, swarm, p, r, **kwargs): # """Updates the global best using a neighborhood approach # # The Von Neumann topology inherits from the Ring topology and uses # the same approach to calculate the global best. The number of # neighbors is determined by the dimension and the range. This # topology is always a :code:`static` topology. # # Parameters # ---------- # swarm : pyswarms.backend.swarms.Swarm # a Swarm instance # r : int # range of the Von Neumann topology # p: int {1,2} # the Minkowski p-norm to use. 1 is the # sum-of-absolute values (or L1 distance) while 2 is # the Euclidean (or L2) distance. # # Returns # ------- # numpy.ndarray # Best position of shape :code:`(n_dimensions, )` # float # Best cost # """ # k = VonNeumann.delannoy(swarm.dimensions, r) # return super(VonNeumann, self).compute_gbest(swarm, p, k) # # @staticmethod # def delannoy(d, r): # """Static helper method to compute Delannoy numbers # # This method computes the number of neighbours of a Von Neumann # topology, i.e. a Delannoy number, dependent on the range and the # dimension of the search space. The Delannoy numbers are computed # recursively. # # Parameters # ---------- # d : int # dimension of the search space # r : int # range of the Von Neumann topology # # Returns # ------- # int # Delannoy number""" # if d == 0 or r == 0: # return 1 # else: # del_number = ( # VonNeumann.delannoy(d - 1, r) # + VonNeumann.delannoy(d - 1, r - 1) # + VonNeumann.delannoy(d, r - 1) # ) # return del_number # # Path: tests/backend/topology/abc_test_topology.py # class ABCTestTopology(abc.ABC): # """Abstract class that defines various tests for topologies # # Whenever a topology inherits from ABCTestTopology, # you don't need to write down all tests anymore. Instead, you can just # specify all required fixtures in the test suite. # """ # # @pytest.fixture # def topology(self): # """Return an instance of the topology""" # raise NotImplementedError("NotImplementedError::topology") # # @pytest.fixture # def options(self): # """Return a dictionary of options""" # raise NotImplementedError("NotImplementedError::options") # # @pytest.mark.parametrize("static", [True, False]) # @pytest.mark.parametrize("clamp", [None, (0, 1), (-1, 1)]) # def test_compute_velocity_return_values( # self, topology, swarm, clamp, static # ): # """Test if compute_velocity() gives the expected shape and range""" # topo = topology(static=static) # v = topo.compute_velocity(swarm, clamp) # assert v.shape == swarm.position.shape # if clamp is not None: # assert (clamp[0] <= v).all() and (clamp[1] >= v).all() # # @pytest.mark.parametrize("static", [True, False]) # @pytest.mark.parametrize( # "bounds", # [None, ([-5, -5, -5], [5, 5, 5]), ([-10, -10, -10], [10, 10, 10])], # ) # def test_compute_position_return_values( # self, topology, swarm, bounds, static # ): # """Test if compute_position() gives the expected shape and range""" # topo = topology(static=static) # p = topo.compute_position(swarm, bounds) # assert p.shape == swarm.velocity.shape # if bounds is not None: # assert (bounds[0] <= p).all() and (bounds[1] >= p).all() # # @pytest.mark.parametrize("static", [True, False]) # def test_neighbor_idx(self, topology, options, swarm, static): # """Test if the neighbor_idx attribute is assigned""" # topo = topology(static=static) # topo.compute_gbest(swarm, **options) # assert topo.neighbor_idx is not None # # @pytest.mark.parametrize("static", [True, False]) # @pytest.mark.parametrize("swarm", [0, (1, 2, 3)]) # def test_input_swarm(self, topology, static, swarm, options): # """Test if AttributeError is raised when passed with a non-Swarm instance""" # with pytest.raises(AttributeError): # topo = topology(static=static) # topo.compute_gbest(swarm, **options) which might include code, classes, or functions. Output only the next line.
def options(self):
Next line prediction: <|code_start|> # Python 2.7 compat shims to_bytes_be = lambda x, sz: x.to_bytes(sz, 'big') try: to_bytes_be(int(1), 1) except AttributeError: to_bytes_be = lambda x, sz: '{:0{}x}'.format(x, sz * 2).decode('hex') from_bytes_be = lambda x: int.from_bytes(x, 'big') try: from_bytes_be(to_bytes_be(1, 1)) except AttributeError: from_bytes_be = lambda x: int(x.encode('hex'), 16) def bxor(ba1, ba2): olen = len(ba1) ba1 = from_bytes_be(ba1) ba2 = from_bytes_be(ba2) return to_bytes_be(ba1 ^ ba2, olen) class AESCipher(object): bpad = '='.encode() cipher = None def __init__(self, key): self.cipher = AES.new(key, AES.MODE_ECB) <|code_end|> . Use current file imports: (from base64 import b64encode, b64decode from Crypto import Random from Crypto.Cipher import AES from sippy.Time.clock_dtime import clock_getntime, CLOCK_MONOTONIC from threading import Thread from time import sleep) and context including class names, function names, or small code snippets from other files: # Path: sippy/Time/clock_dtime.py # def clock_getntime(type): # ts = clock_getitime(type) # return (ts[0] * 10**9 + ts[1]) # # CLOCK_MONOTONIC = 4 # see <linux/time.h> / <include/time.h> . Output only the next line.
def encrypt(self, raw):
Given snippet: <|code_start|> def emit_challenge(self, cmask): ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS) for ms in cmask: ts128 |= ms cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size)) #return cryptic return cryptic.decode() def validate_challenge(self, cryptic, cmask): new_ts = clock_getntime(CLOCK_MONOTONIC) decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode())) for ms in cmask: if (ms & decryptic) == 0: return False orig_ts = decryptic >> len(DGST_PRIOS) tsdiff = new_ts - orig_ts if tsdiff < 0 or tsdiff > self.vtime: return False return True if __name__ == '__main__': class TestExpiration(Thread): nonce = None ho = HashOracle() excpt = None def __init__(self, nonce): Thread.__init__(self) <|code_end|> , continue by predicting the next line. Consider current file imports: from base64 import b64encode, b64decode from Crypto import Random from Crypto.Cipher import AES from sippy.Time.clock_dtime import clock_getntime, CLOCK_MONOTONIC from threading import Thread from time import sleep and context: # Path: sippy/Time/clock_dtime.py # def clock_getntime(type): # ts = clock_getitime(type) # return (ts[0] * 10**9 + ts[1]) # # CLOCK_MONOTONIC = 4 # see <linux/time.h> / <include/time.h> which might include code, classes, or functions. Output only the next line.
self.nonce = nonce
Predict the next line after this snippet: <|code_start|># # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class UaStateFailed(UaStateGeneric): sname = 'Failed' def __init__(self, ua): UaStateGeneric.__init__(self, ua) ua.on_local_sdp_change = None ua.on_remote_sdp_change = None Timeout(self.goDead, ua.godead_timeout) def goDead(self): #print 'Time in Failed state expired, going to the Dead state' self.ua.changeState((UaStateDead,)) <|code_end|> using the current file's imports: from sippy.Time.Timeout import Timeout from sippy.UaStateGeneric import UaStateGeneric from sippy.UaStateDead import UaStateDead and any relevant context from other files: # Path: sippy/UaStateGeneric.py # class UaStateGeneric(object): # sname = 'Generic' # ua = None # connected = False # dead = False # # def __init__(self, ua): # self.ua = ua # # def recvRequest(self, req): # return None # # def recvResponse(self, resp, tr): # return None # # def recvEvent(self, event): # return None # # def cancel(self, rtime, req): # return None # # def onStateChange(self, newstate): # pass # # def __str__(self): # return self.sname . Output only the next line.
if not 'UaStateDead' in globals():
Given the code snippet: <|code_start|># (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class SipAllow(SipGenericHF): hf_names = ('allow',) methods = None def __init__(self, body = None, methods = None): SipGenericHF.__init__(self, body) if body == None: self.parsed = True self.methods = methods[:] def parse(self): self.methods = [x.strip() for x in self.body.split(',')] self.parsed = True def __str__(self): if not self.parsed: return self.body return reduce(lambda x, y: '%s, %s' % (x, y), self.methods) def getCopy(self): if not self.parsed: return SipAllow(self.body) <|code_end|> , generate the next line using the imports in this file: from sippy.SipGenericHF import SipGenericHF from functools import reduce and context (functions, classes, or occasionally code) from other files: # Path: sippy/SipGenericHF.py # class SipGenericHF(object): # hf_names = None # Set this in each subclass!! # body = None # parsed = False # # def __init__(self, body, name = None): # self.body = body # if name != None: # self.hf_names = (name.lower(),) # # def parse(self): # pass # # def localStr(self, local_addr = None, local_port = None): # return self.__str__() # # def __str__(self): # return self.body # # def getCopy(self): # return self.__class__(self.body) # # def getCanName(self, name, compact = False): # return name.capitalize() . Output only the next line.
return SipAllow(methods = self.methods)
Predict the next line for this snippet: <|code_start|># this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class UaStateDead(UaStateGeneric): sname = 'Dead' dead = True def __init__(self, ua): UaStateGeneric.__init__(self, None) if ua.cId != None: ua.global_config['_sip_tm'].unregConsumer(ua, str(ua.cId)) ua.tr = None ua.event_cb = None ua.conn_cbs = () ua.disc_cbs = () ua.fail_cbs = () ua.on_local_sdp_change = None ua.on_remote_sdp_change = None <|code_end|> with the help of current file imports: from sippy.UaStateGeneric import UaStateGeneric and context from other files: # Path: sippy/UaStateGeneric.py # class UaStateGeneric(object): # sname = 'Generic' # ua = None # connected = False # dead = False # # def __init__(self, ua): # self.ua = ua # # def recvRequest(self, req): # return None # # def recvResponse(self, resp, tr): # return None # # def recvEvent(self, event): # return None # # def cancel(self, rtime, req): # return None # # def onStateChange(self, newstate): # pass # # def __str__(self): # return self.sname , which may contain function names, class names, or code. Output only the next line.
ua.expire_timer = None
Given the following code snippet before the placeholder: <|code_start|># # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class SipRSeq(SipNumericHF): hf_names = ('rseq',) def __init__(self, body = None, number = 1): SipNumericHF.__init__(self, body, number) def getCanName(self, name, compact = False): return 'RSeq' if __name__ == '__main__': <|code_end|> , predict the next line using imports from the current file: from sippy.SipNumericHF import SipNumericHF and context including class names, function names, and sometimes code from other files: # Path: sippy/SipNumericHF.py # class SipNumericHF(SipGenericHF): # number = None # # def __init__(self, body = None, number = 0): # SipGenericHF.__init__(self, body) # if body == None: # self.parsed = True # self.number = number # # def parse(self): # self.number = int(self.body) # self.parsed = True # # def __str__(self): # if not self.parsed: # return self.body # return str(self.number) # # def getCopy(self): # if not self.parsed: # return self.__class__(body = self.body) # return self.__class__(number = self.number) # # def getNum(self): # return self.number # # def incNum(self): # self.number += 1 # return self.number . Output only the next line.
rs = SipRSeq(body = '50')