text:
"""
We want to allow users override fields and their attributes on
auto-generated embedded documents based on

We need to take into account the following fields:
 - exclude
 - read_only
 - extra_kwargs
"""

from __future__ import unicode_literals

from django.test import TestCase
from mongoengine import Document, EmbeddedDocument, fields
from rest_framework.serializers import ValidationError

from rest_framework_mongoengine.serializers import DocumentSerializer

from .utils import dedent

class ChildDocument(EmbeddedDocument):
    name = fields.StringField()
    age = fields.IntField()

class ReferencedDocument(Document):
    foo = fields.StringField()
    bar = fields.StringField()

class ParentDocument(Document):
    foo = fields.StringField()
    embedded = fields.EmbeddedDocumentField(ChildDocument)
    nested_reference = fields.ReferenceField(ReferencedDocument)

class CompoundParentDocument(Document):
    foo = fields.StringField()
    embedded_list = fields.EmbeddedDocumentListField(ChildDocument)
    list_of_embedded_documents = fields.ListField(fields.EmbeddedDocumentField(ChildDocument))
    embedded_map = fields.MapField(fields.EmbeddedDocumentField(ChildDocument))

class TestNestedCustomizationMapping(TestCase):
    def test_fields(self):
        """
        Ensure `fields` is passed to embedded documents.
        If 'embedded.name' is included, 'embedded' should be included, too.
        """
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('embedded', 'embedded.name', 'nested_reference', 'nested_reference.foo')
                depth = 1

        expected = dedent("""
            ParentSerializer():
                embedded = EmbeddedSerializer(required=False):
                    name = CharField(required=False)
                nested_reference = NestedSerializer(read_only=True):
                    foo = CharField(required=False)
        """)
        assert repr(ParentSerializer()) == expected

    def test_exclude(self):
        """Ensure `exclude` is passed to embedded documents."""
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                exclude = ('foo', 'embedded.age')
                depth = 1

        expected = dedent("""
            ParentSerializer():
                id = ObjectIdField(read_only=True)
                nested_reference = NestedSerializer(read_only=True):
                    id = ObjectIdField(read_only=True)
                    foo = CharField(required=False)
                    bar = CharField(required=False)
                embedded = EmbeddedSerializer(required=False):
                    name = CharField(required=False)
        """)

        assert repr(ParentSerializer()) == expected

    def test_read_only(self):
        """Ensure `read_only` are passed to embedded documents."""
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                read_only_fields = ('foo', 'embedded.name')
                depth = 1

        expected = dedent("""
            ParentSerializer():
                id = ObjectIdField(read_only=True)
                foo = CharField(read_only=True)
                nested_reference = NestedSerializer(read_only=True):
                    id = ObjectIdField(read_only=True)
                    foo = CharField(required=False)
                    bar = CharField(required=False)
                embedded = EmbeddedSerializer(required=False):
                    name = CharField(read_only=True)
                    age = IntegerField(required=False)
        """)

        assert repr(ParentSerializer()) == expected

    def test_extra_field_kwargs(self):
        """Ensure `extra_kwargs` are passed to embedded documents."""
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded.name': {'default': 'Johnny B. Good'}
                }

        expected = dedent("""
            ParentSerializer():
                id = ObjectIdField(read_only=True)
                foo = CharField(default='bar')
                nested_reference = NestedSerializer(read_only=True):
                    id = ObjectIdField(read_only=True)
                    foo = CharField(required=False)
                    bar = CharField(required=False)
                embedded = EmbeddedSerializer(required=False):
                    name = CharField(default='Johnny B. Good')
                    age = IntegerField(required=False)
        """)

        assert repr(ParentSerializer()) == expected

