Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> User = get_user_model() TEST_SERVER = 'http://testserver' SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send' <|code_end|> , generate the next line using the imports in this file: import datetime import re from collections import OrderedDict from django.contrib.auth import get_user_model, signals from django.contrib.auth.hashers import check_password from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.models import Site from django.core import mail from django.core.cache import cache from django.test import override_settings from django.urls import reverse from django.utils import timezone from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from mock import MagicMock, patch from rest_framework import status from rest_framework.test import APIRequestFactory from user_management.api import models, views from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH from user_management.models.tests.factories import AuthTokenFactory, UserFactory from user_management.models.tests.models import BasicUser from user_management.models.tests.utils import APIRequestTestCase from user_management.tests.utils import iso_8601 and context (functions, classes, or occasionally code) from other files: # Path: user_management/api/models.py # MINUTE = 60 # HOUR = 60 * MINUTE # DAY = 24 * HOUR # DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY # DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR # def update_expiry(created=None): # def __str__(self): # def save(self, *args, **kwargs): # def generate_key(self): # def update_expiry(self, commit=True): # class AuthToken(models.Model): # # Path: user_management/api/views.py # class GetAuthToken(ObtainAuthToken): # class UserRegister(generics.CreateAPIView): # class PasswordResetEmail(generics.GenericAPIView): # class OneTimeUseAPIMixin(object): # class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView): # class PasswordChange(generics.UpdateAPIView): # class VerifyAccountView(VerifyAccountViewMixin, views.APIView): # class ProfileDetail(generics.RetrieveUpdateDestroyAPIView): # class UserList(generics.ListCreateAPIView): # class UserDetail(generics.RetrieveUpdateDestroyAPIView): # class ResendConfirmationEmail(generics.GenericAPIView): # def post(self, request): # def delete(self, request, *args, **kwargs): # def create(self, request, *args, **kwargs): # def is_invalid(self, serializer): # def is_valid(self, serializer): # def post(self, request, *args, **kwargs): # def initial(self, request, *args, **kwargs): # def get_object(self): # def get_object(self): # def initial(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def get_object(self): # def initial(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # # Path: user_management/api/tests/test_throttling.py # THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES' # # Path: user_management/models/tests/factories.py # class AuthTokenFactory(factory.DjangoModelFactory): # key = factory.Sequence('key{}'.format) # user = factory.SubFactory(UserFactory) # # class Meta: # model = AuthToken # # class UserFactory(factory.DjangoModelFactory): # name = factory.Sequence('Test User {}'.format) # email = factory.Sequence('email{}@example.com'.format) # is_active = True # # class Meta: # model = get_user_model() # # @factory.post_generation # def password(self, create, extracted='default password', **kwargs): # self.raw_password = extracted # self.set_password(self.raw_password) # if create: # self.save() # # Path: user_management/models/tests/models.py # class BasicUser(BasicUserFieldsMixin, AbstractBaseUser): # pass # # Path: user_management/models/tests/utils.py # class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase): # user_factory = UserFactory # # Path: user_management/tests/utils.py # def iso_8601(datetime): # """Convert a datetime into an iso 8601 string.""" # if datetime is None: # return datetime # value = datetime.isoformat() # if value.endswith('+00:00'): # value = value[:-6] + 'Z' # return value . Output only the next line.
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
Predict the next line for this snippet: <|code_start|> User = get_user_model() TEST_SERVER = 'http://testserver' SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send' <|code_end|> with the help of current file imports: import datetime import re from collections import OrderedDict from django.contrib.auth import get_user_model, signals from django.contrib.auth.hashers import check_password from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.models import Site from django.core import mail from django.core.cache import cache from django.test import override_settings from django.urls import reverse from django.utils import timezone from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from mock import MagicMock, patch from rest_framework import status from rest_framework.test import APIRequestFactory from user_management.api import models, views from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH from user_management.models.tests.factories import AuthTokenFactory, UserFactory from user_management.models.tests.models import BasicUser from user_management.models.tests.utils import APIRequestTestCase from user_management.tests.utils import iso_8601 and context from other files: # Path: user_management/api/models.py # MINUTE = 60 # HOUR = 60 * MINUTE # DAY = 24 * HOUR # DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY # DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR # def update_expiry(created=None): # def __str__(self): # def save(self, *args, **kwargs): # def generate_key(self): # def update_expiry(self, commit=True): # class AuthToken(models.Model): # # Path: user_management/api/views.py # class GetAuthToken(ObtainAuthToken): # class UserRegister(generics.CreateAPIView): # class PasswordResetEmail(generics.GenericAPIView): # class OneTimeUseAPIMixin(object): # class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView): # class PasswordChange(generics.UpdateAPIView): # class VerifyAccountView(VerifyAccountViewMixin, views.APIView): # class ProfileDetail(generics.RetrieveUpdateDestroyAPIView): # class UserList(generics.ListCreateAPIView): # class UserDetail(generics.RetrieveUpdateDestroyAPIView): # class ResendConfirmationEmail(generics.GenericAPIView): # def post(self, request): # def delete(self, request, *args, **kwargs): # def create(self, request, *args, **kwargs): # def is_invalid(self, serializer): # def is_valid(self, serializer): # def post(self, request, *args, **kwargs): # def initial(self, request, *args, **kwargs): # def get_object(self): # def get_object(self): # def initial(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def get_object(self): # def initial(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # # Path: user_management/api/tests/test_throttling.py # THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES' # # Path: user_management/models/tests/factories.py # class AuthTokenFactory(factory.DjangoModelFactory): # key = factory.Sequence('key{}'.format) # user = factory.SubFactory(UserFactory) # # class Meta: # model = AuthToken # # class UserFactory(factory.DjangoModelFactory): # name = factory.Sequence('Test User {}'.format) # email = factory.Sequence('email{}@example.com'.format) # is_active = True # # class Meta: # model = get_user_model() # # @factory.post_generation # def password(self, create, extracted='default password', **kwargs): # self.raw_password = extracted # self.set_password(self.raw_password) # if create: # self.save() # # Path: user_management/models/tests/models.py # class BasicUser(BasicUserFieldsMixin, AbstractBaseUser): # pass # # Path: user_management/models/tests/utils.py # class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase): # user_factory = UserFactory # # Path: user_management/tests/utils.py # def iso_8601(datetime): # """Convert a datetime into an iso 8601 string.""" # if datetime is None: # return datetime # value = datetime.isoformat() # if value.endswith('+00:00'): # value = value[:-6] + 'Z' # return value , which may contain function names, class names, or code. Output only the next line.
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
Given snippet: <|code_start|> # reserved bamboo keys BAMBOO_RESERVED_KEY_PREFIX = '^^' DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'dataset_id' INDEX = BAMBOO_RESERVED_KEY_PREFIX + 'index' PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id' BAMBOO_RESERVED_KEYS = [ DATASET_ID, INDEX, PARENT_DATASET_ID, ] # all the reserved keys RESERVED_KEYS = BAMBOO_RESERVED_KEYS + [MONGO_ID_ENCODED] def add_id_column(df, dataset_id): <|code_end|> , continue by predicting the next line. Consider current file imports: from cStringIO import StringIO from pandas import Series from bamboo.lib.mongo import MONGO_ID_ENCODED and context: # Path: bamboo/lib/mongo.py # MONGO_ID_ENCODED = MONGO_RESERVED_KEY_PREFIX + '_id' which might include code, classes, or functions. Output only the next line.
return add_constant_column(df, dataset_id, DATASET_ID) if not\
Next line prediction: <|code_start|> def __parse_dates(dframe): for i, dtype in enumerate(dframe.dtypes): if dtype.type == np.object_: column = dframe.columns[i] new_column = _convert_column_to_date(dframe, column) if not new_column is None: dframe[column] = new_column return dframe <|code_end|> . Use current file imports: (from calendar import timegm from datetime import datetime from dateutil.parser import parse as date_parse from bamboo.lib.utils import is_float_nan import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: bamboo/lib/utils.py # def is_float_nan(num): # """Return True is `num` is a float and NaN.""" # return isinstance(num, float) and isnan(num) . Output only the next line.
def __parse_dates_schema(dframe, schema):
Next line prediction: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') def _add_bamboo_reserved_keys(self, value=1): for key in BAMBOO_RESERVED_KEYS: column = Series([value] * len(self.dframe)) column.name = key <|code_end|> . Use current file imports: (from pandas import Series from bamboo.core.frame import BAMBOO_RESERVED_KEYS, remove_reserved_keys,\ rows_for_parent_id, PARENT_DATASET_ID from bamboo.tests.test_base import TestBase) and context including class names, function names, or small code snippets from other files: # Path: bamboo/core/frame.py # BAMBOO_RESERVED_KEYS = [ # DATASET_ID, # INDEX, # PARENT_DATASET_ID, # ] # # def remove_reserved_keys(df, exclude=[]): # """Remove reserved internal columns in this DataFrame. # # :param keep_parent_ids: Keep parent column if True, default False. # """ # reserved_keys = __column_intersect( # df, BAMBOO_RESERVED_KEYS).difference(set(exclude)) # # return df.drop(reserved_keys, axis=1) # # def rows_for_parent_id(df, parent_id): # """DataFrame with only rows for `parent_id`. # # :param parent_id: The ID to restrict rows to. # # :returns: A DataFrame including only rows with a parent ID equal to # that passed in. # """ # return df[df[PARENT_DATASET_ID] == parent_id].drop(PARENT_DATASET_ID, 1) # # PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
self.dframe = self.dframe.join(column)
Predict the next line after this snippet: <|code_start|> def test_add_parent_column(self): value = 1 self._add_bamboo_reserved_keys(value) for index, item in self.dframe[PARENT_DATASET_ID].iteritems(): self.assertEqual(item, value) def test_remove_reserved_keys(self): self._add_bamboo_reserved_keys() for key in BAMBOO_RESERVED_KEYS: self.assertTrue(key in self.dframe.columns) dframe = remove_reserved_keys(self.dframe) for key in BAMBOO_RESERVED_KEYS: self.assertFalse(key in dframe.columns) def test_remove_reserved_keys_exclusion(self): self._add_bamboo_reserved_keys() for key in BAMBOO_RESERVED_KEYS: self.assertTrue(key in self.dframe.columns) dframe = remove_reserved_keys(self.dframe, [PARENT_DATASET_ID]) for key in BAMBOO_RESERVED_KEYS: if key == PARENT_DATASET_ID: self.assertTrue(key in dframe.columns) else: <|code_end|> using the current file's imports: from pandas import Series from bamboo.core.frame import BAMBOO_RESERVED_KEYS, remove_reserved_keys,\ rows_for_parent_id, PARENT_DATASET_ID from bamboo.tests.test_base import TestBase and any relevant context from other files: # Path: bamboo/core/frame.py # BAMBOO_RESERVED_KEYS = [ # DATASET_ID, # INDEX, # PARENT_DATASET_ID, # ] # # def remove_reserved_keys(df, exclude=[]): # """Remove reserved internal columns in this DataFrame. # # :param keep_parent_ids: Keep parent column if True, default False. # """ # reserved_keys = __column_intersect( # df, BAMBOO_RESERVED_KEYS).difference(set(exclude)) # # return df.drop(reserved_keys, axis=1) # # def rows_for_parent_id(df, parent_id): # """DataFrame with only rows for `parent_id`. # # :param parent_id: The ID to restrict rows to. # # :returns: A DataFrame including only rows with a parent ID equal to # that passed in. # """ # return df[df[PARENT_DATASET_ID] == parent_id].drop(PARENT_DATASET_ID, 1) # # PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
self.assertFalse(key in dframe.columns)
Continue the code snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') def _add_bamboo_reserved_keys(self, value=1): for key in BAMBOO_RESERVED_KEYS: column = Series([value] * len(self.dframe)) <|code_end|> . Use current file imports: from pandas import Series from bamboo.core.frame import BAMBOO_RESERVED_KEYS, remove_reserved_keys,\ rows_for_parent_id, PARENT_DATASET_ID from bamboo.tests.test_base import TestBase and context (classes, functions, or code) from other files: # Path: bamboo/core/frame.py # BAMBOO_RESERVED_KEYS = [ # DATASET_ID, # INDEX, # PARENT_DATASET_ID, # ] # # def remove_reserved_keys(df, exclude=[]): # """Remove reserved internal columns in this DataFrame. # # :param keep_parent_ids: Keep parent column if True, default False. # """ # reserved_keys = __column_intersect( # df, BAMBOO_RESERVED_KEYS).difference(set(exclude)) # # return df.drop(reserved_keys, axis=1) # # def rows_for_parent_id(df, parent_id): # """DataFrame with only rows for `parent_id`. # # :param parent_id: The ID to restrict rows to. # # :returns: A DataFrame including only rows with a parent ID equal to # that passed in. # """ # return df[df[PARENT_DATASET_ID] == parent_id].drop(PARENT_DATASET_ID, 1) # # PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
column.name = key
Next line prediction: <|code_start|> def test_remove_reserved_keys(self): self._add_bamboo_reserved_keys() for key in BAMBOO_RESERVED_KEYS: self.assertTrue(key in self.dframe.columns) dframe = remove_reserved_keys(self.dframe) for key in BAMBOO_RESERVED_KEYS: self.assertFalse(key in dframe.columns) def test_remove_reserved_keys_exclusion(self): self._add_bamboo_reserved_keys() for key in BAMBOO_RESERVED_KEYS: self.assertTrue(key in self.dframe.columns) dframe = remove_reserved_keys(self.dframe, [PARENT_DATASET_ID]) for key in BAMBOO_RESERVED_KEYS: if key == PARENT_DATASET_ID: self.assertTrue(key in dframe.columns) else: self.assertFalse(key in dframe.columns) def test_only_rows_for_parent_id(self): parent_id = 1 len_parent_rows = len(self.dframe) / 2 <|code_end|> . Use current file imports: (from pandas import Series from bamboo.core.frame import BAMBOO_RESERVED_KEYS, remove_reserved_keys,\ rows_for_parent_id, PARENT_DATASET_ID from bamboo.tests.test_base import TestBase) and context including class names, function names, or small code snippets from other files: # Path: bamboo/core/frame.py # BAMBOO_RESERVED_KEYS = [ # DATASET_ID, # INDEX, # PARENT_DATASET_ID, # ] # # def remove_reserved_keys(df, exclude=[]): # """Remove reserved internal columns in this DataFrame. # # :param keep_parent_ids: Keep parent column if True, default False. # """ # reserved_keys = __column_intersect( # df, BAMBOO_RESERVED_KEYS).difference(set(exclude)) # # return df.drop(reserved_keys, axis=1) # # def rows_for_parent_id(df, parent_id): # """DataFrame with only rows for `parent_id`. # # :param parent_id: The ID to restrict rows to. # # :returns: A DataFrame including only rows with a parent ID equal to # that passed in. # """ # return df[df[PARENT_DATASET_ID] == parent_id].drop(PARENT_DATASET_ID, 1) # # PARENT_DATASET_ID = BAMBOO_RESERVED_KEY_PREFIX + 'parent_dataset_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
column = Series([parent_id] * len_parent_rows)
Given snippet: <|code_start|> class TestVersion(TestBase): def setUp(self): TestBase.setUp(self) self.controller = Version() def test_index(self): response = json.loads(self.controller.index()) response_keys = response.keys() keys = [ 'version', 'description', <|code_end|> , continue by predicting the next line. Consider current file imports: import json from bamboo.controllers.version import Version from bamboo.tests.test_base import TestBase and context: # Path: bamboo/controllers/version.py # class Version(AbstractController): # # def index(self): # """Return JSON of version and version description""" # return self._dump_or_error(get_version()) # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex which might include code, classes, or functions. Output only the next line.
'branch',
Predict the next line for this snippet: <|code_start|> class TestVersion(TestBase): def setUp(self): TestBase.setUp(self) self.controller = Version() def test_index(self): response = json.loads(self.controller.index()) response_keys = response.keys() keys = [ 'version', <|code_end|> with the help of current file imports: import json from bamboo.controllers.version import Version from bamboo.tests.test_base import TestBase and context from other files: # Path: bamboo/controllers/version.py # class Version(AbstractController): # # def index(self): # """Return JSON of version and version description""" # return self._dump_or_error(get_version()) # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex , which may contain function names, class names, or code. Output only the next line.
'description',
Given snippet: <|code_start|># template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os from bamboo.lib.version import VERSION_NUMBER, VERSION_DESCRIPTION and context: # Path: bamboo/lib/version.py # VERSION_NUMBER = '%.1f.%d' % (VERSION_MAJOR, VERSION_MINOR) # # VERSION_DESCRIPTION = 'alpha' which might include code, classes, or functions. Output only the next line.
htmlhelp_basename = 'bamboodoc'
Given the code snippet: <|code_start|>#html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'bamboodoc' # -- Options for LaTeX output ------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]) latex_documents = [ <|code_end|> , generate the next line using the imports in this file: import sys import os from bamboo.lib.version import VERSION_NUMBER, VERSION_DESCRIPTION and context (functions, classes, or occasionally code) from other files: # Path: bamboo/lib/version.py # VERSION_NUMBER = '%.1f.%d' % (VERSION_MAJOR, VERSION_MINOR) # # VERSION_DESCRIPTION = 'alpha' . Output only the next line.
('index', 'bamboo.tex', u'bamboo Documentation',
Next line prediction: <|code_start|> BROKER_BACKEND = 'mongodb' BROKER_URL = 'mongodb://localhost:27017/%s' % settings.DATABASE_NAME CELERY_RESULT_BACKEND = 'mongodb' CELERY_MONGODB_BACKEND_SETTINGS = { 'host': 'localhost', 'port': 27017, 'database': settings.DATABASE_NAME, 'taskmeta_collection': 'celery_tasks', } <|code_end|> . Use current file imports: (from bamboo.config import settings) and context including class names, function names, or small code snippets from other files: # Path: bamboo/config/settings.py # ASYNC_FLAG = 'BAMBOO_ASYNC_OFF' # DATABASE_NAME = 'bamboo_dev' # TEST_DATABASE_NAME = DATABASE_NAME + '_test' # DATABASE_NAME = TEST_DATABASE_NAME # RUN_PROFILER = False . Output only the next line.
CELERY_IMPORTS = (
Using the snippet: <|code_start|> ERROR_RESPONSE_BODY = """ <html><body><p>Sorry, an error occured. We are working to resolve it. </p><p>For more help please email the <a href= 'https://groups.google.com/forum/#!forum/bamboo-dev'>bamboo-dev list</a></p></body></html>""" def handle_error(): cherrypy.response.status = 500 cherrypy.response.body = [ERROR_RESPONSE_BODY] send_mail('smtp.googlemail.com', 'bamboo.errors', 'test-password', 'bamboo-errors@googlegroups.com', 'bamboo.errors@gmail.com', <|code_end|> , determine the next line of code. You have imports: import cherrypy from bamboo.lib.mail import send_mail and context (class names, function names, or code) available: # Path: bamboo/lib/mail.py # def send_mail(smtp_server, mailbox_name, mailbox_password, recipient, sender, # subject, body): # msg = __format_message(recipient, sender, subject, body) # # server = smtplib.SMTP(smtp_server, 587) # server.ehlo() # server.starttls() # server.ehlo() # server.login(mailbox_name, mailbox_password) # server.sendmail(sender, recipient, msg) # server.close() . Output only the next line.
'[ERROR] 500 Error in Bamboo',
Based on the snippet: <|code_start|> def requires_async(func): @wraps(func) def wrapper(*args, **kwargs): set_async(True) result = func(*args, **kwargs) set_async(False) <|code_end|> , predict the immediate next line with the help of imports: from functools import wraps from bamboo.config.settings import RUN_PROFILER from bamboo.lib.async import set_async import time and context (classes, functions, sometimes code) from other files: # Path: bamboo/config/settings.py # RUN_PROFILER = False # # Path: bamboo/lib/async.py # def set_async(on): # if on: # if not is_async(): # del os.environ[ASYNC_FLAG] # else: # os.environ[ASYNC_FLAG] = 'True' . Output only the next line.
return result
Here is a snippet: <|code_start|> def requires_async(func): @wraps(func) def wrapper(*args, **kwargs): set_async(True) result = func(*args, **kwargs) set_async(False) return result return wrapper def run_profiler(func): @wraps(func) def wrapper(*args, **kwargs): if RUN_PROFILER: return func(*args, **kwargs) <|code_end|> . Write the next line using the current file imports: from functools import wraps from bamboo.config.settings import RUN_PROFILER from bamboo.lib.async import set_async import time and context from other files: # Path: bamboo/config/settings.py # RUN_PROFILER = False # # Path: bamboo/lib/async.py # def set_async(on): # if on: # if not is_async(): # del os.environ[ASYNC_FLAG] # else: # os.environ[ASYNC_FLAG] = 'True' , which may include functions, classes, or code. Output only the next line.
return wrapper
Next line prediction: <|code_start|> 'std(amount)': ['amount'], 'max(amount)': ['amount'], 'mean(amount)': ['amount'], 'median(amount)': ['amount'], 'min(amount)': ['amount'], 'sum(amount)': ['amount'], 'sum(gps_latitude)': ['gps_latitude'], 'ratio(amount, gps_latitude)': ['amount', 'gps_latitude'], 'sum(risk_factor in ["low_risk"])': ['risk_factor'], 'ratio(risk_factor in ["low_risk"], risk_factor in ["low_risk",' ' "medium_risk"])': ['risk_factor'], 'ratio(risk_factor in ["low_risk"], 1)': ['risk_factor'], 'count(risk_factor in ["low_risk"])': ['risk_factor'], 'count()': [], 'argmax(submit_date)': ['submit_date'], 'newest(submit_date, amount)': ['amount', 'submit_date'], } class TestAggregations(TestCalculator): AGGREGATION_RESULTS = { 'var(amount)': 132918.536184, 'std(amount)': 364.57994, 'max(amount)': 1600, 'mean(amount)': 105.65789473684211, 'median(amount)': 12, 'min(amount)': 2.0, 'sum(amount)': 2007.5, 'sum(gps_latitude)': 624.089497667, <|code_end|> . Use current file imports: (from collections import defaultdict from bamboo.tests.core.test_calculator import TestCalculator import pickle import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: bamboo/tests/core/test_calculator.py # class TestCalculator(TestBase): # # def setUp(self): # TestBase.setUp(self) # self.dataset = Dataset() # self.dataset.save( # self.test_dataset_ids['good_eats_with_calculations.csv']) # dframe = recognize_dates( # self.get_data('good_eats_with_calculations.csv')) # self.dataset.save_observations(dframe) # self.group = None # self.places = 5 # # def _equal_msg(self, calculated, stored, formula): # return '(calculated %s) %s != (stored %s) %s ' % (type(calculated), # calculated, type(stored), stored) +\ # '(within %s places), formula: %s' % (self.places, formula) # # def _test_calculator(self): # self.dframe = self.dataset.dframe() # # columns = self.dframe.columns.tolist() # self.start_num_cols = len(columns) # self.added_num_cols = 0 # # column_labels_to_slugs = { # column_attrs[Dataset.LABEL]: (column_name) for # (column_name, column_attrs) in self.dataset.schema.items() # } # self.label_list, self.slugified_key_list = [ # list(ary) for ary in zip(*column_labels_to_slugs.items()) # ] # # for idx, formula in enumerate(self.calculations): # name = 'test-%s' % idx # # Parser.validate_formula(formula, self.dataset) # # calculation = Calculation() # calculation.save(self.dataset, formula, name, self.group) # self.now = now() # calculate_columns(self.dataset, [calculation]) # # self.column_labels_to_slugs = self.dataset.schema.labels_to_slugs # # self._test_calculation_results(name, formula) . Output only the next line.
'ratio(amount, gps_latitude)': 3.184639,
Predict the next line after this snippet: <|code_start|> class TestBamboo(TestBase): def setUp(self): TestBase.setUp(self) def test_bambooapp(self): # this tests that importing bamboo.bambooapp succeeds pass def test_pep8(self): result = call(['pep8', '.']) <|code_end|> using the current file's imports: from subprocess import call from bamboo.tests.test_base import TestBase from bamboo import bambooapp # nopep8 and any relevant context from other files: # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex # # Path: bamboo/bambooapp.py . Output only the next line.
self.assertEqual(result, 0, "Code is not pep8.")
Given the following code snippet before the placeholder: <|code_start|> def group_join(groups, left, other): if groups: other.set_index(groups, inplace=True) <|code_end|> , predict the next line using imports from the current file: from pandas import concat from bamboo.core.aggregations import AGGREGATIONS from bamboo.core.frame import add_parent_column, rows_for_parent_id from bamboo.lib.parsing import parse_columns and context including class names, function names, and sometimes code from other files: # Path: bamboo/core/aggregations.py # AGGREGATIONS = { # cls.formula_name: cls for cls in # Aggregation.__subclasses__() # if cls.formula_name # } # # Path: bamboo/core/frame.py # def add_parent_column(df, parent_dataset_id): # """Add parent ID column to this DataFrame.""" # return add_constant_column(df, parent_dataset_id, PARENT_DATASET_ID) # # def rows_for_parent_id(df, parent_id): # """DataFrame with only rows for `parent_id`. # # :param parent_id: The ID to restrict rows to. # # :returns: A DataFrame including only rows with a parent ID equal to # that passed in. # """ # return df[df[PARENT_DATASET_ID] == parent_id].drop(PARENT_DATASET_ID, 1) # # Path: bamboo/lib/parsing.py # def parse_columns(dataset, formula, name, dframe=None, no_index=False): # """Parse a formula and return columns resulting from its functions. # # Parse a formula into a list of functions then apply those functions to # the Data Frame and return the resulting columns. # # :param formula: The formula to parse. # :param name: Name of the formula. # :param dframe: A DataFrame to apply functions to. # :param no_index: Drop the index on result columns. # """ # functions = Parser.parse_functions(formula) # dependent_columns = Parser.dependent_columns(formula, dataset) # # # make select from dependent_columns # if dframe is None: # select = {col: 1 for col in dependent_columns or [MONGO_ID]} # # dframe = dataset.dframe( # query_args=QueryArgs(select=select), # keep_mongo_keys=True).set_index(MONGO_ID_ENCODED) # # if not dependent_columns: # # constant column, use dummy # dframe['dummy'] = 0 # # return __build_columns(dataset, dframe, functions, name, no_index) . Output only the next line.
return left.join(other, on=groups if len(groups) else None)
Based on the snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') <|code_end|> , predict the immediate next line with the help of imports: from bamboo.lib.jsontools import df_to_json, df_to_jsondict from bamboo.tests.test_base import TestBase and context (classes, functions, sometimes code) from other files: # Path: bamboo/lib/jsontools.py # def df_to_json(df): # """Convert DataFrame to a list of dicts, then dump to JSON.""" # jsondict = df_to_jsondict(df) # return dump_mongo_json(jsondict) # # def df_to_jsondict(df): # """Return DataFrame as a list of dicts for each row.""" # return [series_to_jsondict(series) for _, series in df.iterrows()] # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
def test_to_jsondict(self):
Continue the code snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') <|code_end|> . Use current file imports: from bamboo.lib.jsontools import df_to_json, df_to_jsondict from bamboo.tests.test_base import TestBase and context (classes, functions, or code) from other files: # Path: bamboo/lib/jsontools.py # def df_to_json(df): # """Convert DataFrame to a list of dicts, then dump to JSON.""" # jsondict = df_to_jsondict(df) # return dump_mongo_json(jsondict) # # def df_to_jsondict(df): # """Return DataFrame as a list of dicts for each row.""" # return [series_to_jsondict(series) for _, series in df.iterrows()] # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
def test_to_jsondict(self):
Using the snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') <|code_end|> , determine the next line of code. You have imports: from bamboo.lib.jsontools import df_to_json, df_to_jsondict from bamboo.tests.test_base import TestBase and context (class names, function names, or code) available: # Path: bamboo/lib/jsontools.py # def df_to_json(df): # """Convert DataFrame to a list of dicts, then dump to JSON.""" # jsondict = df_to_jsondict(df) # return dump_mongo_json(jsondict) # # def df_to_jsondict(df): # """Return DataFrame as a list of dicts for each row.""" # return [series_to_jsondict(series) for _, series in df.iterrows()] # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
def test_to_jsondict(self):
Using the snippet: <|code_start|> def parse_order_by(order_by): if order_by: if order_by[0] in ('-', '+'): sort_dir, field = -1 if order_by[0] == '-' else 1, order_by[1:] else: sort_dir, field = 1, order_by order_by = [(field, sort_dir)] return order_by <|code_end|> , determine the next line of code. You have imports: from dateutil import parser from time import mktime from bamboo.lib.utils import combine_dicts, replace_keys and context (class names, function names, or code) available: # Path: bamboo/lib/utils.py # def combine_dicts(*dicts): # """Combine dicts with keys in later dicts taking precedence.""" # return dict(chain(*[_dict.iteritems() for _dict in dicts])) # # def replace_keys(original, mapping): # """Recursively replace any keys in original with their values in mappnig. # # :param original: The dictionary to replace keys in. # :param mapping: A dict mapping keys to new keys. # # :returns: Original with keys replaced via mapping. # """ # return original if not type(original) in (dict, list) else { # mapping.get(k, k): { # dict: lambda: replace_keys(v, mapping), # list: lambda: [replace_keys(vi, mapping) for vi in v] # }.get(type(v), lambda: v)() for k, v in original.iteritems()} . Output only the next line.
def parse_dates_from_query(query, dataset):
Given the following code snippet before the placeholder: <|code_start|> def parse_order_by(order_by): if order_by: if order_by[0] in ('-', '+'): sort_dir, field = -1 if order_by[0] == '-' else 1, order_by[1:] else: sort_dir, field = 1, order_by <|code_end|> , predict the next line using imports from the current file: from dateutil import parser from time import mktime from bamboo.lib.utils import combine_dicts, replace_keys and context including class names, function names, and sometimes code from other files: # Path: bamboo/lib/utils.py # def combine_dicts(*dicts): # """Combine dicts with keys in later dicts taking precedence.""" # return dict(chain(*[_dict.iteritems() for _dict in dicts])) # # def replace_keys(original, mapping): # """Recursively replace any keys in original with their values in mappnig. # # :param original: The dictionary to replace keys in. # :param mapping: A dict mapping keys to new keys. # # :returns: Original with keys replaced via mapping. # """ # return original if not type(original) in (dict, list) else { # mapping.get(k, k): { # dict: lambda: replace_keys(v, mapping), # list: lambda: [replace_keys(vi, mapping) for vi in v] # }.get(type(v), lambda: v)() for k, v in original.iteritems()} . Output only the next line.
order_by = [(field, sort_dir)]
Given the code snippet: <|code_start|> class TestDecorators(TestBase): def setUp(self): def test_func(): <|code_end|> , generate the next line using the imports in this file: from bamboo.tests import decorators as test_decorators from bamboo.tests.test_base import TestBase and context (functions, classes, or occasionally code) from other files: # Path: bamboo/tests/decorators.py # def requires_async(func): # def wrapper(*args, **kwargs): # def run_profiler(func): # def wrapper(*args, **kwargs): # def print_time(func): # def wrapper(*args, **kwargs): # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
pass
Using the snippet: <|code_start|> class TestDecorators(TestBase): def setUp(self): def test_func(): pass self._test_func = test_func def _test_decorator(self, func): wrapped_test_func = func(self._test_func) self.assertTrue(hasattr(wrapped_test_func, '__call__')) <|code_end|> , determine the next line of code. You have imports: from bamboo.tests import decorators as test_decorators from bamboo.tests.test_base import TestBase and context (class names, function names, or code) available: # Path: bamboo/tests/decorators.py # def requires_async(func): # def wrapper(*args, **kwargs): # def run_profiler(func): # def wrapper(*args, **kwargs): # def print_time(func): # def wrapper(*args, **kwargs): # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
wrapped_test_func()
Predict the next line for this snippet: <|code_start|># future must be first from __future__ import division def extract_binary_children(parent): children = [parent.value[0]] for oper, val in parent.operator_operands(parent.value[1:]): children.append(val) <|code_end|> with the help of current file imports: import operator import numpy as np from scipy.stats import percentileofscore from bamboo.lib.datetools import now, parse_date_to_unix_time,\ parse_str_to_unix_time, safe_parse_date_to_unix_time from bamboo.lib.query_args import QueryArgs from bamboo.lib.utils import parse_float and context from other files: # Path: bamboo/lib/datetools.py # def now(): # return datetime.now() # # def parse_date_to_unix_time(date): # return timegm(date.utctimetuple()) # # def parse_str_to_unix_time(value): # return parse_date_to_unix_time(date_parse(value)) # # def safe_parse_date_to_unix_time(date): # if isinstance(date, datetime): # date = parse_date_to_unix_time(date) # # return date # # Path: bamboo/lib/query_args.py # class QueryArgs(object): # def __init__(self, query=None, select=None, distinct=None, limit=0, # order_by=None, dataset=None): # """A holder for query arguments. # # :param query: An optional query. # :param select: An optional select to limit the fields in the dframe. # :param distinct: Return distinct entries for this field. # :param limit: Limit on the number of rows in the returned dframe. # :param order_by: Sort resulting rows according to a column value and # sign indicating ascending or descending. # # Example of `order_by`: # # - ``order_by='mycolumn'`` # - ``order_by='-mycolumn'`` # """ # self.query = parse_dates_from_query(query, dataset) # self.select = select # self.distinct = distinct # self.limit = limit # self.order_by = parse_order_by(order_by) # # def encode(self, encoding, query): # """Encode query, order_by, and select given an encoding. # # The query will be combined with the existing query. # # :param encoding: A dict to encode the QueryArgs fields with. # :param query: An additional dict to combine with the existing query. # """ # self.query = replace_keys(combine_dicts(self.query, query), encoding) # self.order_by = self.order_by and replace_keys(dict(self.order_by), # encoding).items() # self.select = self.select and replace_keys(self.select, encoding) # # def __nonzero__(self): # return bool(self.query or self.select or self.distinct or self.limit # or self.order_by) # # Path: bamboo/lib/utils.py # def parse_float(value, default=None): # return _parse_type(np.float64, value, default) , which may contain function names, class names, or code. Output only the next line.
return children
Next line prediction: <|code_start|># future must be first from __future__ import division def extract_binary_children(parent): children = [parent.value[0]] for oper, val in parent.operator_operands(parent.value[1:]): children.append(val) return children <|code_end|> . Use current file imports: (import operator import numpy as np from scipy.stats import percentileofscore from bamboo.lib.datetools import now, parse_date_to_unix_time,\ parse_str_to_unix_time, safe_parse_date_to_unix_time from bamboo.lib.query_args import QueryArgs from bamboo.lib.utils import parse_float) and context including class names, function names, or small code snippets from other files: # Path: bamboo/lib/datetools.py # def now(): # return datetime.now() # # def parse_date_to_unix_time(date): # return timegm(date.utctimetuple()) # # def parse_str_to_unix_time(value): # return parse_date_to_unix_time(date_parse(value)) # # def safe_parse_date_to_unix_time(date): # if isinstance(date, datetime): # date = parse_date_to_unix_time(date) # # return date # # Path: bamboo/lib/query_args.py # class QueryArgs(object): # def __init__(self, query=None, select=None, distinct=None, limit=0, # order_by=None, dataset=None): # """A holder for query arguments. # # :param query: An optional query. # :param select: An optional select to limit the fields in the dframe. # :param distinct: Return distinct entries for this field. # :param limit: Limit on the number of rows in the returned dframe. # :param order_by: Sort resulting rows according to a column value and # sign indicating ascending or descending. # # Example of `order_by`: # # - ``order_by='mycolumn'`` # - ``order_by='-mycolumn'`` # """ # self.query = parse_dates_from_query(query, dataset) # self.select = select # self.distinct = distinct # self.limit = limit # self.order_by = parse_order_by(order_by) # # def encode(self, encoding, query): # """Encode query, order_by, and select given an encoding. # # The query will be combined with the existing query. # # :param encoding: A dict to encode the QueryArgs fields with. # :param query: An additional dict to combine with the existing query. # """ # self.query = replace_keys(combine_dicts(self.query, query), encoding) # self.order_by = self.order_by and replace_keys(dict(self.order_by), # encoding).items() # self.select = self.select and replace_keys(self.select, encoding) # # def __nonzero__(self): # return bool(self.query or self.select or self.distinct or self.limit # or self.order_by) # # Path: bamboo/lib/utils.py # def parse_float(value, default=None): # return _parse_type(np.float64, value, default) . Output only the next line.
class EvalTerm(object):
Based on the snippet: <|code_start|># future must be first from __future__ import division def extract_binary_children(parent): children = [parent.value[0]] for oper, val in parent.operator_operands(parent.value[1:]): <|code_end|> , predict the immediate next line with the help of imports: import operator import numpy as np from scipy.stats import percentileofscore from bamboo.lib.datetools import now, parse_date_to_unix_time,\ parse_str_to_unix_time, safe_parse_date_to_unix_time from bamboo.lib.query_args import QueryArgs from bamboo.lib.utils import parse_float and context (classes, functions, sometimes code) from other files: # Path: bamboo/lib/datetools.py # def now(): # return datetime.now() # # def parse_date_to_unix_time(date): # return timegm(date.utctimetuple()) # # def parse_str_to_unix_time(value): # return parse_date_to_unix_time(date_parse(value)) # # def safe_parse_date_to_unix_time(date): # if isinstance(date, datetime): # date = parse_date_to_unix_time(date) # # return date # # Path: bamboo/lib/query_args.py # class QueryArgs(object): # def __init__(self, query=None, select=None, distinct=None, limit=0, # order_by=None, dataset=None): # """A holder for query arguments. # # :param query: An optional query. # :param select: An optional select to limit the fields in the dframe. # :param distinct: Return distinct entries for this field. # :param limit: Limit on the number of rows in the returned dframe. # :param order_by: Sort resulting rows according to a column value and # sign indicating ascending or descending. # # Example of `order_by`: # # - ``order_by='mycolumn'`` # - ``order_by='-mycolumn'`` # """ # self.query = parse_dates_from_query(query, dataset) # self.select = select # self.distinct = distinct # self.limit = limit # self.order_by = parse_order_by(order_by) # # def encode(self, encoding, query): # """Encode query, order_by, and select given an encoding. # # The query will be combined with the existing query. # # :param encoding: A dict to encode the QueryArgs fields with. # :param query: An additional dict to combine with the existing query. # """ # self.query = replace_keys(combine_dicts(self.query, query), encoding) # self.order_by = self.order_by and replace_keys(dict(self.order_by), # encoding).items() # self.select = self.select and replace_keys(self.select, encoding) # # def __nonzero__(self): # return bool(self.query or self.select or self.distinct or self.limit # or self.order_by) # # Path: bamboo/lib/utils.py # def parse_float(value, default=None): # return _parse_type(np.float64, value, default) . Output only the next line.
children.append(val)
Predict the next line for this snippet: <|code_start|># future must be first from __future__ import division def extract_binary_children(parent): children = [parent.value[0]] for oper, val in parent.operator_operands(parent.value[1:]): <|code_end|> with the help of current file imports: import operator import numpy as np from scipy.stats import percentileofscore from bamboo.lib.datetools import now, parse_date_to_unix_time,\ parse_str_to_unix_time, safe_parse_date_to_unix_time from bamboo.lib.query_args import QueryArgs from bamboo.lib.utils import parse_float and context from other files: # Path: bamboo/lib/datetools.py # def now(): # return datetime.now() # # def parse_date_to_unix_time(date): # return timegm(date.utctimetuple()) # # def parse_str_to_unix_time(value): # return parse_date_to_unix_time(date_parse(value)) # # def safe_parse_date_to_unix_time(date): # if isinstance(date, datetime): # date = parse_date_to_unix_time(date) # # return date # # Path: bamboo/lib/query_args.py # class QueryArgs(object): # def __init__(self, query=None, select=None, distinct=None, limit=0, # order_by=None, dataset=None): # """A holder for query arguments. # # :param query: An optional query. # :param select: An optional select to limit the fields in the dframe. # :param distinct: Return distinct entries for this field. # :param limit: Limit on the number of rows in the returned dframe. # :param order_by: Sort resulting rows according to a column value and # sign indicating ascending or descending. # # Example of `order_by`: # # - ``order_by='mycolumn'`` # - ``order_by='-mycolumn'`` # """ # self.query = parse_dates_from_query(query, dataset) # self.select = select # self.distinct = distinct # self.limit = limit # self.order_by = parse_order_by(order_by) # # def encode(self, encoding, query): # """Encode query, order_by, and select given an encoding. # # The query will be combined with the existing query. # # :param encoding: A dict to encode the QueryArgs fields with. # :param query: An additional dict to combine with the existing query. # """ # self.query = replace_keys(combine_dicts(self.query, query), encoding) # self.order_by = self.order_by and replace_keys(dict(self.order_by), # encoding).items() # self.select = self.select and replace_keys(self.select, encoding) # # def __nonzero__(self): # return bool(self.query or self.select or self.distinct or self.limit # or self.order_by) # # Path: bamboo/lib/utils.py # def parse_float(value, default=None): # return _parse_type(np.float64, value, default) , which may contain function names, class names, or code. Output only the next line.
children.append(val)
Continue the code snippet: <|code_start|># future must be first from __future__ import division def extract_binary_children(parent): children = [parent.value[0]] for oper, val in parent.operator_operands(parent.value[1:]): children.append(val) <|code_end|> . Use current file imports: import operator import numpy as np from scipy.stats import percentileofscore from bamboo.lib.datetools import now, parse_date_to_unix_time,\ parse_str_to_unix_time, safe_parse_date_to_unix_time from bamboo.lib.query_args import QueryArgs from bamboo.lib.utils import parse_float and context (classes, functions, or code) from other files: # Path: bamboo/lib/datetools.py # def now(): # return datetime.now() # # def parse_date_to_unix_time(date): # return timegm(date.utctimetuple()) # # def parse_str_to_unix_time(value): # return parse_date_to_unix_time(date_parse(value)) # # def safe_parse_date_to_unix_time(date): # if isinstance(date, datetime): # date = parse_date_to_unix_time(date) # # return date # # Path: bamboo/lib/query_args.py # class QueryArgs(object): # def __init__(self, query=None, select=None, distinct=None, limit=0, # order_by=None, dataset=None): # """A holder for query arguments. # # :param query: An optional query. # :param select: An optional select to limit the fields in the dframe. # :param distinct: Return distinct entries for this field. # :param limit: Limit on the number of rows in the returned dframe. # :param order_by: Sort resulting rows according to a column value and # sign indicating ascending or descending. # # Example of `order_by`: # # - ``order_by='mycolumn'`` # - ``order_by='-mycolumn'`` # """ # self.query = parse_dates_from_query(query, dataset) # self.select = select # self.distinct = distinct # self.limit = limit # self.order_by = parse_order_by(order_by) # # def encode(self, encoding, query): # """Encode query, order_by, and select given an encoding. # # The query will be combined with the existing query. # # :param encoding: A dict to encode the QueryArgs fields with. # :param query: An additional dict to combine with the existing query. # """ # self.query = replace_keys(combine_dicts(self.query, query), encoding) # self.order_by = self.order_by and replace_keys(dict(self.order_by), # encoding).items() # self.select = self.select and replace_keys(self.select, encoding) # # def __nonzero__(self): # return bool(self.query or self.select or self.distinct or self.limit # or self.order_by) # # Path: bamboo/lib/utils.py # def parse_float(value, default=None): # return _parse_type(np.float64, value, default) . Output only the next line.
return children
Given the code snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) <|code_end|> , generate the next line using the imports in this file: from bamboo.lib.mongo import df_mongo_decode, MONGO_ID from bamboo.tests.test_base import TestBase and context (functions, classes, or occasionally code) from other files: # Path: bamboo/lib/mongo.py # def df_mongo_decode(df, keep_mongo_keys=False): # """Decode MongoDB reserved keys in this DataFrame.""" # rename_dict = {} # # if MONGO_ID in df.columns: # if keep_mongo_keys: # df.rename(columns={MONGO_ID: MONGO_ID_ENCODED, # MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # else: # del df[MONGO_ID] # if MONGO_ID_ENCODED in df.columns: # rename_dict[MONGO_ID_ENCODED] = MONGO_ID # # if rename_dict: # df.rename(columns={MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # # return df # # MONGO_ID = '_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
self.dframe = self.get_data('good_eats.csv')
Here is a snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') <|code_end|> . Write the next line using the current file imports: from bamboo.lib.mongo import df_mongo_decode, MONGO_ID from bamboo.tests.test_base import TestBase and context from other files: # Path: bamboo/lib/mongo.py # def df_mongo_decode(df, keep_mongo_keys=False): # """Decode MongoDB reserved keys in this DataFrame.""" # rename_dict = {} # # if MONGO_ID in df.columns: # if keep_mongo_keys: # df.rename(columns={MONGO_ID: MONGO_ID_ENCODED, # MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # else: # del df[MONGO_ID] # if MONGO_ID_ENCODED in df.columns: # rename_dict[MONGO_ID_ENCODED] = MONGO_ID # # if rename_dict: # df.rename(columns={MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # # return df # # MONGO_ID = '_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex , which may include functions, classes, or code. Output only the next line.
def test_decode_reserved_keys(self):
Predict the next line after this snippet: <|code_start|> class TestFrame(TestBase): def setUp(self): TestBase.setUp(self) self.dframe = self.get_data('good_eats.csv') <|code_end|> using the current file's imports: from bamboo.lib.mongo import df_mongo_decode, MONGO_ID from bamboo.tests.test_base import TestBase and any relevant context from other files: # Path: bamboo/lib/mongo.py # def df_mongo_decode(df, keep_mongo_keys=False): # """Decode MongoDB reserved keys in this DataFrame.""" # rename_dict = {} # # if MONGO_ID in df.columns: # if keep_mongo_keys: # df.rename(columns={MONGO_ID: MONGO_ID_ENCODED, # MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # else: # del df[MONGO_ID] # if MONGO_ID_ENCODED in df.columns: # rename_dict[MONGO_ID_ENCODED] = MONGO_ID # # if rename_dict: # df.rename(columns={MONGO_ID_ENCODED: MONGO_ID}, inplace=True) # # return df # # MONGO_ID = '_id' # # Path: bamboo/tests/test_base.py # class TestBase(unittest.TestCase): # # FIXTURE_PATH = 'tests/fixtures/' # SLEEP_DELAY = 0.2 # TEST_DATASETS = [ # 'good_eats.csv', # 'good_eats_large.csv', # 'good_eats_with_calculations.csv', # 'kenya_secondary_schools_2007.csv', # 'soil_samples.csv', # 'water_points.csv', # 'unicode.csv', # ] # # test_dataset_ids = {} # # def setUp(self): # self.__drop_database() # self.__create_database() # self.__load_test_data() # # def tearDown(self): # self.__drop_database() # # def get_data(self, dataset_name): # return read_csv('%s%s' % (self._local_fixture_prefix(), dataset_name), # encoding='utf-8') # # def _create_dataset_from_url(self, url): # dataset = Dataset.create() # return dataset.import_from_url(url, allow_local_file=True).dataset_id # # def _local_fixture_prefix(self, filename=''): # return 'file://localhost%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _fixture_path_prefix(self, filename=''): # return '/%s/tests/fixtures/%s' % (os.getcwd(), filename) # # def _file_mock(self, file_path, add_prefix=False): # if add_prefix: # file_path = self._fixture_path_prefix(file_path) # # file_ = open(file_path, 'r') # # return MockUploadedFile(file_) # # def _post_file(self, file_name='good_eats.csv'): # dataset = Dataset.create() # return dataset.import_from_csv( # self._file_mock(self._fixture_path_prefix(file_name))).dataset_id # # def _wait_for_dataset_state(self, dataset_id): # while True: # dataset = Dataset.find_one(dataset_id) # # if dataset.state != Dataset.STATE_PENDING: # break # # sleep(self.SLEEP_DELAY) # # return dataset # # def __create_database(self): # Database.db(TEST_DATABASE_NAME) # # def __drop_database(self): # Database.client().drop_database(TEST_DATABASE_NAME) # # def __load_test_data(self): # for dataset_name in self.TEST_DATASETS: # self.test_dataset_ids[dataset_name] = uuid.uuid4().hex . Output only the next line.
def test_decode_reserved_keys(self):
Continue the code snippet: <|code_start|>#!/usr/bin/env python sys.path.append(os.getcwd()) # use routes dispatcher dispatcher = cherrypy.dispatch.RoutesDispatcher() routes_conf = {'/': {'request.dispatch': dispatcher}} local_conf = 'bamboo/config/local.conf' # connect routes connect_routes(dispatcher) # global config cherrypy.config.update(routes_conf) cherrypy.config.update(local_conf) # app config app = cherrypy.tree.mount(root=None, config=routes_conf) <|code_end|> . Use current file imports: import os import sys import cherrypy from bamboo.config.routes import connect_routes and context (classes, functions, or code) from other files: # Path: bamboo/config/routes.py # def connect_routes(dispatcher): # """This function takes the dispatcher and attaches the routes. # # :param dispatcher: The CherryPy dispatcher. # """ # # controller instances map # controllers = { # 'root': Root(), # 'calculations': Calculations(), # 'datasets': Datasets(), # 'version': Version(), # } # # # map them into args to dispatcher # dictify = lambda x: dict(zip( # ['name', 'conditions', 'route', 'controller', 'action'], x)) # route_case = { # 'conditions': lambda v: dict(method=v), # 'controller': lambda v: controllers[v], # } # kwarg_map = lambda d: { # k: route_case.get(k, lambda v: v)(v) for k, v in d.iteritems() # } # # routes = [kwarg_map(dictify(route)) for route in ROUTES + options()] # # # attach them # for route in routes: # dispatcher.connect(**route) . Output only the next line.
app.merge(local_conf)
Predict the next line after this snippet: <|code_start|> register = Library() class MainMenuItemURLNode(Node): def __init__(self, content_type): self.content_type = Variable(content_type) def render(self, context): try: content_type = self.content_type.resolve(context) <|code_end|> using the current file's imports: from django.core.urlresolvers import reverse, NoReverseMatch from django.template import Library, Variable, Node from django.template import TemplateSyntaxError, VariableDoesNotExist from django.template.defaulttags import URLNode from ..models import MenuItem from ..settings import CONFIG and any relevant context from other files: # Path: lemon/models.py # class MenuItem(models.Model): # # name = models.CharField(_('item name'), max_length=50) # content_type = models.ForeignKey(ContentType, # verbose_name=_('content type')) # section = models.ForeignKey(MenuSection, related_name='sections', # verbose_name=_('section')) # position = models.PositiveIntegerField(_('position'), default=0) # # class Meta: # ordering = ['position'] # verbose_name = _('menu item') # verbose_name_plural = _('menu items') # # def __unicode__(self): # return self.name # # Path: lemon/settings.py # CONFIG = { # 'MARKUP_WIDGET': None, # 'MENU_LINKS': (), # } . Output only the next line.
except VariableDoesNotExist:
Here is a snippet: <|code_start|> class MainMenuItemURLNode(Node): def __init__(self, content_type): self.content_type = Variable(content_type) def render(self, context): try: content_type = self.content_type.resolve(context) except VariableDoesNotExist: return '' opts = content_type.model_class()._meta app_label = opts.app_label module_name = opts.module_name view_name = 'admin:%s_%s_changelist' % \ (app_label, module_name) try: return reverse(view_name) except NoReverseMatch: return '' @register.inclusion_tag('lemon/main_menu.html') def main_menu(): queryset = MenuItem.objects.select_related('section', 'content_type') queryset = queryset.order_by('section__position', 'position') return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']} <|code_end|> . Write the next line using the current file imports: from django.core.urlresolvers import reverse, NoReverseMatch from django.template import Library, Variable, Node from django.template import TemplateSyntaxError, VariableDoesNotExist from django.template.defaulttags import URLNode from ..models import MenuItem from ..settings import CONFIG and context from other files: # Path: lemon/models.py # class MenuItem(models.Model): # # name = models.CharField(_('item name'), max_length=50) # content_type = models.ForeignKey(ContentType, # verbose_name=_('content type')) # section = models.ForeignKey(MenuSection, related_name='sections', # verbose_name=_('section')) # position = models.PositiveIntegerField(_('position'), default=0) # # class Meta: # ordering = ['position'] # verbose_name = _('menu item') # verbose_name_plural = _('menu items') # # def __unicode__(self): # return self.name # # Path: lemon/settings.py # CONFIG = { # 'MARKUP_WIDGET': None, # 'MENU_LINKS': (), # } , which may include functions, classes, or code. Output only the next line.
@register.tag
Here is a snippet: <|code_start|> class Meta(object): fields = ['content_type', 'name', 'position'] def __init__(self, *args, **kwargs): qs = ContentType.objects.all() content_type = ContentTypeChoiceField( self.admin_site, qs, label=_('content type') ) self.base_fields['content_type'] = content_type super(MenuItemForm, self).__init__(*args, **kwargs) formfield_callback = lambda f: f.formfield() def contenttype_inlineformset_factory(parent_model, model, admin_site, formfield_callback, extra=3, can_order=False, can_delete=True, max_num=0): fk = _get_foreign_key(parent_model, model) Meta = type('Meta', (MenuItemForm.Meta,), {'model': model}) class_name = model.__name__ + 'Form' form_class_attrs = { 'admin_site': admin_site, 'Meta': Meta, 'formfield_callback': formfield_callback } form = ModelFormMetaclass(class_name, (MenuItemForm,), form_class_attrs) FormSet = formset_factory(form, BaseInlineFormSet, extra=extra, max_num=max_num, <|code_end|> . Write the next line using the current file imports: from django import forms from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.forms.formsets import formset_factory from django.forms.models import BaseInlineFormSet from django.forms.models import ModelFormMetaclass, _get_foreign_key from django.utils.translation import ugettext_lazy as _ from .fields import ContentTypeChoiceField and context from other files: # Path: lemon/fields.py # class ContentTypeChoiceField(ModelChoiceField): # # def __init__(self, admin_site, *args, **kwargs): # self.admin_site = admin_site # super(ContentTypeChoiceField, self).__init__(*args, **kwargs) # # def _get_choices(self): # if hasattr(self, '_choices'): # return self._choices # return ContentTypeChoiceIterator(self.admin_site, self) # choices = property(_get_choices, ModelChoiceField._set_choices) , which may include functions, classes, or code. Output only the next line.
can_order=can_order, can_delete=can_delete)
Continue the code snippet: <|code_start|> class GenericInlineModelAdmin(generic.GenericInlineModelAdmin, InlineModelAdmin, BaseModelAdmin): pass class GenericStackedInline(GenericInlineModelAdmin): template = 'admin/edit_inline/stacked.html' <|code_end|> . Use current file imports: from django.contrib.contenttypes import generic from .options import BaseModelAdmin, InlineModelAdmin and context (classes, functions, or code) from other files: # Path: lemon/options.py # class BaseModelAdmin(options.BaseModelAdmin): # # markup_fields = () # markup_widget = None # # def __init__(self): # self.filter_vertical = () # self.filter_horizontal = () # if self.fieldsets: # self._fix_fieldsets() # overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() # overrides.update(self.formfield_overrides) # self.formfield_overrides = overrides # super(BaseModelAdmin, self).__init__() # # def _fix_fieldsets(self): # """ # Ugly hack for prevention of 'CollapsedFieldsets.js' inclusion. # """ # for name, options in self.fieldsets: # if 'classes' in options and 'collapse' in options['classes']: # classes = tuple(set(options['classes']) - set(['collapse'])) # options['classes'] = classes # # def formfield_for_dbfield(self, db_field, **kwargs): # request = kwargs.pop('request', None) # # if db_field.choices: # return self.formfield_for_choice_field(db_field, request, **kwargs) # # if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # if db_field.__class__ in self.formfield_overrides: # kwargs = dict( # self.formfield_overrides[db_field.__class__], **kwargs # ) # # if isinstance(db_field, models.ForeignKey): # formfield = self.formfield_for_foreignkey( # db_field, request, **kwargs # ) # elif isinstance(db_field, models.ManyToManyField): # formfield = self.formfield_for_manytomany( # db_field, request, **kwargs # ) # # if formfield and db_field.name not in self.raw_id_fields: # related_modeladmin = self.admin_site._registry.get( # db_field.rel.to, # ) # can_add_related = bool( # related_modeladmin and # related_modeladmin.has_add_permission(request) # ) # formfield.widget = widgets.RelatedFieldWidgetWrapper( # formfield.widget, db_field.rel, self.admin_site, # can_add_related=can_add_related) # return formfield # # markup_widget = self.get_markup_widget(request) # markup_fields = self.get_markup_fields(request) # if markup_widget and db_field.name in markup_fields: # kwargs = dict({'widget': markup_widget}, **kwargs) # return db_field.formfield(**kwargs) # # for klass in db_field.__class__.mro(): # if klass in self.formfield_overrides: # kwargs = dict(self.formfield_overrides[klass], **kwargs) # return db_field.formfield(**kwargs) # # return db_field.formfield(**kwargs) # # def formfield_for_foreignkey(self, db_field, request=None, **kwargs): # db = kwargs.get('using') # if db_field.name in self.raw_id_fields: # kwargs['widget'] = widgets.ForeignKeyRawIdWidget( # db_field.rel, self.admin_site, using=db) # elif db_field.name in self.radio_fields: # kwargs['widget'] = AdminRadioSelect(attrs={ # 'class': get_ul_class(self.radio_fields[db_field.name]), # }) # kwargs['empty_label'] = db_field.blank and _('None') or None # # return db_field.formfield(**kwargs) # # def get_markup_widget(self, request): # return self.markup_widget # # def get_markup_fields(self, request): # return self.markup_fields # # class InlineModelAdmin(options.InlineModelAdmin, BaseModelAdmin): # # def __init__(self, parent_model, admin_site): # super(InlineModelAdmin, self).__init__(parent_model, admin_site) # # @property # def media(self): # js = [static('lemon/js/jquery.inlines.js')] # if self.prepopulated_fields: # js.append(static('admin/js/urlify.js')) # js.append(static('lemon/js/jquery.prepopulate.js')) # return forms.Media(js=js) # # def get_markup_widget(self, request): # return self.markup_widget or self.admin_site.get_markup_widget(request) . Output only the next line.
class GenericTabularInline(GenericInlineModelAdmin):
Given the code snippet: <|code_start|> admin.autodiscover() urlpatterns = patterns('', # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), # (r'^scorecard/agency/(?P<agency_id>\d+)/', 'metrics.views.get_agency_detail'), # (r'^scorecard/program/(?P<program_id>\d+)/', 'metrics.views.get_program_detail'), url(r'^scorecard/$', 'metrics.views.index', name='scorecard-index'), url(r'^scorecard/(?P<unit>\w+)/(?P<fiscal_year>\d{4})/', 'metrics.views.index', name='scorecard-index-extra'), url(r'^bestprograms/(?P<fiscal_year>\d{4})/', 'metrics.views.list_best_programs', name='list-best-programs'), url(r'^results/', direct_to_template, {'template': 'analysis.html'}, name='analysis' ), url(r'^summary/$', direct_to_template, {'template': 'summary.html'}, name='summary' ), <|code_end|> , generate the next line using the imports in this file: from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.views.generic.list_detail import object_list from metrics.models import ProgramCorrection from django.contrib import admin import settings and context (functions, classes, or occasionally code) from other files: # Path: metrics/models.py # class ProgramCorrection(models.Model): # # program = models.ForeignKey('cfda.Program', null=False, blank=False) # program_obligation = models.ForeignKey('cfda.ProgramObligation', null=False, blank=False) # correction_date = models.DateTimeField(null=False, blank=False) # corrected_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # old_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # note = models.TextField("Notes on Correction", blank=True, null=True) . Output only the next line.
url(r'^methodology/', direct_to_template, {'template': 'methodology.html'}, name='methodology'),
Given snippet: <|code_start|>"""Defines the format for agency submission files to USASpending, along with a lazy record parser.""" class FAADSPlusFormat(object): # Based on table from memo m09-19 pages 14-15, which defines the # agency submission record format FIELDS = [ ('CFDA Program Number', 'cfda', 7), ('State Application Identifier (SAI Number)', 'sai', 20), ('Recipient Name', 'recipient_name', 45), ('Recipient City Code', 'recipient_city_code', 5), ('Recipient City Name', 'recipient_city_name', 21), ('Recipient County Code', 'recipient_county_code', 3), <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import re import hashlib from datetime import date from functools import partial from utils import Accumulator, DictSlicer and context: # Path: utils.py # class Accumulator(object): # """Simple callable that returns its current value.""" # def __init__(self, initial=0): # self.value = initial # # def __call__(self, incr=0): # oldvalue = self.value # self.value += incr # return oldvalue # # def getvalue(self): # return self.value # # class DictSlicer(object): # def __init__(self, *ks): # self.ks = ks # # def __call__(self, d): # return dict(((k, v) for (k, v) in d.iteritems() if k in self.ks)) which might include code, classes, or functions. Output only the next line.
('Recipient County Name', 'recipient_county_name', 21),
Next line prediction: <|code_start|> def find_possible_mistakes(): fins = Program.objects.filter(types_of_assistance__financial=True).distinct().order_by('agency') csv_out = csv.writer(open('greater_than_50_pct_change.csv', 'w')) for f in fins: <|code_end|> . Use current file imports: (from metrics.models import * from settings import FISCAL_YEARS from cfda.models import * from django.db.models import Sum from helpers.charts import Line from utils import pretty_money import csv) and context including class names, function names, or small code snippets from other files: # Path: helpers/charts.py # class Line(GridChart): # # def __init__(self, height, width, data, stylesheet=None, *args, **kwargs): # # super(Line, self).__init__(height, width, data, stylesheet, **kwargs) # # self.x_scale = self.set_scale() #find the width of each point in each series # self.x_group_scale = self.x_scale * self.number_of_series #width of each data point grouping over multiple series # self.setup_chart() # # self.data_series() #Chart subclass should have this method to chart the data series # #self.labels.sort() # Yikes! sorting the labels independently from the data leads to problems... # self.set_labels() # # def set_scale(self): # #pixels between data points # return float(self.grid_width - (self.x_padding * 2) ) / (len(self.labels) - 1) # # def data_series(self): # # series_count = 0 # left_offset = self.padding # bottom_offset = self.padding # g_container = ET.Element('g') # # for series in self.data: # series_count += 1 # if series != 'placeholder': # #move path to initial data point # data_point_count = self.labels.index(series[0][0]) # path_string = "M %s %s" % (self.x_padding + int(data_point_count * self.x_scale), self.grid_height - (series[0][1] * self.y_scale)) # # for point in series: # if data_point_count == 0: # data_point_count += 1 # continue # # data_point_count = self.labels.index(point[0]) # path_string += " L " # x = self.x_padding + int(data_point_count * self.x_scale) # point_height = self.y_scale * point[1] # y = self.grid_height - point_height # path_string += "%s %s" % (x, y) # data_point_count += 1 # #put point markers in here at some point? # # line = ET.Element("path", d=path_string) # line.attrib['class'] = 'series-%s-line' % series_count # g_container.append(line) # self.grid.append(g_container) # # def set_labels(self): # # label_count = 0 # # for l in self.labels: # if (self.label_intervals and label_count % self.label_intervals == 0) or not self.label_intervals: # text_item = ET.Element("text") # x_position = self.x_padding + (label_count * self.x_scale) # y_position = self.grid_height + self.x_label_padding # text_item.attrib['x'] = "%s" % x_position # text_item.attrib['y'] = "%s" % y_position # text_item.text = "%s" % l # text_item.attrib['class'] = 'x-axis-label' # self.grid.append(text_item) # # #insert the notch between data point groups # if l != self.labels[-1]: # if self.label_intervals: # skip_labels = self.label_intervals # else: skip_labels = 1 # # notch_x_pos = x_position + (((self.x_padding + ((label_count + skip_labels) * self.x_scale)) - x_position) / 2) # notch_y_pos = self.grid_height # notch = ET.Element("path", d="M %s %s L %s %s" % (notch_x_pos, notch_y_pos, notch_x_pos, notch_y_pos + 5)) # notch.attrib['class'] = 'x-notch' # self.grid.append(notch) # label_count += 1 # # Path: utils.py # def pretty_money(m): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # return locale.currency(m, grouping=True) . Output only the next line.
obs = ProgramObligation.objects.filter(type=1, program=f).order_by('fiscal_year')
Predict the next line for this snippet: <|code_start|> def parse_date(date_candidate): formats = ('%Y-%m-%d', '%Y%m%d', '%m/%d/%Y', '%m/%d/%y') for fmt in formats: try: parsed_date = datetime.strptime(date_candidate, fmt).date() return parsed_date <|code_end|> with the help of current file imports: from django.core.management.base import NoArgsCommand from optparse import make_option from timeliness import crawler from datetime import datetime import sys and context from other files: # Path: timeliness/crawler.py # URL_PATTERN = ("http://www.usaspending.gov/trendslist" # + "?type=1" # # + "&qcount=" This parameter seems to limit the search # # results but it isn't clear to me how it # # is supposed to be used. # + "&trendreport=assistance" # + "&fiscalyear=%(fiscalyear)s" # + "&agencySelect=" # + "&startdate=%(startdate)s" # + "&enddate=%(enddate)s" # + "&page=%(page)s" # + "&rp=50" # + "&sortname=agency_submission_date" # + "&sortorder=desc" # + "&query=" # + "&qtype=") # DATA_URL_BASE = "http://www.usaspending.gov" # def request_listing(fy, startdate, enddate): # def update_download_schedule(schedule, listing): # def obtain_head(href): # def confirm_download_schedule(schedule): # def content_length(tpl): # def status_code(tpl): # def href(tpl): # def is_OK(tpl): # def not_OK(tpl): # def data_file_destination_path(href): # def url_for_href(href): # def download_data_file(href): # def extract_href(html): # def exec_download_schedule(schedule): # def log_inaccessible_files(schedule): # def schedule_file_path(): # def restore_schedule(): # def save_schedule(schedule): # def offer_resume(): # def crawl_main(startdate=None, enddate=None): # def resume_main(): , which may contain function names, class names, or code. Output only the next line.
except ValueError:
Predict the next line after this snippet: <|code_start|> def update_obligation(new_obligation, program): old_obligation = program.obligation program.obligation = int(new_obligation) if program.usaspending_obligation: program.delta = program.usaspending_obligation - program.obligation else: program.delta = -program.obligation try: program.weighted_delta = program.delta / program.obligation except Exception: if program.obligation == 0: if not program.usaspending_obligation: program.weighted_delta = 0 else: program.weighted_delta = 1 <|code_end|> using the current file's imports: from metrics.models import ProgramCorrection from cfda.models import ProgramObligation, Program from datetime import datetime import sys and any relevant context from other files: # Path: metrics/models.py # class ProgramCorrection(models.Model): # # program = models.ForeignKey('cfda.Program', null=False, blank=False) # program_obligation = models.ForeignKey('cfda.ProgramObligation', null=False, blank=False) # correction_date = models.DateTimeField(null=False, blank=False) # corrected_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # old_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # note = models.TextField("Notes on Correction", blank=True, null=True) # # Path: cfda/models.py # class ProgramObligation(models.Model): # # program = models.ForeignKey('Program', blank=False, null=False) # fiscal_year = models.IntegerField(blank=False, null=False) # obligation = models.DecimalField(max_digits=27, decimal_places=2, blank=False, null=False) # usaspending_obligation = models.DecimalField(max_digits=27, decimal_places=2, blank=True, null=True) # delta = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # weighted_delta = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # cfda_version = models.IntegerField(blank=False, null=False) # corrected = models.BooleanField(default=False) # # TYPE_CHOICES = ( # (1, 'Grants'), # (2, 'Loans'), # (3, 'Loan Guarantees'), # (4, 'Insurance') # ) # # type = models.IntegerField(max_length=1, choices=TYPE_CHOICES) #for simplicity's sake this has been collapsed in the actual processing, grants=1 everything else=2 # GRADE_CHOICES = ( # ('p', 'Pass'), # ('o', 'Overreporting Obligations'), # ('u', 'Underreporting Obligations'), # ('n', 'Not reporting Obligations'), # ('t', 'Late reporting'), # ('c', 'Incomplete reporting') # ) # grade = models.TextField(choices=GRADE_CHOICES) # # class Program(models.Model): # # def __unicode__(self): # return "%s %s" % (self.program_number, self.program_title) # # program_number = models.CharField("Program number", max_length=7) # program_title = models.CharField("Program title", max_length=255) # federal_agency = models.TextField("Federal agency", blank=True, default="") # agency = models.ForeignKey('Agency', blank=True, null=True) # authorization = models.TextField("Authorization",blank=True,default="") # objectives = models.TextField("Objectives",blank=True,default="") # types_of_assistance = models.ManyToManyField(AssistanceType) # uses_and_use_restrictions = models.TextField("Uses and use restrictions",blank=True,default="") # applicant_eligibility = models.TextField("Applicant eligibility",blank=True,default="") # beneficiary_eligibility = models.TextField("Beneficiary eligibility",blank=True,default="") # credentials_documentation = models.TextField("Credentials / documentation",blank=True,default="") # preapplication_coordination = models.TextField("Preapplication coordination",blank=True,default="") # application_procedure = models.TextField("Application procedure",blank=True,default="") # award_procedure = models.TextField("Award procedure",blank=True,default="") # deadlines = models.TextField("Deadlines",blank=True,default="") # range_of_approval_disapproval_time = models.TextField("Range of approval / disapproval time",blank=True,default="") # appeals = models.TextField("Appeals",blank=True,default="") # renewals = models.TextField("Renewals",blank=True,default="") # formula_and_matching_requirements = models.TextField("Formula and matching requirements",blank=True,default="") # length_and_time_phasing_of_assistance = models.TextField("Length and time phasing of assistance",blank=True,default="") # reports = models.TextField("Reports",blank=True,default="") # audits = models.TextField("Audits",blank=True,default="") # records = models.TextField("Records",blank=True,default="") # account_identification = models.ManyToManyField(ProgramAccount) # range_and_average_of_financial_assistance = models.TextField("Range and average of financial assistance",blank=True,default="") # program_accomplishments = models.TextField("Program accomplishments",blank=True,default="") # regulations_guidelines_and_literature = models.TextField("Regulations guidelines and literature",blank=True,default="") # regional_or_local_office = models.TextField("Regional or local office",blank=True,default="") # headquarters_office = models.TextField("Headquarters office",blank=True,default="") # web_site_address = models.TextField("Web site address",blank=True,default="") # related_programs = models.TextField("Related programs",blank=True,default="") # examples_of_funded_projects = models.TextField("Examples of funded projects",blank=True,default="") # criteria_for_selecting_proposals = models.TextField("Criteria for selecting proposals",blank=True,default="") # published_date = models.TextField("Published Date", blank=True, default="") # parent_shortname = models.TextField("Parent Shortname", blank=True, default="") # url = models.TextField("URL on CFDA website", blank=True, default="") # recovery = models.BooleanField(default=False) # # cfda_edition = models.IntegerField("CFDA Edition", blank=True, null=True) # load_date = models.DateTimeField("Load Date", auto_now=True) # caveat = models.TextField("Caveats about the spending of this program", blank=True, null=True) . Output only the next line.
program.corrected = True
Continue the code snippet: <|code_start|> for row in rows: agg = USASpendingAggregate(fiscal_year=row['fiscal_year']) agg.total_federal_funding = row['fed_funding_amount'] agg.save() usa_query = "SELECT cfda_program_num, fiscal_year, SUM(fed_funding_amount) as fed_funding_amount, SUM(face_loan_guran) as face_loan_guran FROM %s WHERE fiscal_year >= %s AND fiscal_year <= %s GROUP BY cfda_program_num, fiscal_year ORDER BY cfda_program_num" % (PG_TABLE_NAME, min(FISCAL_YEARS), max(FISCAL_YEARS)) print usa_query print "fetching summary query with rollup of programs, fiscal years and total obligations" rows = conn.query(usa_query).dictresult() for row in rows: print row try: if row['cfda_program_num']: usaspending_total[row['fiscal_year']] += row['fed_funding_amount'] program = Program.objects.get(program_number=row['cfda_program_num']) this_type = 1 if row['face_loan_guran'] > 0: this_type =2 cfda_ob = ProgramObligation.objects.get(program=program, fiscal_year=row['fiscal_year'], type=this_type) if cfda_ob.type == 1: #its direct spending/grants obligation = row['fed_funding_amount'] else: obligation = row['face_loan_guran'] cfda_ob.usaspending_obligation = obligation cfda_ob.delta = (cfda_ob.usaspending_obligation - cfda_ob.obligation) <|code_end|> . Use current file imports: from settings import * from cfda.models import * from metrics.models import ProgramCorrection, USASpendingAggregate from datetime import datetime import pg import csv import numpy as np and context (classes, functions, or code) from other files: # Path: metrics/models.py # class ProgramCorrection(models.Model): # # program = models.ForeignKey('cfda.Program', null=False, blank=False) # program_obligation = models.ForeignKey('cfda.ProgramObligation', null=False, blank=False) # correction_date = models.DateTimeField(null=False, blank=False) # corrected_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # old_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # note = models.TextField("Notes on Correction", blank=True, null=True) # # class USASpendingAggregate(models.Model): # fiscal_year = models.IntegerField(blank=False, null=False, primary_key=True) # total_federal_funding = models.DecimalField("SUM(fed_funding_amount)", max_digits=21, decimal_places=2, null=False) # # def __unicode__(self): # return "<USASpendingAggregate(%d, %s)>" % (self.fiscal_year, unicode(pretty_money(self.total_federal_funding))) . Output only the next line.
try:
Continue the code snippet: <|code_start|> #Metric for consistency in USASpending versus CFDA reported obligations def fix_cfda(): #Identify possible cfda mistakes fin_programs = Program.objects.filter(types_of_assistance__financial=True) fin_obligations = ProgramObligation.objects.filter(program__in=fin_programs) for fy in FISCAL_YEARS: over_programs = fin_obligations.filter(fiscal_year=fy, weighted_delta__gt=0) sd = np.std([float(v) for v in over_programs.values_list('weighted_delta', flat=True)]) avg = np.average([float(v) for v in over_programs.values_list('weighted_delta', flat=True)]) new_over = over_programs.filter(weighted_delta__lte=str(((3*sd) + avg))) sd_new = np.std([float(v) for v in new_over.values_list('weighted_delta', flat=True)]) avg_new = np.average([float(v) for v in new_over.values_list('weighted_delta', flat=True)]) <|code_end|> . Use current file imports: from settings import * from cfda.models import * from metrics.models import ProgramCorrection, USASpendingAggregate from datetime import datetime import pg import csv import numpy as np and context (classes, functions, or code) from other files: # Path: metrics/models.py # class ProgramCorrection(models.Model): # # program = models.ForeignKey('cfda.Program', null=False, blank=False) # program_obligation = models.ForeignKey('cfda.ProgramObligation', null=False, blank=False) # correction_date = models.DateTimeField(null=False, blank=False) # corrected_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # old_obligation = models.DecimalField(max_digits=20, decimal_places=2, blank=False) # note = models.TextField("Notes on Correction", blank=True, null=True) # # class USASpendingAggregate(models.Model): # fiscal_year = models.IntegerField(blank=False, null=False, primary_key=True) # total_federal_funding = models.DecimalField("SUM(fed_funding_amount)", max_digits=21, decimal_places=2, null=False) # # def __unicode__(self): # return "<USASpendingAggregate(%d, %s)>" % (self.fiscal_year, unicode(pretty_money(self.total_federal_funding))) . Output only the next line.
outliers = over_programs.filter(weighted_delta__gte=str(avg_new))
Given snippet: <|code_start|> print "----- Sample Size -----" for fy in FISCAL_YEARS: timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum'] usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=fy).total_federal_funding sample_pct = timeliness_sum * 100 / usaspending_sum print "%d: %.2f%% (%s / %s)" % (fy, round(sample_pct, 2), pretty_money(timeliness_sum), pretty_money(usaspending_sum)) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.db.models import Sum from numpy import mean, std from metrics.models import ProgramTimeliness, AgencyTimeliness, USASpendingAggregate from utils import pretty_money from settings import FISCAL_YEARS and context: # Path: metrics/models.py # class ProgramTimeliness(ProgramMetric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=True, null=True) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # late_pct = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class AgencyTimeliness(Metric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=False, null=False) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class USASpendingAggregate(models.Model): # fiscal_year = models.IntegerField(blank=False, null=False, primary_key=True) # total_federal_funding = models.DecimalField("SUM(fed_funding_amount)", max_digits=21, decimal_places=2, null=False) # # def __unicode__(self): # return "<USASpendingAggregate(%d, %s)>" % (self.fiscal_year, unicode(pretty_money(self.total_federal_funding))) # # Path: utils.py # def pretty_money(m): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # return locale.currency(m, grouping=True) which might include code, classes, or functions. Output only the next line.
print "----- Average Lag (program) -----"
Given the following code snippet before the placeholder: <|code_start|> print "----- Sample Size -----" for fy in FISCAL_YEARS: timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum'] usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=fy).total_federal_funding sample_pct = timeliness_sum * 100 / usaspending_sum print "%d: %.2f%% (%s / %s)" % (fy, round(sample_pct, 2), pretty_money(timeliness_sum), pretty_money(usaspending_sum)) <|code_end|> , predict the next line using imports from the current file: from django.db.models import Sum from numpy import mean, std from metrics.models import ProgramTimeliness, AgencyTimeliness, USASpendingAggregate from utils import pretty_money from settings import FISCAL_YEARS and context including class names, function names, and sometimes code from other files: # Path: metrics/models.py # class ProgramTimeliness(ProgramMetric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=True, null=True) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # late_pct = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class AgencyTimeliness(Metric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=False, null=False) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class USASpendingAggregate(models.Model): # fiscal_year = models.IntegerField(blank=False, null=False, primary_key=True) # total_federal_funding = models.DecimalField("SUM(fed_funding_amount)", max_digits=21, decimal_places=2, null=False) # # def __unicode__(self): # return "<USASpendingAggregate(%d, %s)>" % (self.fiscal_year, unicode(pretty_money(self.total_federal_funding))) # # Path: utils.py # def pretty_money(m): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # return locale.currency(m, grouping=True) . Output only the next line.
print "----- Average Lag (program) -----"
Given the following code snippet before the placeholder: <|code_start|> print "----- Sample Size -----" for fy in FISCAL_YEARS: timeliness_sum = ProgramTimeliness.objects.filter(fiscal_year=fy).aggregate(Sum('total_dollars'))['total_dollars__sum'] usaspending_sum = USASpendingAggregate.objects.get(fiscal_year=fy).total_federal_funding sample_pct = timeliness_sum * 100 / usaspending_sum print "%d: %.2f%% (%s / %s)" % (fy, round(sample_pct, 2), pretty_money(timeliness_sum), pretty_money(usaspending_sum)) print "----- Average Lag (program) -----" for fy in FISCAL_YEARS: lag_values = [pt.avg_lag_rows for pt in ProgramTimeliness.objects.filter(fiscal_year=fy)] <|code_end|> , predict the next line using imports from the current file: from django.db.models import Sum from numpy import mean, std from metrics.models import ProgramTimeliness, AgencyTimeliness, USASpendingAggregate from utils import pretty_money from settings import FISCAL_YEARS and context including class names, function names, and sometimes code from other files: # Path: metrics/models.py # class ProgramTimeliness(ProgramMetric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=True, null=True) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # late_pct = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class AgencyTimeliness(Metric): # # late_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # late_rows = models.IntegerField(blank=False, null=False) # # total_dollars = models.DecimalField(max_digits=21, decimal_places=2, blank=True, null=True) # total_rows = models.IntegerField(blank=True, null=True) # # avg_lag_rows = models.IntegerField(blank=True, null=True) # avg_lag_dollars = models.IntegerField(blank=True, null=True) # # class USASpendingAggregate(models.Model): # fiscal_year = models.IntegerField(blank=False, null=False, primary_key=True) # total_federal_funding = models.DecimalField("SUM(fed_funding_amount)", max_digits=21, decimal_places=2, null=False) # # def __unicode__(self): # return "<USASpendingAggregate(%d, %s)>" % (self.fiscal_year, unicode(pretty_money(self.total_federal_funding))) # # Path: utils.py # def pretty_money(m): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # return locale.currency(m, grouping=True) . Output only the next line.
print "%d: %d mean (days), %.1f stdev" % (fy, mean(lag_values), std(lag_values))
Given the code snippet: <|code_start|> self.assertEquals(getEdge(graphs[0], 1, 2), 1) self.assertEquals(getEdge(graphs[0], 1, 18), 1) self.assertEquals(getEdge(graphs[0],2, 3), 1) self.assertEquals(getEdge(graphs[0],2, 19), 1) self.assertEquals(getEdge(graphs[0],3, 4), 1) self.assertEquals(getEdge(graphs[0],3, 20), 1) self.assertEquals(getEdge(graphs[0],4, 10), 1) self.assertEquals(getEdge(graphs[0],4, 5), 1) self.assertEquals(getEdge(graphs[0],5, 6), 1) self.assertEquals(getEdge(graphs[0],5, 7), 1) self.assertEquals(getEdge(graphs[0],6, 21), 1) self.assertEquals(getEdge(graphs[0],7, 8), 1) self.assertEquals(getEdge(graphs[0],7, 22), 1) self.assertEquals(getEdge(graphs[0],8, 9), 1) self.assertEquals(getEdge(graphs[0],8, 23), 1) self.assertEquals(getEdge(graphs[0],9, 14), 1) self.assertEquals(getEdge(graphs[0],9, 10), 1) self.assertEquals(getEdge(graphs[0],10, 11), 1) self.assertEquals(getEdge(graphs[0],11, 12), 1) self.assertEquals(getEdge(graphs[0],11, 24), 1) self.assertEquals(getEdge(graphs[0],12, 13), 1) self.assertEquals(getEdge(graphs[0],12, 25), 1) self.assertEquals(getEdge(graphs[0],13, 14), 1) self.assertEquals(getEdge(graphs[0],13, 15), 1) self.assertEquals(getEdge(graphs[0],14, 26), 1) self.assertEquals(getEdge(graphs[0],15, 16), 1) self.assertEquals(getEdge(graphs[0],15, 17), 1) #Check the second graph self.assertEquals(graphs[1].getNumVertices(), 19) <|code_end|> , generate the next line using the imports in this file: import unittest from apgl.io.MDLGraphsReader import MDLGraphsReader from apgl.util.PathDefaults import PathDefaults and context (functions, classes, or occasionally code) from other files: # Path: apgl/io/MDLGraphsReader.py # class MDLGraphsReader(): # def __init__(self): # self.atomDict = {} # self.atomDict["C"] = 0 # self.atomDict["H"] = 1 # self.atomDict["N"] = 2 # self.atomDict["O"] = 3 # # def readFromFile(self, fileName): # inFile = open(fileName,"r") # numFeatures = 1 # # graphList = [] # line = inFile.readline() # # while line != "": # #First 3 lines are useless # # inFile.readline() # inFile.readline() # # #4th line has edge information # line = inFile.readline() # valueList = line.split(None) # numVertices = int(valueList[0]) # #Not strictly the number of edges, as molecules can have multiple edges # #between a pair of atoms # numEdges = int(valueList[1]) # # vList = VertexList(numVertices, numFeatures) # # for i in range(numVertices): # line = inFile.readline() # valueList = line.split(None) # vList.setVertex(i, numpy.array([self.atomDict[valueList[3]]])) # # graph = SparseGraph(vList) # # for i in range(numEdges): # line = inFile.readline() # valueList = line.split(None) # graph.addEdge(int(valueList[0])-1, int(valueList[1])-1) # # graphList.append(graph) # # #Ignore next two lines # inFile.readline() # inFile.readline() # line = inFile.readline() # # return graphList # # Path: apgl/util/PathDefaults.py # class PathDefaults(object): # """ # This class stores some useful global default paths. # """ # @staticmethod # def readField(field): # configFileName = expanduser("~") + os.sep + ".apglrc" # # if not os.path.exists(configFileName): # print("Creating missing config file: " + configFileName) # defaultConfig = "[paths]\n" # defaultConfig += "data = " + expanduser("~") + os.sep + "data" + os.sep + "\n" # defaultConfig += "output = " + expanduser("~") + os.sep + "output" + os.sep + "\n" # configFile = open(configFileName, "w") # configFile.write(defaultConfig) # configFile.close() # # parser = SafeConfigParser() # parser.read(configFileName) # return parser.get('paths', field) # # @staticmethod # def getSourceDir(): # """ # Root directory of source code for APGL. # """ # dir = os.path.abspath( __file__ ) # dir, head = os.path.split(dir) # dir, head = os.path.split(dir) # return dir # # @staticmethod # def getDataDir(): # """ # Location of data files. # """ # return PathDefaults.readField("data") # # @staticmethod # def getOutputDir(): # """ # Location of output files. # """ # return PathDefaults.readField("output") # # @staticmethod # def getTempDir(): # return tempfile.gettempdir() + os.sep . Output only the next line.
self.assertEquals(graphs[1].getNumEdges(), 20)
Using the snippet: <|code_start|> self.assertEquals(graphs[0].getNumVertices(), 26) self.assertEquals(graphs[0].getNumEdges(), 28) def getEdge(graph, i, j): return graph.getEdge(i-1, j-1) self.assertEquals(getEdge(graphs[0], 1, 6), 1) self.assertEquals(getEdge(graphs[0], 1, 2), 1) self.assertEquals(getEdge(graphs[0], 1, 18), 1) self.assertEquals(getEdge(graphs[0],2, 3), 1) self.assertEquals(getEdge(graphs[0],2, 19), 1) self.assertEquals(getEdge(graphs[0],3, 4), 1) self.assertEquals(getEdge(graphs[0],3, 20), 1) self.assertEquals(getEdge(graphs[0],4, 10), 1) self.assertEquals(getEdge(graphs[0],4, 5), 1) self.assertEquals(getEdge(graphs[0],5, 6), 1) self.assertEquals(getEdge(graphs[0],5, 7), 1) self.assertEquals(getEdge(graphs[0],6, 21), 1) self.assertEquals(getEdge(graphs[0],7, 8), 1) self.assertEquals(getEdge(graphs[0],7, 22), 1) self.assertEquals(getEdge(graphs[0],8, 9), 1) self.assertEquals(getEdge(graphs[0],8, 23), 1) self.assertEquals(getEdge(graphs[0],9, 14), 1) self.assertEquals(getEdge(graphs[0],9, 10), 1) self.assertEquals(getEdge(graphs[0],10, 11), 1) self.assertEquals(getEdge(graphs[0],11, 12), 1) self.assertEquals(getEdge(graphs[0],11, 24), 1) self.assertEquals(getEdge(graphs[0],12, 13), 1) self.assertEquals(getEdge(graphs[0],12, 25), 1) self.assertEquals(getEdge(graphs[0],13, 14), 1) <|code_end|> , determine the next line of code. You have imports: import unittest from apgl.io.MDLGraphsReader import MDLGraphsReader from apgl.util.PathDefaults import PathDefaults and context (class names, function names, or code) available: # Path: apgl/io/MDLGraphsReader.py # class MDLGraphsReader(): # def __init__(self): # self.atomDict = {} # self.atomDict["C"] = 0 # self.atomDict["H"] = 1 # self.atomDict["N"] = 2 # self.atomDict["O"] = 3 # # def readFromFile(self, fileName): # inFile = open(fileName,"r") # numFeatures = 1 # # graphList = [] # line = inFile.readline() # # while line != "": # #First 3 lines are useless # # inFile.readline() # inFile.readline() # # #4th line has edge information # line = inFile.readline() # valueList = line.split(None) # numVertices = int(valueList[0]) # #Not strictly the number of edges, as molecules can have multiple edges # #between a pair of atoms # numEdges = int(valueList[1]) # # vList = VertexList(numVertices, numFeatures) # # for i in range(numVertices): # line = inFile.readline() # valueList = line.split(None) # vList.setVertex(i, numpy.array([self.atomDict[valueList[3]]])) # # graph = SparseGraph(vList) # # for i in range(numEdges): # line = inFile.readline() # valueList = line.split(None) # graph.addEdge(int(valueList[0])-1, int(valueList[1])-1) # # graphList.append(graph) # # #Ignore next two lines # inFile.readline() # inFile.readline() # line = inFile.readline() # # return graphList # # Path: apgl/util/PathDefaults.py # class PathDefaults(object): # """ # This class stores some useful global default paths. # """ # @staticmethod # def readField(field): # configFileName = expanduser("~") + os.sep + ".apglrc" # # if not os.path.exists(configFileName): # print("Creating missing config file: " + configFileName) # defaultConfig = "[paths]\n" # defaultConfig += "data = " + expanduser("~") + os.sep + "data" + os.sep + "\n" # defaultConfig += "output = " + expanduser("~") + os.sep + "output" + os.sep + "\n" # configFile = open(configFileName, "w") # configFile.write(defaultConfig) # configFile.close() # # parser = SafeConfigParser() # parser.read(configFileName) # return parser.get('paths', field) # # @staticmethod # def getSourceDir(): # """ # Root directory of source code for APGL. # """ # dir = os.path.abspath( __file__ ) # dir, head = os.path.split(dir) # dir, head = os.path.split(dir) # return dir # # @staticmethod # def getDataDir(): # """ # Location of data files. # """ # return PathDefaults.readField("data") # # @staticmethod # def getOutputDir(): # """ # Location of output files. # """ # return PathDefaults.readField("output") # # @staticmethod # def getTempDir(): # return tempfile.gettempdir() + os.sep . Output only the next line.
self.assertEquals(getEdge(graphs[0],13, 15), 1)
Continue the code snippet: <|code_start|> self.assertEquals(graph.getEdge(0, 1), 1) self.assertEquals(graph.getEdge(2, 4), 1) self.assertEquals(graph.getEdge(2, 2), 1) self.assertEquals(graph.getEdge(4, 0), 1) #Now test reading a file with the same graph but vertices indexed differently fileName = PathDefaults.getDataDir() + "test/simpleGraph2.txt" graph = graphReader.readFromFile(fileName) self.assertEquals(graph.isUndirected(), True) self.assertEquals(graph.getNumVertices(), 5) self.assertEquals(graph.getNumEdges(), 4) self.assertEquals(graph.getEdge(0, 1), 1.1) self.assertEquals(graph.getEdge(2, 4), 1) self.assertEquals(graph.getEdge(2, 2), 1.6) self.assertEquals(graph.getEdge(4, 0), 1) #Now test a file with directed edges fileName = PathDefaults.getDataDir() + "test/simpleGraph3.txt" graph = graphReader.readFromFile(fileName) self.assertEquals(graph.isUndirected(), False) self.assertEquals(graph.getNumVertices(), 5) self.assertEquals(graph.getNumEdges(), 4) self.assertEquals(graph.getEdge(0, 1), 1) self.assertEquals(graph.getEdge(2, 4), 1) self.assertEquals(graph.getEdge(2, 2), 1) <|code_end|> . Use current file imports: import unittest import logging from apgl.io.SimpleGraphReader import SimpleGraphReader from apgl.util.PathDefaults import PathDefaults and context (classes, functions, or code) from other files: # Path: apgl/io/SimpleGraphReader.py # class SimpleGraphReader(GraphReader): # ''' # A class to read SimpleGraph files. # ''' # def __init__(self): # pass # # def readFromFile(self, fileName): # """ # Read vertices and edges of the graph from the given file name. The file # must have as its first line "Vertices" followed by a list of # vertex indices (one per line). Then the lines following "Arcs" or "Edges" # have a list of pairs of vertex indices represented directed or undirected # edges. # """ # infile = open(fileName, "r") # line = infile.readline() # line = infile.readline() # ind = 0 # vertexIdDict = {} # # while infile and line != "Edges" and line != "Arcs": # vertexIdDict[int(line)] = ind # line = infile.readline().strip() # ind += 1 # # if line == "Edges": # undirected = True # elif line == "Arcs": # undirected = False # else: # raise ValueError("Unknown edge types: " + line) # # numVertices = len(vertexIdDict) # numFeatures = 0 # vList = VertexList(numVertices, numFeatures) # sGraph = SparseGraph(vList, undirected) # line = infile.readline() # # while line: # s = line.split() # try: # i = vertexIdDict[int(s[0].strip(',').strip())] # j = vertexIdDict[int(s[1].strip(',').strip())] # k = float(s[2].strip(',').strip()) # except KeyError: # print("Vertex not found in list of vertices.") # raise # # sGraph.addEdge(i, j, k) # line = infile.readline() # # logging.info("Read graph with " + str(numVertices) + " vertices and " + str(sGraph.getNumEdges()) + " edges") # # return sGraph # # Path: apgl/util/PathDefaults.py # class PathDefaults(object): # """ # This class stores some useful global default paths. # """ # @staticmethod # def readField(field): # configFileName = expanduser("~") + os.sep + ".apglrc" # # if not os.path.exists(configFileName): # print("Creating missing config file: " + configFileName) # defaultConfig = "[paths]\n" # defaultConfig += "data = " + expanduser("~") + os.sep + "data" + os.sep + "\n" # defaultConfig += "output = " + expanduser("~") + os.sep + "output" + os.sep + "\n" # configFile = open(configFileName, "w") # configFile.write(defaultConfig) # configFile.close() # # parser = SafeConfigParser() # parser.read(configFileName) # return parser.get('paths', field) # # @staticmethod # def getSourceDir(): # """ # Root directory of source code for APGL. # """ # dir = os.path.abspath( __file__ ) # dir, head = os.path.split(dir) # dir, head = os.path.split(dir) # return dir # # @staticmethod # def getDataDir(): # """ # Location of data files. # """ # return PathDefaults.readField("data") # # @staticmethod # def getOutputDir(): # """ # Location of output files. # """ # return PathDefaults.readField("output") # # @staticmethod # def getTempDir(): # return tempfile.gettempdir() + os.sep . Output only the next line.
self.assertEquals(graph.getEdge(4, 0), 1)
Given the code snippet: <|code_start|> class SimpleGraphReaderTest(unittest.TestCase): def testReadGraph(self): fileName = PathDefaults.getDataDir() + "test/simpleGraph.txt" graphReader = SimpleGraphReader() graph = graphReader.readFromFile(fileName) <|code_end|> , generate the next line using the imports in this file: import unittest import logging from apgl.io.SimpleGraphReader import SimpleGraphReader from apgl.util.PathDefaults import PathDefaults and context (functions, classes, or occasionally code) from other files: # Path: apgl/io/SimpleGraphReader.py # class SimpleGraphReader(GraphReader): # ''' # A class to read SimpleGraph files. # ''' # def __init__(self): # pass # # def readFromFile(self, fileName): # """ # Read vertices and edges of the graph from the given file name. The file # must have as its first line "Vertices" followed by a list of # vertex indices (one per line). Then the lines following "Arcs" or "Edges" # have a list of pairs of vertex indices represented directed or undirected # edges. # """ # infile = open(fileName, "r") # line = infile.readline() # line = infile.readline() # ind = 0 # vertexIdDict = {} # # while infile and line != "Edges" and line != "Arcs": # vertexIdDict[int(line)] = ind # line = infile.readline().strip() # ind += 1 # # if line == "Edges": # undirected = True # elif line == "Arcs": # undirected = False # else: # raise ValueError("Unknown edge types: " + line) # # numVertices = len(vertexIdDict) # numFeatures = 0 # vList = VertexList(numVertices, numFeatures) # sGraph = SparseGraph(vList, undirected) # line = infile.readline() # # while line: # s = line.split() # try: # i = vertexIdDict[int(s[0].strip(',').strip())] # j = vertexIdDict[int(s[1].strip(',').strip())] # k = float(s[2].strip(',').strip()) # except KeyError: # print("Vertex not found in list of vertices.") # raise # # sGraph.addEdge(i, j, k) # line = infile.readline() # # logging.info("Read graph with " + str(numVertices) + " vertices and " + str(sGraph.getNumEdges()) + " edges") # # return sGraph # # Path: apgl/util/PathDefaults.py # class PathDefaults(object): # """ # This class stores some useful global default paths. # """ # @staticmethod # def readField(field): # configFileName = expanduser("~") + os.sep + ".apglrc" # # if not os.path.exists(configFileName): # print("Creating missing config file: " + configFileName) # defaultConfig = "[paths]\n" # defaultConfig += "data = " + expanduser("~") + os.sep + "data" + os.sep + "\n" # defaultConfig += "output = " + expanduser("~") + os.sep + "output" + os.sep + "\n" # configFile = open(configFileName, "w") # configFile.write(defaultConfig) # configFile.close() # # parser = SafeConfigParser() # parser.read(configFileName) # return parser.get('paths', field) # # @staticmethod # def getSourceDir(): # """ # Root directory of source code for APGL. # """ # dir = os.path.abspath( __file__ ) # dir, head = os.path.split(dir) # dir, head = os.path.split(dir) # return dir # # @staticmethod # def getDataDir(): # """ # Location of data files. # """ # return PathDefaults.readField("data") # # @staticmethod # def getOutputDir(): # """ # Location of output files. # """ # return PathDefaults.readField("output") # # @staticmethod # def getTempDir(): # return tempfile.gettempdir() + os.sep . Output only the next line.
logging.debug((graph.getAllEdges()))
Here is a snippet: <|code_start|> class PathDefaultsTestCase(unittest.TestCase): def testGetProjectDir(self): print((PathDefaults.getSourceDir())) <|code_end|> . Write the next line using the current file imports: import unittest from apgl.util.PathDefaults import PathDefaults and context from other files: # Path: apgl/util/PathDefaults.py # class PathDefaults(object): # """ # This class stores some useful global default paths. # """ # @staticmethod # def readField(field): # configFileName = expanduser("~") + os.sep + ".apglrc" # # if not os.path.exists(configFileName): # print("Creating missing config file: " + configFileName) # defaultConfig = "[paths]\n" # defaultConfig += "data = " + expanduser("~") + os.sep + "data" + os.sep + "\n" # defaultConfig += "output = " + expanduser("~") + os.sep + "output" + os.sep + "\n" # configFile = open(configFileName, "w") # configFile.write(defaultConfig) # configFile.close() # # parser = SafeConfigParser() # parser.read(configFileName) # return parser.get('paths', field) # # @staticmethod # def getSourceDir(): # """ # Root directory of source code for APGL. # """ # dir = os.path.abspath( __file__ ) # dir, head = os.path.split(dir) # dir, head = os.path.split(dir) # return dir # # @staticmethod # def getDataDir(): # """ # Location of data files. # """ # return PathDefaults.readField("data") # # @staticmethod # def getOutputDir(): # """ # Location of output files. # """ # return PathDefaults.readField("output") # # @staticmethod # def getTempDir(): # return tempfile.gettempdir() + os.sep , which may include functions, classes, or code. Output only the next line.
def testGetDataDir(self):
Given snippet: <|code_start|> return res def _has_nonprintable_char(s): chars = enumerate((unicodedata.category(char) == "Cc", char) for char in s) for pos, (unprintable, char) in chars: if unprintable: return ( s.encode("unicode_escape").decode("utf-8"), char.encode("unicode_escape").decode("utf-8"), pos, ) return None def _check_path(path, target_name, mode): if not path: msg = 'Target "{}" has an empty {} path.'.format(target_name, mode) raise WorkflowError(msg) result = _has_nonprintable_char(path) if result is not None: clean_path, char, pos = result msg = ( 'Path "{}" in target "{}" {}s contains a ' 'non-printable character "{}" on position {}. ' "This is always unintentional and can cause " "strange behaviour." ).format(clean_path, target_name, mode, char, pos) raise WorkflowError(msg) <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import logging import os import os.path import unicodedata from collections import defaultdict from enum import Enum from .backends import Status from .compat import fspath from .exceptions import NameError, WorkflowError from .utils import cache, is_valid_name, timer and context: # Path: src/gwf/backends/base.py # class Status(Enum): # """Status of a target. # # A target is unknown to the backend if it has not been submitted or the # target has completed and thus isn't being tracked anymore by the backend. # # A target is submitted if it has been successfully submitted to the backend # and is pending execution. # # A target is running if it is currently being executed by the backend. # """ # # UNKNOWN = 0 # SUBMITTED = 1 # RUNNING = 2 # # Path: src/gwf/utils.py # def cache(obj): # _cache = obj._cache = {} # # @functools.wraps(obj) # def memoizer(*args, **kwargs): # if args not in _cache: # _cache[args] = obj(*args, **kwargs) # return _cache[args] # # return memoizer # # def is_valid_name(candidate): # """Check whether `candidate` is a valid name for a target or workflow.""" # return re.match(r"^[a-zA-Z_][a-zA-Z0-9._]*$", candidate) is not None # # class timer(ContextDecorator): # def __init__(self, msg, logger=None): # self.msg = msg # self.logger = logger or logging.getLogger(__name__) # # def __enter__(self): # self.start = time.perf_counter() # return self # # def __exit__(self, *args): # self.end = time.perf_counter() # self.duration = self.end - self.start # self.logger.debug(self.msg, self.duration) which might include code, classes, or functions. Output only the next line.
return path
Given snippet: <|code_start|>def _flatten(t): res = [] def flatten_rec(g): if isinstance(g, str) or hasattr(g, "__fspath__"): res.append(g) elif isinstance(g, collections.abc.Mapping): for k, v in g.items(): flatten_rec(v) else: for v in g: flatten_rec(v) flatten_rec(t) return res def _has_nonprintable_char(s): chars = enumerate((unicodedata.category(char) == "Cc", char) for char in s) for pos, (unprintable, char) in chars: if unprintable: return ( s.encode("unicode_escape").decode("utf-8"), char.encode("unicode_escape").decode("utf-8"), pos, ) return None def _check_path(path, target_name, mode): <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import logging import os import os.path import unicodedata from collections import defaultdict from enum import Enum from .backends import Status from .compat import fspath from .exceptions import NameError, WorkflowError from .utils import cache, is_valid_name, timer and context: # Path: src/gwf/backends/base.py # class Status(Enum): # """Status of a target. # # A target is unknown to the backend if it has not been submitted or the # target has completed and thus isn't being tracked anymore by the backend. # # A target is submitted if it has been successfully submitted to the backend # and is pending execution. # # A target is running if it is currently being executed by the backend. # """ # # UNKNOWN = 0 # SUBMITTED = 1 # RUNNING = 2 # # Path: src/gwf/utils.py # def cache(obj): # _cache = obj._cache = {} # # @functools.wraps(obj) # def memoizer(*args, **kwargs): # if args not in _cache: # _cache[args] = obj(*args, **kwargs) # return _cache[args] # # return memoizer # # def is_valid_name(candidate): # """Check whether `candidate` is a valid name for a target or workflow.""" # return re.match(r"^[a-zA-Z_][a-zA-Z0-9._]*$", candidate) is not None # # class timer(ContextDecorator): # def __init__(self, msg, logger=None): # self.msg = msg # self.logger = logger or logging.getLogger(__name__) # # def __enter__(self): # self.start = time.perf_counter() # return self # # def __exit__(self, *args): # self.end = time.perf_counter() # self.duration = self.end - self.start # self.logger.debug(self.msg, self.duration) which might include code, classes, or functions. Output only the next line.
if not path:
Based on the snippet: <|code_start|> res = [] def flatten_rec(g): if isinstance(g, str) or hasattr(g, "__fspath__"): res.append(g) elif isinstance(g, collections.abc.Mapping): for k, v in g.items(): flatten_rec(v) else: for v in g: flatten_rec(v) flatten_rec(t) return res def _has_nonprintable_char(s): chars = enumerate((unicodedata.category(char) == "Cc", char) for char in s) for pos, (unprintable, char) in chars: if unprintable: return ( s.encode("unicode_escape").decode("utf-8"), char.encode("unicode_escape").decode("utf-8"), pos, ) return None def _check_path(path, target_name, mode): if not path: <|code_end|> , predict the immediate next line with the help of imports: import collections import logging import os import os.path import unicodedata from collections import defaultdict from enum import Enum from .backends import Status from .compat import fspath from .exceptions import NameError, WorkflowError from .utils import cache, is_valid_name, timer and context (classes, functions, sometimes code) from other files: # Path: src/gwf/backends/base.py # class Status(Enum): # """Status of a target. # # A target is unknown to the backend if it has not been submitted or the # target has completed and thus isn't being tracked anymore by the backend. # # A target is submitted if it has been successfully submitted to the backend # and is pending execution. # # A target is running if it is currently being executed by the backend. # """ # # UNKNOWN = 0 # SUBMITTED = 1 # RUNNING = 2 # # Path: src/gwf/utils.py # def cache(obj): # _cache = obj._cache = {} # # @functools.wraps(obj) # def memoizer(*args, **kwargs): # if args not in _cache: # _cache[args] = obj(*args, **kwargs) # return _cache[args] # # return memoizer # # def is_valid_name(candidate): # """Check whether `candidate` is a valid name for a target or workflow.""" # return re.match(r"^[a-zA-Z_][a-zA-Z0-9._]*$", candidate) is not None # # class timer(ContextDecorator): # def __init__(self, msg, logger=None): # self.msg = msg # self.logger = logger or logging.getLogger(__name__) # # def __enter__(self): # self.start = time.perf_counter() # return self # # def __exit__(self, *args): # self.end = time.perf_counter() # self.duration = self.end - self.start # self.logger.debug(self.msg, self.duration) . Output only the next line.
msg = 'Target "{}" has an empty {} path.'.format(target_name, mode)
Here is a snippet: <|code_start|> if isinstance(g, str) or hasattr(g, "__fspath__"): res.append(g) elif isinstance(g, collections.abc.Mapping): for k, v in g.items(): flatten_rec(v) else: for v in g: flatten_rec(v) flatten_rec(t) return res def _has_nonprintable_char(s): chars = enumerate((unicodedata.category(char) == "Cc", char) for char in s) for pos, (unprintable, char) in chars: if unprintable: return ( s.encode("unicode_escape").decode("utf-8"), char.encode("unicode_escape").decode("utf-8"), pos, ) return None def _check_path(path, target_name, mode): if not path: msg = 'Target "{}" has an empty {} path.'.format(target_name, mode) raise WorkflowError(msg) <|code_end|> . Write the next line using the current file imports: import collections import logging import os import os.path import unicodedata from collections import defaultdict from enum import Enum from .backends import Status from .compat import fspath from .exceptions import NameError, WorkflowError from .utils import cache, is_valid_name, timer and context from other files: # Path: src/gwf/backends/base.py # class Status(Enum): # """Status of a target. # # A target is unknown to the backend if it has not been submitted or the # target has completed and thus isn't being tracked anymore by the backend. # # A target is submitted if it has been successfully submitted to the backend # and is pending execution. # # A target is running if it is currently being executed by the backend. # """ # # UNKNOWN = 0 # SUBMITTED = 1 # RUNNING = 2 # # Path: src/gwf/utils.py # def cache(obj): # _cache = obj._cache = {} # # @functools.wraps(obj) # def memoizer(*args, **kwargs): # if args not in _cache: # _cache[args] = obj(*args, **kwargs) # return _cache[args] # # return memoizer # # def is_valid_name(candidate): # """Check whether `candidate` is a valid name for a target or workflow.""" # return re.match(r"^[a-zA-Z_][a-zA-Z0-9._]*$", candidate) is not None # # class timer(ContextDecorator): # def __init__(self, msg, logger=None): # self.msg = msg # self.logger = logger or logging.getLogger(__name__) # # def __enter__(self): # self.start = time.perf_counter() # return self # # def __exit__(self, *args): # self.end = time.perf_counter() # self.duration = self.end - self.start # self.logger.debug(self.msg, self.duration) , which may include functions, classes, or code. Output only the next line.
result = _has_nonprintable_char(path)
Using the snippet: <|code_start|>class Backend: """Base class for backends.""" option_defaults = {} log_manager = FileLogManager() @classmethod def list(cls): """Return the names of all registered backends.""" return set(_load_backends().keys()) @classmethod def from_name(cls, name): """Return backend class for the backend given by `name`. Returns the backend class registered with `name`. Note that the *class* is returned, not the instance, since not all uses requires initialization of the backend (e.g. accessing the backends' log manager), and initialization of the backend may be expensive. :arg str name: Path to a workflow file, optionally specifying a workflow object in that file. """ return _load_backends()[name] @classmethod def from_config(cls, config): """Return backend class for the backend specified by `config`. See :func:`Backend.from_name` for further information.""" <|code_end|> , determine the next line of code. You have imports: import sys import logging from importlib_metadata import entry_points from importlib.metadata import entry_points from enum import Enum from ..utils import PersistableDict, retry from .exceptions import BackendError, DependencyError, TargetError from .logmanager import FileLogManager and context (class names, function names, or code) available: # Path: src/gwf/utils.py # class PersistableDict(UserDict): # """A dictionary which can persist itself to JSON.""" # # def __init__(self, path): # super().__init__() # # self.path = path # try: # with open(self.path) as fileobj: # self.data.update(json.load(fileobj)) # except (OSError, ValueError): # # Catch ValueError for compatibility with Python 3.4.2. I haven't been # # able to figure out what is different between 3.4.2 and 3.5 that # # causes this. Essentially, 3.4.2 raises a ValueError saying that it # # cannot parse the empty string instead of raising an OSError # # (FileNotFoundError does not exist in 3.4.2) saying that the file does # # not exist. # pass # # def persist(self): # with open(self.path + ".new", "w") as fileobj: # json.dump(self.data, fileobj) # fileobj.flush() # os.fsync(fileobj.fileno()) # fileobj.close() # os.rename(self.path + ".new", self.path) # # def retry(on_exc, max_retries=3, callback=None): # """Retry a function with exponentially increasing delay. # # This will retry the decorated function up to `max_retries` times. A retry # will only be attempted if the exception raised by the wrapped function is # in `on_exc`. # # If `callback(retries, delay)` is given, it must be a callable the number of # retries so far as the first argument and the current delay as the second # argument. Its return value is ignored. # """ # # def retry_decorator(func): # @wraps(func) # def func_wrapper(*args, **kwargs): # last_exc = None # for retries in itertools.count(): # pragma: no cover # if retries >= max_retries: # raise RetryError(func.__name__) from last_exc # # try: # return func(*args, **kwargs) # except on_exc as exc: # last_exc = exc # # delay = (2 ** retries) // 2 # if callback is not None: # callback(retries, delay) # # logger.exception(exc) # logger.warning( # "Call to %s failed, retrying in %d seconds.", # func.__name__, # delay, # ) # time.sleep(delay) # # return func_wrapper # # return retry_decorator # # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass # # class DependencyError(BackendError): # pass # # class TargetError(BackendError): # pass . Output only the next line.
return cls.from_name(config["backend"])
Predict the next line after this snippet: <|code_start|> """Return the names of all registered backends.""" return set(_load_backends().keys()) @classmethod def from_name(cls, name): """Return backend class for the backend given by `name`. Returns the backend class registered with `name`. Note that the *class* is returned, not the instance, since not all uses requires initialization of the backend (e.g. accessing the backends' log manager), and initialization of the backend may be expensive. :arg str name: Path to a workflow file, optionally specifying a workflow object in that file. """ return _load_backends()[name] @classmethod def from_config(cls, config): """Return backend class for the backend specified by `config`. See :func:`Backend.from_name` for further information.""" return cls.from_name(config["backend"]) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() <|code_end|> using the current file's imports: import sys import logging from importlib_metadata import entry_points from importlib.metadata import entry_points from enum import Enum from ..utils import PersistableDict, retry from .exceptions import BackendError, DependencyError, TargetError from .logmanager import FileLogManager and any relevant context from other files: # Path: src/gwf/utils.py # class PersistableDict(UserDict): # """A dictionary which can persist itself to JSON.""" # # def __init__(self, path): # super().__init__() # # self.path = path # try: # with open(self.path) as fileobj: # self.data.update(json.load(fileobj)) # except (OSError, ValueError): # # Catch ValueError for compatibility with Python 3.4.2. I haven't been # # able to figure out what is different between 3.4.2 and 3.5 that # # causes this. Essentially, 3.4.2 raises a ValueError saying that it # # cannot parse the empty string instead of raising an OSError # # (FileNotFoundError does not exist in 3.4.2) saying that the file does # # not exist. # pass # # def persist(self): # with open(self.path + ".new", "w") as fileobj: # json.dump(self.data, fileobj) # fileobj.flush() # os.fsync(fileobj.fileno()) # fileobj.close() # os.rename(self.path + ".new", self.path) # # def retry(on_exc, max_retries=3, callback=None): # """Retry a function with exponentially increasing delay. # # This will retry the decorated function up to `max_retries` times. A retry # will only be attempted if the exception raised by the wrapped function is # in `on_exc`. # # If `callback(retries, delay)` is given, it must be a callable the number of # retries so far as the first argument and the current delay as the second # argument. Its return value is ignored. # """ # # def retry_decorator(func): # @wraps(func) # def func_wrapper(*args, **kwargs): # last_exc = None # for retries in itertools.count(): # pragma: no cover # if retries >= max_retries: # raise RetryError(func.__name__) from last_exc # # try: # return func(*args, **kwargs) # except on_exc as exc: # last_exc = exc # # delay = (2 ** retries) // 2 # if callback is not None: # callback(retries, delay) # # logger.exception(exc) # logger.warning( # "Call to %s failed, retrying in %d seconds.", # func.__name__, # delay, # ) # time.sleep(delay) # # return func_wrapper # # return retry_decorator # # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass # # class DependencyError(BackendError): # pass # # class TargetError(BackendError): # pass . Output only the next line.
def status(self, target):
Here is a snippet: <|code_start|> @classmethod def list(cls): """Return the names of all registered backends.""" return set(_load_backends().keys()) @classmethod def from_name(cls, name): """Return backend class for the backend given by `name`. Returns the backend class registered with `name`. Note that the *class* is returned, not the instance, since not all uses requires initialization of the backend (e.g. accessing the backends' log manager), and initialization of the backend may be expensive. :arg str name: Path to a workflow file, optionally specifying a workflow object in that file. """ return _load_backends()[name] @classmethod def from_config(cls, config): """Return backend class for the backend specified by `config`. See :func:`Backend.from_name` for further information.""" return cls.from_name(config["backend"]) def __enter__(self): return self <|code_end|> . Write the next line using the current file imports: import sys import logging from importlib_metadata import entry_points from importlib.metadata import entry_points from enum import Enum from ..utils import PersistableDict, retry from .exceptions import BackendError, DependencyError, TargetError from .logmanager import FileLogManager and context from other files: # Path: src/gwf/utils.py # class PersistableDict(UserDict): # """A dictionary which can persist itself to JSON.""" # # def __init__(self, path): # super().__init__() # # self.path = path # try: # with open(self.path) as fileobj: # self.data.update(json.load(fileobj)) # except (OSError, ValueError): # # Catch ValueError for compatibility with Python 3.4.2. I haven't been # # able to figure out what is different between 3.4.2 and 3.5 that # # causes this. Essentially, 3.4.2 raises a ValueError saying that it # # cannot parse the empty string instead of raising an OSError # # (FileNotFoundError does not exist in 3.4.2) saying that the file does # # not exist. # pass # # def persist(self): # with open(self.path + ".new", "w") as fileobj: # json.dump(self.data, fileobj) # fileobj.flush() # os.fsync(fileobj.fileno()) # fileobj.close() # os.rename(self.path + ".new", self.path) # # def retry(on_exc, max_retries=3, callback=None): # """Retry a function with exponentially increasing delay. # # This will retry the decorated function up to `max_retries` times. A retry # will only be attempted if the exception raised by the wrapped function is # in `on_exc`. # # If `callback(retries, delay)` is given, it must be a callable the number of # retries so far as the first argument and the current delay as the second # argument. Its return value is ignored. # """ # # def retry_decorator(func): # @wraps(func) # def func_wrapper(*args, **kwargs): # last_exc = None # for retries in itertools.count(): # pragma: no cover # if retries >= max_retries: # raise RetryError(func.__name__) from last_exc # # try: # return func(*args, **kwargs) # except on_exc as exc: # last_exc = exc # # delay = (2 ** retries) // 2 # if callback is not None: # callback(retries, delay) # # logger.exception(exc) # logger.warning( # "Call to %s failed, retrying in %d seconds.", # func.__name__, # delay, # ) # time.sleep(delay) # # return func_wrapper # # return retry_decorator # # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass # # class DependencyError(BackendError): # pass # # class TargetError(BackendError): # pass , which may include functions, classes, or code. Output only the next line.
def __exit__(self, exc_type, exc_val, exc_tb):
Given the following code snippet before the placeholder: <|code_start|> """Return the names of all registered backends.""" return set(_load_backends().keys()) @classmethod def from_name(cls, name): """Return backend class for the backend given by `name`. Returns the backend class registered with `name`. Note that the *class* is returned, not the instance, since not all uses requires initialization of the backend (e.g. accessing the backends' log manager), and initialization of the backend may be expensive. :arg str name: Path to a workflow file, optionally specifying a workflow object in that file. """ return _load_backends()[name] @classmethod def from_config(cls, config): """Return backend class for the backend specified by `config`. See :func:`Backend.from_name` for further information.""" return cls.from_name(config["backend"]) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() <|code_end|> , predict the next line using imports from the current file: import sys import logging from importlib_metadata import entry_points from importlib.metadata import entry_points from enum import Enum from ..utils import PersistableDict, retry from .exceptions import BackendError, DependencyError, TargetError from .logmanager import FileLogManager and context including class names, function names, and sometimes code from other files: # Path: src/gwf/utils.py # class PersistableDict(UserDict): # """A dictionary which can persist itself to JSON.""" # # def __init__(self, path): # super().__init__() # # self.path = path # try: # with open(self.path) as fileobj: # self.data.update(json.load(fileobj)) # except (OSError, ValueError): # # Catch ValueError for compatibility with Python 3.4.2. I haven't been # # able to figure out what is different between 3.4.2 and 3.5 that # # causes this. Essentially, 3.4.2 raises a ValueError saying that it # # cannot parse the empty string instead of raising an OSError # # (FileNotFoundError does not exist in 3.4.2) saying that the file does # # not exist. # pass # # def persist(self): # with open(self.path + ".new", "w") as fileobj: # json.dump(self.data, fileobj) # fileobj.flush() # os.fsync(fileobj.fileno()) # fileobj.close() # os.rename(self.path + ".new", self.path) # # def retry(on_exc, max_retries=3, callback=None): # """Retry a function with exponentially increasing delay. # # This will retry the decorated function up to `max_retries` times. A retry # will only be attempted if the exception raised by the wrapped function is # in `on_exc`. # # If `callback(retries, delay)` is given, it must be a callable the number of # retries so far as the first argument and the current delay as the second # argument. Its return value is ignored. # """ # # def retry_decorator(func): # @wraps(func) # def func_wrapper(*args, **kwargs): # last_exc = None # for retries in itertools.count(): # pragma: no cover # if retries >= max_retries: # raise RetryError(func.__name__) from last_exc # # try: # return func(*args, **kwargs) # except on_exc as exc: # last_exc = exc # # delay = (2 ** retries) // 2 # if callback is not None: # callback(retries, delay) # # logger.exception(exc) # logger.warning( # "Call to %s failed, retrying in %d seconds.", # func.__name__, # delay, # ) # time.sleep(delay) # # return func_wrapper # # return retry_decorator # # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass # # class DependencyError(BackendError): # pass # # class TargetError(BackendError): # pass . Output only the next line.
def status(self, target):
Using the snippet: <|code_start|> if sys.version_info < (3, 10): else: logger = logging.getLogger(__name__) __all__ = ("Backend", "Status") def _load_backends(): <|code_end|> , determine the next line of code. You have imports: import sys import logging from importlib_metadata import entry_points from importlib.metadata import entry_points from enum import Enum from ..utils import PersistableDict, retry from .exceptions import BackendError, DependencyError, TargetError from .logmanager import FileLogManager and context (class names, function names, or code) available: # Path: src/gwf/utils.py # class PersistableDict(UserDict): # """A dictionary which can persist itself to JSON.""" # # def __init__(self, path): # super().__init__() # # self.path = path # try: # with open(self.path) as fileobj: # self.data.update(json.load(fileobj)) # except (OSError, ValueError): # # Catch ValueError for compatibility with Python 3.4.2. I haven't been # # able to figure out what is different between 3.4.2 and 3.5 that # # causes this. Essentially, 3.4.2 raises a ValueError saying that it # # cannot parse the empty string instead of raising an OSError # # (FileNotFoundError does not exist in 3.4.2) saying that the file does # # not exist. # pass # # def persist(self): # with open(self.path + ".new", "w") as fileobj: # json.dump(self.data, fileobj) # fileobj.flush() # os.fsync(fileobj.fileno()) # fileobj.close() # os.rename(self.path + ".new", self.path) # # def retry(on_exc, max_retries=3, callback=None): # """Retry a function with exponentially increasing delay. # # This will retry the decorated function up to `max_retries` times. A retry # will only be attempted if the exception raised by the wrapped function is # in `on_exc`. # # If `callback(retries, delay)` is given, it must be a callable the number of # retries so far as the first argument and the current delay as the second # argument. Its return value is ignored. # """ # # def retry_decorator(func): # @wraps(func) # def func_wrapper(*args, **kwargs): # last_exc = None # for retries in itertools.count(): # pragma: no cover # if retries >= max_retries: # raise RetryError(func.__name__) from last_exc # # try: # return func(*args, **kwargs) # except on_exc as exc: # last_exc = exc # # delay = (2 ** retries) // 2 # if callback is not None: # callback(retries, delay) # # logger.exception(exc) # logger.warning( # "Call to %s failed, retrying in %d seconds.", # func.__name__, # delay, # ) # time.sleep(delay) # # return func_wrapper # # return retry_decorator # # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass # # class DependencyError(BackendError): # pass # # class TargetError(BackendError): # pass . Output only the next line.
return {ep.name: ep.load() for ep in entry_points(group="gwf.backends")}
Given the code snippet: <|code_start|> def _find_exe(name): exe = shutil.which(name) if exe is None: raise BackendError( <|code_end|> , generate the next line using the imports in this file: import shutil import subprocess from .exceptions import BackendError and context (functions, classes, or occasionally code) from other files: # Path: src/gwf/backends/exceptions.py # class BackendError(GWFError): # pass . Output only the next line.
f'Could not find executable "{name}". This backend requires Slurm '
Predict the next line for this snippet: <|code_start|> @click.command() @click.option( "-n", "--num-workers", type=int, default=config.get("local.num_workers", multiprocessing.cpu_count()), help="Number of workers to spawn.", ) @click.option( "-p", "--port", type=int, default=config.get("local.port", 12345), help="Port that workers will listen on.", <|code_end|> with the help of current file imports: import multiprocessing import click from ..backends.local import Server from ..conf import config and context from other files: # Path: src/gwf/backends/local.py # class Server: # def __init__(self, hostname="", port=0, num_workers=None): # self.hostname = hostname # self.port = port # self.num_workers = num_workers # # self.manager = Manager() # self.status = self.manager.dict() # self.queue = self.manager.Queue() # self.waiting = self.manager.dict() # self.lock = self.manager.Lock() # # def handle_request(self, request): # try: # logger.debug("Received request %r", request) # return request.handle(self.queue, self.status) # except Exception: # logger.error("Invalid request %r", request, exc_info=True) # # def handle_client(self, conn): # logger.debug("Accepted client connection.") # try: # while True: # request = conn.recv() # response = self.handle_request(request) # if response is not None: # conn.send(response) # except EOFError: # logger.debug("Client connection closed.") # # def wait_for_clients(self, serv): # while True: # client = serv.accept() # self.handle_client(client) # # def start(self): # """Starts a server that controls local workers. # # Calling this function starts a pool of `num_workers` workers used to run # targets sent to the server. The server will run indefinitely unless shut # down by the user. # """ # try: # serv = Listener((self.hostname, self.port)) # workers = Pool( # processes=self.num_workers, # initializer=Worker, # initargs=(self.status, self.queue, self.waiting, self.lock), # ) # # logging.info( # "Started %s workers, listening on port %s", # self.num_workers, # serv.address[1], # ) # self.wait_for_clients(serv) # except OSError as e: # if e.errno == 48: # raise ServerError( # ( # "Could not start workers listening on port {}. " # "The port may already be in use." # ).format(self.port) # ) # except KeyboardInterrupt: # logging.info("Shutting down...") # workers.close() # workers.join() # self.manager.shutdown() # # Path: src/gwf/conf.py # CONFIG_DEFAULTS = {"verbose": "info", "backend": "local", "check_updates": True} # class FileConfig: # def __init__(self, path, data, defaults=None): # def validator(self, key): # def _inner(func): # def _validate_value(self, key, value): # def get(self, key, default=None): # def __getitem__(self, key): # def __setitem__(self, key, value): # def __delitem__(self, key): # def __len__(self): # def __iter__(self): # def dump(self): # def load(cls, path, defaults=None): # def config_from_path(path): , which may contain function names, class names, or code. Output only the next line.
)
Next line prediction: <|code_start|> @click.command() @click.option( "-n", "--num-workers", type=int, default=config.get("local.num_workers", multiprocessing.cpu_count()), help="Number of workers to spawn.", ) @click.option( "-p", "--port", type=int, default=config.get("local.port", 12345), help="Port that workers will listen on.", <|code_end|> . Use current file imports: (import multiprocessing import click from ..backends.local import Server from ..conf import config) and context including class names, function names, or small code snippets from other files: # Path: src/gwf/backends/local.py # class Server: # def __init__(self, hostname="", port=0, num_workers=None): # self.hostname = hostname # self.port = port # self.num_workers = num_workers # # self.manager = Manager() # self.status = self.manager.dict() # self.queue = self.manager.Queue() # self.waiting = self.manager.dict() # self.lock = self.manager.Lock() # # def handle_request(self, request): # try: # logger.debug("Received request %r", request) # return request.handle(self.queue, self.status) # except Exception: # logger.error("Invalid request %r", request, exc_info=True) # # def handle_client(self, conn): # logger.debug("Accepted client connection.") # try: # while True: # request = conn.recv() # response = self.handle_request(request) # if response is not None: # conn.send(response) # except EOFError: # logger.debug("Client connection closed.") # # def wait_for_clients(self, serv): # while True: # client = serv.accept() # self.handle_client(client) # # def start(self): # """Starts a server that controls local workers. # # Calling this function starts a pool of `num_workers` workers used to run # targets sent to the server. The server will run indefinitely unless shut # down by the user. # """ # try: # serv = Listener((self.hostname, self.port)) # workers = Pool( # processes=self.num_workers, # initializer=Worker, # initargs=(self.status, self.queue, self.waiting, self.lock), # ) # # logging.info( # "Started %s workers, listening on port %s", # self.num_workers, # serv.address[1], # ) # self.wait_for_clients(serv) # except OSError as e: # if e.errno == 48: # raise ServerError( # ( # "Could not start workers listening on port {}. " # "The port may already be in use." # ).format(self.port) # ) # except KeyboardInterrupt: # logging.info("Shutting down...") # workers.close() # workers.join() # self.manager.shutdown() # # Path: src/gwf/conf.py # CONFIG_DEFAULTS = {"verbose": "info", "backend": "local", "check_updates": True} # class FileConfig: # def __init__(self, path, data, defaults=None): # def validator(self, key): # def _inner(func): # def _validate_value(self, key, value): # def get(self, key, default=None): # def __getitem__(self, key): # def __setitem__(self, key, value): # def __delitem__(self, key): # def __len__(self): # def __iter__(self): # def dump(self): # def load(cls, path, defaults=None): # def config_from_path(path): . Output only the next line.
)
Using the snippet: <|code_start|> def humanbool(x): if x in ("true", "yes"): return True elif x in ("false", "no"): return False raise TypeError("x is not a boolean.") <|code_end|> , determine the next line of code. You have imports: import click from ..conf import config as _config and context (class names, function names, or code) available: # Path: src/gwf/conf.py # CONFIG_DEFAULTS = {"verbose": "info", "backend": "local", "check_updates": True} # class FileConfig: # def __init__(self, path, data, defaults=None): # def validator(self, key): # def _inner(func): # def _validate_value(self, key, value): # def get(self, key, default=None): # def __getitem__(self, key): # def __setitem__(self, key, value): # def __delitem__(self, key): # def __len__(self): # def __iter__(self): # def dump(self): # def load(cls, path, defaults=None): # def config_from_path(path): . Output only the next line.
def cast_value(value):
Predict the next line after this snippet: <|code_start|> banner = r""" .-_'''-. .--. .--. ________ '_( )_ \ | |_ | || | |(_ o _)| ' | _( )_ | || .----' . (_,_)/___| |(_ o _) | || _|____ | | .-----.| (_,_) \ | ||_( )_ | <|code_end|> using the current file's imports: from pathlib import Path from ..backends import Backend from ..conf import config_from_path import click and any relevant context from other files: # Path: src/gwf/backends/base.py # class Backend: # """Base class for backends.""" # # option_defaults = {} # log_manager = FileLogManager() # # @classmethod # def list(cls): # """Return the names of all registered backends.""" # return set(_load_backends().keys()) # # @classmethod # def from_name(cls, name): # """Return backend class for the backend given by `name`. # # Returns the backend class registered with `name`. Note that the *class* # is returned, not the instance, since not all uses requires # initialization of the backend (e.g. accessing the backends' log # manager), and initialization of the backend may be expensive. # # :arg str name: Path to a workflow file, optionally specifying a # workflow object in that file. # """ # return _load_backends()[name] # # @classmethod # def from_config(cls, config): # """Return backend class for the backend specified by `config`. # # See :func:`Backend.from_name` for further information.""" # return cls.from_name(config["backend"]) # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # self.close() # # def status(self, target): # """Return the status of `target`. # # :param gwf.Target target: The target to return the status of. # :return gwf.backends.Status: Status of `target`. # """ # # def submit_full(self, target, dependencies): # """Prepare and submit `target` with `dependencies`. # # Will prepare the target for submission by injecting option defaults # from the backend, check for unsupported options, and removing options # with a `None` value. # # This is the primary way to submit a target. Do not call # :func:`submit` directly, unless you want to manually deal with with # injection of option defaults. # """ # new_options = dict(self.option_defaults) # new_options.update(target.options) # # for option_name, option_value in list(new_options.items()): # if option_name not in self.option_defaults.keys(): # logger.warning( # "Option '%s' used in '%s' is not supported by backend. Ignored.", # option_name, # target.name, # ) # del new_options[option_name] # elif option_value is None: # del new_options[option_name] # target.options = new_options # # self.submit(target, dependencies) # # def submit(self, target, dependencies): # """Submit `target` with `dependencies`. # # This method must submit the `target` and return immediately. That is, # the method must not block while waiting for the target to complete. # # :param gwf.Target target: # The target to submit. # :param dependencies: # An iterable of :class:`gwf.Target` objects that `target` depends on # and that have already been submitted to the backend. # """ # # def cancel(self, target): # """Cancel `target`. # # :param gwf.Target target: # The target to cancel. # :raises gwf.exception.TargetError: # If the target does not exist in the workflow. # """ # # @classmethod # def logs(cls, target, stderr=False): # """Return log files for a target. # # If the backend cannot return logs a # :class:`~gwf.exceptions.NoLogFoundError` is raised. # # By default standard output (stdout) is returned. If `stderr=True` # standard error will be returned instead. # # :param gwf.Target target: # Target to return logs for. # :param bool stderr: # default: False. If true, return standard error. # :return: # A file-like object. The user is responsible for closing the # returned file(s) after use. # :raises gwf.exceptions.NoLogFoundError: # if the backend could not find a log for the given target. # """ # if stderr: # return cls.log_manager.open_stderr(target) # return cls.log_manager.open_stdout(target) # # def close(self): # """Close the backend. # # Called when the backend is no longer needed and should close all # resources (open files, connections) used by the backend. # """ # # Path: src/gwf/conf.py # def config_from_path(path): # return FileConfig.load(path, defaults=CONFIG_DEFAULTS) . Output only the next line.
' \ '- .'| |/ \| |(_ o._)__|
Next line prediction: <|code_start|> banner = r""" .-_'''-. .--. .--. ________ '_( )_ \ | |_ | || | |(_ o _)| ' | _( )_ | || .----' . (_,_)/___| |(_ o _) | || _|____ | | .-----.| (_,_) \ | ||_( )_ | ' \ '- .'| |/ \| |(_ o._)__| \ `-'` | | ' /\ ` ||(_,_) \ / | / \ || | <|code_end|> . Use current file imports: (from pathlib import Path from ..backends import Backend from ..conf import config_from_path import click) and context including class names, function names, or small code snippets from other files: # Path: src/gwf/backends/base.py # class Backend: # """Base class for backends.""" # # option_defaults = {} # log_manager = FileLogManager() # # @classmethod # def list(cls): # """Return the names of all registered backends.""" # return set(_load_backends().keys()) # # @classmethod # def from_name(cls, name): # """Return backend class for the backend given by `name`. # # Returns the backend class registered with `name`. Note that the *class* # is returned, not the instance, since not all uses requires # initialization of the backend (e.g. accessing the backends' log # manager), and initialization of the backend may be expensive. # # :arg str name: Path to a workflow file, optionally specifying a # workflow object in that file. # """ # return _load_backends()[name] # # @classmethod # def from_config(cls, config): # """Return backend class for the backend specified by `config`. # # See :func:`Backend.from_name` for further information.""" # return cls.from_name(config["backend"]) # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # self.close() # # def status(self, target): # """Return the status of `target`. # # :param gwf.Target target: The target to return the status of. # :return gwf.backends.Status: Status of `target`. # """ # # def submit_full(self, target, dependencies): # """Prepare and submit `target` with `dependencies`. # # Will prepare the target for submission by injecting option defaults # from the backend, check for unsupported options, and removing options # with a `None` value. # # This is the primary way to submit a target. Do not call # :func:`submit` directly, unless you want to manually deal with with # injection of option defaults. # """ # new_options = dict(self.option_defaults) # new_options.update(target.options) # # for option_name, option_value in list(new_options.items()): # if option_name not in self.option_defaults.keys(): # logger.warning( # "Option '%s' used in '%s' is not supported by backend. Ignored.", # option_name, # target.name, # ) # del new_options[option_name] # elif option_value is None: # del new_options[option_name] # target.options = new_options # # self.submit(target, dependencies) # # def submit(self, target, dependencies): # """Submit `target` with `dependencies`. # # This method must submit the `target` and return immediately. That is, # the method must not block while waiting for the target to complete. # # :param gwf.Target target: # The target to submit. # :param dependencies: # An iterable of :class:`gwf.Target` objects that `target` depends on # and that have already been submitted to the backend. # """ # # def cancel(self, target): # """Cancel `target`. # # :param gwf.Target target: # The target to cancel. # :raises gwf.exception.TargetError: # If the target does not exist in the workflow. # """ # # @classmethod # def logs(cls, target, stderr=False): # """Return log files for a target. # # If the backend cannot return logs a # :class:`~gwf.exceptions.NoLogFoundError` is raised. # # By default standard output (stdout) is returned. If `stderr=True` # standard error will be returned instead. # # :param gwf.Target target: # Target to return logs for. # :param bool stderr: # default: False. If true, return standard error. # :return: # A file-like object. The user is responsible for closing the # returned file(s) after use. # :raises gwf.exceptions.NoLogFoundError: # if the backend could not find a log for the given target. # """ # if stderr: # return cls.log_manager.open_stderr(target) # return cls.log_manager.open_stdout(target) # # def close(self): # """Close the backend. # # Called when the backend is no longer needed and should close all # resources (open files, connections) used by the backend. # """ # # Path: src/gwf/conf.py # def config_from_path(path): # return FileConfig.load(path, defaults=CONFIG_DEFAULTS) . Output only the next line.
`'-...-' `---' `---`'---'"""
Next line prediction: <|code_start|> class EntryMixin: date_field = "pub_date" model = Entry class CategoryMixin: model = Category class EntryArchiveIndex(EntryMixin, generic.ArchiveIndexView): pass class EntryArchiveYear(EntryMixin, generic.YearArchiveView): make_object_list = True class EntryArchiveMonth(EntryMixin, generic.MonthArchiveView): <|code_end|> . Use current file imports: (from django.views import generic from .models import Category, Entry) and context including class names, function names, or small code snippets from other files: # Path: blog/models.py # class Category(models.Model): # """ # A category into which entries can be filed. # # """ # # title = models.CharField(max_length=250) # slug = models.SlugField(unique=True) # description = models.TextField() # description_html = models.TextField(editable=False, blank=True) # # class Meta: # verbose_name_plural = "Categories" # ordering = ("title",) # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.description_html = markup(self.description) # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "categories:category", kwargs={"slug": self.slug}, current_app="blog" # ) # # def _get_live_entries(self) -> models.QuerySet: # return self.entry_set.filter(status=Entry.LIVE_STATUS) # # live_entries = property(_get_live_entries) # # class Entry(models.Model): # """ # An entry in the blog. # # """ # # LIVE_STATUS = 1 # DRAFT_STATUS = 2 # HIDDEN_STATUS = 3 # STATUS_CHOICES = ( # (LIVE_STATUS, "Live"), # (DRAFT_STATUS, "Draft"), # (HIDDEN_STATUS, "Hidden"), # ) # # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # pub_date = models.DateTimeField("Date posted", default=datetime.datetime.now) # updated_date = models.DateTimeField(blank=True, editable=False) # slug = models.SlugField(unique_for_date="pub_date") # status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) # title = models.CharField(max_length=250) # # body = models.TextField() # body_html = models.TextField(editable=False, blank=True) # # excerpt = models.TextField(blank=True, null=True) # excerpt_html = models.TextField(editable=False, blank=True, null=True) # # categories = models.ManyToManyField("Category") # # live = LiveEntryManager() # objects = models.Manager() # # class Meta: # get_latest_by = "pub_date" # ordering = ("-pub_date",) # verbose_name_plural = "Entries" # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.body_html = markup(self.body) # if self.excerpt: # self.excerpt_html = markup(self.excerpt) # self.updated_date = datetime.datetime.now() # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "entries:entry", # kwargs={ # "year": self.pub_date.strftime("%Y"), # "month": self.pub_date.strftime("%b").lower(), # "day": self.pub_date.strftime("%d"), # "slug": self.slug, # }, # ) . Output only the next line.
pass
Next line prediction: <|code_start|> class EntryMixin: date_field = "pub_date" model = Entry <|code_end|> . Use current file imports: (from django.views import generic from .models import Category, Entry) and context including class names, function names, or small code snippets from other files: # Path: blog/models.py # class Category(models.Model): # """ # A category into which entries can be filed. # # """ # # title = models.CharField(max_length=250) # slug = models.SlugField(unique=True) # description = models.TextField() # description_html = models.TextField(editable=False, blank=True) # # class Meta: # verbose_name_plural = "Categories" # ordering = ("title",) # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.description_html = markup(self.description) # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "categories:category", kwargs={"slug": self.slug}, current_app="blog" # ) # # def _get_live_entries(self) -> models.QuerySet: # return self.entry_set.filter(status=Entry.LIVE_STATUS) # # live_entries = property(_get_live_entries) # # class Entry(models.Model): # """ # An entry in the blog. # # """ # # LIVE_STATUS = 1 # DRAFT_STATUS = 2 # HIDDEN_STATUS = 3 # STATUS_CHOICES = ( # (LIVE_STATUS, "Live"), # (DRAFT_STATUS, "Draft"), # (HIDDEN_STATUS, "Hidden"), # ) # # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # pub_date = models.DateTimeField("Date posted", default=datetime.datetime.now) # updated_date = models.DateTimeField(blank=True, editable=False) # slug = models.SlugField(unique_for_date="pub_date") # status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) # title = models.CharField(max_length=250) # # body = models.TextField() # body_html = models.TextField(editable=False, blank=True) # # excerpt = models.TextField(blank=True, null=True) # excerpt_html = models.TextField(editable=False, blank=True, null=True) # # categories = models.ManyToManyField("Category") # # live = LiveEntryManager() # objects = models.Manager() # # class Meta: # get_latest_by = "pub_date" # ordering = ("-pub_date",) # verbose_name_plural = "Entries" # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.body_html = markup(self.body) # if self.excerpt: # self.excerpt_html = markup(self.excerpt) # self.updated_date = datetime.datetime.now() # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "entries:entry", # kwargs={ # "year": self.pub_date.strftime("%Y"), # "month": self.pub_date.strftime("%b").lower(), # "day": self.pub_date.strftime("%d"), # "slug": self.slug, # }, # ) . Output only the next line.
class CategoryMixin:
Given the code snippet: <|code_start|> @admin.register(License) class LicenseAdmin(admin.ModelAdmin): list_display = ("name",) prepopulated_fields = {"slug": ("name",)} class VersionInline(admin.StackedInline): fields = ("version", "status", "release_date", "is_latest", "license") model = Version @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): fieldsets = ( ("Metadata", {"fields": ("name", "slug", "status")}), ( "Project information", { "fields": ( "description", "package_link", "repository_link", "documentation_link", "tests_link", <|code_end|> , generate the next line using the imports in this file: import typing from django.contrib import admin from .models import License, Project, Version and context (functions, classes, or occasionally code) from other files: # Path: projects/models.py # class License(models.Model): # """ # A license in use for a project. # # This model is related through Version instead of directly on # Project, in order to support re-licensing the project with a new # version. # # """ # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # link = models.URLField() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # class Project(models.Model): # """ # A software project. # # """ # # HIDDEN_STATUS = 0 # PUBLIC_STATUS = 1 # STATUS_CHOICES = ((HIDDEN_STATUS, "Hidden"), (PUBLIC_STATUS, "Public")) # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # status = models.IntegerField(choices=STATUS_CHOICES, default=PUBLIC_STATUS) # description = models.TextField() # # package_link = models.URLField( # blank=True, null=True, help_text="URL of the project's package(s)" # ) # repository_link = models.URLField( # blank=True, null=True, help_text="URL of the project's repostory" # ) # documentation_link = models.URLField( # blank=True, null=True, help_text="URL of the project's documentation" # ) # tests_link = models.URLField( # blank=True, # null=True, # help_text="URL of the project's tests/continuous integration", # ) # # objects = managers.ProjectQuerySet.as_manager() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # def get_absolute_url(self) -> str: # return reverse("projects:detail", kwargs={"slug": self.slug}) # # def latest_version(self) -> typing.Optional[int]: # latest = self.versions.filter(is_latest=True) # if latest: # return latest[0] # return None # # class Version(models.Model): # """ # A version of a software project. # # """ # # PLANNING_STATUS = 1 # PRE_ALPHA_STATUS = 2 # ALPHA_STATUS = 3 # BETA_STATUS = 4 # STABLE_STATUS = 5 # # STATUS_CHOICES = ( # (PLANNING_STATUS, "Planning"), # (PRE_ALPHA_STATUS, "Pre-Alpha"), # (ALPHA_STATUS, "Alpha"), # (BETA_STATUS, "Beta"), # (STABLE_STATUS, "Stable"), # ) # # project = models.ForeignKey( # Project, related_name="versions", on_delete=models.CASCADE # ) # version = models.CharField(max_length=255) # is_latest = models.BooleanField(default=False) # # status = models.IntegerField(choices=STATUS_CHOICES, default=STABLE_STATUS) # license = models.ForeignKey(License, on_delete=models.CASCADE) # release_date = models.DateField(default=datetime.date.today) # # objects = managers.VersionManager() # # class Meta: # ordering = ("project", "version") # unique_together = ("project", "version") # # def __str__(self) -> str: # return "%s %s" % (self.project, self.version) # # def get_absolute_url(self) -> str: # return reverse( # "projects_version_detail", # kwargs={"project_slug": self.project.slug, "slug": self.version}, # ) . Output only the next line.
)
Next line prediction: <|code_start|> @admin.register(License) class LicenseAdmin(admin.ModelAdmin): list_display = ("name",) prepopulated_fields = {"slug": ("name",)} class VersionInline(admin.StackedInline): fields = ("version", "status", "release_date", "is_latest", "license") model = Version @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): fieldsets = ( ("Metadata", {"fields": ("name", "slug", "status")}), ( "Project information", { "fields": ( "description", "package_link", "repository_link", "documentation_link", "tests_link", ) }, <|code_end|> . Use current file imports: (import typing from django.contrib import admin from .models import License, Project, Version) and context including class names, function names, or small code snippets from other files: # Path: projects/models.py # class License(models.Model): # """ # A license in use for a project. # # This model is related through Version instead of directly on # Project, in order to support re-licensing the project with a new # version. # # """ # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # link = models.URLField() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # class Project(models.Model): # """ # A software project. # # """ # # HIDDEN_STATUS = 0 # PUBLIC_STATUS = 1 # STATUS_CHOICES = ((HIDDEN_STATUS, "Hidden"), (PUBLIC_STATUS, "Public")) # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # status = models.IntegerField(choices=STATUS_CHOICES, default=PUBLIC_STATUS) # description = models.TextField() # # package_link = models.URLField( # blank=True, null=True, help_text="URL of the project's package(s)" # ) # repository_link = models.URLField( # blank=True, null=True, help_text="URL of the project's repostory" # ) # documentation_link = models.URLField( # blank=True, null=True, help_text="URL of the project's documentation" # ) # tests_link = models.URLField( # blank=True, # null=True, # help_text="URL of the project's tests/continuous integration", # ) # # objects = managers.ProjectQuerySet.as_manager() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # def get_absolute_url(self) -> str: # return reverse("projects:detail", kwargs={"slug": self.slug}) # # def latest_version(self) -> typing.Optional[int]: # latest = self.versions.filter(is_latest=True) # if latest: # return latest[0] # return None # # class Version(models.Model): # """ # A version of a software project. # # """ # # PLANNING_STATUS = 1 # PRE_ALPHA_STATUS = 2 # ALPHA_STATUS = 3 # BETA_STATUS = 4 # STABLE_STATUS = 5 # # STATUS_CHOICES = ( # (PLANNING_STATUS, "Planning"), # (PRE_ALPHA_STATUS, "Pre-Alpha"), # (ALPHA_STATUS, "Alpha"), # (BETA_STATUS, "Beta"), # (STABLE_STATUS, "Stable"), # ) # # project = models.ForeignKey( # Project, related_name="versions", on_delete=models.CASCADE # ) # version = models.CharField(max_length=255) # is_latest = models.BooleanField(default=False) # # status = models.IntegerField(choices=STATUS_CHOICES, default=STABLE_STATUS) # license = models.ForeignKey(License, on_delete=models.CASCADE) # release_date = models.DateField(default=datetime.date.today) # # objects = managers.VersionManager() # # class Meta: # ordering = ("project", "version") # unique_together = ("project", "version") # # def __str__(self) -> str: # return "%s %s" % (self.project, self.version) # # def get_absolute_url(self) -> str: # return reverse( # "projects_version_detail", # kwargs={"project_slug": self.project.slug, "slug": self.version}, # ) . Output only the next line.
),
Given the code snippet: <|code_start|> @admin.register(License) class LicenseAdmin(admin.ModelAdmin): list_display = ("name",) prepopulated_fields = {"slug": ("name",)} class VersionInline(admin.StackedInline): fields = ("version", "status", "release_date", "is_latest", "license") model = Version @admin.register(Project) <|code_end|> , generate the next line using the imports in this file: import typing from django.contrib import admin from .models import License, Project, Version and context (functions, classes, or occasionally code) from other files: # Path: projects/models.py # class License(models.Model): # """ # A license in use for a project. # # This model is related through Version instead of directly on # Project, in order to support re-licensing the project with a new # version. # # """ # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # link = models.URLField() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # class Project(models.Model): # """ # A software project. # # """ # # HIDDEN_STATUS = 0 # PUBLIC_STATUS = 1 # STATUS_CHOICES = ((HIDDEN_STATUS, "Hidden"), (PUBLIC_STATUS, "Public")) # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # status = models.IntegerField(choices=STATUS_CHOICES, default=PUBLIC_STATUS) # description = models.TextField() # # package_link = models.URLField( # blank=True, null=True, help_text="URL of the project's package(s)" # ) # repository_link = models.URLField( # blank=True, null=True, help_text="URL of the project's repostory" # ) # documentation_link = models.URLField( # blank=True, null=True, help_text="URL of the project's documentation" # ) # tests_link = models.URLField( # blank=True, # null=True, # help_text="URL of the project's tests/continuous integration", # ) # # objects = managers.ProjectQuerySet.as_manager() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # def get_absolute_url(self) -> str: # return reverse("projects:detail", kwargs={"slug": self.slug}) # # def latest_version(self) -> typing.Optional[int]: # latest = self.versions.filter(is_latest=True) # if latest: # return latest[0] # return None # # class Version(models.Model): # """ # A version of a software project. # # """ # # PLANNING_STATUS = 1 # PRE_ALPHA_STATUS = 2 # ALPHA_STATUS = 3 # BETA_STATUS = 4 # STABLE_STATUS = 5 # # STATUS_CHOICES = ( # (PLANNING_STATUS, "Planning"), # (PRE_ALPHA_STATUS, "Pre-Alpha"), # (ALPHA_STATUS, "Alpha"), # (BETA_STATUS, "Beta"), # (STABLE_STATUS, "Stable"), # ) # # project = models.ForeignKey( # Project, related_name="versions", on_delete=models.CASCADE # ) # version = models.CharField(max_length=255) # is_latest = models.BooleanField(default=False) # # status = models.IntegerField(choices=STATUS_CHOICES, default=STABLE_STATUS) # license = models.ForeignKey(License, on_delete=models.CASCADE) # release_date = models.DateField(default=datetime.date.today) # # objects = managers.VersionManager() # # class Meta: # ordering = ("project", "version") # unique_together = ("project", "version") # # def __str__(self) -> str: # return "%s %s" % (self.project, self.version) # # def get_absolute_url(self) -> str: # return reverse( # "projects_version_detail", # kwargs={"project_slug": self.project.slug, "slug": self.version}, # ) . Output only the next line.
class ProjectAdmin(admin.ModelAdmin):
Based on the snippet: <|code_start|> class ProjectMixin(object): model = Project def get_queryset(self): return super().get_queryset().public() class VersionMixin(object): model = Version class ProjectDetail(ProjectMixin, generic.DetailView): pass class ProjectList(ProjectMixin, generic.ListView): pass <|code_end|> , predict the immediate next line with the help of imports: import typing from django.db import models from django.views import generic from .models import Project, Version and context (classes, functions, sometimes code) from other files: # Path: projects/models.py # class Project(models.Model): # """ # A software project. # # """ # # HIDDEN_STATUS = 0 # PUBLIC_STATUS = 1 # STATUS_CHOICES = ((HIDDEN_STATUS, "Hidden"), (PUBLIC_STATUS, "Public")) # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # status = models.IntegerField(choices=STATUS_CHOICES, default=PUBLIC_STATUS) # description = models.TextField() # # package_link = models.URLField( # blank=True, null=True, help_text="URL of the project's package(s)" # ) # repository_link = models.URLField( # blank=True, null=True, help_text="URL of the project's repostory" # ) # documentation_link = models.URLField( # blank=True, null=True, help_text="URL of the project's documentation" # ) # tests_link = models.URLField( # blank=True, # null=True, # help_text="URL of the project's tests/continuous integration", # ) # # objects = managers.ProjectQuerySet.as_manager() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # def get_absolute_url(self) -> str: # return reverse("projects:detail", kwargs={"slug": self.slug}) # # def latest_version(self) -> typing.Optional[int]: # latest = self.versions.filter(is_latest=True) # if latest: # return latest[0] # return None # # class Version(models.Model): # """ # A version of a software project. # # """ # # PLANNING_STATUS = 1 # PRE_ALPHA_STATUS = 2 # ALPHA_STATUS = 3 # BETA_STATUS = 4 # STABLE_STATUS = 5 # # STATUS_CHOICES = ( # (PLANNING_STATUS, "Planning"), # (PRE_ALPHA_STATUS, "Pre-Alpha"), # (ALPHA_STATUS, "Alpha"), # (BETA_STATUS, "Beta"), # (STABLE_STATUS, "Stable"), # ) # # project = models.ForeignKey( # Project, related_name="versions", on_delete=models.CASCADE # ) # version = models.CharField(max_length=255) # is_latest = models.BooleanField(default=False) # # status = models.IntegerField(choices=STATUS_CHOICES, default=STABLE_STATUS) # license = models.ForeignKey(License, on_delete=models.CASCADE) # release_date = models.DateField(default=datetime.date.today) # # objects = managers.VersionManager() # # class Meta: # ordering = ("project", "version") # unique_together = ("project", "version") # # def __str__(self) -> str: # return "%s %s" % (self.project, self.version) # # def get_absolute_url(self) -> str: # return reverse( # "projects_version_detail", # kwargs={"project_slug": self.project.slug, "slug": self.version}, # ) . Output only the next line.
class VersionDetail(VersionMixin, generic.DetailView):
Predict the next line after this snippet: <|code_start|> class ProjectMixin(object): model = Project def get_queryset(self): return super().get_queryset().public() class VersionMixin(object): model = Version <|code_end|> using the current file's imports: import typing from django.db import models from django.views import generic from .models import Project, Version and any relevant context from other files: # Path: projects/models.py # class Project(models.Model): # """ # A software project. # # """ # # HIDDEN_STATUS = 0 # PUBLIC_STATUS = 1 # STATUS_CHOICES = ((HIDDEN_STATUS, "Hidden"), (PUBLIC_STATUS, "Public")) # # name = models.CharField(max_length=255, unique=True) # slug = models.SlugField(unique=True) # status = models.IntegerField(choices=STATUS_CHOICES, default=PUBLIC_STATUS) # description = models.TextField() # # package_link = models.URLField( # blank=True, null=True, help_text="URL of the project's package(s)" # ) # repository_link = models.URLField( # blank=True, null=True, help_text="URL of the project's repostory" # ) # documentation_link = models.URLField( # blank=True, null=True, help_text="URL of the project's documentation" # ) # tests_link = models.URLField( # blank=True, # null=True, # help_text="URL of the project's tests/continuous integration", # ) # # objects = managers.ProjectQuerySet.as_manager() # # class Meta: # ordering = ("name",) # # def __str__(self) -> str: # return self.name # # def get_absolute_url(self) -> str: # return reverse("projects:detail", kwargs={"slug": self.slug}) # # def latest_version(self) -> typing.Optional[int]: # latest = self.versions.filter(is_latest=True) # if latest: # return latest[0] # return None # # class Version(models.Model): # """ # A version of a software project. # # """ # # PLANNING_STATUS = 1 # PRE_ALPHA_STATUS = 2 # ALPHA_STATUS = 3 # BETA_STATUS = 4 # STABLE_STATUS = 5 # # STATUS_CHOICES = ( # (PLANNING_STATUS, "Planning"), # (PRE_ALPHA_STATUS, "Pre-Alpha"), # (ALPHA_STATUS, "Alpha"), # (BETA_STATUS, "Beta"), # (STABLE_STATUS, "Stable"), # ) # # project = models.ForeignKey( # Project, related_name="versions", on_delete=models.CASCADE # ) # version = models.CharField(max_length=255) # is_latest = models.BooleanField(default=False) # # status = models.IntegerField(choices=STATUS_CHOICES, default=STABLE_STATUS) # license = models.ForeignKey(License, on_delete=models.CASCADE) # release_date = models.DateField(default=datetime.date.today) # # objects = managers.VersionManager() # # class Meta: # ordering = ("project", "version") # unique_together = ("project", "version") # # def __str__(self) -> str: # return "%s %s" % (self.project, self.version) # # def get_absolute_url(self) -> str: # return reverse( # "projects_version_detail", # kwargs={"project_slug": self.project.slug, "slug": self.version}, # ) . Output only the next line.
class ProjectDetail(ProjectMixin, generic.DetailView):
Predict the next line for this snippet: <|code_start|> app_name = "blog" urlpatterns = [ path("entries/", EntriesFeed(), name="entries"), path("categories/<slug:slug>/", CategoryFeed(), name="category"), <|code_end|> with the help of current file imports: from django.urls import path from blog.feeds import CategoryFeed, EntriesFeed and context from other files: # Path: blog/feeds.py # class CategoryFeed(EntriesFeed): # def feed_url(self, obj: Category) -> str: # return "https://{}/feeds/categories/{}/".format(current_site.domain, obj.slug) # # def description(self, obj: Category) -> str: # return "Latest entries in category '{}'".format(obj.title) # # def get_object(self, request: HttpRequest, slug: str) -> Category: # return Category.objects.get(slug=slug) # # def items(self, obj: Category) -> typing.List[Category]: # return obj.live_entries[:15] # # def link(self, obj: Category) -> str: # return self.item_link(obj) # # def title(self, obj: Category) -> str: # return "Latest entries in category '{}'".format(obj.title) # # class EntriesFeed(Feed): # author_name = "James Bennett" # copyright = "https://{}/about/copyright/".format(current_site.domain) # description = "Latest entriess" # feed_type = Atom1Feed # item_copyright = "https://{}/about/copyright/".format(current_site.domain) # item_author_name = "James Bennett" # item_author_link = "https://{}/".format(current_site.domain) # feed_url = "https://{}/feeds/entries/".format(current_site.domain) # link = "https://{}/".format(current_site.domain) # title = "James Bennett (b-list.org)" # # description_template = "feeds/entry_description.html" # title_template = "feeds/entry_title.html" # # def item_categories(self, item: Entry) -> typing.List[str]: # return [c.title for c in item.categories.all()] # # def item_guid(self, item: Entry) -> str: # return "tag:{},{}:{}".format( # current_site.domain, # item.pub_date.strftime("%Y-%m-%d"), # item.get_absolute_url(), # ) # # def item_pubdate(self, item: Entry) -> datetime.datetime: # return item.pub_date # # def item_updateddate(self, item: Entry) -> datetime.datetime: # return item.updated_date # # def items(self) -> typing.List[Entry]: # return Entry.live.all()[:15] # # def item_link(self, item: Entry) -> str: # return "https://{}{}".format(current_site.domain, item.get_absolute_url()) , which may contain function names, class names, or code. Output only the next line.
]
Here is a snippet: <|code_start|> app_name = "blog" urlpatterns = [ path("", views.EntryArchiveIndex.as_view(), name="index"), path("<int:year>/", views.EntryArchiveYear.as_view(), name="year"), path("<int:year>/<str:month>/", views.EntryArchiveMonth.as_view(), name="month"), path( "<int:year>/<str:month>/<int:day>/", views.EntryArchiveDay.as_view(), name="day" ), path( "<int:year>/<str:month>/<int:day>/<slug:slug>/", views.EntryDetail.as_view(), <|code_end|> . Write the next line using the current file imports: from django.urls import include, path from blog import views and context from other files: # Path: blog/views.py # class EntryMixin: # class CategoryMixin: # class EntryArchiveIndex(EntryMixin, generic.ArchiveIndexView): # class EntryArchiveYear(EntryMixin, generic.YearArchiveView): # class EntryArchiveMonth(EntryMixin, generic.MonthArchiveView): # class EntryArchiveDay(EntryMixin, generic.DayArchiveView): # class EntryDetail(EntryMixin, generic.DateDetailView): # class CategoryList(CategoryMixin, generic.ListView): # class CategoryDetail(CategoryMixin, generic.DetailView): # def get_queryset(self): , which may include functions, classes, or code. Output only the next line.
name="entry",
Given the code snippet: <|code_start|> ) list_display = ("title", "slug", "num_live_entries") list_display_links = ("title", "slug") prepopulated_fields = {"slug": ("title",)} def num_live_entries(self, obj: Category) -> int: return obj.live_entries.count() num_live_entries.short_description = "Live entries" @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): date_hierarchy = "pub_date" fieldsets = ( ("Metadata", {"fields": ("author", "pub_date", "title", "slug", "status")}), (None, {"fields": ("excerpt", "body")}), (None, {"fields": ("categories",)}), ) filter_horizontal = ("categories",) list_display = ("title", "pub_date", "status") list_display_links = ("title",) list_filter = ("status",) prepopulated_fields = {"slug": ("title",)} search_fields = ("title",) <|code_end|> , generate the next line using the imports in this file: from django.contrib import admin from django.db import models from django.http import HttpRequest from .models import Category, Entry and context (functions, classes, or occasionally code) from other files: # Path: blog/models.py # class Category(models.Model): # """ # A category into which entries can be filed. # # """ # # title = models.CharField(max_length=250) # slug = models.SlugField(unique=True) # description = models.TextField() # description_html = models.TextField(editable=False, blank=True) # # class Meta: # verbose_name_plural = "Categories" # ordering = ("title",) # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.description_html = markup(self.description) # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "categories:category", kwargs={"slug": self.slug}, current_app="blog" # ) # # def _get_live_entries(self) -> models.QuerySet: # return self.entry_set.filter(status=Entry.LIVE_STATUS) # # live_entries = property(_get_live_entries) # # class Entry(models.Model): # """ # An entry in the blog. # # """ # # LIVE_STATUS = 1 # DRAFT_STATUS = 2 # HIDDEN_STATUS = 3 # STATUS_CHOICES = ( # (LIVE_STATUS, "Live"), # (DRAFT_STATUS, "Draft"), # (HIDDEN_STATUS, "Hidden"), # ) # # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # pub_date = models.DateTimeField("Date posted", default=datetime.datetime.now) # updated_date = models.DateTimeField(blank=True, editable=False) # slug = models.SlugField(unique_for_date="pub_date") # status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) # title = models.CharField(max_length=250) # # body = models.TextField() # body_html = models.TextField(editable=False, blank=True) # # excerpt = models.TextField(blank=True, null=True) # excerpt_html = models.TextField(editable=False, blank=True, null=True) # # categories = models.ManyToManyField("Category") # # live = LiveEntryManager() # objects = models.Manager() # # class Meta: # get_latest_by = "pub_date" # ordering = ("-pub_date",) # verbose_name_plural = "Entries" # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.body_html = markup(self.body) # if self.excerpt: # self.excerpt_html = markup(self.excerpt) # self.updated_date = datetime.datetime.now() # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "entries:entry", # kwargs={ # "year": self.pub_date.strftime("%Y"), # "month": self.pub_date.strftime("%b").lower(), # "day": self.pub_date.strftime("%d"), # "slug": self.slug, # }, # ) . Output only the next line.
def get_queryset(self, request: HttpRequest) -> models.QuerySet:
Here is a snippet: <|code_start|>@admin.register(Category) class CategoryAdmin(admin.ModelAdmin): fieldsets = ( ("Metadata", {"fields": ("title", "slug")}), (None, {"fields": ("description",)}), ) list_display = ("title", "slug", "num_live_entries") list_display_links = ("title", "slug") prepopulated_fields = {"slug": ("title",)} def num_live_entries(self, obj: Category) -> int: return obj.live_entries.count() num_live_entries.short_description = "Live entries" @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): date_hierarchy = "pub_date" fieldsets = ( ("Metadata", {"fields": ("author", "pub_date", "title", "slug", "status")}), (None, {"fields": ("excerpt", "body")}), (None, {"fields": ("categories",)}), ) filter_horizontal = ("categories",) list_display = ("title", "pub_date", "status") <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from django.db import models from django.http import HttpRequest from .models import Category, Entry and context from other files: # Path: blog/models.py # class Category(models.Model): # """ # A category into which entries can be filed. # # """ # # title = models.CharField(max_length=250) # slug = models.SlugField(unique=True) # description = models.TextField() # description_html = models.TextField(editable=False, blank=True) # # class Meta: # verbose_name_plural = "Categories" # ordering = ("title",) # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.description_html = markup(self.description) # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "categories:category", kwargs={"slug": self.slug}, current_app="blog" # ) # # def _get_live_entries(self) -> models.QuerySet: # return self.entry_set.filter(status=Entry.LIVE_STATUS) # # live_entries = property(_get_live_entries) # # class Entry(models.Model): # """ # An entry in the blog. # # """ # # LIVE_STATUS = 1 # DRAFT_STATUS = 2 # HIDDEN_STATUS = 3 # STATUS_CHOICES = ( # (LIVE_STATUS, "Live"), # (DRAFT_STATUS, "Draft"), # (HIDDEN_STATUS, "Hidden"), # ) # # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # pub_date = models.DateTimeField("Date posted", default=datetime.datetime.now) # updated_date = models.DateTimeField(blank=True, editable=False) # slug = models.SlugField(unique_for_date="pub_date") # status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) # title = models.CharField(max_length=250) # # body = models.TextField() # body_html = models.TextField(editable=False, blank=True) # # excerpt = models.TextField(blank=True, null=True) # excerpt_html = models.TextField(editable=False, blank=True, null=True) # # categories = models.ManyToManyField("Category") # # live = LiveEntryManager() # objects = models.Manager() # # class Meta: # get_latest_by = "pub_date" # ordering = ("-pub_date",) # verbose_name_plural = "Entries" # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.body_html = markup(self.body) # if self.excerpt: # self.excerpt_html = markup(self.excerpt) # self.updated_date = datetime.datetime.now() # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "entries:entry", # kwargs={ # "year": self.pub_date.strftime("%Y"), # "month": self.pub_date.strftime("%b").lower(), # "day": self.pub_date.strftime("%d"), # "slug": self.slug, # }, # ) , which may include functions, classes, or code. Output only the next line.
list_display_links = ("title",)
Continue the code snippet: <|code_start|> current_site = Site.objects.get_current() class EntriesFeed(Feed): author_name = "James Bennett" copyright = "https://{}/about/copyright/".format(current_site.domain) description = "Latest entriess" feed_type = Atom1Feed item_copyright = "https://{}/about/copyright/".format(current_site.domain) item_author_name = "James Bennett" item_author_link = "https://{}/".format(current_site.domain) <|code_end|> . Use current file imports: import datetime import typing from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.http import HttpRequest from django.utils.feedgenerator import Atom1Feed from .models import Category from .models import Entry and context (classes, functions, or code) from other files: # Path: blog/models.py # class Category(models.Model): # """ # A category into which entries can be filed. # # """ # # title = models.CharField(max_length=250) # slug = models.SlugField(unique=True) # description = models.TextField() # description_html = models.TextField(editable=False, blank=True) # # class Meta: # verbose_name_plural = "Categories" # ordering = ("title",) # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.description_html = markup(self.description) # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "categories:category", kwargs={"slug": self.slug}, current_app="blog" # ) # # def _get_live_entries(self) -> models.QuerySet: # return self.entry_set.filter(status=Entry.LIVE_STATUS) # # live_entries = property(_get_live_entries) # # Path: blog/models.py # class Entry(models.Model): # """ # An entry in the blog. # # """ # # LIVE_STATUS = 1 # DRAFT_STATUS = 2 # HIDDEN_STATUS = 3 # STATUS_CHOICES = ( # (LIVE_STATUS, "Live"), # (DRAFT_STATUS, "Draft"), # (HIDDEN_STATUS, "Hidden"), # ) # # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # pub_date = models.DateTimeField("Date posted", default=datetime.datetime.now) # updated_date = models.DateTimeField(blank=True, editable=False) # slug = models.SlugField(unique_for_date="pub_date") # status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) # title = models.CharField(max_length=250) # # body = models.TextField() # body_html = models.TextField(editable=False, blank=True) # # excerpt = models.TextField(blank=True, null=True) # excerpt_html = models.TextField(editable=False, blank=True, null=True) # # categories = models.ManyToManyField("Category") # # live = LiveEntryManager() # objects = models.Manager() # # class Meta: # get_latest_by = "pub_date" # ordering = ("-pub_date",) # verbose_name_plural = "Entries" # # def __str__(self) -> str: # return self.title # # def save(self, *args, **kwargs): # self.body_html = markup(self.body) # if self.excerpt: # self.excerpt_html = markup(self.excerpt) # self.updated_date = datetime.datetime.now() # super().save(*args, **kwargs) # # def get_absolute_url(self) -> str: # return reverse( # "entries:entry", # kwargs={ # "year": self.pub_date.strftime("%Y"), # "month": self.pub_date.strftime("%b").lower(), # "day": self.pub_date.strftime("%d"), # "slug": self.slug, # }, # ) . Output only the next line.
feed_url = "https://{}/feeds/entries/".format(current_site.domain)
Given snippet: <|code_start|># encoding: utf-8 __all__ = [ u'encrypt', u'encrypt_bytes', u'decrypt', u'decrypt_bytes', ] logger = logging.getLogger(__name__) def _prep_key(key=None): key = key or settings.DJENGA_ENCRYPTION_KEY return _as_bytes(key) def _gcm_pack(header, cipher_text, tag, nonce, kdf_salt): values = [ header, cipher_text, tag, nonce, kdf_salt ] <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import uuid from base64 import b64decode from base64 import b64encode from Crypto.Protocol.KDF import PBKDF2 as derive_key from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from django.conf import settings from .helpers import _as_bytes and context: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value which might include code, classes, or functions. Output only the next line.
values = [ b64encode(x).decode('utf-8') for x in values ]
Using the snippet: <|code_start|>from __future__ import absolute_import, unicode_literals # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djenga_tests.settings') class DjengaCelery(Celery): def __init__(self, main=None, loader=None, backend=None, amqp=None, events=None, log=None, control=None, set_as_current=True, tasks=None, broker=None, include=None, changes=None, config_source=None, fixups=None, task_cls=None, autofinalize=True, namespace=None, strict_typing=True, **kwargs): patch_aliases() super().__init__(main, loader, backend, amqp, events, log, control, set_as_current, tasks, broker, include, changes, config_source, fixups, task_cls=DetailTask, <|code_end|> , determine the next line of code. You have imports: import os import logging import time import logging from celery import Celery from celery.signals import after_setup_logger from celery.signals import worker_process_init from djenga.celery.tasks import DetailTask from djenga.celery.tasks import DetailTask from djenga.celery.backends import patch_aliases from datetime import datetime from djenga.celery.utils import auto_step and context (class names, function names, or code) available: # Path: djenga/celery/tasks.py # class DetailTask(Task): # steps = None # # def __init__(self, steps=None): # super().__init__() # self.steps = self.steps or [] # self.details = OrderedDict() # for key, description in self.steps: # self.details[key] = description # # def initialize_detail(self): # if not hasattr(self.request, 'details'): # self.request.details = OrderedDict([ # (key, TaskDetail(key, description),) # for key, description in self.details.items() # ]) # self.request.detail_stack = list() # self.request.current_detail = None # # def save_details(self): # if self.request.id: # self.backend.store_result( # self.request.id, # result=None, # state=states.STARTED, # details=self.request.details) # # def start_step(self, key, description=None, detail='in progress'): # self.initialize_detail() # r = self.request # if key not in r.details: # r.current_detail = r.details.setdefault( # key, TaskDetail(key, description)) # else: # r.current_detail = r.details[key] # r.current_detail.start_time() # r.current_detail.add_detail(detail) # r.detail_stack.append(r.current_detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # self.save_details() # # def update_step(self, detail, *args): # self.initialize_detail() # r = self.request # if args: # try: # detail = detail % args # except Exception as ex: # pylint: disable=broad-except # logger.exception('%s', ex) # r.current_detail.add_detail(detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # self.save_details() # # def end_step(self, error=None, detail='done'): # self.initialize_detail() # r = self.request # if error: # r.current_detail.error = error # r.current_detail.add_detail(error) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, error) # else: # r.current_detail.add_detail(detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # r.current_detail.end_time() # r.detail_stack.pop() # if r.detail_stack: # r.current_detail = r.detail_stack[-1] # else: # r.current_detail = None # self.save_details() # # @abstractmethod # def run(self, *args, **kwargs): # pass # # Path: djenga/celery/utils.py # def auto_step(key, description=None, # start_detail='in progress', end_detail='done'): # """ # Make sure to apply the `@auto_step` decorator **before** the `@app.task` # decorator. e.g. # # @app.task(bind=True, name='my.cool_task', # base='djenga.celery.tasks.DetailTask') # @auto_step(key=1, description='eat cookies') # def eat_cookies(self): # pass # :param key: # :param description: # :param start_detail: # :param end_detail: # :return: # """ # def decorator(fn): # @wraps(fn) # def decorated(self, *args, **kwargs): # error = None # self.start_step(key, description, start_detail) # try: # result = fn(self, *args, **kwargs) # return result # except Exception as ex: # error = '%s' % (ex,) # raise # finally: # self.end_step(error, end_detail) # return decorated # return decorator . Output only the next line.
autofinalize=autofinalize, namespace=namespace,
Continue the code snippet: <|code_start|>from __future__ import absolute_import, unicode_literals # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djenga_tests.settings') class DjengaCelery(Celery): def __init__(self, main=None, loader=None, backend=None, amqp=None, events=None, log=None, control=None, set_as_current=True, tasks=None, broker=None, include=None, changes=None, config_source=None, fixups=None, task_cls=None, <|code_end|> . Use current file imports: import os import logging import time import logging from celery import Celery from celery.signals import after_setup_logger from celery.signals import worker_process_init from djenga.celery.tasks import DetailTask from djenga.celery.tasks import DetailTask from djenga.celery.backends import patch_aliases from datetime import datetime from djenga.celery.utils import auto_step and context (classes, functions, or code) from other files: # Path: djenga/celery/tasks.py # class DetailTask(Task): # steps = None # # def __init__(self, steps=None): # super().__init__() # self.steps = self.steps or [] # self.details = OrderedDict() # for key, description in self.steps: # self.details[key] = description # # def initialize_detail(self): # if not hasattr(self.request, 'details'): # self.request.details = OrderedDict([ # (key, TaskDetail(key, description),) # for key, description in self.details.items() # ]) # self.request.detail_stack = list() # self.request.current_detail = None # # def save_details(self): # if self.request.id: # self.backend.store_result( # self.request.id, # result=None, # state=states.STARTED, # details=self.request.details) # # def start_step(self, key, description=None, detail='in progress'): # self.initialize_detail() # r = self.request # if key not in r.details: # r.current_detail = r.details.setdefault( # key, TaskDetail(key, description)) # else: # r.current_detail = r.details[key] # r.current_detail.start_time() # r.current_detail.add_detail(detail) # r.detail_stack.append(r.current_detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # self.save_details() # # def update_step(self, detail, *args): # self.initialize_detail() # r = self.request # if args: # try: # detail = detail % args # except Exception as ex: # pylint: disable=broad-except # logger.exception('%s', ex) # r.current_detail.add_detail(detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # self.save_details() # # def end_step(self, error=None, detail='done'): # self.initialize_detail() # r = self.request # if error: # r.current_detail.error = error # r.current_detail.add_detail(error) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, error) # else: # r.current_detail.add_detail(detail) # logger.info( # '[%s/%s] %s', r.current_detail.key, # r.current_detail.description, detail) # r.current_detail.end_time() # r.detail_stack.pop() # if r.detail_stack: # r.current_detail = r.detail_stack[-1] # else: # r.current_detail = None # self.save_details() # # @abstractmethod # def run(self, *args, **kwargs): # pass # # Path: djenga/celery/utils.py # def auto_step(key, description=None, # start_detail='in progress', end_detail='done'): # """ # Make sure to apply the `@auto_step` decorator **before** the `@app.task` # decorator. e.g. # # @app.task(bind=True, name='my.cool_task', # base='djenga.celery.tasks.DetailTask') # @auto_step(key=1, description='eat cookies') # def eat_cookies(self): # pass # :param key: # :param description: # :param start_detail: # :param end_detail: # :return: # """ # def decorator(fn): # @wraps(fn) # def decorated(self, *args, **kwargs): # error = None # self.start_step(key, description, start_detail) # try: # result = fn(self, *args, **kwargs) # return result # except Exception as ex: # error = '%s' % (ex,) # raise # finally: # self.end_step(error, end_detail) # return decorated # return decorator . Output only the next line.
autofinalize=True, namespace=None, strict_typing=True,
Next line prediction: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) alias = _prefix_alias(alias) data = client.encrypt(KeyId=alias, Plaintext=plain_text) return data['CiphertextBlob'] def decrypt_bytes( cipher_text: bytes , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) data = client.decrypt(CiphertextBlob=cipher_text) return data['Plaintext'] def encrypt(plain_text, alias, region: str = None, profile: str = None) -> str: plain_text = _as_bytes(plain_text) data = encrypt_bytes(plain_text, alias, region, profile) return b64_str(data) def decrypt(cipher_text: str, region: str = None, profile: str = None): cipher_text = from_b64_str(cipher_text) data = decrypt_bytes(cipher_text, region, profile) <|code_end|> . Use current file imports: (from .helpers import _as_bytes from .helpers import b64_str from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias) and context including class names, function names, or small code snippets from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def b64_str(value: bytes): # return b64encode(value).decode('utf-8') # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias . Output only the next line.
return data.decode('utf-8')
Next line prediction: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) alias = _prefix_alias(alias) <|code_end|> . Use current file imports: (from .helpers import _as_bytes from .helpers import b64_str from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias) and context including class names, function names, or small code snippets from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def b64_str(value: bytes): # return b64encode(value).decode('utf-8') # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias . Output only the next line.
data = client.encrypt(KeyId=alias, Plaintext=plain_text)
Here is a snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) alias = _prefix_alias(alias) data = client.encrypt(KeyId=alias, Plaintext=plain_text) return data['CiphertextBlob'] <|code_end|> . Write the next line using the current file imports: from .helpers import _as_bytes from .helpers import b64_str from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias and context from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def b64_str(value: bytes): # return b64encode(value).decode('utf-8') # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias , which may include functions, classes, or code. Output only the next line.
def decrypt_bytes(
Next line prediction: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) alias = _prefix_alias(alias) data = client.encrypt(KeyId=alias, Plaintext=plain_text) return data['CiphertextBlob'] def decrypt_bytes( cipher_text: bytes , region: str = None , profile: str = None) -> bytes: client = _get_client(region, profile) data = client.decrypt(CiphertextBlob=cipher_text) return data['Plaintext'] def encrypt(plain_text, alias, region: str = None, profile: str = None) -> str: plain_text = _as_bytes(plain_text) data = encrypt_bytes(plain_text, alias, region, profile) return b64_str(data) def decrypt(cipher_text: str, region: str = None, profile: str = None): cipher_text = from_b64_str(cipher_text) <|code_end|> . Use current file imports: (from .helpers import _as_bytes from .helpers import b64_str from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias) and context including class names, function names, or small code snippets from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def b64_str(value: bytes): # return b64encode(value).decode('utf-8') # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias . Output only the next line.
data = decrypt_bytes(cipher_text, region, profile)
Given the code snippet: <|code_start|> __all__ = [ 'JsonFormatterTest', ] log = logging.getLogger(__name__) class JsonFormatterTest(TestCase): def test_json_formatter(self): formatter = JsonFormatter() with self.assertLogs(log) as log_context: for handler in log.handlers: <|code_end|> , generate the next line using the imports in this file: import json import logging from unittest import mock from django.test import TestCase from djenga.logging.formatters import JsonFormatter, JsonTaskFormatter and context (functions, classes, or occasionally code) from other files: # Path: djenga/logging/formatters.py # class JsonFormatter(logging.Formatter): # """ # This formatter is useful if you want to ship logs to a # json-based centralized log aggregation platform like ELK. # n.b., this formatter is very opinionated. # """ # def format_message(self, record: logging.LogRecord): # noqa: C901 # s = record.getMessage() # if record.exc_info: # # Cache the traceback text to avoid converting it multiple times # # (it's constant anyway) # if not record.exc_text: # record.exc_text = self.formatException(record.exc_info) # if record.exc_text: # if s[-1:] != '\n': # s = s + '\n' # s = s + record.exc_text # if record.stack_info: # if s[-1:] != '\n': # s = s + '\n' # s = s + self.formatStack(record.stack_info) # return s # # def iso_time(self, record: logging.LogRecord): # dt = datetime.utcfromtimestamp(record.created) # return dt.isoformat('T') # # DEFAULT_KEYS = { # 'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', # 'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName', # 'created', 'msecs', 'relativeCreated', 'thread', 'threadName', # 'processName', 'process', # } # # def to_dict(self, record: logging.LogRecord): # data = { # 'timestamp': self.iso_time(record), # 'message': self.format_message(record), # 'function': record.funcName, # 'path': record.pathname, # 'module': record.module, # 'level': record.levelname, # 'line_number': record.lineno, # 'logger': record.name, # } # exception_info = record.exc_info # if exception_info: # exception_type = record.exc_info[0] # data['exception_type'] = ( # f'{exception_type.__module__}.' # f'{exception_type.__name__}' # ) # data['exception_args'] = list(record.exc_info[1].args) # for key, value in record.__dict__.items(): # if key not in JsonFormatter.DEFAULT_KEYS: # data[key] = value # return data # # def format(self, record: logging.LogRecord): # return json.dumps(self.to_dict(record), cls=DjangoJSONEncoder) # # class JsonTaskFormatter(JsonFormatter): # """ # This formatter is useful if you want to ship celery logs to a # json-based centralized log aggregation platform like ELK. # n.b., this formatter is very opinionated. # """ # def to_dict(self, record: logging.LogRecord): # data = super(JsonTaskFormatter, self).to_dict(record) # try: # from celery._state import get_current_task # task = get_current_task() # if task and task.request: # data['task_id'] = task.request.id # data['task_name'] = task.name # except ImportError: # pass # return data . Output only the next line.
handler.setFormatter(formatter)
Next line prediction: <|code_start|> __all__ = [ 'JsonFormatterTest', ] log = logging.getLogger(__name__) class JsonFormatterTest(TestCase): def test_json_formatter(self): formatter = JsonFormatter() with self.assertLogs(log) as log_context: for handler in log.handlers: handler.setFormatter(formatter) log.info('Hello, Gwenna!', extra={'favorite': 'Olive'}) data = log_context.output[-1] data = json.loads(data) self.assertIn('timestamp', data) self.assertEqual(data['message'], 'Hello, Gwenna!') self.assertEqual(data['logger'], 'djenga_tests.tests.json_formatters') self.assertEqual(data['favorite'], 'Olive') try: raise ValueError('test exception') except ValueError as ex: log.exception('%s', ex) data = log_context.output[-1] data = json.loads(data) self.assertEqual(data['exception_type'], 'builtins.ValueError') self.assertIn('test exception', data['message']) <|code_end|> . Use current file imports: (import json import logging from unittest import mock from django.test import TestCase from djenga.logging.formatters import JsonFormatter, JsonTaskFormatter) and context including class names, function names, or small code snippets from other files: # Path: djenga/logging/formatters.py # class JsonFormatter(logging.Formatter): # """ # This formatter is useful if you want to ship logs to a # json-based centralized log aggregation platform like ELK. # n.b., this formatter is very opinionated. # """ # def format_message(self, record: logging.LogRecord): # noqa: C901 # s = record.getMessage() # if record.exc_info: # # Cache the traceback text to avoid converting it multiple times # # (it's constant anyway) # if not record.exc_text: # record.exc_text = self.formatException(record.exc_info) # if record.exc_text: # if s[-1:] != '\n': # s = s + '\n' # s = s + record.exc_text # if record.stack_info: # if s[-1:] != '\n': # s = s + '\n' # s = s + self.formatStack(record.stack_info) # return s # # def iso_time(self, record: logging.LogRecord): # dt = datetime.utcfromtimestamp(record.created) # return dt.isoformat('T') # # DEFAULT_KEYS = { # 'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', # 'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName', # 'created', 'msecs', 'relativeCreated', 'thread', 'threadName', # 'processName', 'process', # } # # def to_dict(self, record: logging.LogRecord): # data = { # 'timestamp': self.iso_time(record), # 'message': self.format_message(record), # 'function': record.funcName, # 'path': record.pathname, # 'module': record.module, # 'level': record.levelname, # 'line_number': record.lineno, # 'logger': record.name, # } # exception_info = record.exc_info # if exception_info: # exception_type = record.exc_info[0] # data['exception_type'] = ( # f'{exception_type.__module__}.' # f'{exception_type.__name__}' # ) # data['exception_args'] = list(record.exc_info[1].args) # for key, value in record.__dict__.items(): # if key not in JsonFormatter.DEFAULT_KEYS: # data[key] = value # return data # # def format(self, record: logging.LogRecord): # return json.dumps(self.to_dict(record), cls=DjangoJSONEncoder) # # class JsonTaskFormatter(JsonFormatter): # """ # This formatter is useful if you want to ship celery logs to a # json-based centralized log aggregation platform like ELK. # n.b., this formatter is very opinionated. # """ # def to_dict(self, record: logging.LogRecord): # data = super(JsonTaskFormatter, self).to_dict(record) # try: # from celery._state import get_current_task # task = get_current_task() # if task and task.request: # data['task_id'] = task.request.id # data['task_name'] = task.name # except ImportError: # pass # return data . Output only the next line.
self.assertEquals('test exception', data['exception_args'][0])
Based on the snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) <|code_end|> , predict the immediate next line with the help of imports: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context (classes, functions, sometimes code) from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data . Output only the next line.
response = client.generate_data_key(KeyId=alias, KeySpec='AES_256')
Here is a snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') data_key = response['Plaintext'] header = response['CiphertextBlob'] value = gcm_encrypt(plain_text, data_key, auth_header=header) return value def decrypt_bytes( packed_value: str , region: str = None , profile: str = None) -> bytes: pieces = packed_value.split('|', 1) wrapped_data_key = pieces[0] wrapped_data_key = from_b64_str(wrapped_data_key) client = _get_client(region, profile) response = client.decrypt(CiphertextBlob=wrapped_data_key) data_key = response['Plaintext'] plain_text = gcm_decrypt(packed_value, data_key) <|code_end|> . Write the next line using the current file imports: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data , which may include functions, classes, or code. Output only the next line.
return plain_text
Using the snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') data_key = response['Plaintext'] header = response['CiphertextBlob'] value = gcm_encrypt(plain_text, data_key, auth_header=header) return value def decrypt_bytes( packed_value: str , region: str = None , profile: str = None) -> bytes: pieces = packed_value.split('|', 1) wrapped_data_key = pieces[0] wrapped_data_key = from_b64_str(wrapped_data_key) client = _get_client(region, profile) response = client.decrypt(CiphertextBlob=wrapped_data_key) data_key = response['Plaintext'] plain_text = gcm_decrypt(packed_value, data_key) <|code_end|> , determine the next line of code. You have imports: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context (class names, function names, or code) available: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data . Output only the next line.
return plain_text
Given the code snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') data_key = response['Plaintext'] header = response['CiphertextBlob'] value = gcm_encrypt(plain_text, data_key, auth_header=header) <|code_end|> , generate the next line using the imports in this file: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context (functions, classes, or occasionally code) from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data . Output only the next line.
return value
Given the code snippet: <|code_start|> def encrypt_bytes( plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') data_key = response['Plaintext'] <|code_end|> , generate the next line using the imports in this file: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context (functions, classes, or occasionally code) from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data . Output only the next line.
header = response['CiphertextBlob']
Predict the next line for this snippet: <|code_start|> plain_text: bytes , alias: str , region: str = None , profile: str = None) -> str: client = _get_client(region, profile) alias = _prefix_alias(alias) response = client.generate_data_key(KeyId=alias, KeySpec='AES_256') data_key = response['Plaintext'] header = response['CiphertextBlob'] value = gcm_encrypt(plain_text, data_key, auth_header=header) return value def decrypt_bytes( packed_value: str , region: str = None , profile: str = None) -> bytes: pieces = packed_value.split('|', 1) wrapped_data_key = pieces[0] wrapped_data_key = from_b64_str(wrapped_data_key) client = _get_client(region, profile) response = client.decrypt(CiphertextBlob=wrapped_data_key) data_key = response['Plaintext'] plain_text = gcm_decrypt(packed_value, data_key) return plain_text def encrypt(plain_text, alias, region: str = None, profile: str = None) -> str: plain_text = _as_bytes(plain_text) data = encrypt_bytes(plain_text, alias, region, profile) <|code_end|> with the help of current file imports: from .helpers import _as_bytes from .helpers import from_b64_str from .helpers import _get_client from .helpers import _prefix_alias from .gcm import encrypt_bytes as gcm_encrypt from .gcm import decrypt_bytes as gcm_decrypt and context from other files: # Path: djenga/encryption/helpers.py # def _as_bytes(value): # if isinstance(value, six.string_types): # value = value.encode('utf-8') # return value # # Path: djenga/encryption/helpers.py # def from_b64_str(value: str): # value = value.encode('utf-8') # return b64decode(value) # # Path: djenga/encryption/helpers.py # def _get_client(region: str = None, profile: str = None): # key = f'{region}-{profile}' # client = thread_local.sessions.get(key) # if not client: # session = boto3.Session(region_name=region, profile_name=profile) # client = session.client('kms') # thread_local.sessions[key] = client # return client # # Path: djenga/encryption/helpers.py # def _prefix_alias(alias: str): # if not alias.startswith('alias/'): # alias = f'alias/{alias}' # return alias # # Path: djenga/encryption/gcm.py # def encrypt_bytes(plain_text, key=None, auth_header='djenga'): # """ # The encrypt function encrypts a unicode string using the # Blowfish cipher (provided by pycrypto). The key used is # the SECRET_KEY specified in the settings file. # # :param plain_text: The plaintext unicode string to be encrypted. # :param key: the password to use for encryption # :param auth_header: str # :return The encrypted ciphertext. # # """ # kdf_salt = get_random_bytes(32) # key = key or settings.DJENGA_ENCRYPTION_KEY # derived_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(derived_key, AES.MODE_GCM) # auth_header = _as_bytes(auth_header) # cipher.update(auth_header) # cipher_text, tag = cipher.encrypt_and_digest(plain_text) # nonce = cipher.nonce # return _gcm_pack(auth_header, cipher_text, tag, nonce, kdf_salt) # # Path: djenga/encryption/gcm.py # def decrypt_bytes(packed_value, key=None): # """ # The decrypt function decrypts unicode strings that have # been encrypted by the util.encryption.encrypt() function. # The cipher used is Blowfish (provided by pcrypto), and the # key used is the SECRET_KEY specified in the settings file. # # :param packed_value: The encrypted pieces needed for decryption. # :param key: the password to use when encrypting # :return The decrypted plaintext (unicode) string. # # >>> import uuid # >>> key = uuid.uuid4() # >>> st = 'hello' # >>> decrypt(encrypt(st, key.bytes), key.bytes) == st # True # """ # header, cipher_text, tag, nonce, kdf_salt = _gcm_unpack(packed_value) # key = key or settings.DJENGA_ENCRYPTION_KEY # decryption_key = derive_key(key, kdf_salt, 32) # cipher = AES.new(decryption_key, AES.MODE_GCM, nonce) # cipher.update(header) # data = cipher.decrypt_and_verify(cipher_text, tag) # return data , which may contain function names, class names, or code. Output only the next line.
return data
Given snippet: <|code_start|> class Command(BaseCommand): def add_arguments(self, parser: ArgumentParser): parser.add_argument( '-n', '--count', dest='count', type=int, help='number of animal pairs to output', metavar='count', default=4, ) def handle(self, count, *args, **options): # pylint: disable=W0221 <|code_end|> , continue by predicting the next line. Consider current file imports: from argparse import ArgumentParser from django.core.management.base import BaseCommand from ...animal_pairs import animal_pair and context: # Path: djenga/animal_pairs/utils.py # def animal_pair(): # return u'%s-%s' % ( # random.choice(ADJECTIVES), # random.choice(ANIMALS), # ) which might include code, classes, or functions. Output only the next line.
for _ in range(count):
Given the code snippet: <|code_start|> class ExampleTest(IntegrationTest): def test_add(self): x = 1 + 1 self.assert_equal(x, 2) x += 5 <|code_end|> , generate the next line using the imports in this file: from djenga.test import IntegrationTest and context (functions, classes, or occasionally code) from other files: # Path: djenga/test/integration_test.py # class IntegrationTest: # """ # Subclass this class to use for running integration # tests with the IntegrationTestCommand. In order # to use this class, a subclass should define one or # more instance member functions that begin with the # word `test` and takes no arguments other than self. # These functions will be called in alphabetical order # by the super classes `run_test` function. Example: # # from djenga.test import IntegrationTest # # class MyIntegrationTest(IntegrationTest): # def test_addition(self): # x = 1 # self.assert_equal(x, 1) # x += 4 # self.assert_equal(x, 5) # # An integration test can also access YAML or JSON test # data from a file specified by the class variable # `test_data_file`. This test data will is made # available to the sub class through `self.test_data`. # Example: # In a file called path/to/my_test_data.yml # # --- # step_1: 1 # step_2: 5 # # In the integration test file: # # class MyIntegrationTest(IntegrationTest): # test_data_file = 'path/to/my_test_data.yml' # # def test_addition(self): # x = 1 # self.assert_equal( # x, self.test_data['step_1'], # 'Oh no! failed step 1') # x += 4 # self.assert_equal( # x, self.test_data['step_2'], # 'Oh no! failed step 2') # """ # test_data_file = '' # # def __init__(self): # self.test_data = None # self.load_test_data() # # def load_test_data(self): # if not self.test_data_file: # return # with open(self.test_data_file, 'r') as f: # self.test_data = yaml.load(f) # # def assert_true(self, value, message=''): # if value is not True: # raise IntegrationTestException( # message or f'failure: [{value}] was not true') # # def assert_truthy(self, value, message=''): # if value: # raise IntegrationTestException( # message or f'failure: [{value}] was not truthy') # # def assert_false(self, value, message=''): # if value is not False: # raise IntegrationTestException( # message or f'failure: [{value}] was true') # # def assert_falsey(self, value, message=''): # if value: # raise IntegrationTestException( # message or f'failure: [{value}] was not falsey') # # def asset_greater_than(self, left, right, message=''): # if left <= right: # raise IntegrationTestException( # message or f'failure: [{left}] <= [{right}]') # # def asset_greater_than_equal(self, left, right, message=''): # if left <= right: # raise IntegrationTestException( # message or f'failure: [{left}] > [{right}]') # # def assert_less_than(self, left, right, message=''): # if left >= right: # raise IntegrationTestException( # message or f'failure: [{left}] >= [{right}]') # # def assert_less_than_equal(self, left, right, message=''): # if left > right: # raise IntegrationTestException( # message or f'failure: [{left}] > [{right}]') # # def assert_equal(self, left, right, message=''): # if left != right: # raise IntegrationTestException( # message or 'failure: [%s] != [%s]' % (left, right)) # # def assert_not_equal(self, left, right, message=''): # if left == right: # raise IntegrationTestException( # message or 'failure: [%s] == [%s]' % (left, right)) # # def setup(self): # pass # # def teardown(self): # pass # # def run_test(self): # test_methods = [ # value # for key, value in inspect.getmembers(self) # if key.startswith('test') and callable(value) # ] # test_methods.sort(key=lambda fn: fn.__name__) # all_passed = True # dot_leader('%s.setup', self.__class__.__name__, end='') # self.setup() # flush_print('done') # try: # for x in test_methods: # dot_leader(f'{self.__class__.__name__}.{x.__name__}', end='') # tm_start = time() # status = 'passed' # units = 's' # try: # x() # except IntegrationTestException as ex: # status = 'failed (%s)' % (ex,) # all_passed = False # finally: # tm_total = time() - tm_start # if tm_total < 1: # tm_total *= 1000 # units = 'ms' # flush_print('%s %.1f%s', status, tm_total, units) # finally: # dot_leader('%s.teardown', self.__class__.__name__, end='') # self.teardown() # flush_print('done') # return all_passed . Output only the next line.
self.assert_equal(7, x)
Next line prediction: <|code_start|> class SecondTest(IntegrationTest): def test_add(self): x = 1 + 1 <|code_end|> . Use current file imports: (from djenga.test import IntegrationTest) and context including class names, function names, or small code snippets from other files: # Path: djenga/test/integration_test.py # class IntegrationTest: # """ # Subclass this class to use for running integration # tests with the IntegrationTestCommand. In order # to use this class, a subclass should define one or # more instance member functions that begin with the # word `test` and takes no arguments other than self. # These functions will be called in alphabetical order # by the super classes `run_test` function. Example: # # from djenga.test import IntegrationTest # # class MyIntegrationTest(IntegrationTest): # def test_addition(self): # x = 1 # self.assert_equal(x, 1) # x += 4 # self.assert_equal(x, 5) # # An integration test can also access YAML or JSON test # data from a file specified by the class variable # `test_data_file`. This test data will is made # available to the sub class through `self.test_data`. # Example: # In a file called path/to/my_test_data.yml # # --- # step_1: 1 # step_2: 5 # # In the integration test file: # # class MyIntegrationTest(IntegrationTest): # test_data_file = 'path/to/my_test_data.yml' # # def test_addition(self): # x = 1 # self.assert_equal( # x, self.test_data['step_1'], # 'Oh no! failed step 1') # x += 4 # self.assert_equal( # x, self.test_data['step_2'], # 'Oh no! failed step 2') # """ # test_data_file = '' # # def __init__(self): # self.test_data = None # self.load_test_data() # # def load_test_data(self): # if not self.test_data_file: # return # with open(self.test_data_file, 'r') as f: # self.test_data = yaml.load(f) # # def assert_true(self, value, message=''): # if value is not True: # raise IntegrationTestException( # message or f'failure: [{value}] was not true') # # def assert_truthy(self, value, message=''): # if value: # raise IntegrationTestException( # message or f'failure: [{value}] was not truthy') # # def assert_false(self, value, message=''): # if value is not False: # raise IntegrationTestException( # message or f'failure: [{value}] was true') # # def assert_falsey(self, value, message=''): # if value: # raise IntegrationTestException( # message or f'failure: [{value}] was not falsey') # # def asset_greater_than(self, left, right, message=''): # if left <= right: # raise IntegrationTestException( # message or f'failure: [{left}] <= [{right}]') # # def asset_greater_than_equal(self, left, right, message=''): # if left <= right: # raise IntegrationTestException( # message or f'failure: [{left}] > [{right}]') # # def assert_less_than(self, left, right, message=''): # if left >= right: # raise IntegrationTestException( # message or f'failure: [{left}] >= [{right}]') # # def assert_less_than_equal(self, left, right, message=''): # if left > right: # raise IntegrationTestException( # message or f'failure: [{left}] > [{right}]') # # def assert_equal(self, left, right, message=''): # if left != right: # raise IntegrationTestException( # message or 'failure: [%s] != [%s]' % (left, right)) # # def assert_not_equal(self, left, right, message=''): # if left == right: # raise IntegrationTestException( # message or 'failure: [%s] == [%s]' % (left, right)) # # def setup(self): # pass # # def teardown(self): # pass # # def run_test(self): # test_methods = [ # value # for key, value in inspect.getmembers(self) # if key.startswith('test') and callable(value) # ] # test_methods.sort(key=lambda fn: fn.__name__) # all_passed = True # dot_leader('%s.setup', self.__class__.__name__, end='') # self.setup() # flush_print('done') # try: # for x in test_methods: # dot_leader(f'{self.__class__.__name__}.{x.__name__}', end='') # tm_start = time() # status = 'passed' # units = 's' # try: # x() # except IntegrationTestException as ex: # status = 'failed (%s)' % (ex,) # all_passed = False # finally: # tm_total = time() - tm_start # if tm_total < 1: # tm_total *= 1000 # units = 'ms' # flush_print('%s %.1f%s', status, tm_total, units) # finally: # dot_leader('%s.teardown', self.__class__.__name__, end='') # self.teardown() # flush_print('done') # return all_passed . Output only the next line.
self.assert_equal(x, 2)
Predict the next line after this snippet: <|code_start|> def test_maximal(): items = map(frozenset, ((1,), (2,), (3,), (1, 2))) assert set(tools.maximal(items)) == {frozenset([3]), frozenset([1, 2])} def test_sha256sum(tmp_path): filepath = tmp_path / 'spam.txt' filepath.write_text('spam', encoding='ascii') result = tools.sha256sum(filepath) <|code_end|> using the current file's imports: import pytest from concepts import tools and any relevant context from other files: # Path: concepts/tools.py # CSV_DIALECT = 'excel' # DEFAULT_ENCODING = 'utf-8' # def snakify(name: str, *, sep: str = '_', # _re_upper=re.compile(r'([A-Z])')) -> str: # def _fromargs(cls, _seen, _items): # def __init__(self, iterable=()): # def copy(self): # def __iter__(self): # def __len__(self): # def __contains__(self, item): # def __repr__(self): # def add(self, item): # def discard(self, item): # def replace(self, item, new_item): # def move(self, item, new_index): # def issuperset(self, items): # def rsub(self, items): # def max_len(iterable, minimum=0): # def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)): # def __init__(self, fget): # def __get__(self, instance, owner): # def crc32_hex(data): # def sha256sum(filepath, bufsize: int = 32_768) -> str: # def write_lines(path, lines: typing.Iterable[str], # *, encoding: str = DEFAULT_ENCODING, # newline: typing.Optional[str] = None): # def csv_iterrows(path, *, dialect: CsvDialectOrStr = csv.excel, # encoding: str = DEFAULT_ENCODING, # newline: typing.Optional[str] = ''): # def write_csv(path, rows, # *, header: typing.Optional[typing.Iterable[str]] = None, # dialect: CsvDialectOrStr = CSV_DIALECT, # encoding: str = DEFAULT_ENCODING, # newline: typing.Optional[str] = ''): # def write_csv_file(file, rows, # *, header: typing.Optional[typing.Iterable[str]] = None, # dialect: CsvDialectOrStr = CSV_DIALECT): # def dump_json(obj, path_or_fileobj, # *, encoding: str = DEFAULT_ENCODING, # mode: str = 'w', **kwargs): # def load_json(path_or_fileobj, # *, encoding: str = DEFAULT_ENCODING, # mode: str = 'r', **kwargs): # def _call_json(funcname, path_or_fileobj, encoding, mode, **kwargs): # def _get_fileobj(path_or_fileobj, mode, encoding): # class Unique(collections.abc.MutableSet): # class lazyproperty: # noqa: N801 . Output only the next line.
assert result == '4e388ab32b10dc8dbc7e28144f552830adc74787c1e2c0824032078a79f227fb'