Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|># All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
ingress_port_UUID = uuidutils.generate_uuid()
egress_port_UUID = uuidutils.generate_uuid()
class CLITestV20PortPairExtensionJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20PortPairExtensionJSON, self).setUp()
self._mock_extension_loading()
self.register_non_admin_status_resource('port_pair')
def _create_patch(self, name, func=None):
<|code_end|>
with the help of current file imports:
import sys
from unittest import mock
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
from networking_sfc.cli import port_pair as pp
from oslo_utils import uuidutils
and context from other files:
# Path: networking_sfc/cli/port_pair.py
# PORT_RESOURCE = 'port'
# PORT_PAIR_RESOURCE = 'port_pair'
# def get_port_id(client, id_or_name):
# def get_port_pair_id(client, id_or_name):
# def add_known_arguments(self, parser):
# def args2body(self, parsed_args):
# def add_known_arguments(self, parser):
# def args2body(self, parsed_args):
# class PortPair(extension.NeutronClientExtension):
# class PortPairCreate(extension.ClientExtensionCreate, PortPair):
# class PortPairUpdate(extension.ClientExtensionUpdate, PortPair):
# class PortPairDelete(extension.ClientExtensionDelete, PortPair):
# class PortPairList(extension.ClientExtensionList, PortPair):
# class PortPairShow(extension.ClientExtensionShow, PortPair):
, which may contain function names, class names, or code. Output only the next line. | patcher = mock.patch(name) |
Given the following code snippet before the placeholder: <|code_start|>
class DriverManagerTestCase(base.BaseTestCase):
def setUp(self):
super(DriverManagerTestCase, self).setUp()
def test_initialize_called(self):
driver1 = Extension('mock_driver1', Mock(), None,
Mock(native_bulk_support=True))
driver2 = Extension('mock_driver2', Mock(), None,
Mock(native_bulk_support=True))
manager = FlowClassifierDriverManager.make_test_instance([driver1,
driver2])
manager.initialize()
driver1.obj.initialize.assert_called_once_with()
driver2.obj.initialize.assert_called_once_with()
def _test_method_called(self, method_name):
driver1 = Extension('mock_driver1', Mock(), None,
Mock(native_bulk_support=True))
driver2 = Extension('mock_driver2', Mock(), None,
Mock(native_bulk_support=True))
manager = FlowClassifierDriverManager.make_test_instance([driver1,
driver2])
mocked_context = Mock()
getattr(manager, method_name)(mocked_context)
getattr(driver1.obj, method_name).assert_called_once_with(
<|code_end|>
, predict the next line using imports from the current file:
from unittest.mock import Mock
from stevedore.extension import Extension
from neutron.tests import base
from networking_sfc.services.flowclassifier.common import exceptions as fc_exc
from networking_sfc.services.flowclassifier.driver_manager \
import FlowClassifierDriverManager
and context including class names, function names, and sometimes code from other files:
# Path: networking_sfc/services/flowclassifier/common/exceptions.py
# class FlowClassifierDriverError(exceptions.NeutronException):
# class FlowClassifierException(exceptions.NeutronException):
# class FlowClassifierBadRequest(exceptions.BadRequest, FlowClassifierException):
#
# Path: networking_sfc/services/flowclassifier/driver_manager.py
# class FlowClassifierDriverManager(NamedExtensionManager):
# """Implementation of Flow Classifier drivers."""
#
# def __init__(self, namespace='networking_sfc.flowclassifier.drivers',
# names=cfg.CONF.flowclassifier.drivers):
# # Registered flow classifier drivers, keyed by name.
# self.drivers = {}
# # Ordered list of flow classifier drivers, defining
# # the order in which the drivers are called.
# self.ordered_drivers = []
# LOG.info("Configured Flow Classifier drivers: %s", names)
# super(FlowClassifierDriverManager, self).__init__(
# namespace,
# names,
# invoke_on_load=True,
# name_order=True)
# LOG.info("Loaded Flow Classifier drivers: %s",
# self.names())
# self._register_drivers()
#
# @classmethod
# def make_test_instance(cls, extensions, namespace='TESTING'):
# """Construct a test FlowClassifierDriverManager
#
# Test instances are passed a list of extensions to use rather than
# loading them from entry points.
#
# :param extensions: Pre-configured Extension instances
# :type extensions: list of :class:`~stevedore.extension.Extension`
# :param namespace: The namespace for the manager; used only for
# identification since the extensions are passed in.
# :type namespace: str
# :return: The manager instance, initialized for testing
#
# """
#
# o = super(FlowClassifierDriverManager, cls).make_test_instance(
# extensions, namespace=namespace)
# o.drivers = {}
# o.ordered_drivers = []
# o._register_drivers()
# return o
#
# def _register_drivers(self):
# """Register all Flow Classifier drivers.
#
# This method should only be called once in the
# FlowClassifierDriverManager constructor.
# """
# for ext in self:
# self.drivers[ext.name] = ext
# self.ordered_drivers.append(ext)
# LOG.info("Registered Flow Classifier drivers: %s",
# [driver.name for driver in self.ordered_drivers])
#
# def initialize(self):
# # ServiceChain bulk operations requires each driver to support them
# self.native_bulk_support = True
# for driver in self.ordered_drivers:
# LOG.info("Initializing Flow Classifier driver '%s'",
# driver.name)
# driver.obj.initialize()
# self.native_bulk_support &= getattr(driver.obj,
# 'native_bulk_support', True)
#
# def _call_drivers(self, method_name, context, raise_orig_exc=False):
# """Helper method for calling a method across all drivers.
#
# :param method_name: name of the method to call
# :param context: context parameter to pass to each method call
# :param raise_orig_exc: whether or not to raise the original
# driver exception, or use a general one
# """
# for driver in self.ordered_drivers:
# try:
# getattr(driver.obj, method_name)(context)
# except Exception as e:
# # This is an internal failure.
# LOG.exception(e)
# LOG.error(
# "Flow Classifier driver '%(name)s' "
# "failed in %(method)s",
# {'name': driver.name, 'method': method_name}
# )
# if raise_orig_exc:
# raise
# raise fc_exc.FlowClassifierDriverError(
# method=method_name
# )
#
# def create_flow_classifier_precommit(self, context):
# """Driver precommit before the db transaction committed."""
# self._call_drivers("create_flow_classifier_precommit", context,
# raise_orig_exc=True)
#
# def create_flow_classifier_postcommit(self, context):
# self._call_drivers("create_flow_classifier_postcommit", context)
#
# def update_flow_classifier_precommit(self, context):
# self._call_drivers("update_flow_classifier_precommit", context)
#
# def update_flow_classifier_postcommit(self, context):
# self._call_drivers("update_flow_classifier_postcommit", context)
#
# def delete_flow_classifier(self, context):
# self._call_drivers("delete_flow_classifier", context)
#
# def delete_flow_classifier_precommit(self, context):
# self._call_drivers("delete_flow_classifier_precommit", context)
#
# def delete_flow_classifier_postcommit(self, context):
# self._call_drivers("delete_flow_classifier_postcommit", context)
. Output only the next line. | mocked_context) |
Given the code snippet: <|code_start|> mock_method = Mock(side_effect=fc_exc.FlowClassifierException)
setattr(driver.obj, method_name, mock_method)
manager = FlowClassifierDriverManager.make_test_instance([driver])
mocked_context = Mock()
self.assertRaises(expected_exc,
getattr(manager, method_name),
mocked_context)
def test_create_flow_classifier_precommit_called(self):
self._test_method_called("create_flow_classifier_precommit")
def test_create_flow_classifier_precommit_exception(self):
self._test_method_exception("create_flow_classifier_precommit",
fc_exc.FlowClassifierException)
def test_create_flow_classifier_postcommit_called(self):
self._test_method_called("create_flow_classifier_postcommit")
def test_create_flow_classifier_postcommit_exception(self):
self._test_method_exception("create_flow_classifier_postcommit")
def test_update_flow_classifier_precommit_called(self):
self._test_method_called("update_flow_classifier_precommit")
def test_update_flow_classifier_precommit_exception(self):
self._test_method_exception("update_flow_classifier_precommit")
def test_update_flow_classifier_postcommit_called(self):
self._test_method_called("update_flow_classifier_postcommit")
<|code_end|>
, generate the next line using the imports in this file:
from unittest.mock import Mock
from stevedore.extension import Extension
from neutron.tests import base
from networking_sfc.services.flowclassifier.common import exceptions as fc_exc
from networking_sfc.services.flowclassifier.driver_manager \
import FlowClassifierDriverManager
and context (functions, classes, or occasionally code) from other files:
# Path: networking_sfc/services/flowclassifier/common/exceptions.py
# class FlowClassifierDriverError(exceptions.NeutronException):
# class FlowClassifierException(exceptions.NeutronException):
# class FlowClassifierBadRequest(exceptions.BadRequest, FlowClassifierException):
#
# Path: networking_sfc/services/flowclassifier/driver_manager.py
# class FlowClassifierDriverManager(NamedExtensionManager):
# """Implementation of Flow Classifier drivers."""
#
# def __init__(self, namespace='networking_sfc.flowclassifier.drivers',
# names=cfg.CONF.flowclassifier.drivers):
# # Registered flow classifier drivers, keyed by name.
# self.drivers = {}
# # Ordered list of flow classifier drivers, defining
# # the order in which the drivers are called.
# self.ordered_drivers = []
# LOG.info("Configured Flow Classifier drivers: %s", names)
# super(FlowClassifierDriverManager, self).__init__(
# namespace,
# names,
# invoke_on_load=True,
# name_order=True)
# LOG.info("Loaded Flow Classifier drivers: %s",
# self.names())
# self._register_drivers()
#
# @classmethod
# def make_test_instance(cls, extensions, namespace='TESTING'):
# """Construct a test FlowClassifierDriverManager
#
# Test instances are passed a list of extensions to use rather than
# loading them from entry points.
#
# :param extensions: Pre-configured Extension instances
# :type extensions: list of :class:`~stevedore.extension.Extension`
# :param namespace: The namespace for the manager; used only for
# identification since the extensions are passed in.
# :type namespace: str
# :return: The manager instance, initialized for testing
#
# """
#
# o = super(FlowClassifierDriverManager, cls).make_test_instance(
# extensions, namespace=namespace)
# o.drivers = {}
# o.ordered_drivers = []
# o._register_drivers()
# return o
#
# def _register_drivers(self):
# """Register all Flow Classifier drivers.
#
# This method should only be called once in the
# FlowClassifierDriverManager constructor.
# """
# for ext in self:
# self.drivers[ext.name] = ext
# self.ordered_drivers.append(ext)
# LOG.info("Registered Flow Classifier drivers: %s",
# [driver.name for driver in self.ordered_drivers])
#
# def initialize(self):
# # ServiceChain bulk operations requires each driver to support them
# self.native_bulk_support = True
# for driver in self.ordered_drivers:
# LOG.info("Initializing Flow Classifier driver '%s'",
# driver.name)
# driver.obj.initialize()
# self.native_bulk_support &= getattr(driver.obj,
# 'native_bulk_support', True)
#
# def _call_drivers(self, method_name, context, raise_orig_exc=False):
# """Helper method for calling a method across all drivers.
#
# :param method_name: name of the method to call
# :param context: context parameter to pass to each method call
# :param raise_orig_exc: whether or not to raise the original
# driver exception, or use a general one
# """
# for driver in self.ordered_drivers:
# try:
# getattr(driver.obj, method_name)(context)
# except Exception as e:
# # This is an internal failure.
# LOG.exception(e)
# LOG.error(
# "Flow Classifier driver '%(name)s' "
# "failed in %(method)s",
# {'name': driver.name, 'method': method_name}
# )
# if raise_orig_exc:
# raise
# raise fc_exc.FlowClassifierDriverError(
# method=method_name
# )
#
# def create_flow_classifier_precommit(self, context):
# """Driver precommit before the db transaction committed."""
# self._call_drivers("create_flow_classifier_precommit", context,
# raise_orig_exc=True)
#
# def create_flow_classifier_postcommit(self, context):
# self._call_drivers("create_flow_classifier_postcommit", context)
#
# def update_flow_classifier_precommit(self, context):
# self._call_drivers("update_flow_classifier_precommit", context)
#
# def update_flow_classifier_postcommit(self, context):
# self._call_drivers("update_flow_classifier_postcommit", context)
#
# def delete_flow_classifier(self, context):
# self._call_drivers("delete_flow_classifier", context)
#
# def delete_flow_classifier_precommit(self, context):
# self._call_drivers("delete_flow_classifier_precommit", context)
#
# def delete_flow_classifier_postcommit(self, context):
# self._call_drivers("delete_flow_classifier_postcommit", context)
. Output only the next line. | def test_update_flow_classifier_postcommit_exception(self): |
Given the code snippet: <|code_start|> self.assertEqual(self.plugin_context_precommit.current,
fc['flow_classifier'])
self.assertEqual(self.plugin_context_postcommit.current,
fc['flow_classifier'])
def _test_delete_flow_classifier_driver_manager_exception(self):
with self.port(
name='test1'
) as port:
with self.flow_classifier(flow_classifier={
'name': 'test1',
'logical_source_port': port['port']['id']
}, do_delete=False) as fc:
req = self.new_delete_request(
'flow_classifiers', fc['flow_classifier']['id']
)
res = req.get_response(self.ext_api)
self.assertEqual(500, res.status_int)
driver_manager = self.fake_driver_manager
driver_manager.delete_flow_classifier.assert_called_once_with(
mock.ANY
)
self._test_list_resources('flow_classifier', [fc])
def test_delete_flow_classifier_driver_manager_exception(self):
self.fake_driver_manager.delete_flow_classifier = mock.Mock(
side_effect=fc_exc.FlowClassifierDriverError(
method='delete_flow_classifier'
)
)
<|code_end|>
, generate the next line using the imports in this file:
import copy
from unittest import mock
from networking_sfc.services.flowclassifier.common import context as fc_ctx
from networking_sfc.services.flowclassifier.common import exceptions as fc_exc
from networking_sfc.tests.unit.db import test_flowclassifier_db
and context (functions, classes, or occasionally code) from other files:
# Path: networking_sfc/services/flowclassifier/common/context.py
# class FlowClassifierPluginContext():
# class FlowClassifierContext(FlowClassifierPluginContext):
# def __init__(self, plugin, plugin_context):
# def __init__(self, plugin, plugin_context, flowclassifier,
# original_flowclassifier=None):
# def current(self):
# def original(self):
#
# Path: networking_sfc/services/flowclassifier/common/exceptions.py
# class FlowClassifierDriverError(exceptions.NeutronException):
# class FlowClassifierException(exceptions.NeutronException):
# class FlowClassifierBadRequest(exceptions.BadRequest, FlowClassifierException):
#
# Path: networking_sfc/tests/unit/db/test_flowclassifier_db.py
# DB_FLOWCLASSIFIER_PLUGIN_CLASS = (
# "networking_sfc.db.flowclassifier_db.FlowClassifierDbPlugin"
# )
# class FlowClassifierDbPluginTestCaseBase(base.BaseTestCase):
# class FlowClassifierDbPluginTestCase(
# base.NeutronDbPluginV2TestCase,
# FlowClassifierDbPluginTestCaseBase
# ):
# def _create_flow_classifier(
# self, fmt, flow_classifier=None, expected_res_status=None, **kwargs
# ):
# def flow_classifier(
# self, fmt=None, flow_classifier=None, do_delete=True, **kwargs
# ):
# def _get_expected_flow_classifier(self, flow_classifier):
# def _assert_flow_classifiers_match_subsets(self, flow_classifiers,
# subsets, sort_key=None):
# def _test_create_flow_classifier(
# self, flow_classifier, expected_flow_classifier=None
# ):
# def setUp(self, core_plugin=None, flowclassifier_plugin=None,
# ext_mgr=None):
# def test_create_flow_classifier(self):
# def test_create_flow_classifier_with_logical_destination_port(self):
# def test_quota_create_flow_classifier(self):
# def test_create_flow_classifier_with_all_fields(self):
# def test_create_flow_classifier_with_all_supported_ethertype(self):
# def test_create_flow_classifier_with_invalid_ethertype(self):
# def test_create_flow_classifier_with_all_supported_protocol(self):
# def test_create_flow_classifier_with_invalid_protocol(self):
# def test_create_flow_classifier_with_all_supported_port_protocol(self):
# def test_create_flow_classifier_with_invalid_ip_prefix_ethertype(self):
# def test_create_flow_classifier_with_invalid_port_protocol(self):
# def test_create_flow_classifier_with_all_supported_ip_prefix(self):
# def test_create_flow_classifier_with_invalid_ip_prefix(self):
# def test_create_flow_classifier_with_all_supported_l7_parameters(self):
# def test_create_flow_classifier_with_invalid_l7_parameters(self):
# def test_create_flow_classifier_with_port_id(self):
# def test_create_flow_classifier_with_nouuid_port_id(self):
# def test_create_flow_classifier_ethertype_conflict(self):
# def test_create_flow_classifier_protocol_conflict(self):
# def test_create_flow_classifier_source_ip_prefix_conflict(self):
# def test_create_flow_classifier_destination_ip_prefix_conflict(self):
# def test_create_flow_classifier_source_port_range_conflict(self):
# def test_create_flow_classifier_destination_port_range_conflict(self):
# def test_create_flow_classifier_not_all_fields_conflict(self):
# def test_create_flow_classifier_with_unknown_port_id(self):
# def test_list_flow_classifiers(self):
# def test_list_flow_classifiers_with_params(self):
# def test_list_flow_classifiers_with_unknown_params(self):
# def test_show_flow_classifier(self):
# def test_show_flow_classifier_noexist(self):
# def test_update_flow_classifier(self):
# def _test_update_with_field(
# self, fc, updates, expected_status_code
# ):
# def test_update_flow_classifer_unsupported_fields(self):
# def test_delete_flow_classifier(self):
# def test_delete_flow_classifier_noexist(self):
. Output only the next line. | self._test_delete_flow_classifier_driver_manager_exception() |
Given the following code snippet before the placeholder: <|code_start|> .assert_called_once_with(mock.ANY))
self.assertIsInstance(
self.plugin_context, fc_ctx.FlowClassifierContext
)
self.assertIsInstance(
self.plugin_context_precommit, fc_ctx.FlowClassifierContext
)
self.assertIsInstance(self.plugin_context_postcommit,
fc_ctx.FlowClassifierContext)
self.assertIn('flow_classifier', fc)
self.assertEqual(
self.plugin_context.current, fc['flow_classifier'])
self.assertEqual(self.plugin_context_precommit.current,
fc['flow_classifier'])
self.assertEqual(self.plugin_context_postcommit.current,
fc['flow_classifier'])
def _test_delete_flow_classifier_driver_manager_exception(self):
with self.port(
name='test1'
) as port:
with self.flow_classifier(flow_classifier={
'name': 'test1',
'logical_source_port': port['port']['id']
}, do_delete=False) as fc:
req = self.new_delete_request(
'flow_classifiers', fc['flow_classifier']['id']
)
res = req.get_response(self.ext_api)
self.assertEqual(500, res.status_int)
<|code_end|>
, predict the next line using imports from the current file:
import copy
from unittest import mock
from networking_sfc.services.flowclassifier.common import context as fc_ctx
from networking_sfc.services.flowclassifier.common import exceptions as fc_exc
from networking_sfc.tests.unit.db import test_flowclassifier_db
and context including class names, function names, and sometimes code from other files:
# Path: networking_sfc/services/flowclassifier/common/context.py
# class FlowClassifierPluginContext():
# class FlowClassifierContext(FlowClassifierPluginContext):
# def __init__(self, plugin, plugin_context):
# def __init__(self, plugin, plugin_context, flowclassifier,
# original_flowclassifier=None):
# def current(self):
# def original(self):
#
# Path: networking_sfc/services/flowclassifier/common/exceptions.py
# class FlowClassifierDriverError(exceptions.NeutronException):
# class FlowClassifierException(exceptions.NeutronException):
# class FlowClassifierBadRequest(exceptions.BadRequest, FlowClassifierException):
#
# Path: networking_sfc/tests/unit/db/test_flowclassifier_db.py
# DB_FLOWCLASSIFIER_PLUGIN_CLASS = (
# "networking_sfc.db.flowclassifier_db.FlowClassifierDbPlugin"
# )
# class FlowClassifierDbPluginTestCaseBase(base.BaseTestCase):
# class FlowClassifierDbPluginTestCase(
# base.NeutronDbPluginV2TestCase,
# FlowClassifierDbPluginTestCaseBase
# ):
# def _create_flow_classifier(
# self, fmt, flow_classifier=None, expected_res_status=None, **kwargs
# ):
# def flow_classifier(
# self, fmt=None, flow_classifier=None, do_delete=True, **kwargs
# ):
# def _get_expected_flow_classifier(self, flow_classifier):
# def _assert_flow_classifiers_match_subsets(self, flow_classifiers,
# subsets, sort_key=None):
# def _test_create_flow_classifier(
# self, flow_classifier, expected_flow_classifier=None
# ):
# def setUp(self, core_plugin=None, flowclassifier_plugin=None,
# ext_mgr=None):
# def test_create_flow_classifier(self):
# def test_create_flow_classifier_with_logical_destination_port(self):
# def test_quota_create_flow_classifier(self):
# def test_create_flow_classifier_with_all_fields(self):
# def test_create_flow_classifier_with_all_supported_ethertype(self):
# def test_create_flow_classifier_with_invalid_ethertype(self):
# def test_create_flow_classifier_with_all_supported_protocol(self):
# def test_create_flow_classifier_with_invalid_protocol(self):
# def test_create_flow_classifier_with_all_supported_port_protocol(self):
# def test_create_flow_classifier_with_invalid_ip_prefix_ethertype(self):
# def test_create_flow_classifier_with_invalid_port_protocol(self):
# def test_create_flow_classifier_with_all_supported_ip_prefix(self):
# def test_create_flow_classifier_with_invalid_ip_prefix(self):
# def test_create_flow_classifier_with_all_supported_l7_parameters(self):
# def test_create_flow_classifier_with_invalid_l7_parameters(self):
# def test_create_flow_classifier_with_port_id(self):
# def test_create_flow_classifier_with_nouuid_port_id(self):
# def test_create_flow_classifier_ethertype_conflict(self):
# def test_create_flow_classifier_protocol_conflict(self):
# def test_create_flow_classifier_source_ip_prefix_conflict(self):
# def test_create_flow_classifier_destination_ip_prefix_conflict(self):
# def test_create_flow_classifier_source_port_range_conflict(self):
# def test_create_flow_classifier_destination_port_range_conflict(self):
# def test_create_flow_classifier_not_all_fields_conflict(self):
# def test_create_flow_classifier_with_unknown_port_id(self):
# def test_list_flow_classifiers(self):
# def test_list_flow_classifiers_with_params(self):
# def test_list_flow_classifiers_with_unknown_params(self):
# def test_show_flow_classifier(self):
# def test_show_flow_classifier_noexist(self):
# def test_update_flow_classifier(self):
# def _test_update_with_field(
# self, fc, updates, expected_status_code
# ):
# def test_update_flow_classifer_unsupported_fields(self):
# def test_delete_flow_classifier(self):
# def test_delete_flow_classifier_noexist(self):
. Output only the next line. | driver_manager = self.fake_driver_manager |
Next line prediction: <|code_start|> }) as fc:
driver_manager = self.fake_driver_manager
(driver_manager.create_flow_classifier_precommit
.assert_called_once_with(mock.ANY))
(driver_manager.create_flow_classifier_postcommit
.assert_called_once_with(mock.ANY))
self.assertIsInstance(
self.plugin_context_precommit,
fc_ctx.FlowClassifierContext)
self.assertIsInstance(
self.plugin_context_postcommit,
fc_ctx.FlowClassifierContext)
self.assertIn('flow_classifier', fc)
self.assertEqual(
self.plugin_context_precommit.current,
fc['flow_classifier'])
self.assertEqual(
self.plugin_context_postcommit.current,
fc['flow_classifier'])
def test_create_flow_classifier_postcommit_driver_manager_exception(self):
self.fake_driver_manager.create_flow_classifier_postcommit = mock.Mock(
side_effect=fc_exc.FlowClassifierDriverError(
method='create_flow_classifier_postcommit'
)
)
with self.port(
name='test1'
) as port:
self._create_flow_classifier(
<|code_end|>
. Use current file imports:
(import copy
from unittest import mock
from networking_sfc.services.flowclassifier.common import context as fc_ctx
from networking_sfc.services.flowclassifier.common import exceptions as fc_exc
from networking_sfc.tests.unit.db import test_flowclassifier_db)
and context including class names, function names, or small code snippets from other files:
# Path: networking_sfc/services/flowclassifier/common/context.py
# class FlowClassifierPluginContext():
# class FlowClassifierContext(FlowClassifierPluginContext):
# def __init__(self, plugin, plugin_context):
# def __init__(self, plugin, plugin_context, flowclassifier,
# original_flowclassifier=None):
# def current(self):
# def original(self):
#
# Path: networking_sfc/services/flowclassifier/common/exceptions.py
# class FlowClassifierDriverError(exceptions.NeutronException):
# class FlowClassifierException(exceptions.NeutronException):
# class FlowClassifierBadRequest(exceptions.BadRequest, FlowClassifierException):
#
# Path: networking_sfc/tests/unit/db/test_flowclassifier_db.py
# DB_FLOWCLASSIFIER_PLUGIN_CLASS = (
# "networking_sfc.db.flowclassifier_db.FlowClassifierDbPlugin"
# )
# class FlowClassifierDbPluginTestCaseBase(base.BaseTestCase):
# class FlowClassifierDbPluginTestCase(
# base.NeutronDbPluginV2TestCase,
# FlowClassifierDbPluginTestCaseBase
# ):
# def _create_flow_classifier(
# self, fmt, flow_classifier=None, expected_res_status=None, **kwargs
# ):
# def flow_classifier(
# self, fmt=None, flow_classifier=None, do_delete=True, **kwargs
# ):
# def _get_expected_flow_classifier(self, flow_classifier):
# def _assert_flow_classifiers_match_subsets(self, flow_classifiers,
# subsets, sort_key=None):
# def _test_create_flow_classifier(
# self, flow_classifier, expected_flow_classifier=None
# ):
# def setUp(self, core_plugin=None, flowclassifier_plugin=None,
# ext_mgr=None):
# def test_create_flow_classifier(self):
# def test_create_flow_classifier_with_logical_destination_port(self):
# def test_quota_create_flow_classifier(self):
# def test_create_flow_classifier_with_all_fields(self):
# def test_create_flow_classifier_with_all_supported_ethertype(self):
# def test_create_flow_classifier_with_invalid_ethertype(self):
# def test_create_flow_classifier_with_all_supported_protocol(self):
# def test_create_flow_classifier_with_invalid_protocol(self):
# def test_create_flow_classifier_with_all_supported_port_protocol(self):
# def test_create_flow_classifier_with_invalid_ip_prefix_ethertype(self):
# def test_create_flow_classifier_with_invalid_port_protocol(self):
# def test_create_flow_classifier_with_all_supported_ip_prefix(self):
# def test_create_flow_classifier_with_invalid_ip_prefix(self):
# def test_create_flow_classifier_with_all_supported_l7_parameters(self):
# def test_create_flow_classifier_with_invalid_l7_parameters(self):
# def test_create_flow_classifier_with_port_id(self):
# def test_create_flow_classifier_with_nouuid_port_id(self):
# def test_create_flow_classifier_ethertype_conflict(self):
# def test_create_flow_classifier_protocol_conflict(self):
# def test_create_flow_classifier_source_ip_prefix_conflict(self):
# def test_create_flow_classifier_destination_ip_prefix_conflict(self):
# def test_create_flow_classifier_source_port_range_conflict(self):
# def test_create_flow_classifier_destination_port_range_conflict(self):
# def test_create_flow_classifier_not_all_fields_conflict(self):
# def test_create_flow_classifier_with_unknown_port_id(self):
# def test_list_flow_classifiers(self):
# def test_list_flow_classifiers_with_params(self):
# def test_list_flow_classifiers_with_unknown_params(self):
# def test_show_flow_classifier(self):
# def test_show_flow_classifier_noexist(self):
# def test_update_flow_classifier(self):
# def _test_update_with_field(
# self, fc, updates, expected_status_code
# ):
# def test_update_flow_classifer_unsupported_fields(self):
# def test_delete_flow_classifier(self):
# def test_delete_flow_classifier_noexist(self):
. Output only the next line. | self.fmt, {'logical_source_port': port['port']['id']}, |
Using the snippet: <|code_start|>
LOG = logging.getLogger(__name__)
cfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.agent.'
'common.config')
# This table is used to process the traffic across differet subnet scenario.
# Flow 1: pri=1, ip,dl_dst=nexthop_mac,nw_src=nexthop_subnet. actions=
# push_mpls:0x8847,set_mpls_label,set_mpls_ttl,push_vlan,output:(patch port
# or resubmit to table(INGRESS_TABLE)
# Flow 2: pri=0, ip,dl_dst=nexthop_mac,, action=push_mpls:0x8847,
# set_mpls_label,set_mpls_ttl,push_vlan,output:(patch port or resubmit to
# table(INGRESS_TABLE)
ACROSS_SUBNET_TABLE = 5
# The table has multiple flows that steer traffic for the different chains
# to the ingress port of different service functions hosted on this Compute
# node.
INGRESS_TABLE = 10
# port chain default flow rule priority
PC_DEF_PRI = 20
PC_INGRESS_PRI = 30
# Reverse group number offset for dump_group
REVERSE_GROUP_NUMBER_OFFSET = 7000
TAP_CLASSIFIER_TABLE = 7
# This table floods TAP packets on tunnel ports
<|code_end|>
, determine the next line of code. You have imports:
from neutron.plugins.ml2.drivers.openvswitch.agent import vlanmanager
from neutron_lib import constants as n_consts
from neutron_lib.plugins.ml2 import ovs_constants as ovs_consts
from oslo_config import cfg
from oslo_log import log as logging
from networking_sfc.services.sfc.agent.extensions import sfc
from networking_sfc.services.sfc.common import ovs_ext_lib
from networking_sfc.services.sfc.drivers.ovs import constants
and context (class names, function names, or code) available:
# Path: networking_sfc/services/sfc/agent/extensions/sfc.py
# LOG = logging.getLogger(__name__)
# class SfcPluginApi():
# class SfcAgentDriver(metaclass=abc.ABCMeta):
# class SfcAgentExtension(l2_extension.L2AgentExtension):
# def __init__(self, topic, host):
# def update_flowrules_status(self, context, flowrules_status):
# def get_flowrules_by_host_portid(self, context, port_id):
# def initialize(self):
# def consume_api(self, agent_api):
# def update_flow_rules(self, flowrule, flowrule_status):
# def delete_flow_rule(self, flowrule, flowrule_status):
# def initialize(self, connection, driver_type):
# def consume_api(self, agent_api):
# def handle_port(self, context, port):
# def delete_port(self, context, port):
# def update_flow_rules(self, context, **kwargs):
# def delete_flow_rules(self, context, **kwargs):
# def _sfc_setup_rpc(self):
# def _delete_ports_flowrules_by_id(self, context, ports_id):
#
# Path: networking_sfc/services/sfc/common/ovs_ext_lib.py
# LOG = logging.getLogger(__name__)
# def get_port_mask(min_port, max_port):
# def __init__(self, ovs_bridge):
# def __getattr__(self, name):
# def do_action_groups(self, action, kwargs_list):
# def add_group(self, **kwargs):
# def mod_group(self, **kwargs):
# def delete_group(self, **kwargs):
# def dump_group_for_id(self, group_id):
# def get_bridge_ports(self):
# def _build_group_expr_str(group_dict, cmd):
# class SfcOVSBridgeExt():
#
# Path: networking_sfc/services/sfc/drivers/ovs/constants.py
# STATUS_BUILDING = 'building'
# STATUS_ACTIVE = 'active'
# STATUS_ERROR = 'error'
# SRC_NODE = 'src_node'
# DST_NODE = 'dst_node'
# SF_NODE = 'sf_node'
# INSERTION_TYPE_L2 = 'l2'
# INSERTION_TYPE_L3 = 'l3'
# INSERTION_TYPE_BITW = 'bitw'
# INSERTION_TYPE_TAP = 'tap'
# MAX_HASH = 16
# INSERTION_TYPE_DICT = {
# n_const.DEVICE_OWNER_ROUTER_HA_INTF: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_INTF: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_GW: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_FLOATINGIP: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_DHCP: INSERTION_TYPE_TAP,
# n_const.DEVICE_OWNER_DVR_INTERFACE: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_AGENT_GW: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_SNAT: INSERTION_TYPE_TAP,
# n_const.DEVICE_OWNER_LOADBALANCER: INSERTION_TYPE_TAP,
# 'compute': INSERTION_TYPE_L2
# }
# ETH_TYPE_IP = 0x0800
# ETH_TYPE_MPLS = 0x8847
# ETH_TYPE_NSH = 0x894f
. Output only the next line. | TAP_TUNNEL_OUTPUT_TABLE = 25 |
Predict the next line after this snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOG = logging.getLogger(__name__)
cfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.agent.'
'common.config')
# This table is used to process the traffic across differet subnet scenario.
# Flow 1: pri=1, ip,dl_dst=nexthop_mac,nw_src=nexthop_subnet. actions=
# push_mpls:0x8847,set_mpls_label,set_mpls_ttl,push_vlan,output:(patch port
# or resubmit to table(INGRESS_TABLE)
# Flow 2: pri=0, ip,dl_dst=nexthop_mac,, action=push_mpls:0x8847,
# set_mpls_label,set_mpls_ttl,push_vlan,output:(patch port or resubmit to
# table(INGRESS_TABLE)
ACROSS_SUBNET_TABLE = 5
# The table has multiple flows that steer traffic for the different chains
# to the ingress port of different service functions hosted on this Compute
# node.
<|code_end|>
using the current file's imports:
from neutron.plugins.ml2.drivers.openvswitch.agent import vlanmanager
from neutron_lib import constants as n_consts
from neutron_lib.plugins.ml2 import ovs_constants as ovs_consts
from oslo_config import cfg
from oslo_log import log as logging
from networking_sfc.services.sfc.agent.extensions import sfc
from networking_sfc.services.sfc.common import ovs_ext_lib
from networking_sfc.services.sfc.drivers.ovs import constants
and any relevant context from other files:
# Path: networking_sfc/services/sfc/agent/extensions/sfc.py
# LOG = logging.getLogger(__name__)
# class SfcPluginApi():
# class SfcAgentDriver(metaclass=abc.ABCMeta):
# class SfcAgentExtension(l2_extension.L2AgentExtension):
# def __init__(self, topic, host):
# def update_flowrules_status(self, context, flowrules_status):
# def get_flowrules_by_host_portid(self, context, port_id):
# def initialize(self):
# def consume_api(self, agent_api):
# def update_flow_rules(self, flowrule, flowrule_status):
# def delete_flow_rule(self, flowrule, flowrule_status):
# def initialize(self, connection, driver_type):
# def consume_api(self, agent_api):
# def handle_port(self, context, port):
# def delete_port(self, context, port):
# def update_flow_rules(self, context, **kwargs):
# def delete_flow_rules(self, context, **kwargs):
# def _sfc_setup_rpc(self):
# def _delete_ports_flowrules_by_id(self, context, ports_id):
#
# Path: networking_sfc/services/sfc/common/ovs_ext_lib.py
# LOG = logging.getLogger(__name__)
# def get_port_mask(min_port, max_port):
# def __init__(self, ovs_bridge):
# def __getattr__(self, name):
# def do_action_groups(self, action, kwargs_list):
# def add_group(self, **kwargs):
# def mod_group(self, **kwargs):
# def delete_group(self, **kwargs):
# def dump_group_for_id(self, group_id):
# def get_bridge_ports(self):
# def _build_group_expr_str(group_dict, cmd):
# class SfcOVSBridgeExt():
#
# Path: networking_sfc/services/sfc/drivers/ovs/constants.py
# STATUS_BUILDING = 'building'
# STATUS_ACTIVE = 'active'
# STATUS_ERROR = 'error'
# SRC_NODE = 'src_node'
# DST_NODE = 'dst_node'
# SF_NODE = 'sf_node'
# INSERTION_TYPE_L2 = 'l2'
# INSERTION_TYPE_L3 = 'l3'
# INSERTION_TYPE_BITW = 'bitw'
# INSERTION_TYPE_TAP = 'tap'
# MAX_HASH = 16
# INSERTION_TYPE_DICT = {
# n_const.DEVICE_OWNER_ROUTER_HA_INTF: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_INTF: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_GW: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_FLOATINGIP: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_DHCP: INSERTION_TYPE_TAP,
# n_const.DEVICE_OWNER_DVR_INTERFACE: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_AGENT_GW: INSERTION_TYPE_L3,
# n_const.DEVICE_OWNER_ROUTER_SNAT: INSERTION_TYPE_TAP,
# n_const.DEVICE_OWNER_LOADBALANCER: INSERTION_TYPE_TAP,
# 'compute': INSERTION_TYPE_L2
# }
# ETH_TYPE_IP = 0x0800
# ETH_TYPE_MPLS = 0x8847
# ETH_TYPE_NSH = 0x894f
. Output only the next line. | INGRESS_TABLE = 10 |
Predict the next line for this snippet: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
pp1 = uuidutils.generate_uuid()
pp2 = uuidutils.generate_uuid()
pp3 = uuidutils.generate_uuid()
pp4 = uuidutils.generate_uuid()
class CLITestV20PortGroupExtensionJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20PortGroupExtensionJSON, self).setUp()
self._mock_extension_loading()
self.register_non_admin_status_resource('port_pair_group')
def _create_patch(self, name, func=None):
patcher = mock.patch(name)
thing = patcher.start()
self.addCleanup(patcher.stop)
return thing
def _mock_extension_loading(self):
ext_pkg = 'neutronclient.common.extension'
port_pair_group = self._create_patch(ext_pkg +
<|code_end|>
with the help of current file imports:
import sys
from unittest import mock
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
from networking_sfc.cli import port_pair_group as pg
from oslo_utils import uuidutils
and context from other files:
# Path: networking_sfc/cli/port_pair_group.py
# PORT_PAIR_GROUP_RESOURCE = 'port_pair_group'
# def get_port_pair_group_id(client, id_or_name):
# def add_common_arguments(parser):
# def update_common_args2body(client, body, parsed_args):
# def add_known_arguments(self, parser):
# def args2body(self, parsed_args):
# def add_known_arguments(self, parser):
# def args2body(self, parsed_args):
# class PortPairGroup(extension.NeutronClientExtension):
# class PortPairGroupCreate(extension.ClientExtensionCreate, PortPairGroup):
# class PortPairGroupUpdate(extension.ClientExtensionUpdate, PortPairGroup):
# class PortPairGroupDelete(extension.ClientExtensionDelete, PortPairGroup):
# class PortPairGroupList(extension.ClientExtensionList, PortPairGroup):
# class PortPairGroupShow(extension.ClientExtensionShow, PortPairGroup):
, which may contain function names, class names, or code. Output only the next line. | '._discover_via_entry_points') |
Predict the next line for this snippet: <|code_start|># Copyright 2015 Futurewei. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
FLOWCLASSIFIER_DRIVER_OPTS = [
cfg.ListOpt('drivers',
default=['dummy'],
help=_("An ordered list of flow classifier drivers "
"entrypoints to be loaded from the "
"networking_sfc.flowclassifier.drivers namespace.")),
]
<|code_end|>
with the help of current file imports:
from oslo_config import cfg
from networking_sfc._i18n import _
and context from other files:
# Path: networking_sfc/_i18n.py
# DOMAIN = "networking_sfc"
# _C = _translators.contextual_form
# _P = _translators.plural_form
# def get_available_languages():
, which may contain function names, class names, or code. Output only the next line. | cfg.CONF.register_opts(FLOWCLASSIFIER_DRIVER_OPTS, "flowclassifier") |
Continue the code snippet: <|code_start|>
floatX = theano.config.floatX
tol = 1e-4
def _wta(X):
M = K.max(X, axis=-1, keepdims=True)
R = K.switch(K.equal(X, M), X, 0.)
<|code_end|>
. Use current file imports:
import numpy as np
import theano
import theano.tensor as T
from keras.layers.recurrent import Recurrent, GRU, LSTM
from keras import backend as K
from seya.utils import rnn_states
and context (classes, functions, or code) from other files:
# Path: seya/utils.py
# def rnn_states(step_function, inputs, initial_states,
# go_backwards=False, masking=True):
# '''Iterates over the time dimension of a tensor.
# Parameters
# ----------
# inputs: tensor of temporal data of shape (samples, time, ...)
# (at least 3D).
# step_function:
# Parameters:
# input: tensor with shape (samples, ...) (no time dimension),
# representing input for the batch of samples at a certain
# time step.
# states: list of tensors.
# Returns:
# output: tensor with shape (samples, ...) (no time dimension),
# new_states: list of tensors, same length and shapes
# as 'states'.
# initial_states: tensor with shape (samples, ...) (no time dimension),
# containing the initial values for the states used in
# the step function.
# go_backwards: boolean. If True, do the iteration over
# the time dimension in reverse order.
# masking: boolean. If true, any input timestep inputs[s, i]
# that is all-zeros will be skipped (states will be passed to
# the next step unchanged) and the corresponding output will
# be all zeros.
# Returns
# -------
# A tuple (last_output, outputs, new_states).
# last_output: the latest output of the rnn, of shape (samples, ...)
# outputs: tensor with shape (samples, time, ...) where each
# entry outputs[s, t] is the output of the step function
# at time t for sample s.
# new_states: list of tensors, latest states returned by
# the step function, of shape (samples, ...).
# '''
# inputs = inputs.dimshuffle((1, 0, 2))
#
# def _step(input, *states):
# output, new_states = step_function(input, states)
# if masking:
# # if all-zero input timestep, return
# # all-zero output and unchanged states
# switch = T.any(input, axis=-1, keepdims=True)
# output = T.switch(switch, output, 0. * output)
# return_states = []
# for state, new_state in zip(states, new_states):
# return_states.append(T.switch(switch, new_state, state))
# return [output] + return_states
# else:
# return [output] + new_states
#
# results, _ = theano.scan(
# _step,
# sequences=inputs,
# outputs_info=[None] + initial_states,
# go_backwards=go_backwards)
#
# # deal with Theano API inconsistency
# if type(results) is list:
# states = results[1:]
# else:
# states = []
#
# return states
. Output only the next line. | return R |
Continue the code snippet: <|code_start|>
def _IstaStep(cost, states, lr=.001, lambdav=.1, x_prior=0):
grads = T.grad(cost, states)
new_x = states-lr*grads
if x_prior != 0:
new_x += lambdav*lr*.1*_proxInnov(states, x_prior)
new_states = _proxOp(new_x, lr*lambdav)
return theano.gradient.disconnected_grad(new_states)
def _RMSPropStep(cost, states, accum_1, accum_2):
rho = .9
lr = .009
momentum = .9
epsilon = 1e-8
grads = T.grad(cost, states)
new_accum_1 = rho * accum_1 + (1 - rho) * grads**2
new_accum_2 = momentum * accum_2 - lr * grads / T.sqrt(new_accum_1 + epsilon)
denominator = T.sqrt(new_accum_1 + epsilon)
new_states = states + momentum * new_accum_2 - lr * (grads / denominator)
new_states = _proxOp(states - lr * (grads / denominator),
.1*lr/denominator) + momentum * new_accum_2
return (theano.gradient.disconnected_grad(new_states),
new_accum_1, new_accum_2)
class SparseCoding(Layer):
<|code_end|>
. Use current file imports:
import theano
import theano.tensor as T
import numpy as np
from theano.tensor.signal.downsample import max_pool_2d
from keras.layers.core import Layer
from keras.layers.recurrent import Recurrent
from keras import activations, initializations
from keras.utils.theano_utils import alloc_zeros_matrix, sharedX
from keras.layers.convolutional import conv_output_length
from ..utils import diff_abs, theano_rng
and context (classes, functions, or code) from other files:
# Path: seya/utils.py
# def diff_abs(z):
# return T.sqrt(T.sqr(z)+1e-6)
#
# def theano_rng(seed=123):
# return MRG_RandomStreams(seed=seed)
. Output only the next line. | def __init__(self, input_dim, output_dim, |
Continue the code snippet: <|code_start|> activity_regularizer.set_layer(self)
self.regularizers.append(activity_regularizer)
kwargs['input_shape'] = (self.input_dim,)
super(SparseCoding, self).__init__(**kwargs)
@property
def output_shape(self):
input_shape = self.input_shape
if self.return_reconstruction:
return input_shape
else:
return input_shape[0], self.ouput_dim
def build(self):
pass
def get_initial_states(self, X):
return alloc_zeros_matrix(X.shape[0], self.output_dim)
def _step(self, x_t, inputs, prior, W):
outputs = self.activation(T.dot(x_t, self.W))
rec_error = T.sqr(inputs - outputs).sum()
x = _IstaStep(rec_error, x_t, lambdav=self.gamma, x_prior=prior)
return x, outputs
def _get_output(self, inputs, train=False, prior=0):
initial_states = self.get_initial_states(inputs)
outputs, updates = theano.scan(
self._step,
<|code_end|>
. Use current file imports:
import theano
import theano.tensor as T
import numpy as np
from theano.tensor.signal.downsample import max_pool_2d
from keras.layers.core import Layer
from keras.layers.recurrent import Recurrent
from keras import activations, initializations
from keras.utils.theano_utils import alloc_zeros_matrix, sharedX
from keras.layers.convolutional import conv_output_length
from ..utils import diff_abs, theano_rng
and context (classes, functions, or code) from other files:
# Path: seya/utils.py
# def diff_abs(z):
# return T.sqrt(T.sqr(z)+1e-6)
#
# def theano_rng(seed=123):
# return MRG_RandomStreams(seed=seed)
. Output only the next line. | sequences=[], |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-texttospeech",
<|code_end|>
. Write the next line using the current file imports:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.texttospeech_v1beta1.types import cloud_tts
and context from other files:
# Path: google/cloud/texttospeech_v1beta1/types/cloud_tts.py
# class SsmlVoiceGender(proto.Enum):
# class AudioEncoding(proto.Enum):
# class ListVoicesRequest(proto.Message):
# class ListVoicesResponse(proto.Message):
# class Voice(proto.Message):
# class SynthesizeSpeechRequest(proto.Message):
# class TimepointType(proto.Enum):
# class SynthesisInput(proto.Message):
# class VoiceSelectionParams(proto.Message):
# class AudioConfig(proto.Message):
# class CustomVoiceParams(proto.Message):
# class ReportedUsage(proto.Enum):
# class SynthesizeSpeechResponse(proto.Message):
# class Timepoint(proto.Message):
# SSML_VOICE_GENDER_UNSPECIFIED = 0
# MALE = 1
# FEMALE = 2
# NEUTRAL = 3
# AUDIO_ENCODING_UNSPECIFIED = 0
# LINEAR16 = 1
# MP3 = 2
# MP3_64_KBPS = 4
# OGG_OPUS = 3
# MULAW = 5
# ALAW = 6
# TIMEPOINT_TYPE_UNSPECIFIED = 0
# SSML_MARK = 1
# REPORTED_USAGE_UNSPECIFIED = 0
# REALTIME = 1
# OFFLINE = 2
, which may include functions, classes, or code. Output only the next line. | ).version, |
Predict the next line for this snippet: <|code_start|>
def test_list_voices_flattened():
client = TextToSpeechClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_voices), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = cloud_tts.ListVoicesResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_voices(language_code="language_code_value",)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].language_code
mock_val = "language_code_value"
assert arg == mock_val
def test_list_voices_flattened_error():
client = TextToSpeechClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_voices(
cloud_tts.ListVoicesRequest(), language_code="language_code_value",
<|code_end|>
with the help of current file imports:
import os
import mock
import grpc
import math
import pytest
import google.auth
from grpc.experimental import aio
from proto.marshal.rules.dates import DurationRule, TimestampRule
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.texttospeech_v1.services.text_to_speech import TextToSpeechAsyncClient
from google.cloud.texttospeech_v1.services.text_to_speech import TextToSpeechClient
from google.cloud.texttospeech_v1.services.text_to_speech import transports
from google.cloud.texttospeech_v1.types import cloud_tts
from google.oauth2 import service_account
and context from other files:
# Path: google/cloud/texttospeech_v1/types/cloud_tts.py
# class SsmlVoiceGender(proto.Enum):
# class AudioEncoding(proto.Enum):
# class ListVoicesRequest(proto.Message):
# class ListVoicesResponse(proto.Message):
# class Voice(proto.Message):
# class SynthesizeSpeechRequest(proto.Message):
# class SynthesisInput(proto.Message):
# class VoiceSelectionParams(proto.Message):
# class AudioConfig(proto.Message):
# class SynthesizeSpeechResponse(proto.Message):
# SSML_VOICE_GENDER_UNSPECIFIED = 0
# MALE = 1
# FEMALE = 2
# NEUTRAL = 3
# AUDIO_ENCODING_UNSPECIFIED = 0
# LINEAR16 = 1
# MP3 = 2
# OGG_OPUS = 3
# MULAW = 5
# ALAW = 6
, which may contain function names, class names, or code. Output only the next line. | ) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-texttospeech",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
<|code_end|>
, generate the next line using the imports in this file:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.texttospeech_v1.types import cloud_tts
and context (functions, classes, or occasionally code) from other files:
# Path: google/cloud/texttospeech_v1/types/cloud_tts.py
# class SsmlVoiceGender(proto.Enum):
# class AudioEncoding(proto.Enum):
# class ListVoicesRequest(proto.Message):
# class ListVoicesResponse(proto.Message):
# class Voice(proto.Message):
# class SynthesizeSpeechRequest(proto.Message):
# class SynthesisInput(proto.Message):
# class VoiceSelectionParams(proto.Message):
# class AudioConfig(proto.Message):
# class SynthesizeSpeechResponse(proto.Message):
# SSML_VOICE_GENDER_UNSPECIFIED = 0
# MALE = 1
# FEMALE = 2
# NEUTRAL = 3
# AUDIO_ENCODING_UNSPECIFIED = 0
# LINEAR16 = 1
# MP3 = 2
# OGG_OPUS = 3
# MULAW = 5
# ALAW = 6
. Output only the next line. | class TextToSpeechTransport(abc.ABC): |
Using the snippet: <|code_start|>class WordDictSyn:
def __init__(self):
self.__words = {}
self.__stemmer = SnowballStemmer("german", ignore_stopwords=False)
self.__id_mapping = {}
self.__current_mapping_id = 0
def analyze(self, word_list):
cleaned_list = []
for word in word_list:
#word to lower
word = word.lower()
#word replace special chars
word = remove_special_chars(word)
#word stem
word = self.__stemmer.stem(word)
cleaned_list.append(word)
sorted_indices = argsort(cleaned_list)
#cleaned_list.sort()
previous_word = None
for i in sorted_indices:
stem = cleaned_list[i]
if stem in self.__words:
item = self.__words[stem]
item.add_variant(word_list[i])
if stem != previous_word:
item.document_count += 1
else:
item = WordDesc(stem)
<|code_end|>
, determine the next line of code. You have imports:
from mlscripts.text.utilities import *
from mlscripts.text.word_desc import WordDesc
from numpy import argsort
from nltk.stem.snowball import SnowballStemmer
and context (class names, function names, or code) available:
# Path: mlscripts/text/word_desc.py
# class WordDesc:
# def __init__(self, id, stem):
# self.__id = id
# self.__stem = stem
# self.__n_doc = 0
# self.__n_upper = 0
# self.__n_lower = 0
#
# def is_noun(self):
# return self.__n_upper >= 1#/ (self.__n_upper + self.__n_lower) >= 0.5
#
# def add_variant(self, variant):
# if variant.istitle():
# self.__n_upper += 1
# else:
# self.__n_lower += 1
#
# @property
# def stem(self):
# return self.__stem
#
# @property
# def total_count(self):
# return (self.__n_upper + self.__n_lower)
#
# @property
# def document_count(self):
# return self.__n_doc
#
# @document_count.setter
# def document_count(self, new_count):
# self.__n_doc = new_count
#
# @property
# def id(self):
# return self.__id
. Output only the next line. | item.add_variant(word_list[i])
|
Here is a snippet: <|code_start|>
def test_url_prefix():
url = "http://127.0.0.1:5000"
meta = requests.get(url, headers={'Accept': 'application/json'}).json()
url_prefix, __, __ = parse_meta(meta)
assert url_prefix == ""
def test_resjs_web(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath,
prefix="/api", min=True)
assert tmpdir.join("res.js").check()
def test_resjs_node(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath, node=True)
assert tmpdir.join("res.js").check()
def test_api_meta_view():
resjs = requests.get("http://127.0.0.1:5000?f=res.js")
assert resjs.headers["Content-Type"] == "application/javascript"
resminjs = requests.get("http://127.0.0.1:5000?f=res.min.js")
assert resminjs.headers["Content-Type"] == "application/javascript"
resjs2 = requests.get("http://127.0.0.1:5000?f=res.js")
assert resjs.content == resjs2.content
resminjs2 = requests.get("http://127.0.0.1:5000?f=res.min.js")
assert resminjs.content == resminjs2.content
resp = requests.get("http://127.0.0.1:5000?f=docs.min.js")
assert resp.status_code == 200
<|code_end|>
. Write the next line using the current file imports:
import requests
from unittest import mock
from flask_restaction.cli import parse_meta, resjs, main
and context from other files:
# Path: flask_restaction/cli.py
# def parse_meta(meta):
# """
# Parse metadata of API
#
# Args:
# meta: metadata of API
# Returns:
# tuple(url_prefix, auth_header, resources)
# """
# resources = {}
# for name in meta:
# if name.startswith("$"):
# continue
# resources[name] = resource = {}
# for action in meta[name]:
# if action.startswith("$"):
# continue
# url, httpmethod = res_to_url(name, action)
# resource[action] = {
# "url": url,
# "method": httpmethod
# }
# url_prefix = meta.get("$url_prefix", "").rstrip("/")
# return url_prefix, meta["$auth"]["header"].lower(), resources
#
# def resjs(url, dest='./res.js', prefix=None, node=False, min=False):
# """Generate res.js and save it"""
# meta = requests.get(url, headers={'Accept': 'application/json'}).json()
# code = generate_code(meta, prefix, node, min)
# save_file(dest, code)
#
# def main():
# parser = argparse.ArgumentParser(
# description="generate res.js for browser or nodejs")
# parser.add_argument("url", help="url of api meta")
# parser.add_argument("-d", "--dest", default="./res.js",
# help="dest path to save res.js")
# parser.add_argument("-p", "--prefix", default="",
# help="url prefix of generated res.js")
# parser.add_argument("-n", "--node", default=False, action='store_true',
# help="generate res.js for nodejs, default for browser")
# parser.add_argument("-m", "--min", default=False, action='store_true',
# help="minimize generated res.js, default not minimize")
# args = parser.parse_args()
# resjs(args.url, args.dest, args.prefix, args.node, args.min)
# print('OK, saved in: %s' % args.dest)
, which may include functions, classes, or code. Output only the next line. | resp = requests.get("http://127.0.0.1:5000?f=docs.min.css") |
Given the following code snippet before the placeholder: <|code_start|>
def test_url_prefix():
url = "http://127.0.0.1:5000"
meta = requests.get(url, headers={'Accept': 'application/json'}).json()
url_prefix, __, __ = parse_meta(meta)
assert url_prefix == ""
def test_resjs_web(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath,
prefix="/api", min=True)
assert tmpdir.join("res.js").check()
def test_resjs_node(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath, node=True)
assert tmpdir.join("res.js").check()
def test_api_meta_view():
resjs = requests.get("http://127.0.0.1:5000?f=res.js")
assert resjs.headers["Content-Type"] == "application/javascript"
resminjs = requests.get("http://127.0.0.1:5000?f=res.min.js")
assert resminjs.headers["Content-Type"] == "application/javascript"
<|code_end|>
, predict the next line using imports from the current file:
import requests
from unittest import mock
from flask_restaction.cli import parse_meta, resjs, main
and context including class names, function names, and sometimes code from other files:
# Path: flask_restaction/cli.py
# def parse_meta(meta):
# """
# Parse metadata of API
#
# Args:
# meta: metadata of API
# Returns:
# tuple(url_prefix, auth_header, resources)
# """
# resources = {}
# for name in meta:
# if name.startswith("$"):
# continue
# resources[name] = resource = {}
# for action in meta[name]:
# if action.startswith("$"):
# continue
# url, httpmethod = res_to_url(name, action)
# resource[action] = {
# "url": url,
# "method": httpmethod
# }
# url_prefix = meta.get("$url_prefix", "").rstrip("/")
# return url_prefix, meta["$auth"]["header"].lower(), resources
#
# def resjs(url, dest='./res.js', prefix=None, node=False, min=False):
# """Generate res.js and save it"""
# meta = requests.get(url, headers={'Accept': 'application/json'}).json()
# code = generate_code(meta, prefix, node, min)
# save_file(dest, code)
#
# def main():
# parser = argparse.ArgumentParser(
# description="generate res.js for browser or nodejs")
# parser.add_argument("url", help="url of api meta")
# parser.add_argument("-d", "--dest", default="./res.js",
# help="dest path to save res.js")
# parser.add_argument("-p", "--prefix", default="",
# help="url prefix of generated res.js")
# parser.add_argument("-n", "--node", default=False, action='store_true',
# help="generate res.js for nodejs, default for browser")
# parser.add_argument("-m", "--min", default=False, action='store_true',
# help="minimize generated res.js, default not minimize")
# args = parser.parse_args()
# resjs(args.url, args.dest, args.prefix, args.node, args.min)
# print('OK, saved in: %s' % args.dest)
. Output only the next line. | resjs2 = requests.get("http://127.0.0.1:5000?f=res.js") |
Given the code snippet: <|code_start|>
def test_resjs_web(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath,
prefix="/api", min=True)
assert tmpdir.join("res.js").check()
def test_resjs_node(tmpdir):
resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath, node=True)
assert tmpdir.join("res.js").check()
def test_api_meta_view():
resjs = requests.get("http://127.0.0.1:5000?f=res.js")
assert resjs.headers["Content-Type"] == "application/javascript"
resminjs = requests.get("http://127.0.0.1:5000?f=res.min.js")
assert resminjs.headers["Content-Type"] == "application/javascript"
resjs2 = requests.get("http://127.0.0.1:5000?f=res.js")
assert resjs.content == resjs2.content
resminjs2 = requests.get("http://127.0.0.1:5000?f=res.min.js")
assert resminjs.content == resminjs2.content
resp = requests.get("http://127.0.0.1:5000?f=docs.min.js")
assert resp.status_code == 200
resp = requests.get("http://127.0.0.1:5000?f=docs.min.css")
assert resp.status_code == 200
resp = requests.get("http://127.0.0.1:5000?f=unknown.js")
assert resp.status_code == 404
def test_cli(tmpdir):
<|code_end|>
, generate the next line using the imports in this file:
import requests
from unittest import mock
from flask_restaction.cli import parse_meta, resjs, main
and context (functions, classes, or occasionally code) from other files:
# Path: flask_restaction/cli.py
# def parse_meta(meta):
# """
# Parse metadata of API
#
# Args:
# meta: metadata of API
# Returns:
# tuple(url_prefix, auth_header, resources)
# """
# resources = {}
# for name in meta:
# if name.startswith("$"):
# continue
# resources[name] = resource = {}
# for action in meta[name]:
# if action.startswith("$"):
# continue
# url, httpmethod = res_to_url(name, action)
# resource[action] = {
# "url": url,
# "method": httpmethod
# }
# url_prefix = meta.get("$url_prefix", "").rstrip("/")
# return url_prefix, meta["$auth"]["header"].lower(), resources
#
# def resjs(url, dest='./res.js', prefix=None, node=False, min=False):
# """Generate res.js and save it"""
# meta = requests.get(url, headers={'Accept': 'application/json'}).json()
# code = generate_code(meta, prefix, node, min)
# save_file(dest, code)
#
# def main():
# parser = argparse.ArgumentParser(
# description="generate res.js for browser or nodejs")
# parser.add_argument("url", help="url of api meta")
# parser.add_argument("-d", "--dest", default="./res.js",
# help="dest path to save res.js")
# parser.add_argument("-p", "--prefix", default="",
# help="url prefix of generated res.js")
# parser.add_argument("-n", "--node", default=False, action='store_true',
# help="generate res.js for nodejs, default for browser")
# parser.add_argument("-m", "--min", default=False, action='store_true',
# help="minimize generated res.js, default not minimize")
# args = parser.parse_args()
# resjs(args.url, args.dest, args.prefix, args.node, args.min)
# print('OK, saved in: %s' % args.dest)
. Output only the next line. | dest = tmpdir.join("res.js").strpath |
Given the following code snippet before the placeholder: <|code_start|>
sys.path.append('./server')
app = importlib.import_module("index").app
@pytest.fixture(params=[
{"url_prefix": "http://127.0.0.1:5000"},
{"test_client": app.test_client}
])
def res(request):
return Res(**request.param)
def test_basic(res):
data = {"name": "kk"}
expect = {"hello": "kk"}
assert res.test.get(data) == expect
assert res.test.post(data) == expect
assert res.test.post_name(data) == expect
assert res.test.put(data) == expect
assert res.test.patch(data) == expect
assert res.test.delete(data) == expect
<|code_end|>
, predict the next line using imports from the current file:
import importlib
import sys
import pytest
from flask_restaction import Res
from requests import HTTPError
and context including class names, function names, and sometimes code from other files:
# Path: flask_restaction/res.py
# class Res:
# """
# A tool for calling API
#
# Will keep a session and handle auth token automatic
#
# Usage:
#
# >>> res = Res(test_client=app.test_client) # used in testing
# >>> res = Res("http://127.0.0.1:5000") # request remote api
# >>> res.ajax("/hello")
# {'message': 'Hello world, Welcome to flask-restaction!'}
# >>> res.hello.get()
# {'message': 'Hello world, Welcome to flask-restaction!'}
# >>> res.hello.get({"name":"kk"})
# {'message': 'Hello kk, Welcome to flask-restaction!'}
# >>> res.xxx.get()
# ...
# requests.exceptions.HTTPError:
# 404 Client Error: NOT FOUND for url: http://127.0.0.1:5000/xxx
#
# Args:
# url_prefix: url prefix of API
# auth_header: auth header name of API
# Attributes:
# url_prefix: url prefix
# auth_header: auth header
# session: requests.Session or TestClientSession
# """
#
# def __init__(self, url_prefix="", test_client=None,
# auth_header="Authorization"):
# self.url_prefix = url_prefix
# self.auth_header = auth_header
# if test_client is None:
# self.session = requests.Session()
# else:
# self.session = TestClientSession(test_client)
# self.session.headers.update({'Accept': 'application/json'})
#
# def ajax(self, url, method="GET", data=None, headers=None):
# """Send request"""
# params = {
# "method": method,
# "url": self.url_prefix + url,
# "headers": headers
# }
# if data is not None:
# if method in ["GET", "DELETE"]:
# params["params"] = data
# elif method in ["POST", "PUT", "PATCH"]:
# params["json"] = data
# resp = self.session.request(**params)
# if self.auth_header in resp.headers:
# self.session.headers[
# self.auth_header] = resp.headers[self.auth_header]
# return resp_json(resp)
#
# def _request(self, resource, action, data=None, headers=None):
# """
# Send request
#
# Args:
# resource: resource
# action: action
# data: string or object which can be json.dumps
# headers: http headers
# """
# url, httpmethod = res_to_url(resource, action)
# return self.ajax(url, httpmethod, data, headers)
#
# def __getattr__(self, resource):
# return Resource(self, resource)
. Output only the next line. | def test_ajax(res): |
Here is a snippet: <|code_start|> }
Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save()
Pusher.send("activity", "my_event", msg)
return self.render_json_response(json_dict)
class AddExp(JSONResponseMixin, AjaxResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
amount = random.randint(1, 100)
self.request.user.exp += amount
self.request.user.save()
json_dict = {
'exp': self.request.user.exp,
}
msg = {
"type": "rpg",
"user": self.request.user.username,
"message": "<strong><a href='/users/%s'>%s</a></strong> get %s XP for fun" % (
self.request.user.username,
self.request.user.username,
amount
)
}
Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save()
Pusher.send("activity", "my_event", msg)
return self.render_json_response(json_dict)
class GiveCoin(JSONResponseMixin, AjaxResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
<|code_end|>
. Write the next line using the current file imports:
from django.views.generic import View
from braces.views import AjaxResponseMixin, JSONResponseMixin
from django.contrib.auth import get_user_model
from activity.models import Event
from rpg.models import Title
from emergent.websockets import Pusher
from datetime import datetime
import random
and context from other files:
# Path: activity/models.py
# class Event(models.Model):
# timestamp = models.DateTimeField(auto_now=True)
# type = models.TextField(choices=(
# ("chat", "Chat"), ("rpg", "RPG"), ("other", "Other"))
# )
# message = models.TextField()
# user = models.ForeignKey(get_user_model())
#
# Path: rpg/models.py
# class Title(models.Model):
# name = models.CharField(max_length=40, unique=True, db_index=True)
#
# def __unicode__(self):
# return self.name
#
# Path: emergent/websockets.py
# class PusherWrapper(object):
# def __init__(self):
# def send(self, channel, event, msg):
, which may include functions, classes, or code. Output only the next line. | if self.request.user.credits: |
Given snippet: <|code_start|> amount
)
}
Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save()
Pusher.send("activity", "my_event", msg)
return self.render_json_response(json_dict)
class GiveCoin(JSONResponseMixin, AjaxResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
if self.request.user.credits:
target_user = get_user_model().objects.get(username=kwargs['username'])
target_user.credits += 1
target_user.save()
self.request.user.credits -= 1
self.request.user.save()
json_dict = {
'success': True,
'my': self.request.user.credits,
'new': target_user.credits
}
else:
json_dict = {
'success': False,
'reason': "No money"
}
return self.render_json_response(json_dict)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.views.generic import View
from braces.views import AjaxResponseMixin, JSONResponseMixin
from django.contrib.auth import get_user_model
from activity.models import Event
from rpg.models import Title
from emergent.websockets import Pusher
from datetime import datetime
import random
and context:
# Path: activity/models.py
# class Event(models.Model):
# timestamp = models.DateTimeField(auto_now=True)
# type = models.TextField(choices=(
# ("chat", "Chat"), ("rpg", "RPG"), ("other", "Other"))
# )
# message = models.TextField()
# user = models.ForeignKey(get_user_model())
#
# Path: rpg/models.py
# class Title(models.Model):
# name = models.CharField(max_length=40, unique=True, db_index=True)
#
# def __unicode__(self):
# return self.name
#
# Path: emergent/websockets.py
# class PusherWrapper(object):
# def __init__(self):
# def send(self, channel, event, msg):
which might include code, classes, or functions. Output only the next line. | class BuyView(JSONResponseMixin, AjaxResponseMixin, View): |
Predict the next line after this snippet: <|code_start|> amount = random.randint(1, 100)
self.request.user.exp += amount
self.request.user.save()
json_dict = {
'exp': self.request.user.exp,
}
msg = {
"type": "rpg",
"user": self.request.user.username,
"message": "<strong><a href='/users/%s'>%s</a></strong> get %s XP for fun" % (
self.request.user.username,
self.request.user.username,
amount
)
}
Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save()
Pusher.send("activity", "my_event", msg)
return self.render_json_response(json_dict)
class GiveCoin(JSONResponseMixin, AjaxResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
if self.request.user.credits:
target_user = get_user_model().objects.get(username=kwargs['username'])
target_user.credits += 1
target_user.save()
self.request.user.credits -= 1
self.request.user.save()
json_dict = {
'success': True,
<|code_end|>
using the current file's imports:
from django.views.generic import View
from braces.views import AjaxResponseMixin, JSONResponseMixin
from django.contrib.auth import get_user_model
from activity.models import Event
from rpg.models import Title
from emergent.websockets import Pusher
from datetime import datetime
import random
and any relevant context from other files:
# Path: activity/models.py
# class Event(models.Model):
# timestamp = models.DateTimeField(auto_now=True)
# type = models.TextField(choices=(
# ("chat", "Chat"), ("rpg", "RPG"), ("other", "Other"))
# )
# message = models.TextField()
# user = models.ForeignKey(get_user_model())
#
# Path: rpg/models.py
# class Title(models.Model):
# name = models.CharField(max_length=40, unique=True, db_index=True)
#
# def __unicode__(self):
# return self.name
#
# Path: emergent/websockets.py
# class PusherWrapper(object):
# def __init__(self):
# def send(self, channel, event, msg):
. Output only the next line. | 'my': self.request.user.credits, |
Based on the snippet: <|code_start|># Create your views here.from datetime import datetime
__all__ = (
'StreamView',
'ChatSendView',
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import random
import misaka as m
from django.conf import settings
from django.contrib.auth import get_user_model
from django.shortcuts import redirect
from django.views.generic import TemplateView, View
from braces.views import LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin
from activity.models import Event
from datetime import datetime
from emergent.websockets import Pusher
and context (classes, functions, sometimes code) from other files:
# Path: activity/models.py
# class Event(models.Model):
# timestamp = models.DateTimeField(auto_now=True)
# type = models.TextField(choices=(
# ("chat", "Chat"), ("rpg", "RPG"), ("other", "Other"))
# )
# message = models.TextField()
# user = models.ForeignKey(get_user_model())
#
# Path: emergent/websockets.py
# class PusherWrapper(object):
# def __init__(self):
# def send(self, channel, event, msg):
. Output only the next line. | 'HistoryView' |
Given the code snippet: <|code_start|>
class StreamView(LoginRequiredMixin, TemplateView):
template_name = 'activity/stream.html'
def get_context_data(self, **kwargs):
context = super(StreamView, self).get_context_data(**kwargs)
return context
class HistoryView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
history = Event.objects.all().order_by("-timestamp")[:10]
json_dict = {"history": []}
for event in reversed(history):
json_dict["history"].append({
'message': m.html(event.message),
'user': event.user.username,
'type': event.type,
'timestamp': event.timestamp.isoformat()
})
return self.render_json_response(json_dict)
class ChatSendView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, View):
def post_ajax(self, request, *args, **kwargs):
msg = {
'message': m.html(self.request.POST['message']),
'user': self.request.user.username,
'type': 'chat',
'timestamp': datetime.now().isoformat()
<|code_end|>
, generate the next line using the imports in this file:
import os
import random
import misaka as m
from django.conf import settings
from django.contrib.auth import get_user_model
from django.shortcuts import redirect
from django.views.generic import TemplateView, View
from braces.views import LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin
from activity.models import Event
from datetime import datetime
from emergent.websockets import Pusher
and context (functions, classes, or occasionally code) from other files:
# Path: activity/models.py
# class Event(models.Model):
# timestamp = models.DateTimeField(auto_now=True)
# type = models.TextField(choices=(
# ("chat", "Chat"), ("rpg", "RPG"), ("other", "Other"))
# )
# message = models.TextField()
# user = models.ForeignKey(get_user_model())
#
# Path: emergent/websockets.py
# class PusherWrapper(object):
# def __init__(self):
# def send(self, channel, event, msg):
. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Marcotti(object):
def __init__(self, config):
logger.info("Marcotti v{0}: Python {1} on {2}".format(
__version__, sys.version, sys.platform))
<|code_end|>
using the current file's imports:
import re
import sys
import logging
import pkg_resources
from contextlib import contextmanager
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.session import Session
from .version import __version__
and any relevant context from other files:
# Path: marcotti/version.py
. Output only the next line. | logger.info("Opened connection to {0}".format(self._public_db_uri(config.database_uri))) |
Next line prediction: <|code_start|> try:
# first get the member meme that the dict refers to
memberMeme = templateRepository.resolveTemplate(memePath, memeberMemePath)
try:
#naturally, that meme should have a registered metameme
member = memberMeme.getParentMetaMeme()
memberMMList.append(member.path.fullTemplatePath)
try:
# THAT metameme should also me a member metameme of this one
# If so, then we increment the total number of occurrences to account for this distinct member
oldCardinalityList = []
extensionParents = []
try:
assert member.path.fullTemplatePath in memberMetaMemeCount
oldCardinalityList = memberMetaMemeCount[member.path.fullTemplatePath]
except AssertionError:
#This assertion error might be falsely triggered, if the member meme is from a metameme that extends the original
for extending in member.extends:
try:
assert extending in memberMetaMemeCount
oldCardinalityList = memberMetaMemeCount[extending]
extensionParents.append(extending)
except AssertionError:
pass
for extending in member.enhances:
try:
assert extending in memberMetaMemeCount
oldCardinalityList = memberMetaMemeCount[extending]
extensionParents.append(extending)
except AssertionError:
<|code_end|>
. Use current file imports:
(from ast import Str
from uuid import UUID
from xml.dom import minidom
from os.path import expanduser
from .DatabaseDrivers import SQLDictionary
from Graphyne import Exceptions
from Graphyne import Condition
from Graphyne import Fileutils
from . import Logger
from .DatabaseDrivers import NonPersistent as persistenceNone
from .DatabaseDrivers import RelationalDatabase as persistenceMemory
from .DatabaseDrivers import RelationalDatabase as persistenceExisting
from .DatabaseDrivers import RelationalDatabase as persistenceNew
from .DatabaseDrivers import RelationalDatabase as persistenceMSSQL
import uuid
import decimal
import copy
import re
import threading
import sys
import os
import queue
import functools
import platform
import json
import time
import sqlite3 as dbDriverMemory
import sqlite3 as dbDriverExisting
import sqlite3 as dbDriverNew
import pyodbc as dbDriverMSSQL
import TestUtils
import sqlite3 as dtDBDriverSQLiteDT
import sqlite3 as dtDBDriverSQLite2)
and context including class names, function names, or small code snippets from other files:
# Path: Graphyne/DatabaseDrivers/SQLDictionary.py
# class SyntaxDefSQLite(object):
# class SyntaxDefMSSQL(object):
# class SyntaxSAPHana(object):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
#
# Path: Graphyne/Exceptions.py
# class TagError(ValueError):
# class TraverseFilterError(ValueError):
# class EmptyFileError(ValueError):
# class UndefinedPersistenceError(ValueError):
# class PersistenceQueryError(ValueError):
# class EnhancementError(ValueError):
# class EventScriptFailure(ValueError):
# class XMLSchemavalidationError(ValueError):
# class UndefinedValueListError(ValueError):
# class DuplicateValueListError(ValueError):
# class UndefinedOperatorError(ValueError):
# class DisallowedCloneError(ValueError):
# class UndefinedUUIDError(ValueError):
# class TemplatePathError(ValueError):
# class MetaMemePropertyNotDefinedError(ValueError):
# class MemePropertyValidationError(ValueError):
# class MemePropertyValueError(ValueError):
# class MemePropertyValueTypeError(ValueError):
# class MemePropertyValueOutOfBoundsError(ValueError):
# class MemeMembershipValidationError(ValueError):
# class NonInstantiatedSingletonError(ValueError):
# class MemeMemberCardinalityError(ValueError):
# class EntityPropertyMissingValueError(ValueError):
# class EntityPropertyValueTypeError(ValueError):
# class EntityPropertyDuplicateError(ValueError):
# class EntityPropertyValueOutOfBoundsError(ValueError):
# class EntityMemberDuplicateError(ValueError):
# class EntityMemberMissingError(ValueError):
# class EntityInitializationError(ValueError):
# class UnknownLinkError(ValueError):
# class UnanchoredReferenceError(ValueError):
# class UndefinedReferenceDirectionalityError(ValueError):
# class UndefinedReferenceValueComparisonOperator(ValueError):
# class ScriptError(ValueError):
# class GeneratorError(ValueError):
# class StateEventScriptInitError(ValueError):
# class SourceMemeManipulationError(ValueError):
# class EntityNotInLinkError(ValueError):
# class EntityLinkFailureError(ValueError):
# class EntityDuplicateLinkError(ValueError):
# class QueueError(ValueError):
# class NoSuchZoneError(ValueError):
# class NoSuchEntityError(ValueError):
# class MissingImlpicitMemeDatabase(ValueError):
# class UndefinedSQLSyntax(Exception):
# class InconsistentPersistenceArchitecture(Exception):
# class MalformedArgumentPathError(ValueError):
# class MismatchedArgumentPathError(ValueError):
# class MissingArgumentError(ValueError):
# class MissingAgentPathError(ValueError):
# class MissingAgentError(ValueError):
# class MalformedConditionalError(ValueError):
# class UtilityError(Exception):
# def __init__(self, persistenceType, persistenceArg, nestedTraceback = None):
# def __str__(self):
#
# Path: Graphyne/Condition.py
# class Condition(threading.Thread):
# ''' An abstract class for defining the three types of conditions, String, Int and Float '''
# className = "Condition"
# entityLock = threading.RLock()
#
# def initializeCondition(self, conditionContainerUUID, path, operator, valueList = None):
# self.uuid = conditionContainerUUID
# self.meme = path
# self.valueList = valueList
# self.operator = operator
#
# Path: Graphyne/Fileutils.py
# def ensureDirectory(targetDir):
# def getModuleFromResolvedPath(fullModuleName):
# def listFromFile(listFileName):
# def getCodePageFromFile(fileURI):
# def walkDirectory(workingDir, packagePath):
# def walkRepository(dataLocation, pathSet, dynamicPackage = None):
# def defaultCSS():
# def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
# class Promise(object):
. Output only the next line. | pass |
Next line prediction: <|code_start|>
#Meme members are stored in unresolved form. When validating, we'll have to pass the full template paths
resolvedMembers = {}
unresolvedMember = False
for unresolvedMemberMeme in self.memberMemes.keys():
memeberMemeOcc = self.memberMemes[unresolvedMemberMeme][0]
try:
resolvedMemberMetaMeme = templateRepository.resolveTemplate(self.path, unresolvedMemberMeme)
resolvedMembers[resolvedMemberMetaMeme.path.fullTemplatePath] = memeberMemeOcc
except Exception as e:
errorMessage = "Problem resolving %s's member MetaMeme %s. Traceback = %s" %(self.path.fullTemplatePath, unresolvedMemberMeme, e)
errorReport.append(errorMessage)
unresolvedMember = True
logQ.put( [logType , logLevel.WARNING , method , errorMessage])
#debug
resolvedMemberMetaMeme = templateRepository.resolveTemplate(self.path, unresolvedMemberMeme)
membersValidReport = parentMetaMeme.validateMembers(resolvedMembers, self.path)
membersValid = membersValidReport[0]
errorReport.extend(membersValidReport[1])
# now make sure that all of the members are also valid
for resolvedMemberMemeKey in resolvedMembers.keys():
try:
resolvedMemberMeme = templateRepository.resolveTemplateAbsolutely(resolvedMemberMemeKey)
if resolvedMemberMemeKey not in memberExcludeList:
try:
memberValidRep = resolvedMemberMeme.validate(self.memberExcludeList)
memberValid = memberValidRep[0]
if memberValid == False:
try:
<|code_end|>
. Use current file imports:
(from ast import Str
from uuid import UUID
from xml.dom import minidom
from os.path import expanduser
from .DatabaseDrivers import SQLDictionary
from Graphyne import Exceptions
from Graphyne import Condition
from Graphyne import Fileutils
from . import Logger
from .DatabaseDrivers import NonPersistent as persistenceNone
from .DatabaseDrivers import RelationalDatabase as persistenceMemory
from .DatabaseDrivers import RelationalDatabase as persistenceExisting
from .DatabaseDrivers import RelationalDatabase as persistenceNew
from .DatabaseDrivers import RelationalDatabase as persistenceMSSQL
import uuid
import decimal
import copy
import re
import threading
import sys
import os
import queue
import functools
import platform
import json
import time
import sqlite3 as dbDriverMemory
import sqlite3 as dbDriverExisting
import sqlite3 as dbDriverNew
import pyodbc as dbDriverMSSQL
import TestUtils
import sqlite3 as dtDBDriverSQLiteDT
import sqlite3 as dtDBDriverSQLite2)
and context including class names, function names, or small code snippets from other files:
# Path: Graphyne/DatabaseDrivers/SQLDictionary.py
# class SyntaxDefSQLite(object):
# class SyntaxDefMSSQL(object):
# class SyntaxSAPHana(object):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
#
# Path: Graphyne/Exceptions.py
# class TagError(ValueError):
# class TraverseFilterError(ValueError):
# class EmptyFileError(ValueError):
# class UndefinedPersistenceError(ValueError):
# class PersistenceQueryError(ValueError):
# class EnhancementError(ValueError):
# class EventScriptFailure(ValueError):
# class XMLSchemavalidationError(ValueError):
# class UndefinedValueListError(ValueError):
# class DuplicateValueListError(ValueError):
# class UndefinedOperatorError(ValueError):
# class DisallowedCloneError(ValueError):
# class UndefinedUUIDError(ValueError):
# class TemplatePathError(ValueError):
# class MetaMemePropertyNotDefinedError(ValueError):
# class MemePropertyValidationError(ValueError):
# class MemePropertyValueError(ValueError):
# class MemePropertyValueTypeError(ValueError):
# class MemePropertyValueOutOfBoundsError(ValueError):
# class MemeMembershipValidationError(ValueError):
# class NonInstantiatedSingletonError(ValueError):
# class MemeMemberCardinalityError(ValueError):
# class EntityPropertyMissingValueError(ValueError):
# class EntityPropertyValueTypeError(ValueError):
# class EntityPropertyDuplicateError(ValueError):
# class EntityPropertyValueOutOfBoundsError(ValueError):
# class EntityMemberDuplicateError(ValueError):
# class EntityMemberMissingError(ValueError):
# class EntityInitializationError(ValueError):
# class UnknownLinkError(ValueError):
# class UnanchoredReferenceError(ValueError):
# class UndefinedReferenceDirectionalityError(ValueError):
# class UndefinedReferenceValueComparisonOperator(ValueError):
# class ScriptError(ValueError):
# class GeneratorError(ValueError):
# class StateEventScriptInitError(ValueError):
# class SourceMemeManipulationError(ValueError):
# class EntityNotInLinkError(ValueError):
# class EntityLinkFailureError(ValueError):
# class EntityDuplicateLinkError(ValueError):
# class QueueError(ValueError):
# class NoSuchZoneError(ValueError):
# class NoSuchEntityError(ValueError):
# class MissingImlpicitMemeDatabase(ValueError):
# class UndefinedSQLSyntax(Exception):
# class InconsistentPersistenceArchitecture(Exception):
# class MalformedArgumentPathError(ValueError):
# class MismatchedArgumentPathError(ValueError):
# class MissingArgumentError(ValueError):
# class MissingAgentPathError(ValueError):
# class MissingAgentError(ValueError):
# class MalformedConditionalError(ValueError):
# class UtilityError(Exception):
# def __init__(self, persistenceType, persistenceArg, nestedTraceback = None):
# def __str__(self):
#
# Path: Graphyne/Condition.py
# class Condition(threading.Thread):
# ''' An abstract class for defining the three types of conditions, String, Int and Float '''
# className = "Condition"
# entityLock = threading.RLock()
#
# def initializeCondition(self, conditionContainerUUID, path, operator, valueList = None):
# self.uuid = conditionContainerUUID
# self.meme = path
# self.valueList = valueList
# self.operator = operator
#
# Path: Graphyne/Fileutils.py
# def ensureDirectory(targetDir):
# def getModuleFromResolvedPath(fullModuleName):
# def listFromFile(listFileName):
# def getCodePageFromFile(fileURI):
# def walkDirectory(workingDir, packagePath):
# def walkRepository(dataLocation, pathSet, dynamicPackage = None):
# def defaultCSS():
# def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
# class Promise(object):
. Output only the next line. | exception = "Meme %s is invalid because member meme %s is invalid. Ivalidity is inherited from members.!" %(self.path.fullTemplatePath, resolvedMemberMemeKey) |
Predict the next line after this snippet: <|code_start|> enhancedByMeme = templateRepository.resolveTemplateAbsolutely(enhancedBy)
enhancedByMM = enhancedByMeme.metaMeme
try:
assert enhancedByMM not in enhancedByMemesList
enhancedByMemesList[enhancedByMM] = 'X'
except AssertionError:
enError = "Meme %s is enhanced by multiple memes derived from metameme %s" % (self.path.fullTemplatePath, enhancedByMM)
logQ.put( [logType , logLevel.WARNING , method , enError])
enhancementErrors.append(enError)
iAmValidlyEnhanced = False
errorReport.extend(enhancementErrors)
#Since we just took the trouble run collectMemesThatEnhanceSelf,
# it is very expensive and we'll need that info again at entity creation,
# catalog it in the Engine's enhancement index
if iAmValidlyEnhanced == True:
enhancementIndex.enhancementLists[self.path.fullTemplatePath] = enhancedByList
if (membersValid == True) and\
(propertiesValid == True) and\
(enhancementsValid == True) and\
(iAmValidlyEnhanced == True) and\
(unresolvedMember == False):
isValid = True
else:
logQ.put( [logType , logLevel.WARNING , method , "Meme %s does not validate!" %(self.path.fullTemplatePath)])
#logQ.put( [logType , logLevel.DEBUG , method , "exiting"])
except TypeError as e:
<|code_end|>
using the current file's imports:
from ast import Str
from uuid import UUID
from xml.dom import minidom
from os.path import expanduser
from .DatabaseDrivers import SQLDictionary
from Graphyne import Exceptions
from Graphyne import Condition
from Graphyne import Fileutils
from . import Logger
from .DatabaseDrivers import NonPersistent as persistenceNone
from .DatabaseDrivers import RelationalDatabase as persistenceMemory
from .DatabaseDrivers import RelationalDatabase as persistenceExisting
from .DatabaseDrivers import RelationalDatabase as persistenceNew
from .DatabaseDrivers import RelationalDatabase as persistenceMSSQL
import uuid
import decimal
import copy
import re
import threading
import sys
import os
import queue
import functools
import platform
import json
import time
import sqlite3 as dbDriverMemory
import sqlite3 as dbDriverExisting
import sqlite3 as dbDriverNew
import pyodbc as dbDriverMSSQL
import TestUtils
import sqlite3 as dtDBDriverSQLiteDT
import sqlite3 as dtDBDriverSQLite2
and any relevant context from other files:
# Path: Graphyne/DatabaseDrivers/SQLDictionary.py
# class SyntaxDefSQLite(object):
# class SyntaxDefMSSQL(object):
# class SyntaxSAPHana(object):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
#
# Path: Graphyne/Exceptions.py
# class TagError(ValueError):
# class TraverseFilterError(ValueError):
# class EmptyFileError(ValueError):
# class UndefinedPersistenceError(ValueError):
# class PersistenceQueryError(ValueError):
# class EnhancementError(ValueError):
# class EventScriptFailure(ValueError):
# class XMLSchemavalidationError(ValueError):
# class UndefinedValueListError(ValueError):
# class DuplicateValueListError(ValueError):
# class UndefinedOperatorError(ValueError):
# class DisallowedCloneError(ValueError):
# class UndefinedUUIDError(ValueError):
# class TemplatePathError(ValueError):
# class MetaMemePropertyNotDefinedError(ValueError):
# class MemePropertyValidationError(ValueError):
# class MemePropertyValueError(ValueError):
# class MemePropertyValueTypeError(ValueError):
# class MemePropertyValueOutOfBoundsError(ValueError):
# class MemeMembershipValidationError(ValueError):
# class NonInstantiatedSingletonError(ValueError):
# class MemeMemberCardinalityError(ValueError):
# class EntityPropertyMissingValueError(ValueError):
# class EntityPropertyValueTypeError(ValueError):
# class EntityPropertyDuplicateError(ValueError):
# class EntityPropertyValueOutOfBoundsError(ValueError):
# class EntityMemberDuplicateError(ValueError):
# class EntityMemberMissingError(ValueError):
# class EntityInitializationError(ValueError):
# class UnknownLinkError(ValueError):
# class UnanchoredReferenceError(ValueError):
# class UndefinedReferenceDirectionalityError(ValueError):
# class UndefinedReferenceValueComparisonOperator(ValueError):
# class ScriptError(ValueError):
# class GeneratorError(ValueError):
# class StateEventScriptInitError(ValueError):
# class SourceMemeManipulationError(ValueError):
# class EntityNotInLinkError(ValueError):
# class EntityLinkFailureError(ValueError):
# class EntityDuplicateLinkError(ValueError):
# class QueueError(ValueError):
# class NoSuchZoneError(ValueError):
# class NoSuchEntityError(ValueError):
# class MissingImlpicitMemeDatabase(ValueError):
# class UndefinedSQLSyntax(Exception):
# class InconsistentPersistenceArchitecture(Exception):
# class MalformedArgumentPathError(ValueError):
# class MismatchedArgumentPathError(ValueError):
# class MissingArgumentError(ValueError):
# class MissingAgentPathError(ValueError):
# class MissingAgentError(ValueError):
# class MalformedConditionalError(ValueError):
# class UtilityError(Exception):
# def __init__(self, persistenceType, persistenceArg, nestedTraceback = None):
# def __str__(self):
#
# Path: Graphyne/Condition.py
# class Condition(threading.Thread):
# ''' An abstract class for defining the three types of conditions, String, Int and Float '''
# className = "Condition"
# entityLock = threading.RLock()
#
# def initializeCondition(self, conditionContainerUUID, path, operator, valueList = None):
# self.uuid = conditionContainerUUID
# self.meme = path
# self.valueList = valueList
# self.operator = operator
#
# Path: Graphyne/Fileutils.py
# def ensureDirectory(targetDir):
# def getModuleFromResolvedPath(fullModuleName):
# def listFromFile(listFileName):
# def getCodePageFromFile(fileURI):
# def walkDirectory(workingDir, packagePath):
# def walkRepository(dataLocation, pathSet, dynamicPackage = None):
# def defaultCSS():
# def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
# class Promise(object):
. Output only the next line. | errorMsg = "Error validating meme %s. Traceback = %s" %(self.path.fullTemplatePath, e) |
Given the code snippet: <|code_start|> maxVal = None
try:
minStr = restrictionMMIElement.getAttribute("restrictionMin")
minVal = int(minStr)
except: pass
try:
maxStr = restrictionMMIElement.getAttribute("restrictionMax")
maxVal = int(maxStr)
except: pass
restriction = PropertyRestrictionInteger(path, minVal, maxVal)
restrictions.append(restriction)
for restrictionMMDElement in restrictionElement.getElementsByTagName("RestrictionMinMaxDecimal"):
minVal = None
maxVal = None
try:
minStr = restrictionMMDElement.getAttribute("restrictionMin")
minVal = decimal.Decimal(minStr)
except: pass
try:
maxStr = restrictionMMDElement.getAttribute("restrictionMax")
maxVal = decimal.Decimal(maxStr)
except: pass
restriction = PropertyRestrictionDecimal(path, minVal, maxVal)
restrictions.append(restriction)
restrictionList = []
for restrictionValElement in restrictionElement.getElementsByTagName("RestrictionValueString"):
restrictionEntry = restrictionValElement.firstChild.data
restrictionList.append(restrictionEntry)
<|code_end|>
, generate the next line using the imports in this file:
from ast import Str
from uuid import UUID
from xml.dom import minidom
from os.path import expanduser
from .DatabaseDrivers import SQLDictionary
from Graphyne import Exceptions
from Graphyne import Condition
from Graphyne import Fileutils
from . import Logger
from .DatabaseDrivers import NonPersistent as persistenceNone
from .DatabaseDrivers import RelationalDatabase as persistenceMemory
from .DatabaseDrivers import RelationalDatabase as persistenceExisting
from .DatabaseDrivers import RelationalDatabase as persistenceNew
from .DatabaseDrivers import RelationalDatabase as persistenceMSSQL
import uuid
import decimal
import copy
import re
import threading
import sys
import os
import queue
import functools
import platform
import json
import time
import sqlite3 as dbDriverMemory
import sqlite3 as dbDriverExisting
import sqlite3 as dbDriverNew
import pyodbc as dbDriverMSSQL
import TestUtils
import sqlite3 as dtDBDriverSQLiteDT
import sqlite3 as dtDBDriverSQLite2
and context (functions, classes, or occasionally code) from other files:
# Path: Graphyne/DatabaseDrivers/SQLDictionary.py
# class SyntaxDefSQLite(object):
# class SyntaxDefMSSQL(object):
# class SyntaxSAPHana(object):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
# def createRuntimeDB(self, db):
# def resetRuntimeDB(self, db):
# def createTestDB(self, db):
#
# Path: Graphyne/Exceptions.py
# class TagError(ValueError):
# class TraverseFilterError(ValueError):
# class EmptyFileError(ValueError):
# class UndefinedPersistenceError(ValueError):
# class PersistenceQueryError(ValueError):
# class EnhancementError(ValueError):
# class EventScriptFailure(ValueError):
# class XMLSchemavalidationError(ValueError):
# class UndefinedValueListError(ValueError):
# class DuplicateValueListError(ValueError):
# class UndefinedOperatorError(ValueError):
# class DisallowedCloneError(ValueError):
# class UndefinedUUIDError(ValueError):
# class TemplatePathError(ValueError):
# class MetaMemePropertyNotDefinedError(ValueError):
# class MemePropertyValidationError(ValueError):
# class MemePropertyValueError(ValueError):
# class MemePropertyValueTypeError(ValueError):
# class MemePropertyValueOutOfBoundsError(ValueError):
# class MemeMembershipValidationError(ValueError):
# class NonInstantiatedSingletonError(ValueError):
# class MemeMemberCardinalityError(ValueError):
# class EntityPropertyMissingValueError(ValueError):
# class EntityPropertyValueTypeError(ValueError):
# class EntityPropertyDuplicateError(ValueError):
# class EntityPropertyValueOutOfBoundsError(ValueError):
# class EntityMemberDuplicateError(ValueError):
# class EntityMemberMissingError(ValueError):
# class EntityInitializationError(ValueError):
# class UnknownLinkError(ValueError):
# class UnanchoredReferenceError(ValueError):
# class UndefinedReferenceDirectionalityError(ValueError):
# class UndefinedReferenceValueComparisonOperator(ValueError):
# class ScriptError(ValueError):
# class GeneratorError(ValueError):
# class StateEventScriptInitError(ValueError):
# class SourceMemeManipulationError(ValueError):
# class EntityNotInLinkError(ValueError):
# class EntityLinkFailureError(ValueError):
# class EntityDuplicateLinkError(ValueError):
# class QueueError(ValueError):
# class NoSuchZoneError(ValueError):
# class NoSuchEntityError(ValueError):
# class MissingImlpicitMemeDatabase(ValueError):
# class UndefinedSQLSyntax(Exception):
# class InconsistentPersistenceArchitecture(Exception):
# class MalformedArgumentPathError(ValueError):
# class MismatchedArgumentPathError(ValueError):
# class MissingArgumentError(ValueError):
# class MissingAgentPathError(ValueError):
# class MissingAgentError(ValueError):
# class MalformedConditionalError(ValueError):
# class UtilityError(Exception):
# def __init__(self, persistenceType, persistenceArg, nestedTraceback = None):
# def __str__(self):
#
# Path: Graphyne/Condition.py
# class Condition(threading.Thread):
# ''' An abstract class for defining the three types of conditions, String, Int and Float '''
# className = "Condition"
# entityLock = threading.RLock()
#
# def initializeCondition(self, conditionContainerUUID, path, operator, valueList = None):
# self.uuid = conditionContainerUUID
# self.meme = path
# self.valueList = valueList
# self.operator = operator
#
# Path: Graphyne/Fileutils.py
# def ensureDirectory(targetDir):
# def getModuleFromResolvedPath(fullModuleName):
# def listFromFile(listFileName):
# def getCodePageFromFile(fileURI):
# def walkDirectory(workingDir, packagePath):
# def walkRepository(dataLocation, pathSet, dynamicPackage = None):
# def defaultCSS():
# def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
# class Promise(object):
. Output only the next line. | for restrictionValElement in restrictionElement.getElementsByTagName("RestrictionValueInteger"): |
Continue the code snippet: <|code_start|> stringArray = str.split(eachReadLine)
Graph.logQ.put( [logType , logLevel.DEBUG , method , "Starting testcase %s, meme %s" %(n, stringArray[0])])
testResult = False
try:
entityID = Graph.api.createEntityFromMeme(stringArray[0])
Graph.api.setEntityPropertyValue(entityID, stringArray[1], stringArray[2])
getter = Graph.api.getEntityPropertyValue(entityID, stringArray[1])
propType = Graph.api.getEntityPropertyType(entityID, stringArray[1])
#reformat the expected result from unicode string to that which is expected in the property
expectedResult = None
if propType == "String":
expectedResult = stringArray[2]
elif propType == "Integer":
expectedResult = int(stringArray[2])
elif propType == "Decimal":
expectedResult = decimal.Decimal(stringArray[2])
else:
expectedResult = False
if str.lower(stringArray[2]) == 'true':
expectedResult = True
#now compare getter to the reformatted stringArray[2] and see if we have successfully altered the property
if getter == expectedResult:
testResult = True
except Exceptions.ScriptError as e:
#Some test cases violate restriction constraints and will raise an exception.
# This works as intended
<|code_end|>
. Use current file imports:
from tkinter.test.runtktests import this_dir_path
from Graphyne.DatabaseDrivers.DriverTermplate import linkTypes
from xml.dom import minidom
from time import ctime
from os.path import expanduser
from Config.Test.TestRepository import InstallPyExecTest as testMod
from Graphyne.DatabaseDrivers import NonPersistent as persistenceModule1
from Graphyne.DatabaseDrivers import RelationalDatabase as persistenceModule2
from Graphyne.DatabaseDrivers import RelationalDatabase as persistenceModule4
from Graphyne.DatabaseDrivers import RelationalDatabase as persistenceModul3
from Graphyne.DatabaseDrivers import RelationalDatabase as persistenceModul32
import copy
import os
import codecs
import time
import decimal
import queue
import sys
import argparse
import Graphyne.Graph as Graph
import Graphyne.Fileutils as Fileutils
import Graphyne.Exceptions as Exceptions
and context (classes, functions, or code) from other files:
# Path: Graphyne/DatabaseDrivers/DriverTermplate.py
# class LogLevel(object):
# class LogType(object):
# class EntityActiveState(object):
# class LinkType(object):
# class LinkDirectionType(object):
# class linkAttributeOperatorType(object):
# class EntityRepository(object):
# class EntityLink(object):
# class LinkRepository(object):
# def __init__(self):
# def __init__(self):
# def initialize(iapi, itemplateRepository, ilogQ, iConnection, passedPersistence = None, reInitialize = False):
# def __init__(self):
# def getEntitiesByTag(self, tag, zone = None):
# def getEntitiesByType(self, memePath, zone = None):
# def getEntitiesByMetaMemeType(self, metaMemePath, zone = None):
# def getEntitiesByPage(self, zone):
# def getEntity(self, uuid):
# def getAllEntities(self, activeState = entityActiveStates.ACTIVE):
# def addEntity(self, entity):
# def removeEntity(self):
# def __init__(self, memberID1, memberID2, membershipType, linkAttributes = {}, masterEntity = None):
# def getMembershipType(self):
# def makeAtomic(self):
# def makeSubAtomic(self, masterEntity):
# def makeAlias(self, keyLink):
# def getCounterpartUUID(self, uuid):
# def getCounterpartEntity(self, uuid):
# def getKeyLink(self):
# def getMasterEntityUUID(self):
# def getMasterEntity(self):
# def __init__(self):
# def getAllLinks(self, entityUUID):
# def getAllInboundLinks(self, entityUUID):
# def getAllOutboundLinks(self, entityUUID):
# def getCounterpartIndices(self, entityUUID):
# def getCounterparts(self, entityUUID, linkDirection = linkDirectionType.BIDIRECTIONAL, traverseParameters = [], nodeParameters = [], memType = None, excludeLinks = []):
# def testLinkedEntityForAttributes(self, entityID, nodeParameters = []):
# def testLinkForAttribute(self, linkID, attributeName = '', value = None, operator = linkAttributeOperator.EQUAL):
# def removeLink(self, memberID1, memberID2, traverseParameters = []):
# def catalogLink(self, memberID1, memberID2, membershipType = 0, linkAttributes = {}, masterEntity = None):
# def testEntityForAttribute(entityID, attributeName = '', value = None, operator = linkAttributeOperator.EQUAL):
# def getUUIDAsString(uuidToParse):
# def filterListDuplicates(listToFilter):
# ACTIVE = 0
# DEPRICATED = 1
# ALL = 2
# ATOMIC = 0
# SUBATOMIC = 1
# ALIAS = 2
# BIDIRECTIONAL = 0
# OUTBOUND = 1
# INBOUND = 2
# EQUAL = 0
# EQUALORGREATER = 1
# EQUALORLESS = 2
# GREATER = 3
# LESS = 4
# NOTEQUAL = 5
# IN = 6
# NOTIN = 7
. Output only the next line. | testResult = False |
Next line prediction: <|code_start|>
class MifareClassic4k():
def __init__(self, carddata):
self._carddata = carddata
<|code_end|>
. Use current file imports:
(from rfid.formats.mifare.Mifare import MifareSector)
and context including class names, function names, or small code snippets from other files:
# Path: rfid/formats/mifare/Mifare.py
# class MifareSector:
# def __init__(self, blocks=None):
# self.key_a = None
# self.key_b = None
# self.permission = None
# self.extrabit = None
# self.blocks = blocks
#
# def block(self, index):
# return self.blocks[index]
#
# def __repr__(self):
# return "Mifare Sector with %d blocks" % len(self.blocks)
. Output only the next line. | self._num_blocks = 256 |
Given the following code snippet before the placeholder: <|code_start|>try:
except ImportError:
@patch("lighthouse.checks.tcp.socket")
<|code_end|>
, predict the next line using imports from the current file:
import unittest2 as unittest
import unittest
import errno
import socket
from mock import patch
from lighthouse.checks.tcp import TCPCheck
and context including class names, function names, and sometimes code from other files:
# Path: lighthouse/checks/tcp.py
# class TCPCheck(check.Check):
# """
# Service health check using TCP request/response messages.
#
# Sends a certain message to the configured port and passes if the response
# is an expected one.
# """
#
# name = "tcp"
#
# def __init__(self, *args, **kwargs):
# super(TCPCheck, self).__init__(*args, **kwargs)
#
# self.query = None
# self.expected_response = None
#
# @classmethod
# def validate_dependencies(cls):
# """
# This check uses stdlib modules so dependencies are always present.
# """
# return True
#
# @classmethod
# def validate_check_config(cls, config):
# """
# Ensures that a query and expected response are configured.
# """
# if "query" not in config and "response" in config:
# raise ValueError("Missing TCP query message.")
# if "response" not in config and "query" in config:
# raise ValueError("Missing expected TCP response message.")
#
# def apply_check_config(self, config):
# """
# Takes the `query` and `response` fields from a validated config
# dictionary and sets the proper instance attributes.
# """
# self.query = config.get("query")
# self.expected_response = config.get("response")
#
# def perform(self):
# """
# Performs a straightforward TCP request and response.
#
# Sends the TCP `query` to the proper host and port, and loops over the
# socket, gathering response chunks until a full line is acquired.
#
# If the response line matches the expected value, the check passes. If
# not, the check fails. The check will also fail if there's an error
# during any step of the send/receive process.
# """
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# sock.connect((self.host, self.port))
#
# # if no query/response is defined, a successful connection is a pass
# if not self.query:
# sock.close()
# return True
#
# try:
# sock.sendall(self.query)
# except Exception:
# logger.exception("Error sending TCP query message.")
# sock.close()
# return False
#
# response, extra = sockutils.get_response(sock)
#
# logger.debug("response: %s (extra: %s)", response, extra)
#
# if response != self.expected_response:
# logger.warn(
# "Response does not match expected value: %s (expected %s)",
# response, self.expected_response
# )
# sock.close()
# return False
#
# sock.close()
# return True
. Output only the next line. | class TCPCheckTests(unittest.TestCase): |
Here is a snippet: <|code_start|> list(check.results),
[False, False]
)
@patch.object(Check, "apply_check_config", Mock())
@patch.object(Check, "validate_config", Mock())
@patch.object(Check, "get_installed_classes")
def test_from_config_uses_installed_classes(self, get_installed):
fake_check_class = Mock()
get_installed.return_value = {
"fakecheck": fake_check_class
}
result = Check.from_config("fakecheck", {"foo": "bar"})
self.assertEqual(result, fake_check_class.return_value)
result.apply_config.assert_called_once_with({"foo": "bar"})
@patch.object(Check, "apply_check_config", Mock())
@patch.object(Check, "validate_config", Mock())
@patch.object(Check, "get_installed_classes")
def test_from_config_with_unknown_check(self, get_installed):
get_installed.return_value = {
"fakecheck": Mock()
}
self.assertRaises(
ValueError,
Check.from_config, "othercheck", {"foo": "bar"}
<|code_end|>
. Write the next line using the current file imports:
import unittest2 as unittest
import unittest
from mock import patch, Mock
from lighthouse.check import Check
and context from other files:
# Path: lighthouse/check.py
# class Check(Pluggable):
# """
# Base class for service check plugins.
#
# Subclasses are expected to define a name for the check, plus methods for
# validating that any dependencies are present, the given config is valid,
# and of course performing the check itself.
# """
#
# entry_point = "lighthouse.checks"
#
# def __init__(self):
# self.host = None
# self.port = None
#
# self.rise = None
# self.fall = None
#
# self.results = deque()
# self.passing = False
#
# @classmethod
# def validate_check_config(cls, config):
# """
# This method should return True if the given config is valid for the
# health check subclass, False otherwise.
# """
# raise NotImplementedError
#
# def apply_check_config(self, config):
# """
# This method takes an already-validated configuration dictionary as its
# only argument.
#
# The method should set any attributes or state in the instance needed
# for performing the health check.
# """
# raise NotImplementedError
#
# def perform(self):
# """
# This `perform()` is at the heart of the check. Subclasses must define
# this method to actually perform their check. If the check passes, the
# method should return True, otherwise False.
#
# Note that this method takes no arguments. Any sort of context required
# for performing a check should be handled by the config.
# """
# raise NotImplementedError
#
# def run(self):
# """
# Calls the `perform()` method defined by subclasses and stores the
# result in a `results` deque.
#
# After the result is determined the `results` deque is analyzed to see
# if the `passing` flag should be updated. If the check was considered
# passing and the previous `self.fall` number of checks failed, the check
# is updated to not be passing. If the check was not passing and the
# previous `self.rise` number of checks passed, the check is updated to
# be considered passing.
# """
# logger.debug("Running %s check", self.name)
#
# try:
# result = self.perform()
# except Exception:
# logger.exception("Error while performing %s check", self.name)
# result = False
#
# logger.debug("Result: %s", result)
#
# self.results.append(result)
# if self.passing and not any(self.last_n_results(self.fall)):
# logger.info(
# "%s check failed %d time(s), no longer passing.",
# self.name, self.fall,
# )
# self.passing = False
# if not self.passing and all(self.last_n_results(self.rise)):
# logger.info(
# "%s check passed %d time(s), is now passing.",
# self.name, self.rise
# )
# self.passing = True
#
# def last_n_results(self, n):
# """
# Helper method for returning a set number of the previous check results.
# """
# return list(
# itertools.islice(
# self.results, len(self.results) - n, len(self.results)
# )
# )
#
# def apply_config(self, config):
# """
# Sets attributes based on the given config.
#
# Also adjusts the `results` deque to either expand (padding itself with
# False results) or contract (by removing the oldest results) until it
# matches the required length.
# """
# self.rise = int(config["rise"])
# self.fall = int(config["fall"])
#
# self.apply_check_config(config)
#
# if self.results.maxlen == max(self.rise, self.fall):
# return
#
# results = list(self.results)
# while len(results) > max(self.rise, self.fall):
# results.pop(0)
# while len(results) < max(self.rise, self.fall):
# results.insert(0, False)
#
# self.results = deque(
# results,
# maxlen=max(self.rise, self.fall)
# )
#
# @classmethod
# def validate_config(cls, config):
# """
# Validates that required config entries are present.
#
# Each check requires a `host`, `port`, `rise` and `fall` to be
# configured.
#
# The rise and fall variables are integers denoting how many times a
# check must pass before being considered passing and how many times a
# check must fail before being considered failing.
# """
# if "rise" not in config:
# raise ValueError("No 'rise' configured")
# if "fall" not in config:
# raise ValueError("No 'fall' configured")
#
# cls.validate_check_config(config)
, which may include functions, classes, or code. Output only the next line. | ) |
Predict the next line for this snippet: <|code_start|> cluster.name = "datastore"
cluster.haproxy = {
"port": 99
}
stanza = FrontendStanza(cluster, bind_address="127.0.0.1")
self.assertEqual(
stanza.lines,
[
"bind 127.0.0.1:99",
"default_backend datastore"
]
)
def test_custom_frontend_lines(self):
cluster = Mock()
cluster.name = "datastore"
cluster.haproxy = {
"port": 99,
"frontend": [
"foo bar bazz", # skipped as invalid
"acl is_api path_beg /api",
]
}
stanza = FrontendStanza(cluster)
self.assertEqual(
stanza.lines,
<|code_end|>
with the help of current file imports:
import unittest2 as unittest
import unittest
from mock import Mock
from lighthouse.haproxy.stanzas.frontend import FrontendStanza
and context from other files:
# Path: lighthouse/haproxy/stanzas/frontend.py
# class FrontendStanza(Stanza):
# """
# Stanza subclass representing a "frontend" stanza.
#
# A frontend stanza defines an address to bind to an a backend to route
# traffic to. A cluster can defined custom lines via a "frontend" entry
# in their haproxy config dictionary.
# """
#
# def __init__(self, cluster, bind_address=None):
# super(FrontendStanza, self).__init__("frontend")
# self.header = "frontend %s" % cluster.name
#
# if not bind_address:
# bind_address = ""
#
# self.add_lines(cluster.haproxy.get("frontend", []))
# self.add_line("bind %s:%s" % (bind_address, cluster.haproxy["port"]))
# self.add_line("default_backend %s" % cluster.name)
, which may contain function names, class names, or code. Output only the next line. | [ |
Based on the snippet: <|code_start|>try:
except ImportError:
class RedisCheckTests(unittest.TestCase):
def test_query_and_response_values(self):
check = RedisCheck()
check.apply_config({
"host": "127.0.0.1", "port": 1234,
"rise": 1, "fall": 1
})
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest2 as unittest
import unittest
from lighthouse.redis.check import RedisCheck
and context (classes, functions, sometimes code) from other files:
# Path: lighthouse/redis/check.py
# class RedisCheck(TCPCheck):
# """
# Redis service checker.
#
# Pings a redis server to make sure that it's available.
# """
#
# name = "redis"
#
# @classmethod
# def validate_check_config(cls, config):
# """
# The base Check class assures that a host and port are configured so
# this method is a no-op.
# """
# pass
#
# def apply_check_config(self, config):
# """
# This method doesn't actually use any configuration data, as the query
# and response for redis are already established.
# """
# self.query = "PING"
# self.expected_response = "PONG"
. Output only the next line. | self.assertEqual(check.query, "PING") |
Continue the code snippet: <|code_start|>try:
except ImportError:
@patch("lighthouse.scripts.reporter.reporter.Reporter")
@patch("lighthouse.scripts.reporter.parser")
<|code_end|>
. Use current file imports:
import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.scripts import reporter
and context (classes, functions, or code) from other files:
# Path: lighthouse/scripts/reporter.py
# def run():
. Output only the next line. | class ReporterScriptTests(unittest.TestCase): |
Given the following code snippet before the placeholder: <|code_start|>try:
except ImportError:
class BaseStanzaTests(unittest.TestCase):
<|code_end|>
, predict the next line using imports from the current file:
import unittest2 as unittest
import unittest
from lighthouse.haproxy.stanzas.stanza import Stanza
and context including class names, function names, and sometimes code from other files:
# Path: lighthouse/haproxy/stanzas/stanza.py
# class Stanza(object):
# """
# Subclass for config file stanzas.
#
# In an HAProxy config file, a stanza is in the form of::
#
# stanza header
# directive
# directive
# directive
#
# Stanza instances have a `header` attribute for the header and a list of
# `lines`, one for each directive line.
# """
#
# def __init__(self, section_name):
# self.section_name = section_name
# self.header = section_name
# self.lines = []
#
# def add_lines(self, lines):
# """
# Simple helper method for adding multiple lines at once.
# """
# for line in lines:
# self.add_line(line)
#
# def add_line(self, line):
# """
# Adds a given line string to the list of lines, validating the line
# first.
# """
# if not self.is_valid_line(line):
# logger.warn(
# "Invalid line for %s section: '%s'",
# self.section_name, line
# )
# return
#
# self.lines.append(line)
#
# def is_valid_line(self, line):
# """
# Validates a given line against the associated "section" (e.g. 'global'
# or 'frontend', etc.) of a stanza.
#
# If a line represents a directive that shouldn't be within the stanza
# it is rejected. See the `directives.json` file for a condensed look
# at valid directives based on section.
# """
# adjusted_line = line.strip().lower()
#
# return any([
# adjusted_line.startswith(directive)
# for directive in directives_by_section[self.section_name]
# ])
#
# def __str__(self):
# """
# Returns the string representation of a Stanza, meant for use in
# config file content.
#
# if no lines are defined an empty string is returned.
# """
# if not self.lines:
# return ""
#
# return self.header + "\n" + "\n".join([
# "\t" + line
# for line in self.lines
# ])
. Output only the next line. | def test_no_lines(self): |
Predict the next line after this snippet: <|code_start|>try:
except ImportError:
class TestTarget(object):
name = "target"
config_subdirectory = None
class TestTargetWithSubdir(object):
name = "target"
config_subdirectory = "bazz"
@patch("lighthouse.configs.monitor.os")
class ConfigMonitorTests(unittest.TestCase):
def test_file_path(self, mock_os):
monitor = ConfigFileMonitor(TestTarget, "/etc/foobar")
self.assertEqual(
monitor.file_path,
mock_os.path.join.return_value
)
mock_os.path.join.assert_called_once_with("/etc/foobar")
<|code_end|>
using the current file's imports:
import unittest2 as unittest
import unittest
import os
from mock import patch, Mock, call
from lighthouse.configs.monitor import ConfigFileMonitor
and any relevant context from other files:
# Path: lighthouse/configs/monitor.py
# class ConfigFileMonitor(object):
# """
# Config file monitoring class.
#
# This class monitors the proper config directory of a target class and
# fires given callbacks whenever a file is added, updated or removed.
# """
#
# def __init__(self, target_class, base_path):
# self.target_class = target_class
#
# path = [base_path]
# if target_class.config_subdirectory:
# path.append(target_class.config_subdirectory)
#
# self.file_path = os.path.join(*path)
#
# def start(self, on_add, on_update, on_delete):
# """
# Starts monitoring the file path, passing along on_(add|update|delete)
# callbacks to a watchdog observer.
#
# Iterates over the files in the target path before starting the observer
# and calls the on_created callback before starting the observer, so
# that existing files aren't missed.
# """
# handler = ConfigFileChangeHandler(
# self.target_class, on_add, on_update, on_delete
# )
#
# for file_name in os.listdir(self.file_path):
# if os.path.isdir(os.path.join(self.file_path, file_name)):
# continue
# if (
# not self.target_class.config_subdirectory and
# not (
# file_name.endswith(".yaml") or file_name.endswith(".yml")
# )
# ):
# continue
#
# handler.on_created(
# events.FileCreatedEvent(
# os.path.join(self.file_path, file_name)
# )
# )
#
# observer = observers.Observer()
# observer.schedule(handler, self.file_path)
# observer.start()
#
# return observer
. Output only the next line. | def test_adds_subdirectory_to_file_path(self, mock_os): |
Predict the next line for this snippet: <|code_start|>
wait_args, _ = wait_on_event.call_args
composite = wait_args[0]
self.assertEqual(composite.is_set(), False)
event2.set()
self.assertEqual(composite.is_set(), True)
@patch.object(events, "wait_on_event")
def test_all_sub_events_clear_for_composite_to_clear(self, wait_on_event):
event1 = threading.Event()
event2 = threading.Event()
event3 = threading.Event()
events.wait_on_any(event1, event2, event3)
wait_args, _ = wait_on_event.call_args
composite = wait_args[0]
self.assertEqual(composite.is_set(), False)
event2.set()
event3.set()
self.assertEqual(composite.is_set(), True)
event2.clear()
<|code_end|>
with the help of current file imports:
import threading
import unittest2 as unittest
import unittest
from mock import patch, Mock
from lighthouse import events
and context from other files:
# Path: lighthouse/events.py
# def wait_on_any(*events, **kwargs):
# def on_change():
# def patch(original):
# def patched():
# def wait_on_event(event, timeout=None):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(composite.is_set(), True) |
Next line prediction: <|code_start|>try:
except ImportError:
@patch("lighthouse.scripts.writer.writer.Writer")
@patch("lighthouse.scripts.writer.parser")
class WriterScriptTests(unittest.TestCase):
def test_run_handles_keyboardinterrupt(self, parser, Writer):
Writer.return_value.start.side_effect = KeyboardInterrupt
writer.run()
Writer.return_value.stop.assert_called_once_with()
@patch("lighthouse.scripts.writer.log")
<|code_end|>
. Use current file imports:
( import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.scripts import writer)
and context including class names, function names, or small code snippets from other files:
# Path: lighthouse/scripts/writer.py
# def run():
. Output only the next line. | def test_log_setup_called(self, log, parser, Writer): |
Predict the next line for this snippet: <|code_start|>
SOCKET_BUFFER_SIZE = 8192
version_re = re.compile('.*(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+).*')
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
<|code_end|>
with the help of current file imports:
import collections
import errno
import logging
import os
import re
import socket
import subprocess
from lighthouse.peer import Peer
and context from other files:
# Path: lighthouse/peer.py
# class Peer(object):
# """
# This class represents a host running a lighthouse reporter.
#
# When a reporter script tells its discovery method that a node is up, it
# includes information about itself via this class so that writer scripts
# reading that information can coordinate their peers.
#
# This is helpful for HAProxy as a way to generate "peers" config stanzas
# so instances of HAProxy in a given cluster can share stick-table data.
# """
#
# def __init__(self, name, ip, port=None):
# self.name = name
# self.ip = ip
# self.port = port or DEFAULT_PEER_PORT
#
# @classmethod
# def current(cls):
# """
# Helper method for getting the current peer of whichever host we're
# running on.
# """
# name = socket.getfqdn()
# ip = socket.gethostbyname(name)
#
# return cls(name, ip)
#
# def serialize(self):
# """
# Serializes the Peer data as a simple JSON map string.
# """
# return json.dumps({
# "name": self.name,
# "ip": self.ip,
# "port": self.port
# }, sort_keys=True)
#
# @classmethod
# def deserialize(cls, value):
# """
# Generates a Peer instance via a JSON string of the sort generated
# by `Peer.deserialize`.
#
# The `name` and `ip` keys are required to be present in the JSON map,
# if the `port` key is not present the default is used.
# """
# parsed = json.loads(value)
#
# if "name" not in parsed:
# raise ValueError("No peer name.")
# if "ip" not in parsed:
# raise ValueError("No peer IP.")
# if "port" not in parsed:
# parsed["port"] = DEFAULT_PEER_PORT
#
# return cls(parsed["name"], parsed["ip"], parsed["port"])
#
# def __hash__(self):
# """
# Hash method used to store peers in sets.
#
# Simply hashes the string <ip address>:<port>.
# """
# return hash(self.ip + ":" + str(self.port))
#
# def __eq__(self, other):
# """
# Peers are considered equal if their IP and port match.
# """
# return self.ip == other.ip and self.port == other.port
, which may contain function names, class names, or code. Output only the next line. | all_cap_re = re.compile('([a-z0-9])([A-Z])') |
Based on the snippet: <|code_start|>try:
except ImportError:
class Balancertests(unittest.TestCase):
def test_entrypoint(self):
self.assertEqual(Balancer.entry_point, "lighthouse.balancers")
@patch.object(Balancer, "apply_config")
@patch.object(Balancer, "validate_config")
def test_sync_file_must_be_implemented(self, validate, apply):
balancer = Balancer()
self.assertRaises(
NotImplementedError,
balancer.sync_file,
[Mock(), Mock()]
)
@patch.object(Balancer, "get_installed_classes")
def test_from_config(self, get_installed_classes):
MockBalancer = Mock()
get_installed_classes.return_value = {"riak": MockBalancer}
balancer = Balancer.from_config("riak", {"foo": "bar"})
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest2 as unittest
import unittest
from mock import patch, Mock
from lighthouse.balancer import Balancer
and context (classes, functions, sometimes code) from other files:
# Path: lighthouse/balancer.py
# class Balancer(Pluggable):
# """
# Base class for load balancer definitions.
#
# The complexity of generating valid configuration content and updating
# the proper file(s) is left as details for subclasses so this base class
# remains incredibly simple.
#
# All subclasses are expected to implement a `sync_file` method that is
# called whenever an update to the topography of nodes happens.
# """
#
# config_subdirectory = "balancers"
# entry_point = "lighthouse.balancers"
#
# def sync_file(self, clusters):
# """
# This method must take a list of clusters and update any and all
# relevant configuration files with valid config content for balancing
# requests for the given clusters.
# """
# raise NotImplementedError
. Output only the next line. | self.assertEqual(balancer, MockBalancer.return_value) |
Given the following code snippet before the placeholder: <|code_start|>try:
except ImportError:
class StatsStanzaTests(unittest.TestCase):
def test_default_uri(self):
stanza = StatsStanza(9000)
<|code_end|>
, predict the next line using imports from the current file:
import unittest2 as unittest
import unittest
from lighthouse.haproxy.stanzas.stats import StatsStanza
and context including class names, function names, and sometimes code from other files:
# Path: lighthouse/haproxy/stanzas/stats.py
# class StatsStanza(Stanza):
# """
# Stanza subclass representing a "listen" stanza specifically for the
# HAProxy stats feature.
#
# Takes an optional uri parameter that defaults to the root uri.
# """
#
# def __init__(self, port, uri="/"):
# super(StatsStanza, self).__init__("listen")
# self.header = "listen stats :" + str(port)
#
# self.add_lines([
# "mode http",
# "stats enable",
# "stats uri " + uri,
# ])
. Output only the next line. | self.assertEqual( |
Here is a snippet: <|code_start|> "abalancer": Balancer(),
"otherbalancer": Balancer()
}
self.assertRaises(
ValueError,
Cluster.validate_config, {"discovery": "zookeeper"}
)
@patch("lighthouse.cluster.Balancer")
def test_applying_config(self, Balancer):
Balancer.get_installed_classes.return_value = {
"abalancer": Balancer(),
"otherbalancer": Balancer()
}
cluster = Cluster()
cluster.apply_config({
"discovery": "zookeeper",
"abalancer": {"foo": "bar"}
})
self.assertEqual(cluster.discovery, "zookeeper")
self.assertEqual(cluster.abalancer, {"foo": "bar"})
self.assertEqual(cluster.meta_cluster, None)
@patch("lighthouse.cluster.Balancer")
def test_optional_meta_cluster_config(self, Balancer):
Balancer.get_installed_classes.return_value = {
"abalancer": Balancer(),
<|code_end|>
. Write the next line using the current file imports:
import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.cluster import Cluster
and context from other files:
# Path: lighthouse/cluster.py
# class Cluster(Configurable):
# """
# The class representing a cluster of member nodes in a service.
#
# A simple class that merely keeps a list of nodes and defines which
# discovery method is used to track said nodes.
# """
#
# config_subdirectory = "clusters"
#
# def __init__(self):
# self.discovery = None
# self.meta_cluster = None
# self.nodes = []
#
# @classmethod
# def validate_config(cls, config):
# """
# Validates a config dictionary parsed from a cluster config file.
#
# Checks that a discovery method is defined and that at least one of
# the balancers in the config are installed and available.
# """
# if "discovery" not in config:
# raise ValueError("No discovery method defined.")
#
# installed_balancers = Balancer.get_installed_classes().keys()
#
# if not any([balancer in config for balancer in installed_balancers]):
# raise ValueError("No available balancer configs defined.")
#
# def apply_config(self, config):
# """
# Sets the `discovery` and `meta_cluster` attributes, as well as the
# configured + available balancer attributes from a given validated
# config.
# """
# self.discovery = config["discovery"]
# self.meta_cluster = config.get("meta_cluster")
# for balancer_name in Balancer.get_installed_classes().keys():
# if balancer_name in config:
# setattr(self, balancer_name, config[balancer_name])
, which may include functions, classes, or code. Output only the next line. | "otherbalancer": Balancer() |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
class SectionTests(unittest.TestCase):
def test_no_stanzas(self):
section = Section("A Section")
self.assertTrue(
"# No stanzas defined for this section." in str(section)
)
def test_heading(self):
section = Section("This is a section, ok")
self.assertTrue(
str(section).startswith(
"#\n" +
"# This is a section, ok\n" +
"#\n" +
"\n"
)
)
def test_stanzas(self):
stanza1 = Stanza("front")
stanza1.lines = ["foo bar", "thing guy"]
stanza2 = Stanza("back")
<|code_end|>
with the help of current file imports:
import unittest2 as unittest
import unittest
from lighthouse.haproxy.stanzas.stanza import Stanza
from lighthouse.haproxy.stanzas.section import Section
and context from other files:
# Path: lighthouse/haproxy/stanzas/stanza.py
# class Stanza(object):
# """
# Subclass for config file stanzas.
#
# In an HAProxy config file, a stanza is in the form of::
#
# stanza header
# directive
# directive
# directive
#
# Stanza instances have a `header` attribute for the header and a list of
# `lines`, one for each directive line.
# """
#
# def __init__(self, section_name):
# self.section_name = section_name
# self.header = section_name
# self.lines = []
#
# def add_lines(self, lines):
# """
# Simple helper method for adding multiple lines at once.
# """
# for line in lines:
# self.add_line(line)
#
# def add_line(self, line):
# """
# Adds a given line string to the list of lines, validating the line
# first.
# """
# if not self.is_valid_line(line):
# logger.warn(
# "Invalid line for %s section: '%s'",
# self.section_name, line
# )
# return
#
# self.lines.append(line)
#
# def is_valid_line(self, line):
# """
# Validates a given line against the associated "section" (e.g. 'global'
# or 'frontend', etc.) of a stanza.
#
# If a line represents a directive that shouldn't be within the stanza
# it is rejected. See the `directives.json` file for a condensed look
# at valid directives based on section.
# """
# adjusted_line = line.strip().lower()
#
# return any([
# adjusted_line.startswith(directive)
# for directive in directives_by_section[self.section_name]
# ])
#
# def __str__(self):
# """
# Returns the string representation of a Stanza, meant for use in
# config file content.
#
# if no lines are defined an empty string is returned.
# """
# if not self.lines:
# return ""
#
# return self.header + "\n" + "\n".join([
# "\t" + line
# for line in self.lines
# ])
#
# Path: lighthouse/haproxy/stanzas/section.py
# class Section(object):
# """
# Represents a section of HAProxy config file stanzas.
#
# This is used to organize generated config file content and provide header
# comments for sections describing nature of the grouped-together stanzas.
# """
#
# def __init__(self, heading, *stanzas):
# self.heading = heading
# self.stanzas = stanzas
# if not self.stanzas:
# self.stanzas = []
#
# @property
# def header(self):
# return "\n".join([
# "#",
# "# %s" % self.heading,
# "#"
# ])
#
# def __str__(self):
# """
# Joins together the section header and stanza strings with space
# inbetween.
# """
# stanzas = list(self.stanzas)
# if not stanzas:
# stanzas = ["# No stanzas defined for this section."]
#
# return "\n\n".join(map(str, [self.header] + stanzas))
, which may contain function names, class names, or code. Output only the next line. | stanza2.lines = ["reticulate_splines=true"] |
Based on the snippet: <|code_start|> def test_no_stanzas(self):
section = Section("A Section")
self.assertTrue(
"# No stanzas defined for this section." in str(section)
)
def test_heading(self):
section = Section("This is a section, ok")
self.assertTrue(
str(section).startswith(
"#\n" +
"# This is a section, ok\n" +
"#\n" +
"\n"
)
)
def test_stanzas(self):
stanza1 = Stanza("front")
stanza1.lines = ["foo bar", "thing guy"]
stanza2 = Stanza("back")
stanza2.lines = ["reticulate_splines=true"]
section = Section(
"A Section",
stanza1, stanza2
)
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest2 as unittest
import unittest
from lighthouse.haproxy.stanzas.stanza import Stanza
from lighthouse.haproxy.stanzas.section import Section
and context (classes, functions, sometimes code) from other files:
# Path: lighthouse/haproxy/stanzas/stanza.py
# class Stanza(object):
# """
# Subclass for config file stanzas.
#
# In an HAProxy config file, a stanza is in the form of::
#
# stanza header
# directive
# directive
# directive
#
# Stanza instances have a `header` attribute for the header and a list of
# `lines`, one for each directive line.
# """
#
# def __init__(self, section_name):
# self.section_name = section_name
# self.header = section_name
# self.lines = []
#
# def add_lines(self, lines):
# """
# Simple helper method for adding multiple lines at once.
# """
# for line in lines:
# self.add_line(line)
#
# def add_line(self, line):
# """
# Adds a given line string to the list of lines, validating the line
# first.
# """
# if not self.is_valid_line(line):
# logger.warn(
# "Invalid line for %s section: '%s'",
# self.section_name, line
# )
# return
#
# self.lines.append(line)
#
# def is_valid_line(self, line):
# """
# Validates a given line against the associated "section" (e.g. 'global'
# or 'frontend', etc.) of a stanza.
#
# If a line represents a directive that shouldn't be within the stanza
# it is rejected. See the `directives.json` file for a condensed look
# at valid directives based on section.
# """
# adjusted_line = line.strip().lower()
#
# return any([
# adjusted_line.startswith(directive)
# for directive in directives_by_section[self.section_name]
# ])
#
# def __str__(self):
# """
# Returns the string representation of a Stanza, meant for use in
# config file content.
#
# if no lines are defined an empty string is returned.
# """
# if not self.lines:
# return ""
#
# return self.header + "\n" + "\n".join([
# "\t" + line
# for line in self.lines
# ])
#
# Path: lighthouse/haproxy/stanzas/section.py
# class Section(object):
# """
# Represents a section of HAProxy config file stanzas.
#
# This is used to organize generated config file content and provide header
# comments for sections describing nature of the grouped-together stanzas.
# """
#
# def __init__(self, heading, *stanzas):
# self.heading = heading
# self.stanzas = stanzas
# if not self.stanzas:
# self.stanzas = []
#
# @property
# def header(self):
# return "\n".join([
# "#",
# "# %s" % self.heading,
# "#"
# ])
#
# def __str__(self):
# """
# Joins together the section header and stanza strings with space
# inbetween.
# """
# stanzas = list(self.stanzas)
# if not stanzas:
# stanzas = ["# No stanzas defined for this section."]
#
# return "\n\n".join(map(str, [self.header] + stanzas))
. Output only the next line. | self.assertEqual( |
Next line prediction: <|code_start|>
class BackendStanzaTests(unittest.TestCase):
def test_includes_cookie_in_http_mode(self):
http_node = Mock(host="server1.int", ip="10.0.1.12", port=8000)
http_node.name = "server1.int:8000"
cluster = Mock()
cluster.name = "accounts"
cluster.nodes = [http_node]
cluster.haproxy = {
"backend": [
"mode http"
]
}
stanza = BackendStanza(cluster)
self.assertEqual(
str(stanza),
"""backend accounts
\tmode http
\tserver server1.int:8000 10.0.1.12:8000 cookie server1.int:8000 """
)
def test_no_nodes(self):
node = Mock(host="server1.int", ip="10.0.1.12", port=8000)
node.name = "server1.int:8000"
<|code_end|>
. Use current file imports:
( import unittest2 as unittest
import unittest
from mock import Mock
from lighthouse.haproxy.stanzas.backend import BackendStanza)
and context including class names, function names, or small code snippets from other files:
# Path: lighthouse/haproxy/stanzas/backend.py
# class BackendStanza(Stanza):
# """
# Stanza subclass representing a "backend" stanza.
#
# A backend stanza defines the nodes (or "servers") belonging to a given
# cluster as well as how routing/load balancing between those nodes happens.
#
# A given cluster can define custom directives via a list of lines in their
# haproxy config with the key "backend".
# """
#
# def __init__(self, cluster):
# super(BackendStanza, self).__init__("backend")
# self.header = "backend %s" % cluster.name
#
# if not cluster.nodes:
# logger.warning(
# "Cluster %s has no nodes, backend stanza may be blank.",
# cluster.name
# )
#
# backend_lines = cluster.haproxy.get("backend", [])
# self.add_lines(backend_lines)
# for node in cluster.nodes:
# http_mode = bool("mode http" in backend_lines)
# self.add_line(
# "server %(name)s %(host)s:%(port)s %(cookie)s %(options)s" % {
# "name": node.name,
# "host": node.ip,
# "port": node.port,
# "cookie": "cookie " + node.name if http_mode else "",
# "options": cluster.haproxy.get("server_options", "")
# }
# )
. Output only the next line. | cluster = Mock() |
Next line prediction: <|code_start|> included_stanzas = []
def add_included_stanzas(heading, *stanzas):
included_stanzas.extend(stanzas)
Section.side_effect = add_included_stanzas
global_stanza = Mock("global")
defaults_stanza = Mock("defaults")
config = HAProxyConfig(global_stanza, defaults_stanza, None)
config.generate([])
self.assertIn(global_stanza, included_stanzas)
self.assertIn(defaults_stanza, included_stanzas)
@patch("lighthouse.haproxy.config.PeersStanza")
@patch("lighthouse.haproxy.config.BackendStanza")
@patch("lighthouse.haproxy.config.FrontendStanza")
@patch("lighthouse.haproxy.config.Section")
def test_includes_frontend_backend_and_peers(self, Section,
FrontendStanza,
BackendStanza,
PeersStanza):
included_stanzas = []
def add_included_stanzas(heading, *stanzas):
included_stanzas.extend(stanzas)
<|code_end|>
. Use current file imports:
( import unittest2 as unittest
import unittest
from mock import Mock, patch
from lighthouse.haproxy.config import HAProxyConfig)
and context including class names, function names, or small code snippets from other files:
# Path: lighthouse/haproxy/config.py
# class HAProxyConfig(object):
# """
# Class for generating HAProxy config file content.
#
# Requires global and defaults stanzas to be passed, can optionally take
# a `stats_stanza` for enabling a stats portal.
# """
#
# def __init__(
# self,
# global_stanza, defaults_stanza,
# proxy_stanzas=None, stats_stanza=None, meta_clusters=None,
# bind_address=None
# ):
# self.global_stanza = global_stanza
# self.defaults_stanza = defaults_stanza
# self.proxy_stanzas = proxy_stanzas or []
# self.stats_stanza = stats_stanza
# self.meta_clusters = meta_clusters or {}
# self.bind_address = bind_address
#
# def generate(self, clusters, version=None):
# """
# Generates HAProxy config file content based on a given list of
# clusters.
# """
# now = datetime.datetime.now()
#
# sections = [
# Section(
# "Auto-generated by Lighthouse (%s)" % now.strftime("%c"),
# self.global_stanza,
# self.defaults_stanza
# )
# ]
#
# meta_stanzas = [
# MetaFrontendStanza(
# name, self.meta_clusters[name]["port"],
# self.meta_clusters[name].get("frontend", []), members,
# self.bind_address
# )
# for name, members
# in six.iteritems(self.get_meta_clusters(clusters))
# ]
# frontend_stanzas = [
# FrontendStanza(cluster, self.bind_address)
# for cluster in clusters
# if "port" in cluster.haproxy
# ]
# backend_stanzas = [BackendStanza(cluster) for cluster in clusters]
#
# if version and version >= (1, 5, 0):
# peers_stanzas = [PeersStanza(cluster) for cluster in clusters]
# else:
# peers_stanzas = []
#
# sections.extend([
# Section("Frontend stanzas for ACL meta clusters", *meta_stanzas),
# Section("Per-cluster frontend definitions", *frontend_stanzas),
# Section("Per-cluster backend definitions", *backend_stanzas),
# Section("Per-cluster peer listings", *peers_stanzas),
# Section("Individual proxy definitions", *self.proxy_stanzas),
# ])
# if self.stats_stanza:
# sections.append(
# Section("Listener for stats web interface", self.stats_stanza)
# )
#
# return "\n\n\n".join([str(section) for section in sections]) + "\n"
#
# def get_meta_clusters(self, clusters):
# """
# Returns a dictionary keyed off of meta cluster names, where the values
# are lists of clusters associated with the meta cluster name.
#
# If a meta cluster name doesn't have a port defined in the
# `meta_cluster_ports` attribute an error is given and the meta cluster
# is removed from the mapping.
# """
# meta_clusters = collections.defaultdict(list)
#
# for cluster in clusters:
# if not cluster.meta_cluster:
# continue
# meta_clusters[cluster.meta_cluster].append(cluster)
#
# unconfigured_meta_clusters = [
# name for name in meta_clusters.keys()
# if name not in self.meta_clusters
# ]
#
# for name in unconfigured_meta_clusters:
# logger.error("Meta cluster %s not configured!")
# del meta_clusters[name]
#
# return meta_clusters
. Output only the next line. | Section.side_effect = add_included_stanzas |
Using the snippet: <|code_start|>try:
except ImportError:
class ProxyStanzaTests(unittest.TestCase):
def test_optional_bind_address(self):
stanza = ProxyStanza("payserver", 2222, [], bind_address="0.0.0.0")
self.assertEqual(stanza.header, "listen payserver")
self.assertIn("bind 0.0.0.0:2222", stanza.lines)
def test_optional_lines(self):
stanza = ProxyStanza(
"payserver", 2222, [], options=["mode http", "maxconn 400"]
)
self.assertIn("mode http", stanza.lines)
self.assertIn("maxconn 400", stanza.lines)
def test_upstream_entries(self):
stanza = ProxyStanza(
"payserver", 2222,
<|code_end|>
, determine the next line of code. You have imports:
import unittest2 as unittest
import unittest
from lighthouse.haproxy.stanzas.proxy import ProxyStanza
and context (class names, function names, or code) available:
# Path: lighthouse/haproxy/stanzas/proxy.py
# class ProxyStanza(Stanza):
# """
# Stanza for independent proxy directives.
#
# These are used to add simple proxying to a system, e.g. communicating
# with a third party service via a dedicated internal machine with a white-
# listed IP.
# """
#
# def __init__(self, name, port, upstreams, options=None, bind_address=None):
# super(ProxyStanza, self).__init__("listen")
# self.header = "listen " + name
#
# if not bind_address:
# bind_address = ""
#
# self.add_line("bind %s:%s" % (bind_address, port))
#
# if options:
# self.add_lines(options)
#
# for upstream in upstreams:
# max_conn = ""
# if "max_conn" in upstream:
# max_conn = "maxconn " + str(upstream["max_conn"])
#
# self.add_line(
# "server %(name)s %(name)s %(maxconn)s" % {
# "name": ":".join(
# [upstream["host"], str(upstream["port"])]
# ),
# "maxconn": max_conn
# }
# )
. Output only the next line. | [ |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
test_content = """
port: 8888
extras:
<|code_end|>
with the help of current file imports:
import unittest2 as unittest
import unittest
import sys
from mock import patch, Mock, mock_open
from watchdog import events
from lighthouse.configs.handler import ConfigFileChangeHandler
and context from other files:
# Path: lighthouse/configs/handler.py
# class ConfigFileChangeHandler(events.PatternMatchingEventHandler):
# """
# Config file change event handler.
#
# A subclass of watchdog's PatternMatchingEventHandler. This class takes
# callbacks for on_(add|update|delete).
#
# When an event comes in the proper callback is fired with processed inputs.
# """
#
# patterns = ("*.yaml", "*.yml")
#
# def __init__(
# self, target_class, on_add, on_update, on_delete,
# *args, **kwargs
# ):
# self.target_class = target_class
# self.on_add = on_add
# self.on_update = on_update
# self.on_delete = on_delete
#
# super(ConfigFileChangeHandler, self).__init__(*args, **kwargs)
#
# def file_name(self, event):
# """
# Helper method for determining the basename of the affected file.
# """
# name = os.path.basename(event.src_path)
# name = name.replace(".yaml", "")
# name = name.replace(".yml", "")
#
# return name
#
# def on_created(self, event):
# """
# Newly created config file handler.
#
# Parses the file's yaml contents and creates a new instance of the
# target_class with the results. Fires the on_add callback with the
# new instance.
# """
# if os.path.isdir(event.src_path):
# return
#
# logger.debug("File created: %s", event.src_path)
#
# name = self.file_name(event)
#
# try:
# result = self.target_class.from_config(
# name, yaml.load(open(event.src_path))
# )
# except Exception as e:
# logger.exception(
# "Error when loading new config file %s: %s",
# event.src_path, str(e)
# )
# return
#
# if not result:
# return
#
# self.on_add(self.target_class, name, result)
#
# def on_modified(self, event):
# """
# Modified config file handler.
#
# If a config file is modified, the yaml contents are parsed and the
# new results are validated by the target class. Once validated, the
# new config is passed to the on_update callback.
# """
# if os.path.isdir(event.src_path):
# return
#
# logger.debug("file modified: %s", event.src_path)
#
# name = self.file_name(event)
#
# try:
# config = yaml.load(open(event.src_path))
# self.target_class.from_config(name, config)
# except Exception:
# logger.exception(
# "Error when loading updated config file %s", event.src_path,
# )
# return
#
# self.on_update(self.target_class, name, config)
#
# def on_deleted(self, event):
# """
# Deleted config file handler.
#
# Simply fires the on_delete callback with the name of the deleted item.
# """
# logger.debug("file removed: %s", event.src_path)
# name = self.file_name(event)
#
# self.on_delete(self.target_class, name)
#
# def on_moved(self, event):
# """
# A move event is just proxied to an on_deleted call followed by
# an on_created call.
# """
# self.on_deleted(events.FileDeletedEvent(event.src_path))
# self.on_created(events.FileCreatedEvent(event.dest_path))
, which may contain function names, class names, or code. Output only the next line. | - "foo" |
Continue the code snippet: <|code_start|> ]
self.assertEqual(
FakePlugin.get_installed_classes(),
{"fakeplugin": FakePlugin}
)
@patch.object(FakePlugin, "validate_config")
@patch.object(FakePlugin, "apply_config")
def test_from_config(self, validate_config, apply_config, pkg_resources):
fake_plugin = Mock()
fake_plugin.name = "fakeplugin"
fake_plugin.load.return_value = FakePlugin
pkg_resources.iter_entry_points.return_value = [fake_plugin]
result = Pluggable.from_config("fakeplugin", {"foo": "bar"})
self.assertEqual(result.name, "fakeplugin")
validate_config.assert_called_once_with({"foo": "bar"})
result.apply_config.assert_called_once_with({"foo": "bar"})
def test_from_config__unknown_plugin(self, pkg_resources):
pkg_resources.iter_entry_points.return_value = []
self.assertRaises(
ValueError,
FakePlugin.from_config, "thing", {}
)
<|code_end|>
. Use current file imports:
import unittest2 as unittest
import unittest
from mock import patch, Mock
from lighthouse.pluggable import Pluggable
and context (classes, functions, or code) from other files:
# Path: lighthouse/pluggable.py
# class Pluggable(Configurable):
# """
# Base class for classes that can be defined via external plugins.
#
# Subclasses define their `entry_point` attribute and subsequent calls to
# `get_installed_classes` will look up any available classes associated
# with that endpoint.
#
# Entry points used by lighthouse can be found in `setup.py` in the root
# of the project.
# """
#
# # the "entry point" for a plugin (e.g. "lighthouse.checks")
# entry_point = None
#
# @classmethod
# def validate_dependencies(cls):
# """
# Validates a plugin's external dependencies. Should return True if
# all dependencies are met and False if not.
#
# Subclasses are expected to define this method.
# """
# raise NotImplementedError
#
# @classmethod
# def get_installed_classes(cls):
# """
# Iterates over installed plugins associated with the `entry_point` and
# returns a dictionary of viable ones keyed off of their names.
#
# A viable installed plugin is one that is both loadable *and* a subclass
# of the Pluggable subclass in question.
# """
# installed_classes = {}
# for entry_point in pkg_resources.iter_entry_points(cls.entry_point):
# try:
# plugin = entry_point.load()
# except ImportError as e:
# logger.error(
# "Could not load plugin %s: %s", entry_point.name, str(e)
# )
# continue
#
# if not issubclass(plugin, cls):
# logger.error(
# "Could not load plugin %s:" +
# " %s class is not subclass of %s",
# entry_point.name, plugin.__class__.__name__, cls.__name__
# )
# continue
#
# if not plugin.validate_dependencies():
# logger.error(
# "Could not load plugin %s:" +
# " %s class dependencies not met",
# entry_point.name, plugin.__name__
# )
# continue
#
# installed_classes[entry_point.name] = plugin
#
# return installed_classes
#
# @classmethod
# def from_config(cls, name, config):
# """
# Behaves like the base Configurable class's `from_config()` except this
# makes sure that the `Pluggable` subclass with the given name is
# actually a properly installed plugin first.
# """
# installed_classes = cls.get_installed_classes()
#
# if name not in installed_classes:
# raise ValueError("Unknown/unavailable %s" % cls.__name__.lower())
#
# pluggable_class = installed_classes[name]
#
# pluggable_class.validate_config(config)
#
# instance = pluggable_class()
# if not instance.name:
# instance.name = name
# instance.apply_config(config)
#
# return instance
. Output only the next line. | def test_from_config__class_level_name(self, pkg_resources): |
Next line prediction: <|code_start|>try:
except ImportError:
class ConfigurableTests(unittest.TestCase):
def test_validate_config_must_be_overridden(self):
self.assertRaises(
NotImplementedError,
Configurable.validate_config,
{"foo": "bar"}
)
@patch.object(Configurable, "validate_config")
def test_apply_config_must_be_overridden(self, validate):
patcher = patch.object(Configurable, "apply_config")
patcher.start()
configurable = Configurable()
<|code_end|>
. Use current file imports:
( import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.configurable import Configurable)
and context including class names, function names, or small code snippets from other files:
# Path: lighthouse/configurable.py
# class Configurable(object):
# """
# Base class for targets configured by the config file watching system.
#
# Each subclass is expected to be able to validate and apply configuration
# dictionaries that come from config file content.
# """
#
# name = None
#
# # This attribute denotes that the config watching system should check
# # a subdirectory for this configurable's files.
# config_subdirectory = None
#
# @classmethod
# def validate_config(cls, config):
# """
# Validates a given config, returns the validated config dictionary
# if valid, raises a ValueError for any invalid values.
#
# Subclasses are expected to define this method.
# """
# raise NotImplementedError
#
# def apply_config(self, config):
# """
# Applies a given config to the subclass.
#
# Setting instance attributes, for example. Subclasses are expected
# to define this method.
#
# NOTE: It is *incredibly important* that this method be idempotent with
# regards to the instance.
# """
# raise NotImplementedError
#
# @classmethod
# def from_config(cls, name, config):
# """
# Returns a Configurable instance with the given name and config.
#
# By default this is a simple matter of calling the constructor, but
# subclasses that are also `Pluggable` instances override this in order
# to check that the plugin is installed correctly first.
# """
#
# cls.validate_config(config)
#
# instance = cls()
# if not instance.name:
# instance.name = config.get("name", name)
# instance.apply_config(config)
#
# return instance
. Output only the next line. | patcher.stop() |
Continue the code snippet: <|code_start|>
class DiscoveryTests(unittest.TestCase):
def test_validate_dependencies_requried(self):
self.assertRaises(
NotImplementedError,
Discovery.validate_dependencies
)
@patch.object(Discovery, "validate_dependencies", True)
@patch.object(Discovery, "get_installed_classes")
def test_from_config_with_unknown_name(self, get_installed_classes):
get_installed_classes.return_value = {"riak": Discovery}
self.assertRaises(
ValueError,
Discovery.from_config, "zookeeper", {}
)
@patch.object(Discovery, "validate_dependencies", True)
@patch.object(Discovery, "get_installed_classes")
def test_from_config(self, get_installed_classes):
MockDiscovery = Mock()
get_installed_classes.return_value = {"riak": MockDiscovery}
discovery = Discovery.from_config("riak", {"foo": "bar"})
self.assertEqual(discovery, MockDiscovery.return_value)
<|code_end|>
. Use current file imports:
import threading
import unittest2 as unittest
import unittest
from mock import patch, Mock
from lighthouse.discovery import Discovery
and context (classes, functions, or code) from other files:
# Path: lighthouse/discovery.py
# class Discovery(Pluggable):
# """
# Base class for discovery method plugins.
#
# Unlike the `Balancer` base class for load balancer plugins, this discovery
# method plugin has several methods that subclasses are expected to define.
#
# Subclasses are used for both the writer process *and* the reporter process
# so each subclass needs to be able to report on individual nodes as well
# as monitor and collect the status of all defined clusters.
#
# It is important that the various instances of lighthouse running on various
# machines agree with each other on the status of clusters so a distributed
# system with strong CP characteristics is recommended.
# """
#
# config_subdirectory = "discovery"
# entry_point = "lighthouse.discovery"
#
# def __init__(self):
# self.shutdown = threading.Event()
#
# def connect(self):
# """
# Subclasses should define this method to handle any sort of connection
# establishment needed.
# """
# raise NotImplementedError
#
# def disconnect(self):
# """
# This method is used to facilitate any shutting down operations needed
# by the subclass (e.g. closing connections and such).
# """
# raise NotImplementedError
#
# def start_watching(self, cluster, should_update):
# """
# Method called whenever a new cluster is defined and must be monitored
# for changes to nodes.
#
# Once a cluster is being successfully watched that cluster *must* be
# added to the `self.watched_clusters` set!
#
# Whenever a change is detected, the given `should_update` threading
# event should be set.
# """
# raise NotImplementedError
#
# def stop_watching(self, cluster):
# """
# This method should halt any of the monitoring started that would be
# started by a call to `start_watching()` with the same cluster.
#
# Once the cluster is no longer being watched that cluster *must* be
# removed from the `self.watched_clusters` set!
# """
# raise NotImplementedError
#
# def report_up(self, service, port):
# """
# This method is used to denote that the given service present on the
# current machine should be considered up and available.
# """
# raise NotImplementedError
#
# def report_down(self, service, port):
# """
# This method is used to denote that the given service present on the
# current machine should be considered down and unavailable.
# """
# raise NotImplementedError
#
# def stop(self):
# """
# Simple method that sets the `shutdown` event and calls the subclass's
# `wind_down()` method.
# """
# self.shutdown.set()
# self.disconnect()
. Output only the next line. | discovery.apply_config.assert_called_once_with({"foo": "bar"}) |
Given the following code snippet before the placeholder: <|code_start|>
class MetaFrontendStanzaTests(unittest.TestCase):
def test_custom_bind_address(self):
cluster1 = Mock(haproxy={})
cluster2 = Mock(haproxy={})
stanza = MetaFrontendStanza(
"api", 8000, [], [cluster1, cluster2],
bind_address="127.0.0.1"
)
self.assertIn("bind 127.0.0.1:8000", stanza.lines)
def test_member_cluster_acls(self):
cluster1 = Mock(haproxy={"acl": "path_beg /api/foo"})
cluster1.name = "foo_api"
cluster2 = Mock(haproxy={"acl": "path_beg /api/bar"})
cluster2.name = "bar_api"
stanza = MetaFrontendStanza("api", 8000, [], [cluster1, cluster2])
self.assertEqual(stanza.header, "frontend api")
self.assertIn("acl is_foo_api path_beg /api/foo", stanza.lines)
self.assertIn("acl is_bar_api path_beg /api/bar", stanza.lines)
self.assertIn("use_backend foo_api if is_foo_api", stanza.lines)
self.assertIn("use_backend bar_api if is_bar_api", stanza.lines)
<|code_end|>
, predict the next line using imports from the current file:
import unittest2 as unittest
import unittest
from mock import Mock
from lighthouse.haproxy.stanzas.meta import MetaFrontendStanza
and context including class names, function names, and sometimes code from other files:
# Path: lighthouse/haproxy/stanzas/meta.py
# class MetaFrontendStanza(Stanza):
# """
# Stanza subclass representing a shared "meta" cluster frontend.
#
# These frontends just contain ACL directives for routing requests to
# separate cluster backends. If a member cluster does not have an ACL rule
# defined in its haproxy config an error is logged and the member cluster
# is skipped.
# """
#
# def __init__(self, name, port, lines, members, bind_address=None):
# super(MetaFrontendStanza, self).__init__("frontend")
# self.header = "frontend %s" % name
#
# if not bind_address:
# bind_address = ""
#
# self.add_line("bind %s:%s" % (bind_address, port))
# self.add_lines(lines)
#
# for cluster in members:
# if "acl" not in cluster.haproxy:
# logger.error(
# "Cluster %s is part of meta-cluster %s," +
# " but no acl rule defined.",
# cluster.name, name
# )
# continue
# self.add_lines([
# "acl is_%s %s" % (cluster.name, cluster.haproxy["acl"]),
# "use_backend %s if is_%s" % (cluster.name, cluster.name)
# ])
. Output only the next line. | def test_member_cluster_with_no_acls(self): |
Predict the next line for this snippet: <|code_start|>
check.perform()
connection.request.assert_called_once_with("POST", "/foo")
def test_perform_with_https(self, client):
connection = client.HTTPSConnection.return_value
connection.getresponse.return_value.status = 200
check = HTTPCheck()
check.apply_config(
{
"uri": "/foo",
"https": True,
"rise": 1, "fall": 1
}
)
check.host = "localhost"
check.port = 9999
check.perform()
client.HTTPSConnection.assert_called_once_with("localhost", 9999)
def test_perform_response_is_200(self, client):
connection = client.HTTPConnection.return_value
connection.getresponse.return_value.status = 200
check = HTTPCheck()
check.apply_config({"uri": "/foo", "rise": 1, "fall": 1})
<|code_end|>
with the help of current file imports:
import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.checks.http import HTTPCheck
and context from other files:
# Path: lighthouse/checks/http.py
# class HTTPCheck(check.Check):
# """
# Simple check for HTTP services.
#
# Pings a configured uri on the host. The check passes if the response
# code is in the 2xx range.
# """
#
# name = "http"
#
# def __init__(self, *args, **kwargs):
# super(HTTPCheck, self).__init__(*args, **kwargs)
#
# self.uri = None
# self.use_https = None
# self.method = None
#
# @classmethod
# def validate_dependencies(cls):
# """
# This check uses stdlib modules so dependencies are always present.
# """
# return True
#
# @classmethod
# def validate_check_config(cls, config):
# """
# Validates the http check config. The "uri" key is required.
# """
# if "uri" not in config:
# raise ValueError("Missing uri.")
#
# def apply_check_config(self, config):
# """
# Takes a validated config dictionary and sets the `uri`, `use_https`
# and `method` attributes based on the config's contents.
# """
# self.uri = config["uri"]
# self.use_https = config.get("https", False)
# self.method = config.get("method", "GET")
#
# def perform(self):
# """
# Performs a simple HTTP request against the configured url and returns
# true if the response has a 2xx code.
#
# The url can be configured to use https via the "https" boolean flag
# in the config, as well as a custom HTTP method via the "method" key.
#
# The default is to not use https and the GET method.
# """
# if self.use_https:
# conn = client.HTTPSConnection(self.host, self.port)
# else:
# conn = client.HTTPConnection(self.host, self.port)
#
# conn.request(self.method, self.uri)
#
# response = conn.getresponse()
#
# conn.close()
#
# return bool(response.status >= 200 and response.status < 300)
, which may contain function names, class names, or code. Output only the next line. | check.host = "localhost" |
Continue the code snippet: <|code_start|>
def test_deserialize(self):
peer = Peer.deserialize(
json.dumps({
"name": "cluster03",
"ip": "196.0.0.8",
"port": 3333
})
)
self.assertEqual(peer.name, "cluster03")
self.assertEqual(peer.ip, "196.0.0.8")
self.assertEqual(peer.port, 3333)
def test_deserialize_without_port(self):
peer = Peer.deserialize(
json.dumps({
"name": "cluster03",
"ip": "196.0.0.8",
})
)
self.assertEqual(peer.name, "cluster03")
self.assertEqual(peer.ip, "196.0.0.8")
self.assertEqual(peer.port, 1024)
def test_deserialize_without_name(self):
self.assertRaises(
ValueError,
Peer.deserialize,
<|code_end|>
. Use current file imports:
import unittest2 as unittest
import unittest
import json
from mock import patch
from lighthouse.peer import Peer
and context (classes, functions, or code) from other files:
# Path: lighthouse/peer.py
# class Peer(object):
# """
# This class represents a host running a lighthouse reporter.
#
# When a reporter script tells its discovery method that a node is up, it
# includes information about itself via this class so that writer scripts
# reading that information can coordinate their peers.
#
# This is helpful for HAProxy as a way to generate "peers" config stanzas
# so instances of HAProxy in a given cluster can share stick-table data.
# """
#
# def __init__(self, name, ip, port=None):
# self.name = name
# self.ip = ip
# self.port = port or DEFAULT_PEER_PORT
#
# @classmethod
# def current(cls):
# """
# Helper method for getting the current peer of whichever host we're
# running on.
# """
# name = socket.getfqdn()
# ip = socket.gethostbyname(name)
#
# return cls(name, ip)
#
# def serialize(self):
# """
# Serializes the Peer data as a simple JSON map string.
# """
# return json.dumps({
# "name": self.name,
# "ip": self.ip,
# "port": self.port
# }, sort_keys=True)
#
# @classmethod
# def deserialize(cls, value):
# """
# Generates a Peer instance via a JSON string of the sort generated
# by `Peer.deserialize`.
#
# The `name` and `ip` keys are required to be present in the JSON map,
# if the `port` key is not present the default is used.
# """
# parsed = json.loads(value)
#
# if "name" not in parsed:
# raise ValueError("No peer name.")
# if "ip" not in parsed:
# raise ValueError("No peer IP.")
# if "port" not in parsed:
# parsed["port"] = DEFAULT_PEER_PORT
#
# return cls(parsed["name"], parsed["ip"], parsed["port"])
#
# def __hash__(self):
# """
# Hash method used to store peers in sets.
#
# Simply hashes the string <ip address>:<port>.
# """
# return hash(self.ip + ":" + str(self.port))
#
# def __eq__(self, other):
# """
# Peers are considered equal if their IP and port match.
# """
# return self.ip == other.ip and self.port == other.port
. Output only the next line. | json.dumps({ |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
class NodeTests(unittest.TestCase):
def test_constructor(self):
peer = Peer("cluster04", 8888)
node = Node("somehost", "10.0.1.12", 1234, peer=peer)
self.assertEqual(node.host, "somehost")
self.assertEqual(node.ip, "10.0.1.12")
self.assertEqual(node.port, 1234)
assert node.peer is peer
@patch.object(Peer, "current")
def test_constructor_defaults_to_current_peer(self, current_peer):
node = Node("somehost", "10.0.1.12", 1234)
<|code_end|>
with the help of current file imports:
import json
import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.node import Node
from lighthouse.peer import Peer
and context from other files:
# Path: lighthouse/node.py
# class Node(object):
# """
# The class representing a member node of a cluster.
#
# Consists of a `port`, a `host` and a `peer`, plus methods for serializing
# and deserializing themselves so that they can be transmitted back and
# forth via discovery methods.
# """
#
# def __init__(self, host, ip, port, peer=None, metadata=None):
# self.port = port
# self.host = host
# self.ip = ip
# self.peer = peer or Peer.current()
# self.metadata = metadata or {}
#
# @property
# def name(self):
# """
# Simple property for "naming" a node via the host and port.
# """
# return self.host + ":" + str(self.port)
#
# @classmethod
# def current(cls, service, port):
# """
# Returns a Node instance representing the current service node.
#
# Collects the host and IP information for the current machine and
# the port information from the given service.
# """
# host = socket.getfqdn()
# return cls(
# host=host,
# ip=socket.gethostbyname(host),
# port=port,
# metadata=service.metadata
# )
#
# def serialize(self):
# """
# Serializes the node data as a JSON map string.
# """
# return json.dumps({
# "port": self.port,
# "ip": self.ip,
# "host": self.host,
# "peer": self.peer.serialize() if self.peer else None,
# "metadata": json.dumps(self.metadata or {}, sort_keys=True),
# }, sort_keys=True)
#
# @classmethod
# def deserialize(cls, value):
# """
# Creates a new Node instance via a JSON map string.
#
# Note that `port` and `ip` and are required keys for the JSON map,
# `peer` and `host` are optional. If `peer` is not present, the new Node
# instance will use the current peer. If `host` is not present, the
# hostname of the given `ip` is looked up.
# """
# if getattr(value, "decode", None):
# value = value.decode()
#
# logger.debug("Deserializing node data: '%s'", value)
# parsed = json.loads(value)
#
# if "port" not in parsed:
# raise ValueError("No port defined for node.")
# if "ip" not in parsed:
# raise ValueError("No IP address defined for node.")
# if "host" not in parsed:
# host, aliases, ip_list = socket.gethostbyaddr(parsed["ip"])
# parsed["host"] = socket.get_fqdn(host)
# if "peer" in parsed:
# peer = Peer.deserialize(parsed["peer"])
# else:
# peer = None
#
# return cls(
# parsed["host"], parsed["ip"], parsed["port"],
# peer=peer, metadata=parsed.get("metadata")
# )
#
# def __eq__(self, other):
# """
# Nodes are considered equal if their IPs and ports both match.
# """
# return bool(self.ip == other.ip and self.port == other.port)
#
# Path: lighthouse/peer.py
# class Peer(object):
# """
# This class represents a host running a lighthouse reporter.
#
# When a reporter script tells its discovery method that a node is up, it
# includes information about itself via this class so that writer scripts
# reading that information can coordinate their peers.
#
# This is helpful for HAProxy as a way to generate "peers" config stanzas
# so instances of HAProxy in a given cluster can share stick-table data.
# """
#
# def __init__(self, name, ip, port=None):
# self.name = name
# self.ip = ip
# self.port = port or DEFAULT_PEER_PORT
#
# @classmethod
# def current(cls):
# """
# Helper method for getting the current peer of whichever host we're
# running on.
# """
# name = socket.getfqdn()
# ip = socket.gethostbyname(name)
#
# return cls(name, ip)
#
# def serialize(self):
# """
# Serializes the Peer data as a simple JSON map string.
# """
# return json.dumps({
# "name": self.name,
# "ip": self.ip,
# "port": self.port
# }, sort_keys=True)
#
# @classmethod
# def deserialize(cls, value):
# """
# Generates a Peer instance via a JSON string of the sort generated
# by `Peer.deserialize`.
#
# The `name` and `ip` keys are required to be present in the JSON map,
# if the `port` key is not present the default is used.
# """
# parsed = json.loads(value)
#
# if "name" not in parsed:
# raise ValueError("No peer name.")
# if "ip" not in parsed:
# raise ValueError("No peer IP.")
# if "port" not in parsed:
# parsed["port"] = DEFAULT_PEER_PORT
#
# return cls(parsed["name"], parsed["ip"], parsed["port"])
#
# def __hash__(self):
# """
# Hash method used to store peers in sets.
#
# Simply hashes the string <ip address>:<port>.
# """
# return hash(self.ip + ":" + str(self.port))
#
# def __eq__(self, other):
# """
# Peers are considered equal if their IP and port match.
# """
# return self.ip == other.ip and self.port == other.port
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(node.peer, current_peer.return_value) |
Next line prediction: <|code_start|>try:
except ImportError:
class LogConfigTests(unittest.TestCase):
def test_validate_config_is_noop(self):
self.assertEqual(
config.Logging.validate_config({}),
None
)
@patch("lighthouse.log.config.logging")
def test_apply_config_calls_dictconfig(self, mock_logging):
log = config.Logging()
log.apply_config({"foo": "bar"})
mock_logging.config.dictConfig.assert_called_once_with({"foo": "bar"})
@patch("lighthouse.log.config.logging")
<|code_end|>
. Use current file imports:
( import unittest2 as unittest
import unittest
from mock import patch
from lighthouse.log import config)
and context including class names, function names, or small code snippets from other files:
# Path: lighthouse/log/config.py
# class Logging(Configurable):
# def from_config(cls, name, config):
# def validate_config(cls, config):
# def apply_config(self, config):
. Output only the next line. | def test_from_config_returns_none_on_name_mismatch(self, mock_logging): |
Given snippet: <|code_start|>try:
except ImportError:
class PeersStanzaTests(unittest.TestCase):
def test_peers(self):
peer1 = Mock()
peer1.name = "server1"
peer1.ip = "192.168.0.13"
peer1.port = "88"
peer2 = Mock()
peer2.name = "server2"
peer2.ip = "192.168.0.22"
peer2.port = "88"
cluster = Mock()
cluster.name = "a_cluster"
cluster.nodes = [
Mock(peer=peer1),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest2 as unittest
import unittest
from mock import Mock
from lighthouse.haproxy.stanzas.peers import PeersStanza
and context:
# Path: lighthouse/haproxy/stanzas/peers.py
# class PeersStanza(Stanza):
# """
# Stanza subclass representing a "peers" stanza.
#
# This stanza lists "peer" haproxy instances in a cluster, so that each
# instance can coordinate and share stick-table information. Useful for
# tracking cluster-wide stats.
# """
#
# def __init__(self, cluster):
# super(PeersStanza, self).__init__("peers")
# self.header = "peers " + cluster.name
#
# self.add_lines([
# "peer %s %s:%s" % (peer.name, peer.ip, peer.port)
# for peer in set([node.peer for node in cluster.nodes if node.peer])
# ])
which might include code, classes, or functions. Output only the next line. | Mock(peer=None), # skipped |
Using the snippet: <|code_start|>
class InstituteAddressAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'hostel', 'room']
list_filter = ['hostel']
search_fields = ['user__username', 'user__first_name', 'room']
class ProgramAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'department', 'join_year', 'graduation_year', 'degree']
list_filter = ['department', 'join_year', 'graduation_year', 'degree', ]
search_fields = ['user__username', 'user__first_name', ]
class Media:
js = ['admin/js/list_filter_collapse.js', ]
class ContactNumberAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'number']
search_fields = ['user__username', 'user__first_name', 'number', ]
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail, SentMessage
and context (class names, function names, or code) available:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
. Output only the next line. | class SecondaryEmailAdmin(SimpleHistoryAdmin): |
Given the code snippet: <|code_start|>
class InstituteAddressAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'hostel', 'room']
list_filter = ['hostel']
search_fields = ['user__username', 'user__first_name', 'room']
class ProgramAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'department', 'join_year', 'graduation_year', 'degree']
list_filter = ['department', 'join_year', 'graduation_year', 'degree', ]
search_fields = ['user__username', 'user__first_name', ]
class Media:
js = ['admin/js/list_filter_collapse.js', ]
class ContactNumberAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'number']
search_fields = ['user__username', 'user__first_name', 'number', ]
class SecondaryEmailAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'email']
search_fields = ['user__username', 'user__first_name', 'email', ]
class SentMessageAdmin(SimpleHistoryAdmin):
list_display = ['id', 'message_id', 'sender', 'user', 'status', 'created', ]
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail, SentMessage
and context (functions, classes, or occasionally code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
. Output only the next line. | list_filter = ['status', 'sender', ] |
Next line prediction: <|code_start|>class InstituteAddressAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'hostel', 'room']
list_filter = ['hostel']
search_fields = ['user__username', 'user__first_name', 'room']
class ProgramAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'department', 'join_year', 'graduation_year', 'degree']
list_filter = ['department', 'join_year', 'graduation_year', 'degree', ]
search_fields = ['user__username', 'user__first_name', ]
class Media:
js = ['admin/js/list_filter_collapse.js', ]
class ContactNumberAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'number']
search_fields = ['user__username', 'user__first_name', 'number', ]
class SecondaryEmailAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'email']
search_fields = ['user__username', 'user__first_name', 'email', ]
class SentMessageAdmin(SimpleHistoryAdmin):
list_display = ['id', 'message_id', 'sender', 'user', 'status', 'created', ]
list_filter = ['status', 'sender', ]
search_fields = ['sender__id', 'sender__name', 'user__username', 'user__first_name', 'message_id', ]
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail, SentMessage)
and context including class names, function names, or small code snippets from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
. Output only the next line. | class Media: |
Predict the next line after this snippet: <|code_start|>
class InstituteAddressAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'hostel', 'room']
list_filter = ['hostel']
<|code_end|>
using the current file's imports:
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail, SentMessage
and any relevant context from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
. Output only the next line. | search_fields = ['user__username', 'user__first_name', 'room'] |
Given snippet: <|code_start|>
class InstituteAddressAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'hostel', 'room']
list_filter = ['hostel']
search_fields = ['user__username', 'user__first_name', 'room']
class ProgramAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'department', 'join_year', 'graduation_year', 'degree']
list_filter = ['department', 'join_year', 'graduation_year', 'degree', ]
search_fields = ['user__username', 'user__first_name', ]
class Media:
js = ['admin/js/list_filter_collapse.js', ]
class ContactNumberAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'number']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail, SentMessage
and context:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
which might include code, classes, or functions. Output only the next line. | search_fields = ['user__username', 'user__first_name', 'number', ] |
Using the snippet: <|code_start|>
class RegistrationForm(forms.ModelForm):
name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control'}))
authorization_grant_type = forms.ChoiceField(choices=get_choices_with_blank_dash(Application.GRANT_TYPES[:2]),
widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Application
fields = (
'name', 'description', 'logo', 'website', 'privacy_policy', 'client_id', 'client_secret', 'client_type',
'authorization_grant_type', 'redirect_uris')
widgets = {
'description': forms.Textarea(
attrs={'class': 'form-control', 'rows': 3, }
),
'logo': forms.ClearableFileInput(
attrs={'class': 'form-control', 'accept': 'image/*', }
),
'website': forms.URLInput(
attrs={'class': 'form-control', }
),
'privacy_policy': forms.URLInput(
attrs={'class': 'form-control', }
),
'client_id': forms.TextInput(
attrs={'class': 'form-control', }
<|code_end|>
, determine the next line of code. You have imports:
from django import forms
from core.utils import get_choices_with_blank_dash
from .models import Application
and context (class names, function names, or code) available:
# Path: core/utils.py
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
. Output only the next line. | ), |
Given the following code snippet before the placeholder: <|code_start|>
class RegistrationForm(forms.ModelForm):
name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control'}))
authorization_grant_type = forms.ChoiceField(choices=get_choices_with_blank_dash(Application.GRANT_TYPES[:2]),
widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Application
fields = (
'name', 'description', 'logo', 'website', 'privacy_policy', 'client_id', 'client_secret', 'client_type',
'authorization_grant_type', 'redirect_uris')
widgets = {
'description': forms.Textarea(
attrs={'class': 'form-control', 'rows': 3, }
),
'logo': forms.ClearableFileInput(
attrs={'class': 'form-control', 'accept': 'image/*', }
),
'website': forms.URLInput(
attrs={'class': 'form-control', }
),
'privacy_policy': forms.URLInput(
attrs={'class': 'form-control', }
),
'client_id': forms.TextInput(
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from core.utils import get_choices_with_blank_dash
from .models import Application
and context including class names, function names, and sometimes code from other files:
# Path: core/utils.py
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
. Output only the next line. | attrs={'class': 'form-control', } |
Using the snippet: <|code_start|>
try:
except ImportError:
class LoginViewTestCase(TestCase):
login_url = reverse('account:login')
login_redirect_url = reverse(settings.LOGIN_REDIRECT_URL)
next_ = reverse('oauth2_provider:list')
template_name = 'account/login.html'
def setUp(self):
self.test_user = User.objects.create_user(username='test_user', password='test123')
self.userprofile = UserProfile.objects.create(user=self.test_user)
def tearDown(self):
self.client.logout()
self.test_user.delete()
def test_userprofile_unicode(self):
self.assertEqual(str(self.userprofile), self.test_user.username)
def test_application_logo_upload(self):
with mock.patch('uuid.uuid4') as uuid_mock:
uuid_mock.return_value = '1234567890'
filename = user_profile_picture(self.test_user, 'hola.png')
self.assertNotEqual(filename, 'app_logo/1234567890.png')
<|code_end|>
, determine the next line of code. You have imports:
import django.utils.six as six
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase, mock
from .models import UserProfile, user_profile_picture
from urllib.parse import quote_plus
from urllib import quote_plus
and context (class names, function names, or code) available:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# def user_profile_picture(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("profile_picture", uuid4().hex + "." + ext)
. Output only the next line. | def test_application_logo_default_ext(self): |
Given the code snippet: <|code_start|>
try:
except ImportError:
class LoginViewTestCase(TestCase):
login_url = reverse('account:login')
login_redirect_url = reverse(settings.LOGIN_REDIRECT_URL)
next_ = reverse('oauth2_provider:list')
template_name = 'account/login.html'
def setUp(self):
self.test_user = User.objects.create_user(username='test_user', password='test123')
self.userprofile = UserProfile.objects.create(user=self.test_user)
def tearDown(self):
self.client.logout()
self.test_user.delete()
def test_userprofile_unicode(self):
self.assertEqual(str(self.userprofile), self.test_user.username)
<|code_end|>
, generate the next line using the imports in this file:
import django.utils.six as six
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase, mock
from .models import UserProfile, user_profile_picture
from urllib.parse import quote_plus
from urllib import quote_plus
and context (functions, classes, or occasionally code) from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# def user_profile_picture(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("profile_picture", uuid4().hex + "." + ext)
. Output only the next line. | def test_application_logo_upload(self): |
Given the code snippet: <|code_start|>
router = DefaultRouter()
router.register('resources', ResourcesViewset, base_name='resources')
urlpatterns = [
url('^api/', include(router.urls, namespace='api')),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import include, url
from rest_framework.routers import DefaultRouter
from .views import ResourcesViewset
and context (functions, classes, or occasionally code) from other files:
# Path: resources/views.py
# class ResourcesViewset(viewsets.GenericViewSet):
#
# pagination_class = DefaultLimitOffsetPagination
# permission_classes = [TokenHasScope]
# required_scopes = ['priv_rooms']
#
# @list_route(methods=['GET'], serializer_class=UserRoomSerializer)
# def rooms(self, request):
# queryset = InstituteAddress.objects.all().order_by('id').prefetch_related('user__userprofile')
# queryset = self.paginate_queryset(queryset)
# serialized_queryset = self.serializer_class(queryset, many=True)
# return self.get_paginated_response(serialized_queryset.data)
. Output only the next line. | ] |
Continue the code snippet: <|code_start|> redirect_uris='http://localhost:7000/',
logo='app_logo/1235.png',
user=self.u1,
)
self.app_admin = ApplicationAdmin(Application, AdminSite())
def tearDown(self):
self.u1.delete()
self.application1.delete()
def test_get_user_count_zero_user(self):
self.assertEqual(0, self.app_admin.total_users(self.application1))
def test_get_user_count_one_user(self):
access_token1 = AccessToken.objects.create(user=self.u1, application=self.application1, token='123',
expires=now())
access_token2 = AccessToken.objects.create(user=self.u1, application=self.application1, token='123456',
expires=now())
self.assertEqual(self.app_admin.total_users(self.application1), 1)
access_token1.delete()
access_token2.delete()
def test_get_use_count_multiple_user(self):
u2 = User.objects.create(username='u2', password='p2')
access_token1 = AccessToken.objects.create(user=self.u1, application=self.application1, token='123',
expires=now())
access_token2 = AccessToken.objects.create(user=u2, application=self.application1, token='123456',
expires=now())
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase, mock
from django.utils.timezone import now
from oauth2_provider.models import AccessToken
from account.models import UserProfile
from .admin import ApplicationAdmin
from .models import Application, application_logo
and context (classes, functions, or code) from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: application/admin.py
# class ApplicationAdmin(SimpleHistoryAdmin):
# list_display = ['id', 'name', 'user', 'total_users', 'created_on', 'modified_on', 'is_anonymous']
# list_filter = ['is_anonymous', ]
# search_fields = ['name', 'user__username', 'user__first_name', ]
#
# def total_users(self, obj):
# return obj.get_user_count()
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# def application_logo(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("app_logo", uuid4().hex + "." + ext)
. Output only the next line. | self.assertEqual(self.app_admin.total_users(self.application1), 2) |
Continue the code snippet: <|code_start|> )
self.assertNotEqual(str(application3), '')
def test_validation_error_on_clean(self):
application4 = Application(
name='resource_owner_password_based_app',
description='testapp',
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_PASSWORD,
user=self.u1,
redirect_uris='http://localhost:4000'
)
self.assertRaises(ValidationError, application4.clean)
def test_application_logo_upload(self):
with mock.patch('uuid.uuid4') as uuid_mock:
uuid_mock.return_value = '1234567890'
filename = application_logo(self.application1, 'hola.png')
self.assertNotEqual(filename, 'app_logo/1234567890.png')
def test_application_logo_default_ext(self):
with mock.patch('uuid.uuid4') as uuid_mock:
uuid_mock.return_value = '987654321'
filename = application_logo(self.application1, 'hola')
self.assertNotEqual(filename, 'app_logo/987654321.png')
class ApplicationAdminTestCase(TestCase):
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase, mock
from django.utils.timezone import now
from oauth2_provider.models import AccessToken
from account.models import UserProfile
from .admin import ApplicationAdmin
from .models import Application, application_logo
and context (classes, functions, or code) from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: application/admin.py
# class ApplicationAdmin(SimpleHistoryAdmin):
# list_display = ['id', 'name', 'user', 'total_users', 'created_on', 'modified_on', 'is_anonymous']
# list_filter = ['is_anonymous', ]
# search_fields = ['name', 'user__username', 'user__first_name', ]
#
# def total_users(self, obj):
# return obj.get_user_count()
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# def application_logo(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("app_logo", uuid4().hex + "." + ext)
. Output only the next line. | def setUp(self): |
Based on the snippet: <|code_start|> client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='http://localhost:5000/',
user=self.u1,
)
self.assertNotEqual(str(application3), '')
def test_validation_error_on_clean(self):
application4 = Application(
name='resource_owner_password_based_app',
description='testapp',
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_PASSWORD,
user=self.u1,
redirect_uris='http://localhost:4000'
)
self.assertRaises(ValidationError, application4.clean)
def test_application_logo_upload(self):
with mock.patch('uuid.uuid4') as uuid_mock:
uuid_mock.return_value = '1234567890'
filename = application_logo(self.application1, 'hola.png')
self.assertNotEqual(filename, 'app_logo/1234567890.png')
def test_application_logo_default_ext(self):
with mock.patch('uuid.uuid4') as uuid_mock:
uuid_mock.return_value = '987654321'
filename = application_logo(self.application1, 'hola')
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase, mock
from django.utils.timezone import now
from oauth2_provider.models import AccessToken
from account.models import UserProfile
from .admin import ApplicationAdmin
from .models import Application, application_logo
and context (classes, functions, sometimes code) from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: application/admin.py
# class ApplicationAdmin(SimpleHistoryAdmin):
# list_display = ['id', 'name', 'user', 'total_users', 'created_on', 'modified_on', 'is_anonymous']
# list_filter = ['is_anonymous', ]
# search_fields = ['name', 'user__username', 'user__first_name', ]
#
# def total_users(self, obj):
# return obj.get_user_count()
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# def application_logo(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("app_logo", uuid4().hex + "." + ext)
. Output only the next line. | self.assertNotEqual(filename, 'app_logo/987654321.png') |
Next line prediction: <|code_start|>
class ApplicationModelTestCase(TestCase):
def setUp(self):
self.u1 = User.objects.create(username='username', password='password')
UserProfile.objects.create(user=self.u1)
self.application1 = Application.objects.create(
name='application1',
description='testapp',
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='http://localhost:7000/',
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase, mock
from django.utils.timezone import now
from oauth2_provider.models import AccessToken
from account.models import UserProfile
from .admin import ApplicationAdmin
from .models import Application, application_logo)
and context including class names, function names, or small code snippets from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: application/admin.py
# class ApplicationAdmin(SimpleHistoryAdmin):
# list_display = ['id', 'name', 'user', 'total_users', 'created_on', 'modified_on', 'is_anonymous']
# list_filter = ['is_anonymous', ]
# search_fields = ['name', 'user__username', 'user__first_name', ]
#
# def total_users(self, obj):
# return obj.get_user_count()
#
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# def application_logo(instance, filename): # pylint: disable=unused-argument
# filename = filename.split('.')
# if len(filename) > 1:
# ext = filename[-1]
# else:
# ext = "png"
# return os.path.join("app_logo", uuid4().hex + "." + ext)
. Output only the next line. | logo='app_logo/1235.png', |
Here is a snippet: <|code_start|>
class ResourcesViewset(viewsets.GenericViewSet):
pagination_class = DefaultLimitOffsetPagination
permission_classes = [TokenHasScope]
required_scopes = ['priv_rooms']
@list_route(methods=['GET'], serializer_class=UserRoomSerializer)
def rooms(self, request):
queryset = InstituteAddress.objects.all().order_by('id').prefetch_related('user__userprofile')
queryset = self.paginate_queryset(queryset)
serialized_queryset = self.serializer_class(queryset, many=True)
<|code_end|>
. Write the next line using the current file imports:
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from core.pagination import DefaultLimitOffsetPagination
from user_resource.models import InstituteAddress
from .serializers import UserRoomSerializer
and context from other files:
# Path: core/pagination.py
# class DefaultLimitOffsetPagination(pagination.LimitOffsetPagination):
#
# default_limit = 20
# max_limit = 500
#
# Path: user_resource/models.py
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# Path: resources/serializers.py
# class UserRoomSerializer(serializers.ModelSerializer):
# roll_number = serializers.CharField(source='user.userprofile.roll_number')
#
# class Meta:
# model = InstituteAddress
# exclude = ['id', 'user']
, which may include functions, classes, or code. Output only the next line. | return self.get_paginated_response(serialized_queryset.data) |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^login/$', LoginView.as_view(), name="login"),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from .views import LoginView, LogoutView
and context (class names, function names, or code) available:
# Path: account/views.py
# class LoginView(SensitivePostParametersMixin, View):
# """
# GET: If user is already logged in then redirect to 'next' parameter in query_params
# Else render the login form
# POST:
# Validate form, login user
# """
# form_class = LoginForm
# template_name = 'account/login.html'
#
# def get(self, request):
# next_ = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
# if next_ == '':
# next_ = settings.LOGIN_REDIRECT_URL
# if request.user.is_authenticated():
# return redirect(next_)
# return render(request, self.template_name, {'form': self.form_class})
#
# def post(self, request):
# form = self.form_class(request.POST)
# next_ = request.POST.get('next', settings.LOGIN_REDIRECT_URL)
# if next_ == '':
# next_ = settings.LOGIN_REDIRECT_URL
# if form.is_valid():
# username = form.cleaned_data['username']
# password = form.cleaned_data['password']
# remember = form.cleaned_data['remember']
#
# user = authenticate(username=username, password=password)
# if user is not None:
# if remember:
# # Yearlong Session
# request.session.set_expiry(24 * 365 * 3600)
# else:
# request.session.set_expiry(0)
# login(request, user)
# return redirect(next_)
# else:
# form.add_error(None, "Unable to authorize user. Try again!")
# return render(request, self.template_name, {'form': form})
#
# class LogoutView(View):
# def get(self, request):
# logout(request)
# next_ = request.GET.get('next')
# if next_ is None:
# return redirect('index')
# next_ = quote_plus(next_)
# login_url = reverse('account:login')
# redirect_to = '%s?next=%s' % (login_url, next_) if next_ else login_url
# return HttpResponseRedirect(redirect_to)
. Output only the next line. | ] |
Predict the next line for this snippet: <|code_start|>
class CustomOAuth2Validator(OAuth2Validator):
def get_default_scopes(self, client_id, request, *args, **kwargs):
application = get_object_or_404(get_oauth2_application_model(), client_id=client_id)
return get_default_scopes(application)
<|code_end|>
with the help of current file imports:
from datetime import timedelta
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.utils import timezone
from oauth2_provider.models import get_application_model as get_oauth2_application_model
from oauth2_provider.models import AccessToken, RefreshToken
from oauth2_provider.oauth2_validators import OAuth2Validator
from oauth2_provider.settings import oauth2_settings
from core.utils import get_default_scopes
and context from other files:
# Path: core/utils.py
# def get_default_scopes(application):
# if application.is_anonymous:
# return application.required_scopes.split()
# return settings.OAUTH2_DEFAULT_SCOPES
, which may contain function names, class names, or code. Output only the next line. | def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): |
Based on the snippet: <|code_start|>
class ProgramSerializer(serializers.ModelSerializer):
department_name = serializers.SerializerMethodField()
degree_name = serializers.SerializerMethodField()
def get_department_name(self, obj):
return obj.get_department_display()
def get_degree_name(self, obj):
return obj.get_degree_display()
class Meta:
model = Program
exclude = ['user']
class SecondaryEmailSerializer(serializers.ModelSerializer):
class Meta:
model = SecondaryEmail
exclude = ['user']
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .oauth import DEFAULT_FIELDS, USER_FIELDS
and context (classes, functions, sometimes code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
. Output only the next line. | class ContactNumberSerializer(serializers.ModelSerializer): |
Given the code snippet: <|code_start|>class ContactNumberSerializer(serializers.ModelSerializer):
class Meta:
model = ContactNumber
exclude = ['user']
class InstituteAddressSerializer(serializers.ModelSerializer):
hostel_name = serializers.SerializerMethodField()
def get_hostel_name(self, obj):
return obj.get_hostel_display()
class Meta:
model = InstituteAddress
exclude = ['user']
class UserSerializer(serializers.ModelSerializer):
program = ProgramSerializer()
secondary_emails = SecondaryEmailSerializer(many=True)
contacts = ContactNumberSerializer(many=True)
insti_address = InstituteAddressSerializer()
mobile = serializers.CharField(source='userprofile.mobile')
roll_number = serializers.CharField(source='userprofile.roll_number')
profile_picture = serializers.ImageField(source='userprofile.profile_picture')
sex = serializers.CharField(source='userprofile.sex')
type = serializers.CharField(source='userprofile.type')
is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
def __init__(self, *args, **kwargs):
<|code_end|>
, generate the next line using the imports in this file:
import copy
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .oauth import DEFAULT_FIELDS, USER_FIELDS
and context (functions, classes, or occasionally code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
. Output only the next line. | super(UserSerializer, self).__init__(*args, **kwargs) |
Continue the code snippet: <|code_start|> return obj.get_hostel_display()
class Meta:
model = InstituteAddress
exclude = ['user']
class UserSerializer(serializers.ModelSerializer):
program = ProgramSerializer()
secondary_emails = SecondaryEmailSerializer(many=True)
contacts = ContactNumberSerializer(many=True)
insti_address = InstituteAddressSerializer()
mobile = serializers.CharField(source='userprofile.mobile')
roll_number = serializers.CharField(source='userprofile.roll_number')
profile_picture = serializers.ImageField(source='userprofile.profile_picture')
sex = serializers.CharField(source='userprofile.sex')
type = serializers.CharField(source='userprofile.type')
is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
fields = self.context.get('fields')
if not isinstance(fields, list) and not isinstance(fields, set):
fields = []
fields.extend(DEFAULT_FIELDS)
if fields is not None:
allowed = set(fields)
existing = set(self.fields.keys())
fields_to_remove = existing - allowed
<|code_end|>
. Use current file imports:
import copy
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .oauth import DEFAULT_FIELDS, USER_FIELDS
and context (classes, functions, or code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
. Output only the next line. | for field in fields_to_remove: |
Predict the next line for this snippet: <|code_start|>
class SecondaryEmailSerializer(serializers.ModelSerializer):
class Meta:
model = SecondaryEmail
exclude = ['user']
class ContactNumberSerializer(serializers.ModelSerializer):
class Meta:
model = ContactNumber
exclude = ['user']
class InstituteAddressSerializer(serializers.ModelSerializer):
hostel_name = serializers.SerializerMethodField()
def get_hostel_name(self, obj):
return obj.get_hostel_display()
class Meta:
model = InstituteAddress
exclude = ['user']
class UserSerializer(serializers.ModelSerializer):
program = ProgramSerializer()
secondary_emails = SecondaryEmailSerializer(many=True)
contacts = ContactNumberSerializer(many=True)
insti_address = InstituteAddressSerializer()
mobile = serializers.CharField(source='userprofile.mobile')
<|code_end|>
with the help of current file imports:
import copy
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .oauth import DEFAULT_FIELDS, USER_FIELDS
and context from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
, which may contain function names, class names, or code. Output only the next line. | roll_number = serializers.CharField(source='userprofile.roll_number') |
Given the code snippet: <|code_start|> secondary_emails = SecondaryEmailSerializer(many=True)
contacts = ContactNumberSerializer(many=True)
insti_address = InstituteAddressSerializer()
mobile = serializers.CharField(source='userprofile.mobile')
roll_number = serializers.CharField(source='userprofile.roll_number')
profile_picture = serializers.ImageField(source='userprofile.profile_picture')
sex = serializers.CharField(source='userprofile.sex')
type = serializers.CharField(source='userprofile.type')
is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
fields = self.context.get('fields')
if not isinstance(fields, list) and not isinstance(fields, set):
fields = []
fields.extend(DEFAULT_FIELDS)
if fields is not None:
allowed = set(fields)
existing = set(self.fields.keys())
fields_to_remove = existing - allowed
for field in fields_to_remove:
self.fields.pop(field)
class Meta:
model = User
fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
<|code_end|>
, generate the next line using the imports in this file:
import copy
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .oauth import DEFAULT_FIELDS, USER_FIELDS
and context (functions, classes, or occasionally code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
. Output only the next line. | subject = serializers.CharField() |
Given the code snippet: <|code_start|> if self.room:
return "%s-%s" % (self.hostel, self.room)
return self.hostel
return ''
@python_2_unicode_compatible
class Program(models.Model):
user = models.OneToOneField(User, related_name='program')
department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
_history_ = HistoricalRecords()
def __str__(self):
return "%s, %s" % (self.get_degree_display(), self.get_department_display())
@python_2_unicode_compatible
class ContactNumber(models.Model):
user = models.ForeignKey(User, related_name='contacts')
number = models.CharField(max_length=16)
_history_ = HistoricalRecords()
def __str__(self):
return self.number
@python_2_unicode_compatible
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from simple_history.models import HistoricalRecords
from application.models import Application
from core.utils import DEGREES, HOSTELS, HOSTELS_WITH_WINGS, ROOM_VALIDATION_REGEX, SORTED_DISCIPLINES
and context (functions, classes, or occasionally code) from other files:
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# HOSTELS_WITH_WINGS = ['10', '11', '12', '13', '14', '15', '16']
#
# ROOM_VALIDATION_REGEX = re.compile(r'[A-Z]-\d+')
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
. Output only the next line. | class SecondaryEmail(models.Model): |
Here is a snippet: <|code_start|>
def __str__(self):
return "%s, %s" % (self.get_degree_display(), self.get_department_display())
@python_2_unicode_compatible
class ContactNumber(models.Model):
user = models.ForeignKey(User, related_name='contacts')
number = models.CharField(max_length=16)
_history_ = HistoricalRecords()
def __str__(self):
return self.number
@python_2_unicode_compatible
class SecondaryEmail(models.Model):
user = models.ForeignKey(User, related_name='secondary_emails')
email = models.EmailField()
_history_ = HistoricalRecords()
def __str__(self):
return self.email
@python_2_unicode_compatible
class SentMessage(models.Model):
message_id = models.CharField(max_length=256)
sender = models.ForeignKey(Application)
user = models.ForeignKey(User)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from simple_history.models import HistoricalRecords
from application.models import Application
from core.utils import DEGREES, HOSTELS, HOSTELS_WITH_WINGS, ROOM_VALIDATION_REGEX, SORTED_DISCIPLINES
and context from other files:
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# HOSTELS_WITH_WINGS = ['10', '11', '12', '13', '14', '15', '16']
#
# ROOM_VALIDATION_REGEX = re.compile(r'[A-Z]-\d+')
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
, which may include functions, classes, or code. Output only the next line. | status = models.BooleanField(default=True) |
Here is a snippet: <|code_start|>
def validate_join_year(value):
current_year = timezone.now().year
if value < 1958:
raise ValidationError(_('%d! Are you kidding me? IITB was not even there back then!' % value))
if value > current_year:
raise ValidationError(_('Welcome kiddo, welcome to IITB in future!'))
def validate_graduation_year(value):
current_year = timezone.now().year
if value < 1958:
raise ValidationError(_('%d! Are you kidding me? IITB was not even there back then!' % value))
if value > (current_year + 6):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from simple_history.models import HistoricalRecords
from application.models import Application
from core.utils import DEGREES, HOSTELS, HOSTELS_WITH_WINGS, ROOM_VALIDATION_REGEX, SORTED_DISCIPLINES
and context from other files:
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# HOSTELS_WITH_WINGS = ['10', '11', '12', '13', '14', '15', '16']
#
# ROOM_VALIDATION_REGEX = re.compile(r'[A-Z]-\d+')
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
, which may include functions, classes, or code. Output only the next line. | raise ValidationError(_('Please enter your expected graduation year')) |
Given the code snippet: <|code_start|> if value > current_year:
raise ValidationError(_('Welcome kiddo, welcome to IITB in future!'))
def validate_graduation_year(value):
current_year = timezone.now().year
if value < 1958:
raise ValidationError(_('%d! Are you kidding me? IITB was not even there back then!' % value))
if value > (current_year + 6):
raise ValidationError(_('Please enter your expected graduation year'))
@python_2_unicode_compatible
class InstituteAddress(models.Model):
user = models.OneToOneField(User, related_name='insti_address')
room = models.CharField(max_length=8, null=True, blank=True)
hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
_history_ = HistoricalRecords()
def clean(self):
if self.room:
if self.hostel in HOSTELS_WITH_WINGS:
if not ROOM_VALIDATION_REGEX.match(self.room):
raise ValidationError(_('Room number must have wing name like A-123'))
def __str__(self):
if self.hostel:
if self.room:
return "%s-%s" % (self.hostel, self.room)
return self.hostel
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from simple_history.models import HistoricalRecords
from application.models import Application
from core.utils import DEGREES, HOSTELS, HOSTELS_WITH_WINGS, ROOM_VALIDATION_REGEX, SORTED_DISCIPLINES
and context (functions, classes, or occasionally code) from other files:
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# HOSTELS_WITH_WINGS = ['10', '11', '12', '13', '14', '15', '16']
#
# ROOM_VALIDATION_REGEX = re.compile(r'[A-Z]-\d+')
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
. Output only the next line. | return '' |
Predict the next line after this snippet: <|code_start|> graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
_history_ = HistoricalRecords()
def __str__(self):
return "%s, %s" % (self.get_degree_display(), self.get_department_display())
@python_2_unicode_compatible
class ContactNumber(models.Model):
user = models.ForeignKey(User, related_name='contacts')
number = models.CharField(max_length=16)
_history_ = HistoricalRecords()
def __str__(self):
return self.number
@python_2_unicode_compatible
class SecondaryEmail(models.Model):
user = models.ForeignKey(User, related_name='secondary_emails')
email = models.EmailField()
_history_ = HistoricalRecords()
def __str__(self):
return self.email
@python_2_unicode_compatible
class SentMessage(models.Model):
<|code_end|>
using the current file's imports:
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from simple_history.models import HistoricalRecords
from application.models import Application
from core.utils import DEGREES, HOSTELS, HOSTELS_WITH_WINGS, ROOM_VALIDATION_REGEX, SORTED_DISCIPLINES
and any relevant context from other files:
# Path: application/models.py
# class Application(AbstractApplication):
# """
# Extended oauth2_provider.models.AbstractApplication to include application description and logo
# """
# description = models.TextField()
# logo = models.ImageField(upload_to=application_logo, blank=True, null=True)
# is_anonymous = models.BooleanField(default=False,
# help_text='Valid for complete anonymous apps. Requires admin permission')
# required_scopes = models.CharField(max_length=256,
# help_text='Default non-tracking permissions. '
# 'Valid only if application is anonymous', null=True, blank=True)
# private_scopes = models.CharField(max_length=256, help_text='Private API scopes', null=True, blank=True)
# website = models.URLField(null=True, blank=True)
# privacy_policy = models.URLField(null=True, blank=True, help_text='Link of privacy policy of application')
# created_on = models.DateTimeField(auto_now_add=True)
# modified_on = models.DateTimeField(auto_now=True)
# _history_ = HistoricalRecords()
#
# def get_logo_url(self):
# try:
# url = self.logo.url
# url = urljoin(settings.MEDIA_URL, url)
# except ValueError:
# url = None
# return url
#
# def get_absolute_url(self):
# return reverse('oauth2_provider:detail', args=[str(self.id)])
#
# def clean(self):
# super(Application, self).clean()
# if self.authorization_grant_type == AbstractApplication.GRANT_PASSWORD:
# error = _("Resource owner password based grants are not allowed for now")
# raise ValidationError(error)
#
# def get_user_count(self):
# return AccessToken.objects.all().filter(application=self).values_list('user', flat=True).distinct().count()
#
# def __str__(self):
# if self.name:
# return self.name
# else:
# return self.client_id
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# HOSTELS_WITH_WINGS = ['10', '11', '12', '13', '14', '15', '16']
#
# ROOM_VALIDATION_REGEX = re.compile(r'[A-Z]-\d+')
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
. Output only the next line. | message_id = models.CharField(max_length=256) |
Using the snippet: <|code_start|>
class DocView(TemplateView):
template_name = 'sso/5-minutes-doc.html'
tabs = [TabNav(tab[0], tab[1], tab[2], 'doc', tab[0] == 'basic') for tab in tabs_list]
def get_context_data(self, **kwargs):
context = super(DocView, self).get_context_data(**kwargs)
context['login_js_url'] = static('widget/js/login.min.js')
context['Message_ID'] = make_msgid()
context['SORTED_DISCIPLINES'] = SORTED_DISCIPLINES
context['DEGREES'] = DEGREES
context['HOSTELS'] = HOSTELS
context['SEXES'] = SEXES
context['USER_TYPES'] = UserProfile.objects.values_list('type').distinct()
# Mark all tabs as inactive
for tab_ in self.tabs:
tab_.is_active = False
tab = context.get('tab', '')
for tab_ in self.tabs:
if tab == tab_.tab_name:
tab = tab_
break
else:
tab = self.tabs[0]
tab.is_active = True
context['tabs'] = self.tabs
context['active_tab'] = tab
<|code_end|>
, determine the next line of code. You have imports:
from django.core.mail.message import make_msgid
from django.templatetags.static import static
from django.views.generic import TemplateView
from account.models import UserProfile
from core.utils import DEGREES, HOSTELS, SEXES, SORTED_DISCIPLINES, TabNav
and context (class names, function names, or code) available:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
#
# class TabNav(object):
# def __init__(self, tab, name=None, template_name=None, base_url=None, is_default=False):
# if not tab or not base_url:
# raise ValueError('tab and base_url cannot be None')
# self.tab = tab
# if not name:
# self.name = tab.title()
# else:
# self.name = name
# if not template_name:
# self.template_name = '%s.html' % tab
# else:
# self.template_name = template_name
# self.is_default = is_default
# self.base_url = base_url
# self.is_active = False
#
# @property
# def url(self):
# if not self.is_default:
# return reverse(self.base_url, args=[self.tab])
# return reverse(self.base_url)
#
# @property
# def tab_name(self):
# if not self.is_default:
# return self.tab
# return ''
. Output only the next line. | return context |
Using the snippet: <|code_start|>
class IndexView(TemplateView):
template_name = 'sso/index.html'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if request.user.is_authenticated():
context['base_template'] = 'sso/logged_in.html'
else:
context['base_template'] = 'sso/root.html'
return self.render_to_response(context)
tabs_list = [
('basic', 'Basic', 'basic.html'),
('api', 'APIs', 'api.html'),
('widgets', 'Widgets', 'widget.html'),
('best-practices', 'Best Practices', 'practices.html'),
<|code_end|>
, determine the next line of code. You have imports:
from django.core.mail.message import make_msgid
from django.templatetags.static import static
from django.views.generic import TemplateView
from account.models import UserProfile
from core.utils import DEGREES, HOSTELS, SEXES, SORTED_DISCIPLINES, TabNav
and context (class names, function names, or code) available:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
#
# class TabNav(object):
# def __init__(self, tab, name=None, template_name=None, base_url=None, is_default=False):
# if not tab or not base_url:
# raise ValueError('tab and base_url cannot be None')
# self.tab = tab
# if not name:
# self.name = tab.title()
# else:
# self.name = name
# if not template_name:
# self.template_name = '%s.html' % tab
# else:
# self.template_name = template_name
# self.is_default = is_default
# self.base_url = base_url
# self.is_active = False
#
# @property
# def url(self):
# if not self.is_default:
# return reverse(self.base_url, args=[self.tab])
# return reverse(self.base_url)
#
# @property
# def tab_name(self):
# if not self.is_default:
# return self.tab
# return ''
. Output only the next line. | ('libraries', 'Libraries', 'library.html'), |
Next line prediction: <|code_start|>
class IndexView(TemplateView):
template_name = 'sso/index.html'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if request.user.is_authenticated():
context['base_template'] = 'sso/logged_in.html'
else:
context['base_template'] = 'sso/root.html'
return self.render_to_response(context)
tabs_list = [
('basic', 'Basic', 'basic.html'),
('api', 'APIs', 'api.html'),
('widgets', 'Widgets', 'widget.html'),
('best-practices', 'Best Practices', 'practices.html'),
('libraries', 'Libraries', 'library.html'),
]
<|code_end|>
. Use current file imports:
(from django.core.mail.message import make_msgid
from django.templatetags.static import static
from django.views.generic import TemplateView
from account.models import UserProfile
from core.utils import DEGREES, HOSTELS, SEXES, SORTED_DISCIPLINES, TabNav)
and context including class names, function names, or small code snippets from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
#
# class TabNav(object):
# def __init__(self, tab, name=None, template_name=None, base_url=None, is_default=False):
# if not tab or not base_url:
# raise ValueError('tab and base_url cannot be None')
# self.tab = tab
# if not name:
# self.name = tab.title()
# else:
# self.name = name
# if not template_name:
# self.template_name = '%s.html' % tab
# else:
# self.template_name = template_name
# self.is_default = is_default
# self.base_url = base_url
# self.is_active = False
#
# @property
# def url(self):
# if not self.is_default:
# return reverse(self.base_url, args=[self.tab])
# return reverse(self.base_url)
#
# @property
# def tab_name(self):
# if not self.is_default:
# return self.tab
# return ''
. Output only the next line. | class DocView(TemplateView): |
Based on the snippet: <|code_start|>
class IndexView(TemplateView):
template_name = 'sso/index.html'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if request.user.is_authenticated():
context['base_template'] = 'sso/logged_in.html'
else:
context['base_template'] = 'sso/root.html'
return self.render_to_response(context)
tabs_list = [
('basic', 'Basic', 'basic.html'),
('api', 'APIs', 'api.html'),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.mail.message import make_msgid
from django.templatetags.static import static
from django.views.generic import TemplateView
from account.models import UserProfile
from core.utils import DEGREES, HOSTELS, SEXES, SORTED_DISCIPLINES, TabNav
and context (classes, functions, sometimes code) from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
#
# class TabNav(object):
# def __init__(self, tab, name=None, template_name=None, base_url=None, is_default=False):
# if not tab or not base_url:
# raise ValueError('tab and base_url cannot be None')
# self.tab = tab
# if not name:
# self.name = tab.title()
# else:
# self.name = name
# if not template_name:
# self.template_name = '%s.html' % tab
# else:
# self.template_name = template_name
# self.is_default = is_default
# self.base_url = base_url
# self.is_active = False
#
# @property
# def url(self):
# if not self.is_default:
# return reverse(self.base_url, args=[self.tab])
# return reverse(self.base_url)
#
# @property
# def tab_name(self):
# if not self.is_default:
# return self.tab
# return ''
. Output only the next line. | ('widgets', 'Widgets', 'widget.html'), |
Predict the next line for this snippet: <|code_start|>
class IndexView(TemplateView):
template_name = 'sso/index.html'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if request.user.is_authenticated():
context['base_template'] = 'sso/logged_in.html'
else:
context['base_template'] = 'sso/root.html'
return self.render_to_response(context)
tabs_list = [
('basic', 'Basic', 'basic.html'),
('api', 'APIs', 'api.html'),
('widgets', 'Widgets', 'widget.html'),
('best-practices', 'Best Practices', 'practices.html'),
('libraries', 'Libraries', 'library.html'),
]
class DocView(TemplateView):
template_name = 'sso/5-minutes-doc.html'
tabs = [TabNav(tab[0], tab[1], tab[2], 'doc', tab[0] == 'basic') for tab in tabs_list]
def get_context_data(self, **kwargs):
context = super(DocView, self).get_context_data(**kwargs)
<|code_end|>
with the help of current file imports:
from django.core.mail.message import make_msgid
from django.templatetags.static import static
from django.views.generic import TemplateView
from account.models import UserProfile
from core.utils import DEGREES, HOSTELS, SEXES, SORTED_DISCIPLINES, TabNav
and context from other files:
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
#
# Path: core/utils.py
# DEGREES = [
# ['BTECH', 'Bachelor of Technology'],
# ['MTECH', 'Master of Technology'],
# ['DD', 'B.Tech. + M.Tech. Dual Degree'],
# ['MSC', 'Master of Science'],
# ['PHD', 'Doctor of Philosophy'],
# ['BDES', 'Bachelor of Design'],
# ['MDES', 'Master of Design'],
# ['MPHIL', 'Master of Philosophy'],
# ['MMG', 'Master of Management'],
# ['MSEx', 'M.S. (Exit Degree)'],
# ['MtechEx', 'Master of Technology (Exit Degree)'],
# ['MtechPhDDD', 'M.Tech. + Ph.D. Dual Degree'],
# ['PC', 'Preparatory Course'],
# ['VS', 'Visiting Student'],
# ['MPhilEx', 'Master of Philosophy (Exit Degree)'],
# ['MScEx', 'Master of Science (Exit Degree)'],
# ['MScMTechDD', 'M.Sc. + M.Tech. Dual Degree'],
# ['MScPhDDD', 'M.Sc. + Ph.D. Dual Degree'],
# ['MPhilPhDDD', 'M.Phil. + Ph.D. Dual Degree'],
# ['EMBA', 'Executive MBA'],
# ['FYBS', 'Four Year BS'],
# ['IMTECH', 'Integrated M.Tech.'],
# ['MSCBR', 'Master of Science By Research'],
# ['TYMSC', 'Two Year M.Sc.'],
# ['FYIMSC', 'Five Year Integrated M.Sc.'],
# ['DIIT', 'D.I.I.T.'],
# ['DIITEx', 'D.I.T.T. (Exit Degree)'],
# ]
#
# HOSTELS = [
# ['1', 'Hostel 1'],
# ['2', 'Hostel 2'],
# ['3', 'Hostel 3'],
# ['4', 'Hostel 4'],
# ['5', 'Hostel 5'],
# ['6', 'Hostel 6'],
# ['7', 'Hostel 7'],
# ['8', 'Hostel 8'],
# ['9', 'Hostel 9'],
# ['10', 'Hostel 10'],
# ['11', 'Hostel 11'],
# ['12', 'Hostel 12'],
# ['13', 'Hostel 13'],
# ['14', 'Hostel 14'],
# ['15', 'Hostel 15'],
# ['16', 'Hostel 16'],
# ['tansa', 'Tansa'],
# ['qip', 'QIP'],
# ]
#
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# SORTED_DISCIPLINES = sorted(DISCIPLINES, key=lambda x: x[1])
#
# class TabNav(object):
# def __init__(self, tab, name=None, template_name=None, base_url=None, is_default=False):
# if not tab or not base_url:
# raise ValueError('tab and base_url cannot be None')
# self.tab = tab
# if not name:
# self.name = tab.title()
# else:
# self.name = name
# if not template_name:
# self.template_name = '%s.html' % tab
# else:
# self.template_name = template_name
# self.is_default = is_default
# self.base_url = base_url
# self.is_active = False
#
# @property
# def url(self):
# if not self.is_default:
# return reverse(self.base_url, args=[self.tab])
# return reverse(self.base_url)
#
# @property
# def tab_name(self):
# if not self.is_default:
# return self.tab
# return ''
, which may contain function names, class names, or code. Output only the next line. | context['login_js_url'] = static('widget/js/login.min.js') |
Continue the code snippet: <|code_start|>
class UserProfileAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'roll_number', 'sex', 'type']
list_filter = ['sex', 'type', ]
search_fields = ['user__username', 'user__first_name', 'roll_number']
class InstituteAddressInline(admin.TabularInline):
model = InstituteAddress
class UserProfileInline(admin.StackedInline):
model = UserProfile
class ProgramInline(admin.StackedInline):
model = Program
class ContactInline(admin.TabularInline):
model = ContactNumber
class SecondaryEmailInline(admin.TabularInline):
model = SecondaryEmail
class CustomUserAdmin(UserAdmin):
<|code_end|>
. Use current file imports:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from user_resource.models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .models import UserProfile
and context (classes, functions, or code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
. Output only the next line. | fieldsets = ( |
Here is a snippet: <|code_start|>
class UserProfileAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'roll_number', 'sex', 'type']
list_filter = ['sex', 'type', ]
search_fields = ['user__username', 'user__first_name', 'roll_number']
class InstituteAddressInline(admin.TabularInline):
model = InstituteAddress
class UserProfileInline(admin.StackedInline):
model = UserProfile
class ProgramInline(admin.StackedInline):
model = Program
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from user_resource.models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .models import UserProfile
and context from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
, which may include functions, classes, or code. Output only the next line. | class ContactInline(admin.TabularInline): |
Here is a snippet: <|code_start|>
class UserProfileAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'roll_number', 'sex', 'type']
list_filter = ['sex', 'type', ]
search_fields = ['user__username', 'user__first_name', 'roll_number']
class InstituteAddressInline(admin.TabularInline):
model = InstituteAddress
class UserProfileInline(admin.StackedInline):
model = UserProfile
class ProgramInline(admin.StackedInline):
model = Program
class ContactInline(admin.TabularInline):
model = ContactNumber
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from user_resource.models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .models import UserProfile
and context from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
, which may include functions, classes, or code. Output only the next line. | class SecondaryEmailInline(admin.TabularInline): |
Given the code snippet: <|code_start|>class UserProfileAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'roll_number', 'sex', 'type']
list_filter = ['sex', 'type', ]
search_fields = ['user__username', 'user__first_name', 'roll_number']
class InstituteAddressInline(admin.TabularInline):
model = InstituteAddress
class UserProfileInline(admin.StackedInline):
model = UserProfile
class ProgramInline(admin.StackedInline):
model = Program
class ContactInline(admin.TabularInline):
model = ContactNumber
class SecondaryEmailInline(admin.TabularInline):
model = SecondaryEmail
class CustomUserAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from user_resource.models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .models import UserProfile
and context (functions, classes, or occasionally code) from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
. Output only the next line. | (_('Important dates'), {'fields': ('last_login', 'date_joined')}), |
Next line prediction: <|code_start|>
class UserProfileAdmin(SimpleHistoryAdmin):
list_display = ['id', 'user', 'roll_number', 'sex', 'type']
list_filter = ['sex', 'type', ]
search_fields = ['user__username', 'user__first_name', 'roll_number']
class InstituteAddressInline(admin.TabularInline):
model = InstituteAddress
class UserProfileInline(admin.StackedInline):
model = UserProfile
class ProgramInline(admin.StackedInline):
model = Program
class ContactInline(admin.TabularInline):
model = ContactNumber
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from user_resource.models import ContactNumber, InstituteAddress, Program, SecondaryEmail
from .models import UserProfile)
and context including class names, function names, or small code snippets from other files:
# Path: user_resource/models.py
# class ContactNumber(models.Model):
# user = models.ForeignKey(User, related_name='contacts')
# number = models.CharField(max_length=16)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.number
#
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
#
# class SecondaryEmail(models.Model):
# user = models.ForeignKey(User, related_name='secondary_emails')
# email = models.EmailField()
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.email
#
# Path: account/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# profile_picture = models.ImageField(upload_to=user_profile_picture, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# roll_number = models.CharField(max_length=16, null=True, blank=True)
# type = models.CharField(max_length=16, null=True, blank=True)
# mobile = models.CharField(max_length=16, null=True, blank=True)
# is_alumni = models.BooleanField(default=False)
# sex = models.CharField(max_length=10, choices=SEXES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return self.user.username
. Output only the next line. | class SecondaryEmailInline(admin.TabularInline): |
Continue the code snippet: <|code_start|>
class ProfilePictureForm(forms.Form):
profile_picture = forms.ImageField()
def clean_profile_picture(self):
profile_picture = self.cleaned_data['profile_picture']
content_type = profile_picture.content_type.split('/')[0]
if content_type in ['image']:
if profile_picture.size > 5242880:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (
filesizeformat(5242880), filesizeformat(profile_picture.size)))
else:
raise forms.ValidationError(_('File type is not supported'))
return profile_picture
class SexUpdateForm(forms.Form):
sex = forms.ChoiceField(choices=get_choices_with_blank_dash(SEXES), required=False,
widget=forms.Select(
attrs={'class': 'form-control', },
))
class InstituteAddressForm(forms.ModelForm):
class Meta:
model = InstituteAddress
fields = ['hostel', 'room']
widgets = {
<|code_end|>
. Use current file imports:
from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from core.utils import SEXES, get_choices_with_blank_dash
from .models import InstituteAddress, Program
and context (classes, functions, or code) from other files:
# Path: core/utils.py
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: user_resource/models.py
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
. Output only the next line. | 'hostel': forms.Select( |
Based on the snippet: <|code_start|> ),
'room': forms.TextInput(
attrs={'class': 'form-control', },
),
}
class ProgramForm(forms.ModelForm):
def clean(self):
cleaned_data = super(ProgramForm, self).clean()
join_year = cleaned_data.get('join_year')
graduation_year = cleaned_data.get('graduation_year')
if join_year and graduation_year:
if graduation_year <= join_year:
validation_err = forms.ValidationError(_('How come you graduated before you joined?'), code='bad_input')
self.add_error('graduation_year', validation_err)
if join_year >= graduation_year:
validation_err = forms.ValidationError(
_('How come you joined after you graduated? You must be in alternate timeline!'), code='bade_input')
self.add_error('join_year', validation_err)
class Meta:
model = Program
fields = ['department', 'join_year', 'graduation_year', 'degree']
widgets = {
'department': forms.Select(
attrs={'class': 'form-control', },
),
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from core.utils import SEXES, get_choices_with_blank_dash
from .models import InstituteAddress, Program
and context (classes, functions, sometimes code) from other files:
# Path: core/utils.py
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: user_resource/models.py
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
. Output only the next line. | 'join_year': forms.NumberInput( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.