class TestCompoundCustomizationMapping(TestCase):
    def test_fields(self):
        """Ensure `fields` is passed to embedded documents."""
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = (
                    'embedded_list',
                    'embedded_list.child.name',
                    'embedded_map',
                    'embedded_map.child.age',
                    'list_of_embedded_documents',
                    'list_of_embedded_documents.child.name')
                depth = 1

        expected = dedent("""
            CompoundParentSerializer():
                embedded_list = EmbeddedSerializer(many=True, required=False):
                    name = CharField(required=False)
                embedded_map = DictField(child=EmbeddedSerializer(required=False), required=False):
                    age = IntegerField(required=False)
                list_of_embedded_documents = EmbeddedSerializer(many=True, required=False):
                    name = CharField(required=False)
        """)

        serializer = CompoundParentSerializer()
        repr(serializer)

        assert repr(CompoundParentSerializer()) == expected

    def test_exclude(self):
        """Ensure `exclude` is passed to embedded documents."""
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                exclude = (
                    'id',
                    'foo',
                    'embedded_list.child.age',
                    'embedded_map.child.name',
                    'list_of_embedded_documents.child.age'
                )

        expected = dedent("""
            CompoundParentSerializer():
                embedded_list = EmbeddedSerializer(many=True, required=False):
                    name = CharField(required=False)
                list_of_embedded_documents = EmbeddedSerializer(many=True, required=False):
                    name = CharField(required=False)
                embedded_map = DictField(child=EmbeddedSerializer(required=False), required=False):
                    age = IntegerField(required=False)
        """)

        assert repr(CompoundParentSerializer()) == expected

    def test_read_only(self):
        """Ensure `read_only` are passed to embedded documents."""
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                read_only_fields = (
                    'foo',
                    'embedded_list.child.name',
                    'list_of_embedded_documents.child.name',
                    'embedded_map.child.name'
                )

        expected = dedent("""
            CompoundParentSerializer():
                id = ObjectIdField(read_only=True)
                foo = CharField(read_only=True)
                embedded_list = EmbeddedSerializer(many=True, required=False):
                    name = CharField(read_only=True)
                    age = IntegerField(required=False)
                list_of_embedded_documents = EmbeddedSerializer(many=True, required=False):
                    name = CharField(read_only=True)
                    age = IntegerField(required=False)
                embedded_map = DictField(child=EmbeddedSerializer(required=False), required=False):
                    name = CharField(read_only=True)
                    age = IntegerField(required=False)
        """)

        assert repr(CompoundParentSerializer()) == expected

    def test_extra_field_kwargs(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded_list.child.name': {'default': 'Johnny'},
                    'list_of_embedded_documents.child.name': {'default': 'B'},
                    'embedded_map.child.name': {'default': 'Good'}
                }

        expected = dedent("""
            CompoundParentSerializer():
                id = ObjectIdField(read_only=True)
                foo = CharField(default='bar')
                embedded_list = EmbeddedSerializer(many=True, required=False):
                    name = CharField(default='Johnny')
                    age = IntegerField(required=False)
                list_of_embedded_documents = EmbeddedSerializer(many=True, required=False):
                    name = CharField(default='B')
                    age = IntegerField(required=False)
                embedded_map = DictField(child=EmbeddedSerializer(required=False), required=False):
                    name = CharField(default='Good')
                    age = IntegerField(required=False)
        """)

        assert repr(CompoundParentSerializer()) == expected

class TestNestedCustomizationFieldsIntegration(TestCase):
    def doCleanups(self):
        ReferencedDocument.drop_collection()
        ParentDocument.drop_collection()

    def test_parsing(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('embedded', 'embedded.name', 'nested_reference', 'nested_reference.foo')
                depth = 1

        input_data = {
            "foo": "x",
            "embedded": {'name': 'Joe', 'age': 9},
            "nested_reference": {'foo': 'a', 'bar': 'b'}
        }

        serializer = ParentSerializer(data=input_data)
        assert serializer.is_valid(), serializer.errors

        expected = {
            u'embedded': {u'name': u'Joe'}
        }

        assert serializer.validated_data == expected

    def test_retrieval(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('embedded', 'embedded.name', 'nested_reference', 'nested_reference.foo')
                depth = 1

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'nested_reference': {'foo': 'a'},
            'embedded': {'name': 'Joe'}
        }
        assert serializer.data == expected

    def test_create(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('embedded', 'embedded.name', 'nested_reference')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'nested_reference': nested_reference.id,
            'embedded': {'name': 'Joe'}
        }

        serializer = ParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Joe'}
        }
        assert serializer.data == expected

    def test_update(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('embedded', 'embedded.name', 'nested_reference')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'name': 'Jack'}
        }

        serializer = ParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Jack'}
        }
        assert serializer.data == expected

class TestNestedCustomizationExcludeIntegration(TestCase):
    def doCleanups(self):
        ReferencedDocument.drop_collection()
        ParentDocument.drop_collection()

    def test_parsing(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                exclude = ('foo', 'embedded.age', 'nested_reference.bar')
                depth = 1

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a'},
            'embedded': {'name': 'Joe'}
        }
        assert serializer.data == expected

    def test_retrieval(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                exclude = ('foo', 'embedded.age', 'nested_reference.bar')
                depth = 1

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a'},
            'embedded': {'name': 'Joe'}
        }
        assert serializer.data == expected

    def test_create(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                exclude = ('foo', 'embedded.age')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'nested_reference': nested_reference.id,
            'embedded': {'name': 'Joe'}
        }

        serializer = ParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Joe'}
        }
        assert serializer.data == expected

    def test_update(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                exclude = ('foo', 'embedded.age')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'name': 'Jack'}
        }

        serializer = ParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Jack'}
        }
        assert serializer.data == expected

