text:
import datetime
import json

from oslo.config import cfg
import routes
import webob

import glance.api.common
import glance.common.config
import glance.context
from glance.db.sqlalchemy import api as db_api
from glance.db.sqlalchemy import models as db_models
from glance.openstack.common import timeutils
from glance.openstack.common import uuidutils
from glance.registry.api import v2 as rserver
import glance.store.filesystem
from glance.tests.unit import base
from glance.tests import utils as test_utils

CONF = cfg.CONF

_gen_uuid = uuidutils.generate_uuid

UUID1 = _gen_uuid()
UUID2 = _gen_uuid()

class TestRegistryRPC(base.IsolatedUnitTest):

    def setUp(self):
        super(TestRegistryRPC, self).setUp()
        self.mapper = routes.Mapper()
        self.api = test_utils.FakeAuthMiddleware(rserver.API(self.mapper),
                                                 is_admin=True)

        self.FIXTURES = [
            {'id': UUID1,
             'name': 'fake image #1',
             'status': 'active',
             'disk_format': 'ami',
             'container_format': 'ami',
             'is_public': False,
             'created_at': timeutils.utcnow(),
             'updated_at': timeutils.utcnow(),
             'deleted_at': None,
             'deleted': False,
             'checksum': None,
             'min_disk': 0,
             'min_ram': 0,
             'size': 13,
             'locations': [{'url': "file:///%s/%s" % (self.test_dir, UUID1),
                            'metadata': {}}],
             'properties': {'type': 'kernel'}},
            {'id': UUID2,
             'name': 'fake image #2',
             'status': 'active',
             'disk_format': 'vhd',
             'container_format': 'ovf',
             'is_public': True,
             'created_at': timeutils.utcnow(),
             'updated_at': timeutils.utcnow(),
             'deleted_at': None,
             'deleted': False,
             'checksum': None,
             'min_disk': 5,
             'min_ram': 256,
             'size': 19,
             'locations': [{'url': "file:///%s/%s" % (self.test_dir, UUID2),
                            'metadata': {}}],
             'properties': {}}]

        self.context = glance.context.RequestContext(is_admin=True)
        db_api.setup_db_env()
        db_api.get_engine()
        self.destroy_fixtures()
        self.create_fixtures()

    def tearDown(self):
        """Clear the test environment"""
        super(TestRegistryRPC, self).tearDown()
        self.destroy_fixtures()

    def create_fixtures(self):
        for fixture in self.FIXTURES:
            db_api.image_create(self.context, fixture)
            # We write a fake image file to the filesystem
            with open("%s/%s" % (self.test_dir, fixture['id']), 'wb') as image:
                image.write("chunk00000remainder")
                image.flush()

    def destroy_fixtures(self):
        # Easiest to just drop the models and re-create them...
        db_models.unregister_models(db_api._ENGINE)
        db_models.register_models(db_api._ENGINE)

    def test_show(self):
        """
        Tests that registry API endpoint
        returns the expected image
        """
        fixture = {'id': UUID2,
                   'name': 'fake image #2',
                   'size': 19,
                   'min_ram': 256,
                   'min_disk': 5,
                   'checksum': None}
        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get',
            'kwargs': {'image_id': UUID2},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]
        image = res_dict
        for k, v in fixture.iteritems():
            self.assertEquals(v, image[k])

    def test_show_unknown(self):
        """
        Tests that the registry API endpoint
        returns a 404 for an unknown image id
        """
        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get',
            'kwargs': {'image_id': _gen_uuid()},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res_dict["_error"]["cls"],
                          'glance.common.exception.NotFound')

    def test_get_index(self):
        """
        Tests that the image_get_all command returns list of
        images
        """
        fixture = {'id': UUID2,
                   'name': 'fake image #2',
                   'size': 19,
                   'checksum': None}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'filters': fixture},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 1)

        for k, v in fixture.iteritems():
            self.assertEquals(v, images[0][k])

    def test_get_index_marker(self):
        """
        Tests that the registry API returns list of
        public images that conforms to a marker query param
        """
        time1 = timeutils.utcnow() + datetime.timedelta(seconds=5)
        time2 = timeutils.utcnow() + datetime.timedelta(seconds=4)
        time3 = timeutils.utcnow()

        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None,
                         'created_at': time1}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': time2}

        db_api.image_create(self.context, extra_fixture)

        UUID5 = _gen_uuid()
        extra_fixture = {'id': UUID5,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': time3}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID4, "is_public": True},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        images = json.loads(res.body)[0]
        # should be sorted by created_at desc, id desc
        # page should start after marker 4
        self.assertEquals(len(images), 2)
        self.assertEquals(images[0]['id'], UUID5)
        self.assertEquals(images[1]['id'], UUID2)

    def test_get_index_marker_and_name_asc(self):
        """Test marker and null name ascending

        Tests that the registry API returns 200
        when a marker and a null name are combined
        ascending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': None,
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'name',
                       'sort_dir': 'asc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 2)

    def test_get_index_marker_and_name_desc(self):
        """Test marker and null name descending

        Tests that the registry API returns 200
        when a marker and a null name are combined
        descending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': None,
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'name',
                       'sort_dir': 'desc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 0)

    def test_get_index_marker_and_disk_format_asc(self):
        """Test marker and null disk format ascending

        Tests that the registry API returns 200
        when a marker and a null disk_format are combined
        ascending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': None,
                         'container_format': 'ovf',
                         'name': 'Fake image',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'disk_format',
                       'sort_dir': 'asc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 2)

    def test_get_index_marker_and_disk_format_desc(self):
        """Test marker and null disk format descending

        Tests that the registry API returns 200
        when a marker and a null disk_format are combined
        descending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': None,
                         'container_format': 'ovf',
                         'name': 'Fake image',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'disk_format',
                       'sort_dir': 'desc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 0)

    def test_get_index_marker_and_container_format_asc(self):
        """Test marker and null container format ascending

        Tests that the registry API returns 200
        when a marker and a null container_format are combined
        ascending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': None,
                         'name': 'Fake image',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'container_format',
                       'sort_dir': 'asc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 2)

    def test_get_index_marker_and_container_format_desc(self):
        """Test marker and null container format descending

        Tests that the registry API returns 200
        when a marker and a null container_format are combined
        descending order
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': None,
                         'name': 'Fake image',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'sort_key': 'container_format',
                       'sort_dir': 'desc'},
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        images = json.loads(res.body)[0]
        self.assertEquals(len(images), 0)

    def test_get_index_unknown_marker(self):
        """
        Tests that the registry API returns a NotFound
        when an unknown marker is provided
        """
        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': _gen_uuid()},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        result = json.loads(res.body)[0]

        self.assertIn("_error", result)
        self.assertIn("NotFound", result["_error"]["cls"])

    def test_get_index_limit(self):
        """
        Tests that the registry API returns list of
        public images that conforms to a limit query param
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'limit': 1},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        images = res_dict
        self.assertEquals(len(images), 1)

        # expect list to be sorted by created_at desc
        self.assertEqual(images[0]['id'], UUID4)

    def test_get_index_limit_marker(self):
        """
        Tests that the registry API returns list of
        public images that conforms to limit and marker query params
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        extra_fixture = {'id': _gen_uuid(),
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'marker': UUID3, 'limit': 1},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        images = res_dict
        self.assertEquals(len(images), 1)

        # expect list to be sorted by created_at desc
        self.assertEqual(images[0]['id'], UUID2)

    def test_get_index_filter_name(self):
        """
        Tests that the registry API returns list of
        public images that have a specific name. This is really a sanity
        check, filtering is tested more in-depth using /images/detail
        """
        extra_fixture = {'id': _gen_uuid(),
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        extra_fixture = {'id': _gen_uuid(),
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'filters': {'name': 'new name! #123'}},
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        images = res_dict
        self.assertEquals(len(images), 2)

        for image in images:
            self.assertEqual('new name! #123', image['name'])

    def test_get_index_sort_default_created_at_desc(self):
        """
        Tests that the registry API returns list of
        public images that conforms to a default sort key/dir
        """
        time1 = timeutils.utcnow() + datetime.timedelta(seconds=5)
        time2 = timeutils.utcnow() + datetime.timedelta(seconds=4)
        time3 = timeutils.utcnow()

        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None,
                         'created_at': time1}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': time2}

        db_api.image_create(self.context, extra_fixture)

        UUID5 = _gen_uuid()
        extra_fixture = {'id': UUID5,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': time3}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        images = res_dict
        # (flaper87)registry's v1 forced is_public to True
        # when no value was specified. This is not
        # the default behaviour anymore.
        self.assertEquals(len(images), 5)
        self.assertEquals(images[0]['id'], UUID3)
        self.assertEquals(images[1]['id'], UUID4)
        self.assertEquals(images[2]['id'], UUID5)
        self.assertEquals(images[3]['id'], UUID2)
        self.assertEquals(images[4]['id'], UUID1)

    def test_get_index_sort_name_asc(self):
        """
        Tests that the registry API returns list of
        public images sorted alphabetically by name in
        ascending order.
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'asdf',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'xyz',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)
        UUID5 = _gen_uuid()
        extra_fixture = {'id': UUID5,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': None,
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'name', 'sort_dir': 'asc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 5)
        self.assertEquals(images[0]['id'], UUID5)
        self.assertEquals(images[1]['id'], UUID3)
        self.assertEquals(images[2]['id'], UUID1)
        self.assertEquals(images[3]['id'], UUID2)
        self.assertEquals(images[4]['id'], UUID4)

    def test_get_index_sort_status_desc(self):
        """
        Tests that the registry API returns list of
        public images sorted alphabetically by status in
        descending order.
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'queued',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'asdf',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'xyz',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'status', 'sort_dir': 'asc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID1)
        self.assertEquals(images[1]['id'], UUID2)
        self.assertEquals(images[2]['id'], UUID4)
        self.assertEquals(images[3]['id'], UUID3)

    def test_get_index_sort_disk_format_asc(self):
        """
        Tests that the registry API returns list of
        public images sorted alphabetically by disk_format in
        ascending order.
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'ami',
                         'container_format': 'ami',
                         'name': 'asdf',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vdi',
                         'container_format': 'ovf',
                         'name': 'xyz',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'disk_format', 'sort_dir': 'asc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID1)
        self.assertEquals(images[1]['id'], UUID3)
        self.assertEquals(images[2]['id'], UUID4)
        self.assertEquals(images[3]['id'], UUID2)

    def test_get_index_sort_container_format_desc(self):
        """
        Tests that the registry API returns list of
        public images sorted alphabetically by container_format in
        descending order.
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'ami',
                         'container_format': 'ami',
                         'name': 'asdf',
                         'size': 19,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'iso',
                         'container_format': 'bare',
                         'name': 'xyz',
                         'size': 20,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'container_format',
                       'sort_dir': 'desc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID2)
        self.assertEquals(images[1]['id'], UUID4)
        self.assertEquals(images[2]['id'], UUID3)
        self.assertEquals(images[3]['id'], UUID1)

    def test_get_index_sort_size_asc(self):
        """
        Tests that the registry API returns list of
        public images sorted by size in ascending order.
        """
        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'ami',
                         'container_format': 'ami',
                         'name': 'asdf',
                         'size': 100,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'iso',
                         'container_format': 'bare',
                         'name': 'xyz',
                         'size': 2,
                         'checksum': None}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'size',
                       'sort_dir': 'asc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID4)
        self.assertEquals(images[1]['id'], UUID1)
        self.assertEquals(images[2]['id'], UUID2)
        self.assertEquals(images[3]['id'], UUID3)

    def test_get_index_sort_created_at_asc(self):
        """
        Tests that the registry API returns list of
        public images sorted by created_at in ascending order.
        """
        now = timeutils.utcnow()
        time1 = now + datetime.timedelta(seconds=5)
        time2 = now

        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None,
                         'created_at': time1}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': time2}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'created_at',
                       'sort_dir': 'asc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID1)
        self.assertEquals(images[1]['id'], UUID2)
        self.assertEquals(images[2]['id'], UUID4)
        self.assertEquals(images[3]['id'], UUID3)

    def test_get_index_sort_updated_at_desc(self):
        """
        Tests that the registry API returns list of
        public images sorted by updated_at in descending order.
        """
        now = timeutils.utcnow()
        time1 = now + datetime.timedelta(seconds=5)
        time2 = now

        UUID3 = _gen_uuid()
        extra_fixture = {'id': UUID3,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 19,
                         'checksum': None,
                         'created_at': None,
                         'updated_at': time1}

        db_api.image_create(self.context, extra_fixture)

        UUID4 = _gen_uuid()
        extra_fixture = {'id': UUID4,
                         'status': 'active',
                         'is_public': True,
                         'disk_format': 'vhd',
                         'container_format': 'ovf',
                         'name': 'new name! #123',
                         'size': 20,
                         'checksum': None,
                         'created_at': None,
                         'updated_at': time2}

        db_api.image_create(self.context, extra_fixture)

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'sort_key': 'updated_at',
                       'sort_dir': 'desc'}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)
        res_dict = json.loads(res.body)[0]

        images = res_dict
        self.assertEquals(len(images), 4)
        self.assertEquals(images[0]['id'], UUID3)
        self.assertEquals(images[1]['id'], UUID4)
        self.assertEquals(images[2]['id'], UUID2)
        self.assertEquals(images[3]['id'], UUID1)

    def test_create_image(self):
        """Tests that the registry API creates the image"""
        fixture = {'name': 'fake public image',
                   'status': 'active',
                   'is_public': True,
                   'disk_format': 'vhd',
                   'container_format': 'ovf'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_create',
            'kwargs': {'values': fixture}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)

        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        for k, v in fixture.iteritems():
            self.assertEquals(v, res_dict[k])

        # Test status was updated properly
        self.assertEquals('active', res_dict['status'])

    def test_create_image_with_min_disk(self):
        """Tests that the registry API creates the image"""
        fixture = {'name': 'fake public image',
                   'is_public': True,
                   'status': 'active',
                   'min_disk': 5,
                   'disk_format': 'vhd',
                   'container_format': 'ovf'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_create',
            'kwargs': {'values': fixture}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        self.assertEquals(5, res_dict['min_disk'])

    def test_create_image_with_min_ram(self):
        """Tests that the registry API creates the image"""
        fixture = {'name': 'fake public image',
                   'is_public': True,
                   'status': 'active',
                   'min_ram': 256,
                   'disk_format': 'vhd',
                   'container_format': 'ovf'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_create',
            'kwargs': {'values': fixture}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        self.assertEquals(256, res_dict['min_ram'])

    def test_create_image_with_min_ram_default(self):
        """Tests that the registry API creates the image"""
        fixture = {'name': 'fake public image',
                   'status': 'active',
                   'is_public': True,
                   'disk_format': 'vhd',
                   'container_format': 'ovf'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_create',
            'kwargs': {'values': fixture}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        self.assertEquals(0, res_dict['min_ram'])

    def test_create_image_with_min_disk_default(self):
        """Tests that the registry API creates the image"""
        fixture = {'name': 'fake public image',
                   'status': 'active',
                   'is_public': True,
                   'disk_format': 'vhd',
                   'container_format': 'ovf'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_create',
            'kwargs': {'values': fixture}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        self.assertEquals(0, res_dict['min_disk'])

    def test_update_image(self):
        """Tests that the registry API updates the image"""
        fixture = {'name': 'fake public image #2',
                   'min_disk': 5,
                   'min_ram': 256,
                   'disk_format': 'raw'}

        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_update',
            'kwargs': {'values': fixture,
                       'image_id': UUID2}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        res_dict = json.loads(res.body)[0]

        self.assertNotEquals(res_dict['created_at'],
                             res_dict['updated_at'])

        for k, v in fixture.iteritems():
            self.assertEquals(v, res_dict[k])

    def test_delete_image(self):
        """Tests that the registry API deletes the image"""

        # Grab the original number of images
        req = webob.Request.blank('/rpc')
        req.method = "POST"
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'filters': {'deleted': False}}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        orig_num_images = len(res_dict)

        # Delete image #2
        cmd = [{
            'command': 'image_destroy',
            'kwargs': {'image_id': UUID2}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        # Verify one less image
        cmd = [{
            'command': 'image_get_all',
            'kwargs': {'filters': {'deleted': False}}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)
        res_dict = json.loads(res.body)[0]
        self.assertEquals(res.status_int, 200)

        new_num_images = len(res_dict)
        self.assertEquals(new_num_images, orig_num_images - 1)

    def test_delete_image_response(self):
        """Tests that the registry API delete returns the image metadata"""

        image = self.FIXTURES[0]
        req = webob.Request.blank('/rpc')
        req.method = 'POST'
        cmd = [{
            'command': 'image_destroy',
            'kwargs': {'image_id': image['id']}
        }]
        req.body = json.dumps(cmd)
        res = req.get_response(self.api)

        self.assertEquals(res.status_int, 200)
        deleted_image = json.loads(res.body)[0]

        self.assertEquals(image['id'], deleted_image['id'])
        self.assertTrue(deleted_image['deleted'])
        self.assertTrue(deleted_image['deleted_at'])

    def test_get_image_members(self):
        """
        Tests members listing for existing images
        """
        req = webob.Request.blank('/rpc')
        req.method = 'POST'
        cmd = [{
            'command': 'image_member_find',
            'kwargs': {'image_id': UUID2}
        }]
        req.body = json.dumps(cmd)

        res = req.get_response(self.api)
        self.assertEquals(res.status_int, 200)

        memb_list = json.loads(res.body)[0]
        self.assertEquals(len(memb_list), 0)

class TestRegistryRPCDBPoolEnabled(TestRegistryRPC):
    def setUp(self):
        CONF.set_override('use_tpool', True)
        super(TestRegistryRPCDBPoolEnabled, self).setUp()

    def tearDown(self):
        super(TestRegistryRPCDBPoolEnabled, self).tearDown()
        CONF.set_override('use_tpool', False)


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteInEditMode]
public class IPSpritePicker : IPPickerSpriteBase {

	public List < string > spriteNames;

	public bool 	normalizeSprites = true;
	public float 	normalizedMax = 50f;
	public int 		initIndex;

	public string CurrentSpriteName
	{
		get;
		private set;
	}

	public void ResetPickerAtContentIndex ( int index )
	{
		ResetPickerAtIndex ( index );
	}

	public void InsertElement ( string spriteName )
	{
		InsertElementAtIndex ( spriteName, _selectedIndex, true );
	}

	public void InsertElementAtIndex ( string spriteName, int index, bool resetPicker = true )
	{
		spriteNames.Insert ( index, spriteName );
		if ( resetPicker )
			ResetPickerAtIndex ( _selectedIndex );
	}

	public void RemoveElementAtIndex ( int index, bool resetPicker = true )
	{
		if ( _nbOfVirtualElements == 0 )
		{
			return;
		}
		spriteNames.RemoveAt ( index );
		if ( resetPicker )
			ResetPickerAtIndex ( IPTools.GetSelectedIndexAfterRemoveElement ( index, _selectedIndex, _nbOfVirtualElements - 1 ) );
	}

	#region compulsory_overrides

	protected override int GetInitIndex ()
	{
		return initIndex;
	}

	protected override void UpdateCurrentValue ()
	{
		CurrentSpriteName = spriteNames[_selectedIndex];
	}

	public override void UpdateWidget ( int widgetIndex, int contentIndex )
	{
		uiSprites[widgetIndex].spriteName = spriteNames[contentIndex];
		if ( normalizeSprites )
			IPTools.NormalizeWidget ( uiSprites[widgetIndex], normalizedMax );
	}

	public override void UpdateVirtualElementsCount ()
	{
		_nbOfVirtualElements = spriteNames == null ? 0 : spriteNames.Count;
	}

	#endregion
}

redpajama_set_name: RedPajamaGithub


text:
/*
    Leola Programming Language
    Author: Tony Sparks
    See license.txt
*/
package leola.vm.types;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.DecimalFormat;

import leola.vm.util.ClassUtil;

/**
 * Represents a double float precision number
 *
 * @author Tony
 *
 */
public class LeoDouble extends LeoObject {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat
        ("############################################.###############################");
    private static final int CACHE_SIZE = 512;
    private static final int NCACHE_SIZE = CACHE_SIZE / 2;
    private static final LeoDouble[] CACHE = new LeoDouble[CACHE_SIZE];
    static {
        for(int i = 0; i < CACHE_SIZE; i++) {
            CACHE[i] = new LeoDouble(i - NCACHE_SIZE);
        }
    }

    /**
     * Creates a {@link LeoDouble}
     *
     * @param number
     * @return
     */
    public static LeoDouble valueOf(Double number) {
        return valueOf(number.doubleValue());
    }

    /**
     * Creates a {@link LeoDouble}
     * @param number
     * @return
     */
    public static LeoDouble valueOf(double number) {
        int n = (int)number;
        if ( n == number ) {
            if ( number < NCACHE_SIZE && n >= -NCACHE_SIZE ) {
                return CACHE[ n + NCACHE_SIZE ];
            }
        }

        return new LeoDouble(number);
    }

    public static LeoDouble valueOf(float number) {
        return valueOf((double)number);
    }

    public static LeoDouble valueOf(int number) {
        if ( number < NCACHE_SIZE && number > -NCACHE_SIZE ) {
            return CACHE[ number + NCACHE_SIZE ];
        }

        return new LeoDouble(number);
    }

    /**
     * Number
     */
    private double number;

    /**
     * @param number
     */
    private LeoDouble(double number) {
        super(LeoType.REAL);
        this.number = number;
    }

    /* (non-Javadoc)
     * @see leola.vm.types.LeoObject#hashCode()
     */
    @Override
    public int hashCode() {
//        return Double.hashCode(this.number);
        long bits = Double.doubleToLongBits(this.number);
        return (int)(bits ^ (bits >>> 32));
    }

    /**
     * @return the number
     */
    public double getNumber() {
        return number;
    }

    @Override
    public int asInt() {
        return (int)this.number;
    }

    @Override
    public double asDouble() {
        return this.number;
    }

    @Override
    public long asLong() {
        return (long)this.number;
    }

    @Override
    public float asFloat() {
        return (float)this.number;
    }

    @Override
    public byte asByte() {
        return (byte)this.number;
    }

    @Override
    public short asShort() {
        return (short)this.number;
    }

    @Override
    public char asChar() {
        return (char)this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#isNumber()
     */
    @Override
    public boolean isNumber() {
        return true;
    }

    /* (non-Javadoc)
     * @see leola.vm.types.LeoObject#isTrue()
     */
    @Override
    public boolean isTrue() {
        return this.number != 0;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#toString()
     */
    @Override
    public String toString() {
        return DECIMAL_FORMAT.format(this.number);
//        return Double.toString(this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#getValue()
     */
    @Override
    public Object getValue() {
        return this.number;
    }

    /* (non-Javadoc)
     * @see leola.vm.types.LeoObject#getValue(java.lang.Class)
     */
    @Override
    public Object getValue(Class<?> type) {
        if ( ClassUtil.isType(type, ClassUtil.FLOAT) ){
            return (float)this.number;
        }
        else if ( ClassUtil.isType(type, ClassUtil.DOUBLE) ){
            return this.number;
        }
        else if(ClassUtil.inheritsFrom(type, LeoObject.class) ) {
            return this;
        }
        else if ( ClassUtil.isType(type, ClassUtil.BYTE) ){
            return (byte)this.number;
        }
        else if ( ClassUtil.isType(type, ClassUtil.CHAR) ){
            return (char)this.number;
        }
        else if ( ClassUtil.isType(type, ClassUtil.SHORT) ){
            return (short)this.number;
        }
        else if ( ClassUtil.isType(type, ClassUtil.INT) ){
            return (int)this.number;
        }

        else if ( ClassUtil.isType(type, ClassUtil.LONG) ){
            return (long)this.number;
        }
        else if ( ClassUtil.isType(type, ClassUtil.STRING) ){
            return this.number + "";
        }

        return this.number;
    }

    @Override
    public boolean isAssignable(Class<?> javaType) {
        if(javaType.isPrimitive()) {
            javaType = ClassUtil.primitiveToWrapper(javaType);
        }
        return Number.class.isAssignableFrom(javaType);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#clone()
     */
    @Override
    public LeoObject clone() {
        return this;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#eq(leola.types.LeoObject)
     */
    @Override
    public boolean $eq(LeoObject other) {
        return other.$eq(this.number);
    }
    @Override
    public boolean $eq(double other) {
        return other == this.number;
    }
    @Override
    public boolean $eq(int other) {
        return other == this.number;
    }
    @Override
    public boolean $eq(long other) {
        return other == this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#gt(leola.types.LeoObject)
     */

    @Override
    public boolean $gt(LeoObject other) {
        return other.$gt(this.number);
    }
    @Override
    public boolean $gt(double other) {
        return other > this.number;
    }
    @Override
    public boolean $gt(int other) {
        return other > this.number;
    }
    @Override
    public boolean $gt(long other) {
        return other > this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#lt(leola.types.LeoObject)
     */
    @Override
    public boolean $lt(LeoObject other) {
        return other.$lt(this.number);
    }
    @Override
    public boolean $lt(double other) {
        return other < this.number;
    }
    @Override
    public boolean $lt(int other) {
        return other < this.number;
    }
    @Override
    public boolean $lt(long other) {
        return other < this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#gte(leola.types.LeoObject)
     */
    @Override
    public boolean $gte(LeoObject other) {
        return other.$gte(this.number);
    }
    @Override
    public boolean $gte(double other) {
        return other >= this.number;
    }
    @Override
    public boolean $gte(int other) {
        return other >= this.number;
    }
    @Override
    public boolean $gte(long other) {
        return other >= this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#lte(leola.types.LeoObject)
     */
    @Override
    public boolean $lte(LeoObject other) {
        return other.$lte(this.number);
    }
    @Override
    public boolean $lte(double other) {
        return other <= this.number;
    }
    @Override
    public boolean $lte(int other) {
        return other <= this.number;
    }
    @Override
    public boolean $lte(long other) {
        return other <= this.number;
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#add(leola.types.LeoObject)
     */
    @Override
    public LeoObject $add(LeoObject other) {
        return other.$add(this.number);
    }
    @Override
    public LeoObject $add(double other) {
        return LeoDouble.valueOf(other + this.number);
    }
    @Override
    public LeoObject $add(int other) {
        return LeoDouble.valueOf(other + this.number);
    }
    @Override
    public LeoObject $add(long other) {
        return LeoDouble.valueOf(other + this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#sub(leola.types.LeoObject)
     */
    @Override
    public LeoObject $sub(LeoObject other) {
        return other.$sub(this.number);
    }
    @Override
    public LeoObject $sub(double other) {
        return LeoDouble.valueOf(other - this.number);
    }
    @Override
    public LeoObject $sub(int other) {
        return LeoDouble.valueOf(other - this.number);
    }
    @Override
    public LeoObject $sub(long other) {
        return LeoDouble.valueOf(other - this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#mul(leola.types.LeoObject)
     */
    @Override
    public LeoObject $mul(LeoObject other) {
        return other.$mul(this.number);
    }
    @Override
    public LeoObject $mul(double other) {
        return LeoDouble.valueOf(other * this.number);
    }
    @Override
    public LeoObject $mul(int other) {
        return LeoDouble.valueOf(other * this.number);
    }
    @Override
    public LeoObject $mul(long other) {
        return LeoDouble.valueOf(other * this.number);
    }
    /* (non-Javadoc)
     * @see leola.types.LeoObject#div(leola.types.LeoObject)
     */
    @Override
    public LeoObject $div(LeoObject other) {
        return other.$div(this.number);
    }
    @Override
    public LeoObject $div(double other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other / this.number);
    }
    @Override
    public LeoObject $div(int other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other / this.number);
    }
    @Override
    public LeoObject $div(long other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other / this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#mod(leola.types.LeoObject)
     */
    @Override
    public LeoObject $mod(LeoObject other) {
        return other.$mod(this.number);
    }
    @Override
    public LeoObject $mod(double other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other % this.number);
    }
    @Override
    public LeoObject $mod(int other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other % this.number);
    }
    @Override
    public LeoObject $mod(long other) {
        if ( number == 0 ) {
            throwDivideByZeroError();
        }
        return LeoDouble.valueOf(other % this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#neg()
     */
    @Override
    public LeoObject $neg() {
        return LeoDouble.valueOf(-this.number);
    }
    @Override
    public LeoObject $bnot() {
        LeoObject result = LeoInteger.valueOf( ~(int)this.number );
        return result;
    }

    @Override
    public LeoObject $bsl(LeoObject other) {
        return other.$bsl(this.number);
    }
    @Override
    public LeoObject $bsl(double other) {
        return LeoInteger.valueOf((int)other << (int)this.number);
    }
    @Override
    public LeoObject $bsl(int other) {
        return LeoInteger.valueOf(other << (int)this.number);
    }
    @Override
    public LeoObject $bsl(long other) {
        return LeoLong.valueOf(other << (int)this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#bsr(leola.types.LeoObject)
     */
    @Override
    public LeoObject $bsr(LeoObject other) {
        return other.$bsr(this.number);
    }
    @Override
    public LeoObject $bsr(double other) {
        return LeoInteger.valueOf((int)other >> (int)this.number);
    }
    @Override
    public LeoObject $bsr(int other) {
        return LeoInteger.valueOf(other >> (int)this.number);
    }
    @Override
    public LeoObject $bsr(long other) {
        return LeoLong.valueOf(other >> (int)this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#xor(leola.types.LeoObject)
     */
    @Override
    public LeoObject $xor(LeoObject other) {
        return other.$xor(this.number);
    }
    @Override
    public LeoObject $xor(double other) {
        return LeoInteger.valueOf((int)other ^ (int)this.number);
    }
    @Override
    public LeoObject $xor(int other) {
        return LeoInteger.valueOf(other ^ (int)this.number);
    }
    @Override
    public LeoObject $xor(long other) {
        return LeoLong.valueOf(other ^ (int)this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#lor(leola.types.LeoObject)
     */
    @Override
    public LeoObject $bor(LeoObject other) {
        return other.$bor(this.number);
    }
    @Override
    public LeoObject $bor(double other) {
        return LeoInteger.valueOf((int)other | (int)this.number);
    }
    @Override
    public LeoObject $bor(int other) {
        return LeoInteger.valueOf(other | (int)this.number);
    }
    @Override
    public LeoObject $bor(long other) {
        return LeoLong.valueOf(other | (int)this.number);
    }

    /* (non-Javadoc)
     * @see leola.types.LeoObject#land(leola.types.LeoObject)
     */
    @Override
    public LeoObject $band(LeoObject other) {
        return other.$band(this.number);
    }
    @Override
    public LeoObject $band(double other) {
        return LeoInteger.valueOf((int)other & (int)this.number);
    }
    @Override
    public LeoObject $band(int other) {
        return LeoInteger.valueOf(other & (int)this.number);
    }
    @Override
    public LeoObject $band(long other) {
        return LeoLong.valueOf(other & (int)this.number);
    }

    @Override
    public void write(DataOutput out) throws IOException {
        out.write(this.getType().ordinal());
        out.writeDouble(this.number);
    }

    /**
     * Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
     *
     * @param in
     * @return the {@link LeoObject}
     * @throws IOException
     */
    public static LeoDouble read(DataInput in) throws IOException {
        double number = in.readDouble();
        return LeoDouble.valueOf(number);
    }
}


text:
type Proxy$traps<T> = {
  getPrototypeOf?: (target: T) => ?Object;
  setPrototypeOf?: (target: T, prototype: ?Object) => boolean;
  isExtensible?: (target: T) => boolean;
  preventExtensions?: (target: T) => boolean;
  getOwnPropertyDescriptor?: (target: T, property: string) => void | Object;
  defineProperty?: (target: T, property: string, descriptor: Object) => boolean;
  has?: (target: T, key: string) => boolean;
  get?: (target: T, property: string, reciever: Proxy<T>) => any;
  set?: (target: T, property: string, value: any, receiver: Proxy<T>) => boolean;
  deleteProperty?: (target: T, property: string) => boolean;
  ownKeys?: (target: T) => Array<string>;
  apply?: (target: T, context: any, args: Array<any>) => any;
  construct?: (target: T, args: Array<any>, newTarget: Function) => Object;
};

type Proxy$revocable<T> = T & {
  revoke(): void;
};

declare class Proxy<T> {
  constructor(target: T, handler: Proxy$traps<T>): T;

  static revocable(target: T, handler: Proxy$traps<T>): Proxy$revocable<T>;
}


text:
const DrawCard = require('../../../drawcard.js');
const AbilityLimit = require('../../../abilitylimit.js');

class XaroXhoanDaxos extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            when: {
                onCardEntersPlay: (event, card) => card.getType() === 'attachment' && card.isUnique() && this.game.currentPhase === 'marshal'
            },
            limit: AbilityLimit.perPhase(1),
            handler: () => {
                this.game.addGold(this.controller, 2);
                this.game.addMessage('{0} uses {1} to gain 2 gold as a unique attachment has been marshalled', this.controller, this);
            }
        });
    }
}

XaroXhoanDaxos.code = '04093';

module.exports = XaroXhoanDaxos;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pseudocyphellaria multipartita Vain.

### Remarks
null


text:
rg=dcosworkshop
acsname=myDCOSCluster

# create resource group
az group create --name  $rg --location canadacentral

# create dcos with generate keys
#az acs create --orchestrator-type dcos --resource-group $rg --name  $acsname --generate-ssh-keys --agent-count 1

# create dcos with predefined keys
az acs create --orchestrator-type dcos --resource-group $rg --name  $acsname --ssh-key-value ~/.ssh/id_rsa.pub --agent-count 1


text:
layout: meetingrss
type: rss
sitemap: false
lang: zh_CN
permalink: /zh_CN/meetingrss.xml
---


text:
'use strict';

const expect = require('chai').expect;
const RSVP = require('rsvp');
const request = RSVP.denodeify(require('request'));

const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;

describe('FastBootLocation Configuration', function () {
  this.timeout(300000);

  let app;

  before(function () {
    app = new AddonTestApp();

    return app
      .create('fastboot-location-config', {
        skipNpm: true,
        emberVersion: 'latest',
        emberDataVersion: 'latest',
      })
      .then(function () {
        app.editPackageJSON((pkg) => {
          delete pkg.devDependencies['ember-fetch'];
          delete pkg.devDependencies['ember-welcome-page'];
        });
        return app.run('npm', 'install');
      })
      .then(function () {
        return app.startServer({
          command: 'serve',
        });
      });
  });

  after(function () {
    return app.stopServer();
  });

  it('should use the redirect code provided by the EmberApp', function () {
    return request({
      url: 'http://localhost:49741/redirect-on-transition-to',
      followRedirect: false,
      headers: {
        Accept: 'text/html',
      },
    }).then(function (response) {
      if (response.statusCode === 500) throw new Error(response.body);
      expect(response.statusCode).to.equal(302);
      expect(response.headers.location).to.equal(
        '//localhost:49741/test-passed'
      );
    });
  });

  describe('when fastboot.fastbootHeaders is false', function () {
    it('should not send the "x-fastboot-path" header on a redirect', function () {
      return request({
        url: 'http://localhost:49741/redirect-on-transition-to',
        followRedirect: false,
        headers: {
          Accept: 'text/html',
        },
      }).then(function (response) {
        if (response.statusCode === 500) throw new Error(response.body);
        expect(response.headers).to.not.include.keys(['x-fastboot-path']);
      });
    });
  });
});


text:
#
#
# /* Revised by Paul Mensonides (2002) */
#
# ifndef BOOST_PREPROCESSOR_LIST_ADT_HPP
# define BOOST_PREPROCESSOR_LIST_ADT_HPP
#
# include <cutl/details/boost/preprocessor/config/config.hpp>
# include <cutl/details/boost/preprocessor/detail/is_binary.hpp>
# include <cutl/details/boost/preprocessor/logical/compl.hpp>
# include <cutl/details/boost/preprocessor/tuple/eat.hpp>
#
# /* BOOST_PP_LIST_CONS */
#
# define BOOST_PP_LIST_CONS(head, tail) (head, tail)
#
# /* BOOST_PP_LIST_NIL */
#
# define BOOST_PP_LIST_NIL BOOST_PP_NIL
#
# /* BOOST_PP_LIST_FIRST */
#
# define BOOST_PP_LIST_FIRST(list) BOOST_PP_LIST_FIRST_D(list)
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
#    define BOOST_PP_LIST_FIRST_D(list) BOOST_PP_LIST_FIRST_I list
# else
#    define BOOST_PP_LIST_FIRST_D(list) BOOST_PP_LIST_FIRST_I ## list
# endif
#
# define BOOST_PP_LIST_FIRST_I(head, tail) head
#
# /* BOOST_PP_LIST_REST */
#
# define BOOST_PP_LIST_REST(list) BOOST_PP_LIST_REST_D(list)
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
#    define BOOST_PP_LIST_REST_D(list) BOOST_PP_LIST_REST_I list
# else
#    define BOOST_PP_LIST_REST_D(list) BOOST_PP_LIST_REST_I ## list
# endif
#
# define BOOST_PP_LIST_REST_I(head, tail) tail
#
# /* BOOST_PP_LIST_IS_CONS */
#
# if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_BCC()
#    define BOOST_PP_LIST_IS_CONS(list) BOOST_PP_LIST_IS_CONS_D(list)
#    define BOOST_PP_LIST_IS_CONS_D(list) BOOST_PP_LIST_IS_CONS_ ## list
#    define BOOST_PP_LIST_IS_CONS_(head, tail) 1
#    define BOOST_PP_LIST_IS_CONS_BOOST_PP_NIL 0
# else
#    define BOOST_PP_LIST_IS_CONS(list) BOOST_PP_IS_BINARY(list)
# endif
#
# /* BOOST_PP_LIST_IS_NIL */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_BCC()
#    define BOOST_PP_LIST_IS_NIL(list) BOOST_PP_COMPL(BOOST_PP_IS_BINARY(list))
# else
#    define BOOST_PP_LIST_IS_NIL(list) BOOST_PP_COMPL(BOOST_PP_LIST_IS_CONS(list))
# endif
#
# endif


text:
var app = angular.module('amp', ['ui.bootstrap', 'ngAnimate']);

app.controller('NavCtrl', function ($scope, $uibModal, $log) {

  $scope.open = function () {

    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'ContactUs',
      controller: 'CUCtrl',
    });

    modalInstance.result.then(function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };

});

app.controller('CUCtrl', function ($scope, $modalInstance) {
  $scope.name;
  $scope.email;
  $scope.subject;
  $scope.message;

  $scope.cover = true;

  $scope.submit = function (form) {

    if (form.$invalid) {
      console.log("INVALID");
      $scope.cover = false;
    }

    if(form.$valid){

    var link = "mailto:csmith@parkland.edu"
             // + "?cc=myCCaddress@example.com"
             + "?subject=" + escape($scope.subject)
             + "&body=" + escape($scope.message + "\n --From: " + $scope.name
                                  + "\n --Email: " + $scope.email);

    window.location.href = link;
   }

  }

  $scope.ok = function (form) {
    if (form.$invalid) {
      console.log("INVALID");
      $scope.cover = false;
    }

    if(form.$valid){
      $modalInstance.close();
   }
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

app.controller('PortCtrl', function ($scope){

  $scope.projects = [
    {name:'Wesley Food Pantry',
    info:'Wesley Food Pantry asked AMP to update their logo and raise awareness of \
     their new satellite location on Parkland\'s campus.\
      AMP created print and digital advertising material, updated social media graphics,\
       and wrote a radio public service announcement.',
    img:'http://lorempixel.com/280/180/abstract/'},

    {name:'Illinois Radio Reader',
    info:'Wesley Food Pantry asked AMP to update their logo and raise awareness of \
     their new satellite location on Parkland\'s campus.\
      AMP created print and digital advertising material, updated social media graphics,\
       and wrote a radio public service announcement.',
    img:'http://lorempixel.com/280/180/abstract/'},

    {name:'The Bottom Line Diaper Bank',
    info:'Wesley Food Pantry asked AMP to update their logo and raise awareness of \
     their new satellite location on Parkland\'s campus.\
      AMP created print and digital advertising material, updated social media graphics,\
       and wrote a radio public service announcement.',
    img:'http://lorempixel.com/280/180/abstract/'},

    {name:'The Presentation Center at Parkland College',
    info:'Wesley Food Pantry asked AMP to update their logo and raise awareness of \
     their new satellite location on Parkland\'s campus.\
      AMP created print and digital advertising material, updated social media graphics,\
       and wrote a radio public service announcement.',
    img:'http://lorempixel.com/280/180/abstract/'},

    {name:'Parkland Entrepreneurial Network',
    info:'Wesley Food Pantry asked AMP to update their logo and raise awareness of \
     their new satellite location on Parkland\'s campus.\
      AMP created print and digital advertising material, updated social media graphics,\
       and wrote a radio public service announcement.',
    img:'http://lorempixel.com/280/180/abstract/'}
  ]

})


text:
module Lexicon

import Docile.Interface:

    parsedocs,
    macroname,
    name

import Base:

    start,
    next,
    done,
    length,
    push!,
    run,
    writemime,
    ==

using

    Base.Meta,
    Compat,
    Docile,
    Docile.Interface

export

    @query,
    query,
    save,
    update!,

    doctest,
    failed,
    passed,
    skipped,
    EachEntry,
    Config,
    Index

@document

# Conditional importing of the `Markdown` module.
if VERSION < v"0.4-dev+1488"
    include("../deps/Markdown/src/Markdown.jl")
    import .Markdown
end

include("compat.jl")
include("query.jl")
include("render.jl")
include("doctest.jl")
include("filtering.jl")

__init__() = setup_help() # Hook into the REPL's `?`.

end # module


text:
<md-card id="popupContainer">
    <md-card-title>
        <md-card-title-text>
             Export Bash Script
             (*) Required
        </md-card-title-text>

    </md-card-title>
    <md-card-content>

        <form name="shform">
            <md-input-container class="md-block">
                Git Capsule
                <md-select ng-model="model.capsuleName">
                    <md-option ng-value="">None</md-option>
                    <md-option ng-repeat="name in model.capsuleNames" ng-value="name">
                        {{name}}
                    </md-option>
                </md-select>
            </md-input-container>
            <md-input-container class="md-block">
                File Name
                <input ng-model="model.name" required>

This is required!

            </md-input-container>
            <md-input-container class="md-block" ng-click="model.SaveScriptLocation()">
                 File Location
                <input type="text" ng-model="model.outputLocation" disabled="true" flex placeholder="export location" required>

This is required!

            </md-input-container>
            <md-input-container class="md-block">
                Comment
                <textarea ng-model="model.comment" md-maxlength="500" rows="5" md-select-on-focus></textarea>
            </md-input-container>
            <md-chips ng-show="model.gitFolders.length > 0">
                <md-chip ng-repeat="git in model.gitFolders"> {{ git.file.name }}</md-chip>
            </md-chips>
            <md-card-actions layout="row" layout-align="center">

                <md-button md-colors="{color: 'default-background-hue-1'}" class="md-accent md-raised" ng-click="model.exportSh()"> Export </md-button>
            </md-card-actions>
        </form>
    </md-card-content>
</md-card>


text:
'use strict';
var Q = require('q')
  , _ = require('underscore');

exports.defaults = function () { return { storage: {} }; };

exports.mixin = {

  /**
   * Converts `arguments` to a key to be stored.
   */
  toKey: function () {
    return _.toArray(arguments);
  },

  contains: function () {
    return this.containsKey(this.toKey.apply(this, _.toArray(arguments)));
  },

  containsKey: function (key) {
    return Q.when(_.has(this.storage, key));
  },

  del: function () {
    var args = _.toArray(arguments)
      , key = this.toKey.apply(this, arguments);

    if (!this.containsKey(key)) return Q.when(false);

    this.emit.apply(this, [ 'del' ].concat(args));
    delete this.storage[key];
    return Q.when(true);
  },

  set: function (key, val) {
    this.storage[key] = val;
    return Q.when(true);
  },

  get: function (key) {
    return Q.when(this.storage[key]);
  }

};


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik;

use Piwik\Config\ConfigNotFoundException;
use Piwik\Container\StaticContainer;
use Piwik\Plugin\Manager as PluginManager;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class Console extends Application
{
    public function __construct()
    {
        $this->checkCompatibility();

        parent::__construct();

        $option = new InputOption('piwik-domain',
            null,
            InputOption::VALUE_OPTIONAL,
            'Piwik URL (protocol and domain) eg. "http://piwik.example.org"'
        );

        $this->getDefinition()->addOption($option);

        $option = new InputOption('xhprof',
            null,
            InputOption::VALUE_NONE,
            'Enable profiling with XHProf'
        );

        $this->getDefinition()->addOption($option);

        StaticContainer::setEnvironment('cli');
    }

    public function doRun(InputInterface $input, OutputInterface $output)
    {
        if ($input->hasParameterOption('--xhprof')) {
            Profiler::setupProfilerXHProf(true, true);
        }

        $this->initPiwikHost($input);
        $this->initConfig($output);
        $this->initLoggerOutput($output);

        try {
            self::initPlugins();
        } catch (ConfigNotFoundException $e) {
            // Piwik not installed yet, no config file?
            Log::warning($e->getMessage());
        }

        $commands = $this->getAvailableCommands();

        foreach ($commands as $command) {
            $this->addCommandIfExists($command);
        }

        $self = $this;
        return Access::doAsSuperUser(function () use ($input, $output, $self) {
            return call_user_func(array($self, 'Symfony\Component\Console\Application::doRun'), $input, $output);
        });
    }

    private function addCommandIfExists($command)
    {
        if (!class_exists($command)) {
            Log::warning(sprintf('Cannot add command %s, class does not exist', $command));
        } else if (!is_subclass_of($command, 'Piwik\Plugin\ConsoleCommand')) {
            Log::warning(sprintf('Cannot add command %s, class does not extend Piwik\Plugin\ConsoleCommand', $command));
        } else {
            /** @var Command $commandInstance */
            $commandInstance = new $command;

            // do not add the command if it already exists; this way we can add the command ourselves in tests
            if (!$this->has($commandInstance->getName())) {
                $this->add($commandInstance);
            }
        }
    }

    /**
     * Returns a list of available command classnames.
     *
     * @return string[]
     */
    private function getAvailableCommands()
    {
        $commands = $this->getDefaultPiwikCommands();
        $detected = PluginManager::getInstance()->findMultipleComponents('Commands', 'Piwik\\Plugin\\ConsoleCommand');

        $commands = array_merge($commands, $detected);

        /**
         * Triggered to filter / restrict console commands. Plugins that want to restrict commands
         * should subscribe to this event and remove commands from the existing list.
         *
         * **Example**
         *
         *     public function filterConsoleCommands(&$commands)
         *     {
         *         $key = array_search('Piwik\Plugins\MyPlugin\Commands\MyCommand', $commands);
         *         if (false !== $key) {
         *             unset($commands[$key]);
         *         }
         *     }
         *
         * @param array &$commands An array containing a list of command class names.
         */
        Piwik::postEvent('Console.filterCommands', array(&$commands));

        $commands = array_values(array_unique($commands));

        return $commands;
    }

    private function checkCompatibility()
    {
        if (Common::isPhpCgiType()) {
            echo 'Piwik Console is known to be not compatible with PHP-CGI (you are using '.php_sapi_name().'). ' .
                 'Please execute console using PHP-CLI. For instance "/usr/bin/php-cli console ..."';
            echo "\n";
            exit(1);
        }
    }

    public static function isSupported()
    {
        return Common::isPhpCliMode() && !Common::isPhpCgiType();
    }

    protected function initPiwikHost(InputInterface $input)
    {
        $piwikHostname = $input->getParameterOption('--piwik-domain');

        if (empty($piwikHostname)) {
            $piwikHostname = $input->getParameterOption('--url');
        }

        $piwikHostname = UrlHelper::getHostFromUrl($piwikHostname);
        Url::setHost($piwikHostname);
    }

    protected function initConfig(OutputInterface $output)
    {
        $config = Config::getInstance();

        try {
            $config->checkLocalConfigFound();
            return $config;
        } catch (\Exception $e) {
            $output->writeln($e->getMessage() . "\n");
        }
    }

    /**
     * Register the console output into the logger.
     *
     * Ideally, this should be done automatically with events:
     * @see http://symfony.com/fr/doc/current/components/console/events.html
     * @see Symfony\Bridge\Monolog\Handler\ConsoleHandler::onCommand()
     * But it would require to install Symfony's Event Dispatcher.
     */
    private function initLoggerOutput(OutputInterface $output)
    {
        /** @var ConsoleHandler $consoleLogHandler */
        $consoleLogHandler = StaticContainer::get('Symfony\Bridge\Monolog\Handler\ConsoleHandler');
        $consoleLogHandler->setOutput($output);
    }

    public static function initPlugins()
    {
        Plugin\Manager::getInstance()->loadActivatedPlugins();
        Plugin\Manager::getInstance()->loadPluginTranslations();
    }

    private function getDefaultPiwikCommands()
    {
        $commands = array(
            'Piwik\CliMulti\RequestCommand'
        );

        if (class_exists('Piwik\Plugins\EnterpriseAdmin\EnterpriseAdmin')) {
            $extra = new \Piwik\Plugins\EnterpriseAdmin\EnterpriseAdmin();
            $extra->addConsoleCommands($commands);
        }

        return $commands;
    }

}


text:
/****** Object:  User Defined Function dbo.CalcProbingDefencePower    Script Date: 5/1/2004 6:12:45 PM ******/
CREATE FUNCTION dbo.CalcProbingDefencePower
	(
		@Attacker int,
		@Defender int,
		@Probes bigint
	)
RETURNS bigint
BEGIN
	DECLARE @RawPower bigint
	DECLARE @DefencePower bigint
	DECLARE @Land bigint
	DECLARE @AttackerSector int
	DECLARE @DefenderSector int
	DECLARE @ProbesB bigint
	SET @ProbesB = (SELECT Probes FROM Kingdoms WHERE kdID = @Defender)
	SET @Land = (SELECT Land FROM Land WHERE kdID = @Defender)
	SET @AttackerSector = (SELECT SectorID FROM Kingdoms WHERE kdID = @Attacker)
	SET @DefenderSector = (SELECT SectorID FROM Kingdoms WHERE kdID = @Defender)
	IF (@Land * 4) <= @Probes
	BEGIN
	SET @RawPower = @Land * 4
	END
	ELSE
	IF @ProbesB >=  0
	BEGIN
	SET @RawPower = @ProbesB
	END
	SET @DefencePower = @RawPower
	RETURN(@DefencePower)
END


text:
import numpy as np
from copy import deepcopy

def distort_binnary(pattern_number, percentage_to_corrupt, X):
    """
    Ths functions takes the pattern number (index) and returns both
    the pattern as it is distorted version (specificied as a percentage)

    arguments:
    pattern_numnber: The label -index- of the image
    percentage: specifies how much the pattern will be
    corrupt (0.5 is 50 per cent)
    """
    image_size = X.shape[1]

    # Take the patterns

    dis_pattern = deepcopy(X[pattern_number])

    N_to_corrupt = int(percentage_to_corrupt * image_size)
    index_set = np.arange(0, image_size)
    corrupt_index = np.random.choice(index_set, N_to_corrupt, replace=False)

    dis_pattern[corrupt_index] = 1 - dis_pattern[corrupt_index]

    return dis_pattern


text:
package com.gemstone.gemfire.cache.server;

import com.gemstone.gemfire.cache.CacheCallback;

/**
 * A load probe is installed in a bridge server to measure the load on the
 * bridge server for balancing load between multiple bridge servers.
 *
 *

 * The getLoad method will be called once per poll interval see
 * {@link CacheServer#setLoadPollInterval(long)} The {@link ServerLoad} object
 * returned by the getLoad method will be sent to the locator every time the
 * load for this server changes. To conserve bandwidth, it's a good idea to
 * round the load calculations so that the load will not be sent too frequently.
 *

 *

 * The {@link ServerLoad} object contains two floating point numbers indicating
 * the load on the server due to client to server connections and due to
 * subscription connections. When routing a connection, the locator will choose
 * the server that has the lowest load.
 *

 *

 * It is generally a good idea to pick a load function where 0 connections
 * corresponds to 0 load. The default gemfire load probes return a fraction
 * between 0 and 1, where 0 indicates no load, and 1 indicates the server is
 * completely loaded.
 *

 *

 * Because cache servers can be stopped, reconfigured, and restarted, the open
 * and close methods on this callback can be called several times. If the same
 * callback object is installed on multiple cache servers, open and close will
 * be called once for each bridge server.
 *

 *
 * @author dsmith
 * @since 5.7
 *
 */
public interface ServerLoadProbe extends CacheCallback {
  /**
   * Get the load on this server. This method will be called once every pool
   * interval.
   *
   * @return The current load on this server.
   */
  ServerLoad getLoad(ServerMetrics metrics);

  /** Signals that a bridge server
   * using this load probe has been started.
   */
  void open();

  /**
   * Signals that a bridge server
   * using this load probe has been closed.
   */
  void close();
}


text:
<?php
require '../src/Curl/Curl.php';

use \Curl\Curl;

define('API_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXX');
define('API_SECRET', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('OAUTH_ACCESS_TOKEN', 'XXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('OAUTH_TOKEN_SECRET', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

$woeid = '2487956';

$oauth_data = array(
    'id' => $woeid,
    'oauth_consumer_key' => API_KEY,
    'oauth_nonce' => md5(microtime() .  mt_rand()),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_timestamp' => time(),
    'oauth_token' => OAUTH_ACCESS_TOKEN,
    'oauth_version' => '1.0',
);

$request_values = $oauth_data;
ksort($request_values);

$url = 'https://api.twitter.com/1.1/trends/place.json';
$request = implode('&', array(
    'GET',
    rawurlencode($url),
    rawurlencode(http_build_query($request_values, '', '&', PHP_QUERY_RFC3986)),
));
$key = implode('&', array(rawurlencode(API_SECRET), rawurlencode(OAUTH_TOKEN_SECRET)));
$oauth_data['oauth_signature'] = base64_encode(hash_hmac('sha1', $request, $key, true));

$authorization = array();
foreach ($oauth_data as $key => $value) {
    $authorization[] = $key . '="' . rawurlencode($value) . '"';
}
$authorization = 'Authorization: OAuth ' . implode(', ', $authorization);

$curl = new Curl();
$curl->setOpt(CURLOPT_HTTPHEADER, array($authorization));
$curl->get($url, array(
    'id' => $woeid,
));

echo 'Current trends:' . "\n";
foreach ($curl->response['0']->trends as $trend) {
    echo '- ' . $trend->name . "\n";
}


text:
package registry

import (
	"container/list"

	. "github.com/ligato/vpp-agent/plugins/kvscheduler/api"
	"github.com/ligato/vpp-agent/plugins/kvscheduler/internal/utils"
)

const (
	// maxKeyCacheSize is the maximum number of key->descriptor entries the registry
	// will cache.
	maxKeyCacheSize = 500
)

// registry is an implementation of Registry for descriptors.
type registry struct {
	descriptors      map[string]*KVDescriptor // descriptor name -> descriptor
	descriptorList   []*KVDescriptor          // ordered by dump dependencies
	upToDateDescList bool                     // true if descriptorList is in sync with descriptors
	keyToCacheEntry  map[string]*list.Element // key -> cache entry
	keyCache         *list.List               // doubly linked list of cached entries key->descriptor
}

// cacheEntry encapsulates data for one entry in registry.keyCache
type cacheEntry struct {
	key        string
	descriptor *KVDescriptor
}

// NewRegistry creates a new instance of registry.
func NewRegistry() Registry {
	return &registry{
		descriptors:     make(map[string]*KVDescriptor),
		keyToCacheEntry: make(map[string]*list.Element),
		keyCache:        list.New(),
	}
}

// RegisterDescriptor add new descriptor into the registry.
func (reg *registry) RegisterDescriptor(descriptor *KVDescriptor) {
	reg.descriptors[descriptor.Name] = descriptor
	reg.upToDateDescList = false
}

// GetAllDescriptors returns all registered descriptors.
func (reg *registry) GetAllDescriptors() (descriptors []*KVDescriptor) {
	if reg.upToDateDescList {
		return reg.descriptorList
	}

	// collect descriptor dump dependencies
	deps := make(map[string]utils.KeySet)
	descNames := utils.NewMapBasedKeySet()
	for _, descriptor := range reg.descriptors {
		descNames.Add(descriptor.Name)
		deps[descriptor.Name] = utils.NewMapBasedKeySet(descriptor.DumpDependencies...)
	}

	// order topologically respecting dependencies.
	orderedNames := utils.TopologicalOrder(descNames, deps, true, false)
	reg.descriptorList = []*KVDescriptor{}
	for _, descName := range orderedNames {
		reg.descriptorList = append(reg.descriptorList, reg.descriptors[descName])
	}

	reg.upToDateDescList = true
	return reg.descriptorList
}

// GetDescriptor returns descriptor with the given name.
func (reg *registry) GetDescriptor(name string) *KVDescriptor {
	descriptor, has := reg.descriptors[name]
	if !has {
		return nil
	}
	return descriptor
}

// GetDescriptorForKey returns descriptor handling the given key.
func (reg *registry) GetDescriptorForKey(key string) *KVDescriptor {
	elem, cached := reg.keyToCacheEntry[key]
	if cached {
		// get descriptor from the cache
		entry := elem.Value.(*cacheEntry)
		reg.keyCache.MoveToFront(elem)
		return entry.descriptor
	}
	if reg.keyCache.Len() == maxKeyCacheSize {
		// the cache is full => remove the last used key
		toRemove := reg.keyCache.Back()
		toRemoveKey := toRemove.Value.(*cacheEntry).key
		delete(reg.keyToCacheEntry, toRemoveKey)
		reg.keyCache.Remove(toRemove)
	}
	// find the descriptor
	var keyDescriptor *KVDescriptor
	for _, descriptor := range reg.descriptors {
		if descriptor.KeySelector(key) {
			keyDescriptor = descriptor
			break
		}
	}
	// add entry to cache
	entry := &cacheEntry{key: key, descriptor: keyDescriptor}
	elem = reg.keyCache.PushFront(entry)
	reg.keyToCacheEntry[key] = elem
	return keyDescriptor
}


text:
namespace StringsOperations
{
    using System.ServiceModel;

    [ServiceContract]
    public interface IStringsService
    {
        [OperationContract]
        int NumberOfContains(string subString, string text);
    }
}


text:
__author__ = "github.com/woolworths"
__version__ = "1.0"
__copyright__ = "Copyright (c) github.com/woolworths"
__license__ = "The MIT Licence"


text:
/*
 * Task.cpp
 *
 *  Created on: 23 mai 2016
 *      Author: jul
 */

#include "Middleware/Task.h"

Task::Task() {
	// TODO Auto-generated constructor stub

}

Task::Task(char * name,osPriority priority,uint32_t  instanceNb, uint32_t stacksize)
{
	m_TreadDef.instances = instanceNb;
	m_TreadDef.name = name;
	m_TreadDef.tpriority = priority;
	m_TreadDef.stacksize = stacksize;

}

void Task::Init()
{
	m_TaskHandle = osThreadCreate(&m_TreadDef,NULL);
}

Task::~Task() {
	// TODO Auto-generated destructor stub
}

void Task::Thread(void const * argument)
{

}


text:
This is a plugin to be used in conjunction with the Google Mobile Ads SDK in
Google Play services. For requirements, instructions, and other info, see the
[Unity Ads Adapter Integration Guide](https://developers.google.com/admob/unity/mediation/unity).

See the [changelog](https://developers.google.com/admob/unity/mediation/unity#unity-ads-unity-mediation-plugin-changelog)
to view the version history.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:mapsme="http://schemas.android.com/apk/res-auto"
  android:background="?cardBackground"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_centerHorizontal="true"
  android:gravity="center_horizontal"
  android:paddingTop="@dimen/margin_base"
  android:paddingBottom="@dimen/margin_base"
  android:paddingLeft="@dimen/margin_base"
  android:paddingRight="@dimen/margin_base">
  <ImageView
    android:id="@+id/close_btn"
    android:minHeight="@dimen/margin_base_plus"
    android:minWidth="@dimen/margin_base_plus"
    android:src="@drawable/ic_clear"
    android:tint="?iconTint"
    android:layout_gravity="end"
    android:background="?selectableItemBackgroundBorderless"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
  <com.mapswithme.maps.widget.PlaceholderView
    android:id="@+id/placeholder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:layout_weight="1"
    mapsme:imgSrcDefault="@drawable/img_editonweb"
    mapsme:titleDefault="@string/edit_guide_title"
    mapsme:subTitleDefault="@string/edit_guide_subtitle"/>
  <Button
    android:id="@+id/send_me_link_btn"
    android:layout_width="@dimen/button_width"
    android:layout_height="wrap_content"
    style="@style/MwmWidget.Button.Primary"
    android:layout_weight="0"
    android:layout_marginTop="@dimen/margin_base_plus"
    android:text="@string/send_a_link_btn"
    android:textAppearance="@style/MwmTextAppearance.Body1.Light"/>
  <TextView
    android:id="@+id/cancel_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="@dimen/primary_button_min_height"
    android:textColor="?attr/colorAccent"
    android:gravity="center"
    android:layout_marginTop="@dimen/margin_half_plus"
    android:text="@string/cancel"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textAllCaps="true"
    android:textStyle="bold"
    android:background="?attr/selectableItemBackground"/>
</LinearLayout>


text:
namespace tcp_moe_client.Forms
{
    partial class Authentication
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Authentication));
            this.lblUsername = new System.Windows.Forms.Label();
            this.grpLogin = new System.Windows.Forms.GroupBox();
            this.chkRemember = new System.Windows.Forms.CheckBox();
            this.btnLogin = new System.Windows.Forms.Button();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtUsername = new System.Windows.Forms.TextBox();
            this.picLogo = new System.Windows.Forms.PictureBox();
            this.grpLogin.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.picLogo)).BeginInit();
            this.SuspendLayout();
            //
            // lblUsername
            //
            this.lblUsername.AutoSize = true;
            this.lblUsername.Location = new System.Drawing.Point(79, 29);
            this.lblUsername.Name = "lblUsername";
            this.lblUsername.Size = new System.Drawing.Size(75, 20);
            this.lblUsername.TabIndex = 1;
            this.lblUsername.Text = "Username";
            //
            // grpLogin
            //
            this.grpLogin.Controls.Add(this.chkRemember);
            this.grpLogin.Controls.Add(this.btnLogin);
            this.grpLogin.Controls.Add(this.txtPassword);
            this.grpLogin.Controls.Add(this.label1);
            this.grpLogin.Controls.Add(this.txtUsername);
            this.grpLogin.Controls.Add(this.lblUsername);
            this.grpLogin.Location = new System.Drawing.Point(13, 105);
            this.grpLogin.Name = "grpLogin";
            this.grpLogin.Size = new System.Drawing.Size(383, 186);
            this.grpLogin.TabIndex = 0;
            this.grpLogin.TabStop = false;
            this.grpLogin.Text = "Login with your tcp-moe account";
            //
            // chkRemember
            //
            this.chkRemember.AutoSize = true;
            this.chkRemember.Location = new System.Drawing.Point(93, 144);
            this.chkRemember.Name = "chkRemember";
            this.chkRemember.Size = new System.Drawing.Size(126, 24);
            this.chkRemember.TabIndex = 5;
            this.chkRemember.Text = "Remember me";
            this.chkRemember.UseVisualStyleBackColor = true;
            //
            // btnLogin
            //
            this.btnLogin.Enabled = false;
            this.btnLogin.Location = new System.Drawing.Point(225, 139);
            this.btnLogin.Name = "btnLogin";
            this.btnLogin.Size = new System.Drawing.Size(81, 32);
            this.btnLogin.TabIndex = 6;
            this.btnLogin.Text = "Login";
            this.btnLogin.UseVisualStyleBackColor = true;
            this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click);
            //
            // txtPassword
            //
            this.txtPassword.Location = new System.Drawing.Point(83, 106);
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.Size = new System.Drawing.Size(223, 27);
            this.txtPassword.TabIndex = 4;
            this.txtPassword.UseSystemPasswordChar = true;
            this.txtPassword.TextChanged += new System.EventHandler(this.Credentials_TextChanged);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(79, 82);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(71, 20);
            this.label1.TabIndex = 3;
            this.label1.Text = "Password";
            //
            // txtUsername
            //
            this.txtUsername.Location = new System.Drawing.Point(83, 52);
            this.txtUsername.Name = "txtUsername";
            this.txtUsername.Size = new System.Drawing.Size(223, 27);
            this.txtUsername.TabIndex = 2;
            this.txtUsername.TextChanged += new System.EventHandler(this.Credentials_TextChanged);
            //
            // picLogo
            //
            this.picLogo.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("picLogo.BackgroundImage")));
            this.picLogo.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.picLogo.Location = new System.Drawing.Point(12, 15);
            this.picLogo.Name = "picLogo";
            this.picLogo.Size = new System.Drawing.Size(384, 92);
            this.picLogo.TabIndex = 2;
            this.picLogo.TabStop = false;
            //
            // Authentication
            //
            this.AcceptButton = this.btnLogin;
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(408, 298);
            this.Controls.Add(this.picLogo);
            this.Controls.Add(this.grpLogin);
            this.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Authentication";
            this.ShowIcon = false;
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Authentication_FormClosing);
            this.Load += new System.EventHandler(this.Authentication_Load);
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.frmAuthentication_Paint);
            this.grpLogin.ResumeLayout(false);
            this.grpLogin.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.picLogo)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label lblUsername;
        private System.Windows.Forms.GroupBox grpLogin;
        private System.Windows.Forms.TextBox txtPassword;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtUsername;
        private System.Windows.Forms.Button btnLogin;
        private System.Windows.Forms.CheckBox chkRemember;
        private System.Windows.Forms.PictureBox picLogo;
    }
}


text:
package com.ibm.watson.natural_language_understanding.v1.model;

import com.ibm.cloud.sdk.core.service.model.GenericModel;

/** The object containing the actions and the objects the actions act upon. */
public class SemanticRolesResult extends GenericModel {

  protected String sentence;
  protected SemanticRolesResultSubject subject;
  protected SemanticRolesResultAction action;
  protected SemanticRolesResultObject object;

  /**
   * Gets the sentence.
   *
   *
Sentence from the source that contains the subject, action, and object.
   *
   * @return the sentence
   */
  public String getSentence() {
    return sentence;
  }

  /**
   * Gets the subject.
   *
   *
The extracted subject from the sentence.
   *
   * @return the subject
   */
  public SemanticRolesResultSubject getSubject() {
    return subject;
  }

  /**
   * Gets the action.
   *
   *
The extracted action from the sentence.
   *
   * @return the action
   */
  public SemanticRolesResultAction getAction() {
    return action;
  }

  /**
   * Gets the object.
   *
   *
The extracted object from the sentence.
   *
   * @return the object
   */
  public SemanticRolesResultObject getObject() {
    return object;
  }
}