class TestNestedCustomizationReadOnlyIntegration(TestCase):
    def doCleanups(self):
        ReferencedDocument.drop_collection()
        ParentDocument.drop_collection()

    def test_parsing(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                read_only_fields = ('foo', 'embedded.name')
                depth = 1

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a', 'bar': 'b'},
            'embedded': {'name': 'Joe', 'age': 9}
        }
        assert serializer.data == expected

    def test_retrieval(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                read_only_fields = ('foo', 'embedded.name')
                depth = 1

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a', 'bar': 'b'},
            'embedded': {'name': 'Joe', 'age': 9}
        }
        assert serializer.data == expected

    def test_create(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                read_only_fields = ('foo', 'embedded.age')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'foo': 'x',
            'nested_reference': nested_reference.id,
            'embedded': {'name': 'Joe', 'age': 9}
        }

        serializer = ParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': None,
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Joe', 'age': None}
        }
        assert serializer.data == expected

    def test_update(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                read_only_fields = ('foo', 'embedded.age')

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'name': 'Jack', 'age': 10}
        }

        serializer = ParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'x',
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Jack', 'age': None}
        }
        assert serializer.data == expected

class TestNestedCustomizationExtraFieldKwargsIntegration(TestCase):
    def doCleanups(self):
        ReferencedDocument.drop_collection()
        ParentDocument.drop_collection()

    def test_parsing(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded.name': {'default': 'Johnny B. Good'}
                }

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a', 'bar': 'b'},
            'embedded': {'name': 'Joe', 'age': 9}
        }
        assert serializer.data == expected

    def test_retrieval(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded.name': {'default': 'Johnny B. Good'}
                }

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )
        serializer = ParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'nested_reference': {'id': str(nested_reference.id), 'foo': 'a', 'bar': 'b'},
            'embedded': {'name': 'Joe', 'age': 9}
        }
        assert serializer.data == expected

    def test_create(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded.name': {'default': 'Johnny B. Good'}
                }

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'nested_reference': nested_reference.id,
            'embedded': {'age': 9}
        }

        serializer = ParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'bar',
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Johnny B. Good', 'age': 9}
        }
        assert serializer.data == expected

    def test_update(self):
        class ParentSerializer(DocumentSerializer):
            class Meta:
                model = ParentDocument
                fields = ('__all__')
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded.name': {'default': 'Johnny B. Good'}
                }

        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Joe', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'age': 10}
        }

        serializer = ParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'bar',
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Johnny B. Good', 'age': 10}
        }
        assert serializer.data == expected

class TestNestedCustomizationValidateMethodIntegration(TestCase):
    class ParentSerializer(DocumentSerializer):
        class Meta:
            model = ParentDocument
            fields = ('__all__')

        def validate_embedded__name(self, value):
            if len(value) < 4:
                raise ValidationError('Minimum 4 characters.')
            return value.title()

    def doCleanups(self):
        ReferencedDocument.drop_collection()
        ParentDocument.drop_collection()

    def test_create_success(self):
        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'foo': 'x',
            'nested_reference': nested_reference.id,
            'embedded': {'name': "Jack", 'age': 9}
        }

        serializer = self.ParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'x',
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Jack', 'age': 9}
        }
        assert serializer.data == expected

    def test_create_fail(self):
        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        data = {
            'foo': 'x',
            'nested_reference': nested_reference.id,
            'embedded': {'name': "Joe", 'age': 9}
        }

        serializer = self.ParentSerializer(data=data)
        assert not serializer.is_valid()
        assert serializer.errors == {'embedded': {'name': [u'Minimum 4 characters.']}}

    def test_update_success(self):
        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Jack', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'name': 'Johnny B. Good'}
        }

        serializer = self.ParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        # TODO: passing empty 'age' resets it to None - is this expected behavior, or we should raise error?
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'x',
            'nested_reference': str(nested_reference.id),
            'embedded': {'name': 'Johnny B. Good', 'age': None}
        }
        assert serializer.data == expected

    def test_update_fail(self):
        nested_reference = ReferencedDocument.objects.create(foo='a', bar='b')
        instance = ParentDocument.objects.create(
            foo='x',
            embedded=ChildDocument(name='Jack', age=9),
            nested_reference=nested_reference
        )

        data = {
            'embedded': {'name': 'Joe'}
        }

        serializer = self.ParentSerializer(instance, data=data)
        assert not serializer.is_valid()
        assert dict(serializer.errors) == {'embedded': {'name': [u'Minimum 4 characters.']}}

class TestNestedCompoundCustomizationFieldsIntegration(TestCase):
    def doCleanups(self):
        CompoundParentDocument.drop_collection()

    def test_parsing(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = (
                    'embedded_list',
                    'embedded_list.child.name',
                    'embedded_map',
                    'embedded_map.child.age',
                    'list_of_embedded_documents',
                    'list_of_embedded_documents.child.name'
                )
                depth = 1

        input_data = {
            "embedded_list": [{'name': 'Joe'}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe'}]
        }

        serializer = CompoundParentSerializer(data=input_data)
        assert serializer.is_valid(), serializer.errors

        expected = {
            "embedded_list": [{'name': 'Joe'}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe'}]
        }

        assert serializer.validated_data == expected

    def test_retrieval(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = (
                    'embedded_list',
                    'embedded_list.child.name',
                    'embedded_map',
                    'embedded_map.child.age',
                    'list_of_embedded_documents',
                    'list_of_embedded_documents.child.name'
                )
                depth = 1

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )
        serializer = CompoundParentSerializer(instance)
        expected = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }
        assert serializer.data == expected

    def test_create(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = (
                    'embedded_list',
                    'embedded_list.child.name',
                    'embedded_map',
                    'embedded_map.child.age',
                    'list_of_embedded_documents',
                    'list_of_embedded_documents.child.name'
                )

        data = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }

        serializer = CompoundParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }
        assert serializer.data == expected

    def test_update(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = (
                    'embedded_list',
                    'embedded_list.child.name',
                    'embedded_map',
                    'embedded_map.child.age',
                    'list_of_embedded_documents',
                    'list_of_embedded_documents.child.name'
                )

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            'embedded_list': [{'name': 'Jack'}],
            'embedded_map': {'Joe': {'age': 10}},
            'list_of_embedded_documents': [{'name': 'Jack'}]
        }

        serializer = CompoundParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'embedded_list': [{'name': 'Jack'}],
            'embedded_map': {'Joe': {'age': 10}},
            'list_of_embedded_documents': [{'name': 'Jack'}]
        }
        assert serializer.data == expected

class TestNestedCompoundCustomizationExcludeIntegration(TestCase):
    def doCleanups(self):
        CompoundParentDocument.drop_collection()

    def test_parsing(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                exclude = (
                    'id',
                    'foo',
                    'embedded_list.child.age',
                    'embedded_map.child.name',
                    'list_of_embedded_documents.child.age'
                )
                depth = 1

        input_data = {
            "embedded_list": [{'name': 'Joe'}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe'}]
        }

        serializer = CompoundParentSerializer(data=input_data)
        assert serializer.is_valid(), serializer.errors

        expected = {
            "embedded_list": [{'name': 'Joe'}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe'}]
        }

        assert serializer.validated_data == expected

    def test_retrieval(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                exclude = (
                    'id',
                    'foo',
                    'embedded_list.child.age',
                    'embedded_map.child.name',
                    'list_of_embedded_documents.child.age'
                )
                depth = 1

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )
        serializer = CompoundParentSerializer(instance)
        expected = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }
        assert serializer.data == expected

    def test_create(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                exclude = (
                    'id',
                    'foo',
                    'embedded_list.child.age',
                    'embedded_map.child.name',
                    'list_of_embedded_documents.child.age'
                )

        data = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }

        serializer = CompoundParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'embedded_list': [{'name': 'Joe'}],
            'embedded_map': {'Joe': {'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe'}]
        }
        assert serializer.data == expected

    def test_update(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                exclude = (
                    'id',
                    'foo',
                    'embedded_list.child.age',
                    'embedded_map.child.name',
                    'list_of_embedded_documents.child.age'
                )

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            'embedded_list': [{'name': 'Jack'}],
            'embedded_map': {'Joe': {'age': 10}},
            'list_of_embedded_documents': [{'name': 'Jack'}]
        }

        serializer = CompoundParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'embedded_list': [{'name': 'Jack'}],
            'embedded_map': {'Joe': {'age': 10}},
            'list_of_embedded_documents': [{'name': 'Jack'}]
        }
        assert serializer.data == expected

class TestNestedCompoundCustomizationReadOnlyIntegration(TestCase):
    def doCleanups(self):
        CompoundParentDocument.drop_collection()

    def test_parsing(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                read_only_fields = (
                    'foo',
                    'embedded_list.child.name',
                    'list_of_embedded_documents.child.name',
                    'embedded_map.child.name'
                )

        input_data = {
            "foo": "x",
            "embedded_list": [{'name': 'Joe', 'age': 9}],
            "embedded_map": {'0': {'name': 'Joe', 'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe', 'age': 9}]
        }

        serializer = CompoundParentSerializer(data=input_data)
        assert serializer.is_valid(), serializer.errors

        expected = {
            "embedded_list": [{'age': 9}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'age': 9}]
        }

        assert serializer.validated_data == expected

    def test_retrieval(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                read_only_fields = (
                    'foo',
                    'embedded_list.child.name',
                    'list_of_embedded_documents.child.name',
                    'embedded_map.child.name'
                )

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )
        serializer = CompoundParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'embedded_list': [{'name': 'Joe', 'age': 9}],
            'embedded_map': {'Joe': {'name': 'Joe', 'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe', 'age': 9}]
        }
        assert serializer.data == expected

    def test_create(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                read_only_fields = (
                    'foo',
                    'embedded_list.child.name',
                    'list_of_embedded_documents.child.name',
                    'embedded_map.child.name'
                )

        data = {
            "foo": "bar",
            "embedded_list": [{'name': 'Joe', 'age': 9}],
            "embedded_map": {'0': {'name': 'Joe', 'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe', 'age': 9}]
        }

        serializer = CompoundParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': None,
            'embedded_list': [{'name': None, 'age': 9}],
            'embedded_map': {'0': {'name': None, 'age': 9}},
            'list_of_embedded_documents': [{'name': None, 'age': 9}]
        }
        assert serializer.data == expected

    def test_update(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                read_only_fields = (
                    'foo',
                    'embedded_list.child.name',
                    'list_of_embedded_documents.child.name',
                    'embedded_map.child.name'
                )

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            "foo": "y",
            "embedded_list": [{'name': 'Jack', 'age': 10}],
            "embedded_map": {'0': {'name': 'Jack', 'age': 10}},
            "list_of_embedded_documents": [{'name': 'Jack', 'age': 10}]
        }

        serializer = CompoundParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'foo': 'x',
            'id': str(instance.id),
            'embedded_list': [{'name': None, 'age': 10}],
            'embedded_map': {'0': {'name': None, 'age': 10}},
            'list_of_embedded_documents': [{'name': None, 'age': 10}]
        }
        assert serializer.data == expected

class TestNestedCompoundCustomizationExtraFieldKwargsIntegration(TestCase):
    def doCleanups(self):
        CompoundParentDocument.drop_collection()

    def test_parsing(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded_list.child.name': {'default': 'Johnny'},
                    'embedded_map.child.name': {'default': 'B'},
                    'list_of_embedded_documents.child.name': {'default': 'Good'},
                }

        input_data = {
            "embedded_list": [{'age': 9}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'age': 9}]
        }

        serializer = CompoundParentSerializer(data=input_data)
        assert serializer.is_valid(), serializer.errors

        expected = {
            "foo": 'bar',
            "embedded_list": [{'name': 'Johnny', 'age': 9}],
            "embedded_map": {'0': {'name': 'B', 'age': 9}},
            "list_of_embedded_documents": [{'name': 'Good', 'age': 9}]
        }

        assert serializer.validated_data == expected

    def test_retrieval(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded_list.child.name': {'default': 'Johnny'},
                    'embedded_map.child.name': {'default': 'B'},
                    'list_of_embedded_documents.child.name': {'default': 'Good'}
                }

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )
        serializer = CompoundParentSerializer(instance)
        expected = {
            'id': str(instance.id),
            'foo': 'x',
            'embedded_list': [{'name': 'Joe', 'age': 9}],
            'embedded_map': {'Joe': {'name': 'Joe', 'age': 9}},
            'list_of_embedded_documents': [{'name': 'Joe', 'age': 9}]
        }
        assert serializer.data == expected

    def test_create(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded_list.child.name': {'default': 'Johnny'},
                    'embedded_map.child.name': {'default': 'B'},
                    'list_of_embedded_documents.child.name': {'default': 'Good'}
                }

        data = {
            "foo": "bar",
            "embedded_list": [{'age': 9}],
            "embedded_map": {'0': {'age': 9}},
            "list_of_embedded_documents": [{'age': 9}]
        }

        serializer = CompoundParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'id': str(serializer.instance.id),
            'foo': 'bar',
            'embedded_list': [{'name': 'Johnny', 'age': 9}],
            'embedded_map': {'0': {'name': 'B', 'age': 9}},
            'list_of_embedded_documents': [{'name': 'Good', 'age': 9}]
        }
        assert serializer.data == expected

    def test_update(self):
        class CompoundParentSerializer(DocumentSerializer):
            class Meta:
                model = CompoundParentDocument
                fields = ('__all__')
                depth = 1
                extra_kwargs = {
                    'foo': {'default': 'bar'},
                    'embedded_list.child.name': {'default': 'Johnny'},
                    'embedded_map.child.name': {'default': 'B'},
                    'list_of_embedded_documents.child.name': {'default': 'Good'}
                }

        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            "foo": "y",
            "embedded_list": [{'age': 10}],
            "embedded_map": {'0': {'age': 10}},
            "list_of_embedded_documents": [{'age': 10}]
        }

        serializer = CompoundParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'foo': 'y',
            'id': str(instance.id),
            'embedded_list': [{'name': 'Johnny', 'age': 10}],
            'embedded_map': {'0': {'name': 'B', 'age': 10}},
            'list_of_embedded_documents': [{'name': 'Good', 'age': 10}]
        }
        assert serializer.data == expected

class TestNestedCompoundCustomizationValidateMethodIntegration(TestCase):
    class CompoundParentSerializer(DocumentSerializer):
        class Meta:
            model = CompoundParentDocument
            fields = ('__all__')

        def validate_embedded_list__child__name(self, value):
            if len(value) < 4:
                raise ValidationError('Minimum 4 characters.')
            return value.title()

        def validated_embedded_map__child__name(self, value):
            if len(value) < 4:
                raise ValidationError('Minimum 4 characters.')
            return value.title()

        def validated_list_of_embedded_documents__child__name(self, value):
            if len(value) < 4:
                raise ValidationError('Minimum 4 characters.')
            return value.title()

    def doCleanups(self):
        CompoundParentDocument.drop_collection()

    def test_create_success(self):
        data = {
            "foo": 'x',
            "embedded_list": [{'name': 'Jack', 'age': 9}],
            "embedded_map": {'0': {'name': 'Jack', 'age': 9}},
            "list_of_embedded_documents": [{'name': 'Jack', 'age': 9}]
        }

        serializer = self.CompoundParentSerializer(data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()
        expected = {
            'embedded_list': [{'name': u'Jack', 'age': 9}],
            'list_of_embedded_documents': [{'name': 'Jack', 'age': 9}],
            'foo': 'x',
            'id': str(serializer.instance.id),
            'embedded_map': {'0': {'name': 'Jack', 'age': 9}}
        }

        assert serializer.data == expected

    def test_create_fail(self):
        data = {
            "foo": "bar",
            "embedded_list": [{'name': 'Joe', 'age': 9}],
            "embedded_map": {'0': {'name': 'Joe', 'age': 9}},
            "list_of_embedded_documents": [{'name': 'Joe', 'age': 9}]
        }

        serializer = self.CompoundParentSerializer(data=data)
        assert not serializer.is_valid()
        assert dict(serializer.errors) == {'embedded_list': {0: {'name': [u'Minimum 4 characters.']}}}

    def test_update_success(self):
        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            "foo": "y",
            "embedded_list": [{'name': 'Jack', 'age': 10}],
            "embedded_map": {'0': {'name': 'Jack', 'age': 10}},
            "list_of_embedded_documents": [{'name': 'Jack', 'age': 10}]
        }

        serializer = self.CompoundParentSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors
        serializer.save()

        expected = {
            'id': str(serializer.instance.id),
            'foo': 'y',
            "embedded_list": [{'name': 'Jack', 'age': 10}],
            "embedded_map": {'0': {'name': 'Jack', 'age': 10}},
            "list_of_embedded_documents": [{'name': 'Jack', 'age': 10}]
        }
        assert serializer.data == expected

    def test_update_fail(self):
        instance = CompoundParentDocument.objects.create(
            foo='x',
            embedded_list=[ChildDocument(name='Joe', age=9)],
            embedded_map={'Joe': ChildDocument(name='Joe', age=9)},
            list_of_embedded_documents=[ChildDocument(name='Joe', age=9)]
        )

        data = {
            "foo": "y",
            "embedded_list": [{'name': 'Jim', 'age': 10}],
            "embedded_map": {'0': {'name': 'Jim', 'age': 10}},
            "list_of_embedded_documents": [{'name': 'Jim', 'age': 10}]
        }

        serializer = self.CompoundParentSerializer(instance, data=data)
        assert not serializer.is_valid()
        assert dict(serializer.errors) == {'embedded_list': {0: {'name': [u'Minimum 4 characters.']}}}


text:
\section{Queueing Theory}
\label{sec:Queueing-Theory}

The queueing theory is built on the stochastic modeling and analysis, which represents service demands and interarrivals as random variables.
It is the theory behind what makes queues appear and how to make them go away.
It is the study of queueing behavior in systems and networks.

Queueing theory applies anywhere that queues come up. It is also at the heart of any computer system.

Queueing theory has its origins in research by Agner Krarup Erlang when he created models to describe the Copenhagen telephone exchange.

Queues results from variability in service time and/or interarrival time distribution.

A major reason why computer scientists are so slow to adopt queueing theory is that standard assumptions often do not fit. In some cases they are very far from reality: for example, in the case of high variability and correlations. However there are often ways to work around these assumptions.

The goals of a queueing theorist is \textit{predicting} the system performance and \textit{designing} it to improve performance.

There are many questions in computer systems design that lend themselves to a queueing-theoretic solution (e.g., power management, priority scheduling, and so on).
However, there are  lots of problems that we can at best only analyze approximately (e.g., mean response time for M/G/k queue). Typically, approximations are very poor when jobs size variability gets high \cite{gupta2010inapproximability}.

\subsection{Queue Metrics}
\label{sec:Queue-Metrics}

A queue node is described by the following parameters and performance metrics:

\begin{description}
	\item [Service Order] The scheduling discipline.

	\item [Average Arrival Rate]  ($\lambda$) The rate at which jobs arrive to the node.

	\item [Interarrival Time] ($\tau$) The time between successive job arrivals.

	\item [Mean Interarrival Time] ($\expected{\tau}=\frac{1}{\lambda}$) The average time between successive job arrivals.

	\item [Service Requirement, Size] ($S$) The time taken by a job to run on server.

	\item [Average Service Rate] ($\mu$) The rate at which jobs are served by the server.

	\item [Mean Service Time] ($\expected{S}=\frac{1}{\mu}$) The average time required to serve a job.

	\item [Waiting Time, Delay] ($T_{Q}$) The time that the job spends in the queue.

	\item [Response Time, Turnaround Time] ($T$) The time during which the job is in the node. Thus $T=T_{departure}-T_{arrival}$. Note that $\expected{T}=\expected{T_{Q}}+\expected{S}$.

	\item [Number of System Jobs] ($N$) The number of jobs in the queue plus the ones being served.

	\item [Number of Queued Jobs] ($N_{Q}$) The number of jobs in the queue.

	\item [Utilization] ($\varrho$) The fraction of time the server is busy, the probability of the server to be busy, the mean number of jobs in that node.

	\item [Throughput] ($X$) The rate of completions at server.
\end{description}

\subsection{Kendall notation}
A queue node il classified using the Kendall notation \cite{kendall1953stochastic}.

\begin{equation}
A/S/m/c/N/D
\end{equation}

where

\begin{description}
	\item [A] the arrival process, the value indicates the probability distribution of inter-arrival times.

	\item [S] the service process, the value indicates the probability distribution of service times.

	\item [A] the number of servers.

	\item [c] the capacity of the system (that is, the number of servers plus the buffer size).

	\item [N] the size of the population, that is the total number of jobs.

	\item [D] the scheduling discipline.
\end{description}

The arrival process \textit{A} and service process \textit{S} could be equal to

\begin{description}
	\item [$M$] Exponential distribution.

	\item [$D$] Deterministic distribution.

	\item [$E_{n}$] Erlang distribution of order $n$.

	\item [$H_{n}$] Hyper-exponential distribution of order $n$.

	\item [$G$] Generic distribution of independent variables.
\end{description}

The scheduling discipline \textit{D} could be equal to

\begin{description}
	\item [$FCFS (FIFO)$] first come, first served.

	\item [$LCFS (LIFO)$] last come, first served.

	\item [$RO$] random order.

	\item [$RR$] round robin.

	\item [$PS$] processor sharing.

	\item [$P$] custom priority.
\end{description}

When the final three parameters are not specified (e.g. M/M/1 queue), it is assumed $K=\infty$, $N=\infty$ and $D=FIFO$.

\subsection{Classification of Queueing Networks}
\label{sec:Classification-Queueing-Networks}

Queueing networks can be classified into two categories:

\begin{description}
	\item [Open Networks] They have external arrivals and departures. In such systems, $X=\lambda$

	\item [Closed Networks] They have no external arrivals or departures. In such systems, $X=\mu$. The number of jobs in the system is fixed to $N$, and it is called \textit{load} or \textit{multiprogramming level (MPL)}. $\expected{T}=\expected{T_{R}}+\expected{Z}$. Closed networks can be classified in two categories:

	\begin{description}
		\item [Interactive Networks] There are $N$ \textit{terminals} which submit jobs to a network of queues, called \textit{central subsystem}. After submission, a terminal waits for job completion, then sleeps for a think-time $Z$, then can submit again. Thus, a terminal oscillates between a submission-state and a think-state. The goal is to limit the rise of $\expected{T_{R}}$ with $N$.

		\item [Batch Networks] They are interactive networks with no think-time ($Z=0$). The goal is to obtain high throughput.
	\end{description}

\end{description}

%\begin{figure}[tp]
%\label{fig:Open-Network-Sample}
%	\centering
%	\includegraphics{fig/Open-Network-Sample}
%	\caption{An Open network.}
%\end{figure}

%\begin{figure}[tp]
%\label{fig:Interactive-Network-Sample}
%	\centering
%	\includegraphics{fig/Interactive-Network-Sample}
%	\caption{An Interactive network.}
%\end{figure}

%\begin{figure}[tp]
%\label{fig:Batch-Network-Sample}
%	\centering
%	\includegraphics{fig/Batch-Network-Sample}
%		\caption{A Batch network.}
%\end{figure}

\cite{schroeder2006open} proposed the notion of \textit{partly-open networks}. Here terminals arrive from outside as in open networks, but make request as in closed ones.

\subsection{Utilization}
\label{sec:Utilization}

The utilization of a queue node is the fraction of time the node is busy, the probability that it is busy, and the mean number of jobs in that node.

\begin{theorem}[Utilization Law]
\label{thm:Utilization-Law}

	For every stable queue node, we have that:

	\begin{equation}
	\label{eqn:Utilization-Law}
	\varrho = \frac{\lambda}{\mu} = X \cdot \mathbf{E}[S]
	\end{equation}

	\begin{proof}
		Let us consider the definition of throughput ($X=\frac{C}{\tau}$) and utilization ($\varrho=\frac{B}{\tau}$). We have that

		\begin{equation*}
			X = \frac{C}{\tau} = \frac{C}{B} \cdot \frac{B}{\tau} = \frac{C}{B} \cdot \varrho
		\end{equation*}

		Since $\frac{B}{C}=\expected{S}$ and $\frac{C}{B}=\mu$, we have that

		\begin{equation*}
			X = \mu \cdot \varrho \equiv \frac{\varrho}{\expected{S}} \Rightarrow \varrho = X \cdot \expected{S}
		\end{equation*}
	\end{proof}
\end{theorem}

\subsection{Stability}
\label{sec:Stability}

The stability condition guarantees that the queue cannot grow unbounded.

\begin{theorem}
\label{thm:Stability}
	A queue node is stable if and only if \footnote{The condition is necessary, but there are more complex networks (not examined here) where it is not sufficient \cite{bramson2008stability}.}

	\begin{equation}
	\label{eqn:Stability}
	\lambda < \mu
	\end{equation}

	\begin{proof}
		Let's prove that if $\lambda > \mu$ then the queue would grow to infinity over time.
		Given a time $t$, the number of system jobs $N(t)$, the number of arriving jobs $A(t)$ and the number of departing jobs $D(t)$, we have that

		\begin{equation*}
		\expected{N(t)}=\expected{A(t)}-\expected{D(t)} \geq t(\lambda - \mu)
		\end{equation*}

		where the inequality holds because the server is not always busy, then the departures at time $t$ are less than $\mu t$.
		At the end, we have that

		\begin{equation*}
		\lambda > \mu \Rightarrow \lim_{t \to \infty} \expected{N(t)} = \infty
		\end{equation*}
	\end{proof}
\end{theorem}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Carcel\Bundle\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Form type for editing user information.
 *
 * @author Damien Carcel <damien.carcel@gmail.com>
 */
class UserType extends AbstractType
{
    /** @var string */
    protected $class;

    /** @var TranslatorInterface */
    protected $translator;

    /**
     * @param TranslatorInterface $translator
     * @param string              $class
     */
    public function __construct(TranslatorInterface $translator, $class)
    {
        $this->translator = $translator;
        $this->class = $class;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'username',
            TextType::class,
            ['label' => $this->translator->trans('carcel_user.form.name.label')]
        );

        $builder->add(
            'email',
            EmailType::class,
            ['label' => $this->translator->trans('carcel_user.form.email.label')]
        );

        $builder->add(
            'submit',
            SubmitType::class,
            ['label' => $this->translator->trans('carcel_user.button.update')]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => $this->class]);
    }
}