text:
import hashlib

import mock
from oslo_config import cfg
from testtools import matchers

from ironic.common import exception
from ironic.common import hash_ring
from ironic.tests import base
from ironic.tests.db import base as db_base

CONF = cfg.CONF

class HashRingTestCase(base.TestCase):

    # NOTE(deva): the mapping used in these tests is as follows:
    #             if hosts = [foo, bar]:
    #                fake -> foo, bar
    #             if hosts = [foo, bar, baz]:
    #                fake -> foo, bar, baz
    #                fake-again -> bar, baz, foo

    @mock.patch.object(hashlib, 'md5', autospec=True)
    def test__hash2int_returns_int(self, mock_md5):
        CONF.set_override('hash_partition_exponent', 0)
        r1 = 32 * 'a'
        r2 = 32 * 'b'
        mock_md5.return_value.hexdigest.side_effect = [r1, r2]

        hosts = ['foo', 'bar']
        replicas = 1
        ring = hash_ring.HashRing(hosts, replicas=replicas)

        self.assertIn(int(r1, 16), ring._host_hashes)
        self.assertIn(int(r2, 16), ring._host_hashes)

    def test_create_ring(self):
        hosts = ['foo', 'bar']
        replicas = 2
        ring = hash_ring.HashRing(hosts, replicas=replicas)
        self.assertEqual(set(hosts), ring.hosts)
        self.assertEqual(replicas, ring.replicas)

    def test_create_with_different_partition_counts(self):
        hosts = ['foo', 'bar']
        CONF.set_override('hash_partition_exponent', 2)
        ring = hash_ring.HashRing(hosts)
        self.assertEqual(2 ** 2 * 2, len(ring._partitions))

        CONF.set_override('hash_partition_exponent', 8)
        ring = hash_ring.HashRing(hosts)
        self.assertEqual(2 ** 8 * 2, len(ring._partitions))

        CONF.set_override('hash_partition_exponent', 16)
        ring = hash_ring.HashRing(hosts)
        self.assertEqual(2 ** 16 * 2, len(ring._partitions))

    def test_distribution_one_replica(self):
        hosts = ['foo', 'bar', 'baz']
        ring = hash_ring.HashRing(hosts, replicas=1)
        fake_1_hosts = ring.get_hosts('fake')
        fake_2_hosts = ring.get_hosts('fake-again')
        # We should have one hosts for each thing
        self.assertThat(fake_1_hosts, matchers.HasLength(1))
        self.assertThat(fake_2_hosts, matchers.HasLength(1))
        # And they must not be the same answers even on this simple data.
        self.assertNotEqual(fake_1_hosts, fake_2_hosts)

    def test_distribution_two_replicas(self):
        hosts = ['foo', 'bar', 'baz']
        ring = hash_ring.HashRing(hosts, replicas=2)
        fake_1_hosts = ring.get_hosts('fake')
        fake_2_hosts = ring.get_hosts('fake-again')
        # We should have two hosts for each thing
        self.assertThat(fake_1_hosts, matchers.HasLength(2))
        self.assertThat(fake_2_hosts, matchers.HasLength(2))
        # And they must not be the same answers even on this simple data
        # because if they were we'd be making the active replica a hot spot.
        self.assertNotEqual(fake_1_hosts, fake_2_hosts)

    def test_distribution_three_replicas(self):
        hosts = ['foo', 'bar', 'baz']
        ring = hash_ring.HashRing(hosts, replicas=3)
        fake_1_hosts = ring.get_hosts('fake')
        fake_2_hosts = ring.get_hosts('fake-again')
        # We should have two hosts for each thing
        self.assertThat(fake_1_hosts, matchers.HasLength(3))
        self.assertThat(fake_2_hosts, matchers.HasLength(3))
        # And they must not be the same answers even on this simple data
        # because if they were we'd be making the active replica a hot spot.
        self.assertNotEqual(fake_1_hosts, fake_2_hosts)
        self.assertNotEqual(fake_1_hosts[0], fake_2_hosts[0])

    def test_ignore_hosts(self):
        hosts = ['foo', 'bar', 'baz']
        ring = hash_ring.HashRing(hosts, replicas=1)
        equals_bar_or_baz = matchers.MatchesAny(
            matchers.Equals(['bar']),
            matchers.Equals(['baz']))
        self.assertThat(
            ring.get_hosts('fake', ignore_hosts=['foo']),
            equals_bar_or_baz)
        self.assertThat(
            ring.get_hosts('fake', ignore_hosts=['foo', 'bar']),
            equals_bar_or_baz)
        self.assertEqual([], ring.get_hosts('fake', ignore_hosts=hosts))

    def test_ignore_hosts_with_replicas(self):
        hosts = ['foo', 'bar', 'baz']
        ring = hash_ring.HashRing(hosts, replicas=2)
        self.assertEqual(
            set(['bar', 'baz']),
            set(ring.get_hosts('fake', ignore_hosts=['foo'])))
        self.assertEqual(
            set(['baz']),
            set(ring.get_hosts('fake', ignore_hosts=['foo', 'bar'])))
        self.assertEqual(
            set(['baz', 'foo']),
            set(ring.get_hosts('fake-again', ignore_hosts=['bar'])))
        self.assertEqual(
            set(['foo']),
            set(ring.get_hosts('fake-again', ignore_hosts=['bar', 'baz'])))
        self.assertEqual([], ring.get_hosts('fake', ignore_hosts=hosts))

    def _compare_rings(self, nodes, conductors, ring,
                       new_conductors, new_ring):
        delta = {}
        mapping = dict((node, ring.get_hosts(node)[0]) for node in nodes)
        new_mapping = dict(
            (node, new_ring.get_hosts(node)[0]) for node in nodes)

        for key, old in mapping.items():
            new = new_mapping.get(key, None)
            if new != old:
                delta[key] = (old, new)
        return delta

    def test_rebalance_stability_join(self):
        num_conductors = 10
        num_nodes = 10000
        # Adding 1 conductor to a set of N should move 1/(N+1) of all nodes
        # Eg, for a cluster of 10 nodes, adding one should move 1/11, or 9%
        # We allow for 1/N to allow for rounding in tests.
        redistribution_factor = 1.0 / num_conductors

        nodes = [str(x) for x in range(num_nodes)]
        conductors = [str(x) for x in range(num_conductors)]
        new_conductors = conductors + ['new']
        delta = self._compare_rings(
            nodes, conductors, hash_ring.HashRing(conductors),
            new_conductors, hash_ring.HashRing(new_conductors))

        self.assertTrue(len(delta) < num_nodes * redistribution_factor)

    def test_rebalance_stability_leave(self):
        num_conductors = 10
        num_nodes = 10000
        # Removing 1 conductor from a set of N should move 1/(N) of all nodes
        # Eg, for a cluster of 10 nodes, removing one should move 1/10, or 10%
        # We allow for 1/(N-1) to allow for rounding in tests.
        redistribution_factor = 1.0 / (num_conductors - 1)

        nodes = [str(x) for x in range(num_nodes)]
        conductors = [str(x) for x in range(num_conductors)]
        new_conductors = conductors[:]
        new_conductors.pop()
        delta = self._compare_rings(
            nodes, conductors, hash_ring.HashRing(conductors),
            new_conductors, hash_ring.HashRing(new_conductors))

        self.assertTrue(len(delta) < num_nodes * redistribution_factor)

    def test_more_replicas_than_hosts(self):
        hosts = ['foo', 'bar']
        ring = hash_ring.HashRing(hosts, replicas=10)
        self.assertEqual(set(hosts), set(ring.get_hosts('fake')))

    def test_ignore_non_existent_host(self):
        hosts = ['foo', 'bar']
        ring = hash_ring.HashRing(hosts, replicas=1)
        self.assertEqual(['foo'], ring.get_hosts('fake',
                                                 ignore_hosts=['baz']))

    def test_create_ring_invalid_data(self):
        hosts = None
        self.assertRaises(exception.Invalid,
                          hash_ring.HashRing,
                          hosts)

    def test_get_hosts_invalid_data(self):
        hosts = ['foo', 'bar']
        ring = hash_ring.HashRing(hosts)
        self.assertRaises(exception.Invalid,
                          ring.get_hosts,
                          None)

class HashRingManagerTestCase(db_base.DbTestCase):

    def setUp(self):
        super(HashRingManagerTestCase, self).setUp()
        self.ring_manager = hash_ring.HashRingManager()

    def register_conductors(self):
        self.dbapi.register_conductor({
            'hostname': 'host1',
            'drivers': ['driver1', 'driver2'],
        })
        self.dbapi.register_conductor({
            'hostname': 'host2',
            'drivers': ['driver1'],
        })

    def test_hash_ring_manager_get_ring_success(self):
        self.register_conductors()
        ring = self.ring_manager['driver1']
        self.assertEqual(sorted(['host1', 'host2']), sorted(ring.hosts))

    def test_hash_ring_manager_driver_not_found(self):
        self.register_conductors()
        self.assertRaises(exception.DriverNotFound,
                          self.ring_manager.__getitem__,
                          'driver3')

    def test_hash_ring_manager_no_refresh(self):
        # If a new conductor is registered after the ring manager is
        # initialized, it won't be seen. Long term this is probably
        # undesirable, but today is the intended behavior.
        self.assertRaises(exception.DriverNotFound,
                          self.ring_manager.__getitem__,
                          'driver1')
        self.register_conductors()
        self.assertRaises(exception.DriverNotFound,
                          self.ring_manager.__getitem__,
                          'driver1')


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Alphabetical List

Class List

Class Hierarchy

Class Members

Stats::ScalarPrint Member List
This is the complete list of members for Stats::ScalarPrint, including all inherited members.

cdf	Stats::ScalarPrint

desc	Stats::ScalarPrint

descriptions	Stats::ScalarPrint

flags	Stats::ScalarPrint

name	Stats::ScalarPrint

operator()(ostream &stream, bool oneLine=false) const 	Stats::ScalarPrint

pdf	Stats::ScalarPrint

precision	Stats::ScalarPrint

update(Result val, Result total)	Stats::ScalarPrint

value	Stats::ScalarPrint

<address style="align: right;">
Generated on Fri Apr 17 12:41:54 2015 for gem5 by  doxygen 1.4.7</address>

redpajama_set_name: RedPajamaGithub


text:
typedef void(^CCCPushManagerChannelBlock)(NSArray *channels);

@protocol CCCPushManagerDelegate;

@interface CCCPushManager : NSObject

@property (nonatomic, weak) id<CCCPushManagerDelegate> delegate;
@property (nonatomic, readonly) NSString *deviceTokenString;
@property (nonatomic, readonly) NSArray *channelArray;
@property (nonatomic, readonly) NSSet *channelSet;

+ (CCCPushManager *)sharedManager;

- (void)updateDeviceToken:(NSString *)deviceTokenString;
- (void)subscribeToChannels:(NSArray *)channels;
- (void)unsubscribeFromChannels:(NSArray *)channels;
- (void)getChannels:(CCCPushManagerChannelBlock)block;

@end

@protocol CCCPushManagerDelegate <NSObject>

- (NSString *)rootDomainForPushManager:(CCCPushManager *)pushManager;
- (BOOL)shouldUseSSLForPushManager:(CCCPushManager *)pushManager;

@end


text:
/*
 *  Written for the Asn1Net project by:
 *  Peter Polacko <peter.polacko+asn1net@gmail.com>
 */

namespace Net.Asn1.Type
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    /// <summary>
    /// Implementation of ASN.1 SET
    /// </summary>
    public class Asn1Set : Asn1Object<List<Asn1ObjectBase>>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Asn1Set"/> class.
        /// Preferably used when encoding SET.
        /// The encoding of a set value shall be constructed.
        /// </summary>
        /// <param name="asn1Class">Class of given Asn.1 object.</param>
        /// <param name="content">Content to be encoded.</param>
        /// <param name="constructed">Flag if type is constructed or primitive.</param>
        public Asn1Set(Asn1Class asn1Class, List<Asn1ObjectBase> content, bool constructed = true)
            : base(asn1Class, constructed, (int)Asn1Type.Set, content)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Asn1Set"/> class.
        /// Preferably used when reading SET.
        /// The encoding of a set value shall be constructed.
        /// </summary>
        /// <param name="asn1Class">Class of given Asn.1 object.</param>
        /// <param name="content">BER encoded value in a Stream.</param>
        /// <param name="constructed">Flag if type is constructed or primitive.</param>
        internal Asn1Set(Asn1Class asn1Class, SubStream content, bool constructed)
            : base(asn1Class, constructed, (int)Asn1Type.Set, content)
        {
        }

        /// <inheritdoc/>
        public override byte[] Write()
        {
            if (Constructed == false)
                throw new FormatException("The encoding of a sequence value shall be constructed.");

            var contentBytes = new List<byte>();
            var comparer = new SetComparer();

            var orderedContent = this.Content.OrderBy(p => p, comparer);

            foreach (var item in orderedContent)
            {
                contentBytes.AddRange(item.Write());
            }

            var resBytes = new List<byte>();
            resBytes.AddRange(DerWriter.WriteTag(this.Asn1Class, this.Asn1Tag, this.Constructed));
            resBytes.AddRange(DerWriter.WriteLength(contentBytes, (Asn1Type)this.Asn1Tag));
            resBytes.AddRange(contentBytes);

            return resBytes.ToArray();
        }

        /// <inheritdoc/>
        public override string ToString()
        {
            return base.ToString();
        }

        /// <summary>
        /// Read the value of the given node as list of children in the set.
        /// </summary>
        /// <returns>Value of the given node as list of children in the set.</returns>
        internal override List<Asn1ObjectBase> ReadEncodedValue()
        {
            if (this.RawContent == null)
            {
                throw new ArgumentException("Stream that contains encoded value is null.");
            }

            var content = this.RawContent;
            content.Seek(0, SeekOrigin.Begin);
            var internalReader = new BerReader(content);
            List<Asn1ObjectBase> children;
            internalReader.Read(out children);

            return children;
        }

        private class SetComparer : IComparer<Asn1ObjectBase>
        {
            public int Compare(Asn1ObjectBase x, Asn1ObjectBase y)
            {
                if (x == null)
                {
                    throw new ArgumentNullException(nameof(x));
                }

                if (y == null)
                {
                    throw new ArgumentNullException(nameof(y));
                }

                // The encodings of the component values of a set value shall appear in an order determined by their tags as specified
                // in 8.6 of Rec. ITU - T X.680 | ISO / IEC 8824 - 1.

                // those elements or alternatives with universal class tags shall appear first, followed by those with
                // application class tags, followed by those with context-specific tags, followed by those with private class
                // tags;
                var xVal = x.Asn1Class == Asn1Class.Universal ? x.Asn1Tag : x.Asn1Tag * (int)x.Asn1Class;
                var yVal = y.Asn1Class == Asn1Class.Universal ? y.Asn1Tag : y.Asn1Tag * (int)y.Asn1Class;

                return xVal.CompareTo(yVal);
            }
        }
    }
}


text:
function HomeController(gameSessionsFactory){
    console.log('Home component');

    var vm = this;

    vm.newSession = {
        players: []
    };

    gameSessionsFactory.getGames().then(function(games){
        vm.games = games;
    });
    gameSessionsFactory.getPlayers().then(function(players){
        vm.players = players;
        vm.newSession.gameMaster = players[0];
        vm.newPlayer = players[0];
    });

    vm.getSessions = function(){
        gameSessionsFactory.getGameSessions().then((function(gameSessions){
            vm.gameSessions = gameSessions;
            vm.gameSessions.forEach(function(gameSession){
                gameSessionsFactory.getGameById(gameSession.game).then(function(game){
                    gameSession.game = game;
                });
                gameSessionsFactory.getPlayerById(gameSession.gameMaster).then(function(gameMaster){
                    gameSession.gameMaster = gameMaster;
                });
                gameSession.players.forEach(function(player, index){
                    gameSessionsFactory.getPlayerById(player).then(function(playerDetail){
                        gameSession.players[index] = playerDetail;
                    });
                });
            });
        }));
    };
    vm.getSessions();

    vm.addSession = function(player){
        vm.newSession.players.push(player);
    };

    vm.addPlayer = function(){
        vm.newSession.players.push(vm.newPlayer);
        vm.newPlayer = null;
    };

    vm.addGameSession = function(){
        console.log(vm.newSession);
        vm.newSession.game = vm.newSession.game.id;
        vm.newSession.gameMaster = vm.newSession.gameMaster.id;
        vm.newSession.characters = [];
        vm.newSession.players.forEach(function(player, index){
            vm.newSession.players[index] = player.id;
            vm.newSession.characters.push({
                player: player.id,
                characterSheet: {}
            });
        });
        console.log(vm.newSession);

        gameSessionsFactory.addGameSession(vm.newSession).then(function(response){
            vm.getSessions();
            vm.newSession = {
                players: []
            };
        });

    }
    vm.deleteGameSession = function(gameSessionId){
        if(confirm('Are you sure you want to delete this game ?')){
            gameSessionsFactory.deleteGameSession(gameSessionId).then(function(response){
                vm.getSessions();
            });
        }
    };

}

HomeController.$inject = ['gameSessionsFactory'];

angular.module('characterSheetmanager.homeComponent', []).component('homeComponent', {
    templateUrl: 'home/home.component.html',
    controller: HomeController,
    controllerAs: "homeCtrl",
    require: {
        parent: '^rootComponent'
    },
    bindings: {}
}).factory('gameSessionsFactory', function($http){
    return {
        getGameSessions: function(){
            var url = "http://localhost:3000/gameSessions";
            return $http({
                method: 'GET',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [getGameSessions] . "+response.status+" : "+response.statusText);
            });
        },
        addGameSession: function(gameSession){
            var url = "http://localhost:3000/gameSessions";
            return $http({
                method: 'POST',
                url: url,
                headers : {
                    'Content-Type': 'application/json'
                },
                data: gameSession
            }).then(function(response){
                return response;
            }).catch(function(response){
                console.log("[Error] [addGameSession] . "+response.status+" : "+response.statusText);
            });
        },
        deleteGameSession: function(gameSessionId){
            var url = "http://localhost:3000/gameSessions/"+gameSessionId;
            return $http({
                method: 'DELETE',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [deleteGameSession] . "+response.status+" : "+response.statusText);
            });
        },
        getGameById: function(gameId){
            var url = "http://localhost:3000/games/"+gameId;
            return $http({
                method: 'GET',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [getGameById] . "+response.status+" : "+response.statusText);
            });
        },
        getGames: function(){
            var url = "http://localhost:3000/games";
            return $http({
                method: 'GET',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [getGames] . "+response.status+" : "+response.statusText);
            });
        },
        getPlayerById: function(playerId){
            var url = "http://localhost:3000/players/"+playerId;
            return $http({
                method: 'GET',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [getPlayerById] . "+response.status+" : "+response.statusText);
            });
        },
        getPlayers: function(){
            var url = "http://localhost:3000/players";
            return $http({
                method: 'GET',
                url: url
            }).then(function(response){
                return response.data;
            }).catch(function(response){
                console.log("[Error] [getPlayers] . "+response.status+" : "+response.statusText);
            });
        }
    }
});


text:
> Stability: 1 - Experimental

Domains provide a way to handle multiple different IO operations as a
single group. The Domain class encapsulates the functionality of routing errors
and uncaught exceptions to the active Domain object.

Domain is a child class of EventEmitter.  To handle the errors that it
catches, listen to its `error` event. If any of the event emitters or callbacks
registered to a
domain emit an `error` event, or throw an error, then the domain object
will be notified, rather than losing the context of the error in the
`process.on('uncaughtException')` handler, or causing the program to
exit with an error code.

This feature is new in Node.js version 0.8.  It is a first pass, and is
expected to change significantly in future versions.  Please use it and
provide feedback.

Due to their experimental nature, the Domains features are disabled unless
the `domain` module is loaded at least once.  No domains are created or
registered by default.  This is by design, to prevent adverse effects on
current programs.  It is expected to be enabled by default in future
Node.js versions.

#### Additions to Error objects

Any time an Error object is routed through a domain, a few extra fields
are added to it.

* `error.domain` The domain that first handled the error.
* `error.domain_emitter` The event emitter that emitted an 'error' event
  with the error object.
* `error.domain_bound` The callback function which was bound to the
  domain, and passed an error as its first argument.
* `error.domain_thrown` A boolean indicating whether the error was
  thrown, emitted, or passed to a bound callback function.

#### Implicit Binding

If domains are in use, then all new EventEmitter objects (including
Stream objects, requests, responses, etc.) will be implicitly bound to
the active domain at the time of their creation.

Additionally, callbacks passed to lowlevel event loop requests (such as
to fs.open, or other callback-taking methods) will automatically be
bound to the active domain.  If they throw, then the domain will catch
the error.

In order to prevent excessive memory usage, Domain objects themselves
are not implicitly added as children of the active domain.  If they
were, then it would be too easy to prevent request and response objects
from being properly garbage collected.

If you *want* to nest Domain objects as children of a parent Domain,
then you must explicitly add them, and then dispose of them later.

Implicit binding routes thrown errors and `'error'` events to the
Domain's `error` event, but does not register the EventEmitter on the
Domain, so `domain.dispose()` will not shut down the EventEmitter.
Implicit binding only takes care of thrown errors and `'error'` events.

#### Explicit Binding

Sometimes, the domain in use is not the one that ought to be used for a
specific event emitter.  Or, the event emitter could have been created
in the context of one domain, but ought to instead be bound to some
other domain.

For example, there could be one domain in use for an HTTP server, but
perhaps we would like to have a separate domain to use for each request.

That is possible via explicit binding.

For example:

```
// create a top-level domain for the server
var serverDomain = domain.create();

serverDomain.run(function() {
  // server is created in the scope of serverDomain
  http.createServer(function(req, res) {
    // req and res are also created in the scope of serverDomain
    // however, we'd prefer to have a separate domain for each request.
    // create it first thing, and add req and res to it.
    var reqd = domain.create();
    reqd.add(req);
    reqd.add(res);
    reqd.on('error', function(er) {
      console.error('Error', er, req.url);
      try {
        res.writeHead(500);
        res.end('Error occurred, sorry.');
        res.on('close', function() {
          // forcibly shut down any other things added to this domain
          reqd.dispose();
        });
      } catch (er) {
        console.error('Error sending 500', er, req.url);
        // tried our best.  clean up anything remaining.
        reqd.dispose();
      }
    });
  }).listen(1337);
});
```

### domain.create()
+ {domain} A new Domain object

Returns a new Domain object.

### domain.run(fn)
- fn {Function} A function to run

Run the supplied function in the context of the domain, implicitly
binding all event emitters, timers, and lowlevel requests that are
created in that context.

This is the most basic way to use a domain.

#### Example

```
var d = domain.create();
d.on('error', function(er) {
  console.error('Caught error!', er);
});
d.run(function() {
  process.nextTick(function() {
    setTimeout(function() { // simulating some various async stuff
      fs.open('non-existent file', 'r', function(er, fd) {
        if (er) throw er;
        // proceed...
      });
    }, 100);
  });
});
```

In this example, the `d.on('error')` handler will be triggered, rather
than crashing the program.

### domain.members, Array

An array of timers and event emitters that have been explicitly added
to the domain.

### domain.add(emitter)
- emitter {eventemitter | timer} An emitter or timer to be added to the domain

Explicitly adds an emitter to the domain.  If any event handlers called by
the emitter throw an error, or if the emitter emits an `error` event, it
will be routed to the domain's `error` event, just like with implicit
binding.

This also works with timers that are returned from `setInterval` and
`setTimeout`.  If their callback function throws, it will be caught by
the domain 'error' handler.

If the Timer or EventEmitter was already bound to a domain, it is removed
from that one, and bound to this one instead.

### domain.remove(emitter)
- emitter {eventemitter | timer} An emitter or timer to be removed from the
domain

The opposite of [[domain.add `domain.add()`]].  Removes domain handling from the
specified emitter.

### domain.bind(callback), Function
- callback {Function} The callback function
+ {Function} The bound function

The returned function will be a wrapper around the supplied callback
function.  When the returned function is called, any errors that are
thrown will be routed to the domain's `error` event.

#### Example

```
    var d = domain.create();

    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.bind(function(er, data) {
        // if this throws, it will also be passed to the domain
        return cb(er, data ? JSON.parse(data) : null);
      }));
    }

    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });
```

### domain.intercept(callback)
- callback {Function} The callback function
+ {Function} The intercepted function

This method is almost identical to `domain.bind(callback)`.  However, in
addition to catching thrown errors, it will also intercept `Error`
objects sent as the first argument to the function.

In this way, the common `if (er) return callback(er);` pattern can be replaced
with a single error handler in a single place.

#### Example

```
    var d = domain.create();

    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.intercept(function(data) {
        // note, the first argument is never passed to the
        // callback since it is assumed to be the 'Error' argument
        // and thus intercepted by the domain.

        // if this throws, it will also be passed to the domain
        // so the error-handling logic can be moved to the 'error'
        // event on the domain instead of being repeated throughout
        // the program.
        return cb(null, JSON.parse(data));
      }));
    }

    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });
```

### domain.dispose()

The dispose method destroys a domain, and makes a best effort attempt to
clean up any and all IO that is associated with the domain.  Streams are
aborted, ended, closed, and/or destroyed.  Timers are cleared.
Explicitly bound callbacks are no longer called.  Any error events that
are raised as a result of this are ignored.

The intention of calling `dispose` is generally to prevent cascading
errors when a critical part of the Domain context is found to be in an
error state.

Note that IO might still be performed.  However, to the highest degree
possible, once a domain is disposed, further errors from the emitters in
that set will be ignored.  So, even if some remaining actions are still
in flight, Node.js will not communicate further about them.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.lang.java.symboltable Class Hierarchy (PMD 5.0.4 API)</title>
<meta name="date" content="2013-05-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package net.sourceforge.pmd.lang.java.symboltable

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

net.sourceforge.pmd.lang.java.symboltable.AbstractNameDeclaration (implements net.sourceforge.pmd.lang.java.symboltable.NameDeclaration)

net.sourceforge.pmd.lang.java.symboltable.ClassNameDeclaration

net.sourceforge.pmd.lang.java.symboltable.MethodNameDeclaration

net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration

net.sourceforge.pmd.lang.java.symboltable.AbstractScope (implements net.sourceforge.pmd.lang.java.symboltable.Scope)

net.sourceforge.pmd.lang.java.symboltable.ClassScope

net.sourceforge.pmd.lang.java.symboltable.LocalScope

net.sourceforge.pmd.lang.java.symboltable.MethodScope

net.sourceforge.pmd.lang.java.symboltable.SourceFileScope

net.sourceforge.pmd.lang.java.symboltable.Applier

net.sourceforge.pmd.lang.java.symboltable.DummyScope (implements net.sourceforge.pmd.lang.java.symboltable.Scope)

net.sourceforge.pmd.lang.java.symboltable.ImageFinderFunction (implements net.sourceforge.pmd.util.UnaryFunction<E>)

net.sourceforge.pmd.lang.java.ast.JavaParserVisitorAdapter (implements net.sourceforge.pmd.lang.java.ast.JavaParserVisitor)

net.sourceforge.pmd.lang.java.symboltable.OccurrenceFinder

net.sourceforge.pmd.lang.java.symboltable.ScopeAndDeclarationFinder

net.sourceforge.pmd.lang.java.symboltable.NameFinder

net.sourceforge.pmd.lang.java.symboltable.NameOccurrence

net.sourceforge.pmd.lang.java.symboltable.Search

net.sourceforge.pmd.lang.java.symboltable.SymbolFacade

net.sourceforge.pmd.lang.java.symboltable.TypeSet

net.sourceforge.pmd.lang.java.symboltable.TypeSet.CurrentPackageResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.ExplicitImportResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.FullyQualifiedNameResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.ImplicitImportResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.ImportOnDemandResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.PrimitiveTypeResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.TypeSet.VoidResolver (implements net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver)

net.sourceforge.pmd.lang.java.symboltable.VariableUsageFinderFunction (implements net.sourceforge.pmd.util.UnaryFunction<E>)

Interface Hierarchy

net.sourceforge.pmd.lang.java.symboltable.NameDeclaration

net.sourceforge.pmd.lang.java.symboltable.Scope

net.sourceforge.pmd.lang.java.symboltable.TypeSet.Resolver

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002-2013 InfoEther. All Rights Reserved.


text:
'''Some utilities used around town'''

import struct

def pack_string(message):
    '''Pack a single message in the TCP protocol format'''
    # [ 4-byte message size ][ N-byte binary data ]
    return struct.pack('>l', len(message)) + message

def pack_iterable(messages):
    '''Pack an iterable of messages in the TCP protocol format'''
    # [ 4-byte body size ]
    # [ 4-byte num messages ]
    # [ 4-byte message #1 size ][ N-byte binary data ]
    #      ... (repeated <num_messages> times)
    return pack_string(
        struct.pack('>l', len(messages)) +
        b''.join(map(pack_string, messages)))

def pack(message):
    '''Pack the provided message'''
    if isinstance(message, bytes):
        return pack_string(message)
    else:
        return pack_iterable(message)

def hexify(message):
    '''Print out printable characters, but others in hex'''
    import string
    hexified = []
    for char in message:
        if (char in '\n\r \t') or (char not in string.printable):
            hexified.append('\\x%02x' % ord(char))
        else:
            hexified.append(char)
    return ''.join(hexified)

def distribute(total, objects):
    '''Generator for (count, object) tuples that distributes count evenly among
    the provided objects'''
    for index, obj in enumerate(objects):
        start = (index * total) // len(objects)
        stop = ((index + 1) * total) // len(objects)
        yield (stop - start, obj)


text:
from __future__ import unicode_literals

import datetime
import os

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("discount", "0002_voucher")]

    operations = [
        migrations.AlterField(
            model_name="sale",
            name="type",
            field=models.CharField(
                choices=[
                    ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
                    ("percentage", "%"),
                ],
                default="fixed",
                max_length=10,
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="code",
            field=models.CharField(
                db_index=True, max_length=12, unique=True, verbose_name="code"
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="discount_value",
            field=models.DecimalField(
                decimal_places=2, max_digits=12, verbose_name="discount value"
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="discount_value_type",
            field=models.CharField(
                choices=[
                    ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
                    ("percentage", "%"),
                ],
                default="fixed",
                max_length=10,
                verbose_name="discount type",
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="end_date",
            field=models.DateField(blank=True, null=True, verbose_name="end date"),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="name",
            field=models.CharField(
                blank=True, max_length=255, null=True, verbose_name="name"
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="start_date",
            field=models.DateField(
                default=datetime.date.today, verbose_name="start date"
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="type",
            field=models.CharField(
                choices=[
                    ("value", "All purchases"),
                    ("product", "One product"),
                    ("category", "A category of products"),
                    ("shipping", "Shipping"),
                ],
                default="value",
                max_length=20,
                verbose_name="discount for",
            ),
        ),
        migrations.AlterField(
            model_name="voucher",
            name="usage_limit",
            field=models.PositiveIntegerField(
                blank=True, null=True, verbose_name="usage limit"
            ),
        ),
    ]


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../../base/Page');
import Response = require('../../../../../http/response');
import V1 = require('../../../V1');
import serialize = require('../../../../../base/serialize');
import { SerializableClass } from '../../../../../interfaces';

/**
 * @description Initialize the InviteList
 *
 * @param version - Version of the resource
 * @param serviceSid - The unique id of the Service this member belongs to.
 * @param channelSid - The unique id of the Channel for this member.
 */
declare function InviteList(version: V1, serviceSid: string, channelSid: string): InviteListInstance;

interface InviteListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): InviteContext;
  /**
   * create a InviteInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  create(opts: InviteListInstanceCreateOptions, callback?: (error: Error | null, item: InviteInstance) => any): Promise<InviteInstance>;
  /**
   * Streams InviteInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void;
  /**
   * Constructs a invite
   *
   * @param sid - The sid
   */
  get(sid: string): InviteContext;
  /**
   * Retrieve a single target page of InviteInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: InvitePage) => any): Promise<InvitePage>;
  /**
   * Lists InviteInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: InviteListInstanceOptions, callback?: (error: Error | null, items: InviteInstance[]) => any): Promise<InviteInstance[]>;
  /**
   * Retrieve a single page of InviteInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: InviteListInstancePageOptions, callback?: (error: Error | null, items: InvitePage) => any): Promise<InvitePage>;
}

/**
 * Options to pass to create
 *
 * @property identity - A unique string identifier for this User in this Service.
 * @property roleSid - The Role assigned to this member.
 */
interface InviteListInstanceCreateOptions {
  identity: string;
  roleSid?: string;
}

/**
 * Options to pass to each
 *
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property done - Function to be called upon completion of streaming
 * @property identity - A unique string identifier for this User in this Service.
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 */
interface InviteListInstanceEachOptions {
  callback?: (item: InviteInstance, done: (err?: Error) => void) => void;
  done?: Function;
  identity?: string[];
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to list
 *
 * @property identity - A unique string identifier for this User in this Service.
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 */
interface InviteListInstanceOptions {
  identity?: string[];
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to page
 *
 * @property identity - A unique string identifier for this User in this Service.
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 */
interface InviteListInstancePageOptions {
  identity?: string[];
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
}

interface InvitePayload extends InviteResource, Page.TwilioResponsePayload {
}

interface InviteResource {
  account_sid: string;
  channel_sid: string;
  created_by: string;
  date_created: Date;
  date_updated: Date;
  identity: string;
  role_sid: string;
  service_sid: string;
  sid: string;
  url: string;
}

interface InviteSolution {
  channelSid?: string;
  serviceSid?: string;
}

declare class InviteContext {
  /**
   * Initialize the InviteContext
   *
   * @param version - Version of the resource
   * @param serviceSid - The service_sid
   * @param channelSid - The channel_sid
   * @param sid - The sid
   */
  constructor(version: V1, serviceSid: string, channelSid: string, sid: string);

  /**
   * fetch a InviteInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: InviteInstance) => any): Promise<InviteInstance>;
  /**
   * remove a InviteInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: InviteInstance) => any): void;
}

declare class InviteInstance extends SerializableClass {
  /**
   * Initialize the InviteContext
   *
   * @property sid - A 34 character string that uniquely identifies this resource.
   * @property accountSid - The unique id of the Account[/console] responsible for this member.
   * @property channelSid - The unique id of the Channel for this member.
   * @property serviceSid - The unique id of the Service this member belongs to.
   * @property identity - A unique string identifier for this User in this Service.
   * @property dateCreated - The date that this resource was created.
   * @property dateUpdated - The date that this resource was last updated.
   * @property roleSid - The Role assigned to this member.
   * @property createdBy - The created_by
   * @property url - An absolute URL for this member.
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param serviceSid - The unique id of the Service this member belongs to.
   * @param channelSid - The unique id of the Channel for this member.
   * @param sid - The sid
   */
  constructor(version: V1, payload: InvitePayload, serviceSid: string, channelSid: string, sid: string);

  private _proxy: InviteContext;
  accountSid: string;
  channelSid: string;
  createdBy: string;
  dateCreated: Date;
  dateUpdated: Date;
  /**
   * fetch a InviteInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: InviteInstance) => any): void;
  identity: string;
  /**
   * remove a InviteInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: InviteInstance) => any): void;
  roleSid: string;
  serviceSid: string;
  sid: string;
  /**
   * Produce a plain JSON object version of the InviteInstance for serialization.
   * Removes any circular references in the object.
   */
  toJSON(): any;
  url: string;
}

declare class InvitePage extends Page<V1, InvitePayload, InviteResource, InviteInstance> {
  /**
   * Initialize the InvitePage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V1, response: Response<string>, solution: InviteSolution);

  /**
   * Build an instance of InviteInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: InvitePayload): InviteInstance;
}

export { InviteContext, InviteInstance, InviteList, InviteListInstance, InviteListInstanceCreateOptions, InviteListInstanceEachOptions, InviteListInstanceOptions, InviteListInstancePageOptions, InvitePage, InvitePayload, InviteResource, InviteSolution }


text:
Date: 10/20/2016

## Status

Accepted

## Context

Context

## Decision

Decision

## Consequences

Consequences


text:
package org.apache.catalina.core;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.servlet4preview.http.PushBuilder;
import org.apache.catalina.servlet4preview.http.ServletMapping;
import org.apache.catalina.util.ParameterMap;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.Parameters;

/**
 * Wrapper around a javax.servlet.http.HttpServletRequest
 * that transforms an application request object (which might be the original
 * one passed to a servlet, or might be based on the 2.3
 * javax.servlet.http.HttpServletRequestWrapper class)
 * back into an internal org.apache.catalina.HttpRequest.
 *

 * WARNING:  Due to Java's lack of support for multiple
 * inheritance, all of the logic in ApplicationRequest is
 * duplicated in ApplicationHttpRequest.  Make sure that you
 * keep these two classes in synchronization when making changes!
 *
 * @author Craig R. McClanahan
 * @author Remy Maucherat
 */
class ApplicationHttpRequest
        extends org.apache.catalina.servlet4preview.http.HttpServletRequestWrapper {

    // ------------------------------------------------------- Static Variables

    /**
     * The set of attribute names that are special for request dispatchers.
     */
    protected static final String specials[] =
    { RequestDispatcher.INCLUDE_REQUEST_URI,
      RequestDispatcher.INCLUDE_CONTEXT_PATH,
      RequestDispatcher.INCLUDE_SERVLET_PATH,
      RequestDispatcher.INCLUDE_PATH_INFO,
      RequestDispatcher.INCLUDE_QUERY_STRING,
      org.apache.catalina.servlet4preview.RequestDispatcher.INCLUDE_MAPPING,
      RequestDispatcher.FORWARD_REQUEST_URI,
      RequestDispatcher.FORWARD_CONTEXT_PATH,
      RequestDispatcher.FORWARD_SERVLET_PATH,
      RequestDispatcher.FORWARD_PATH_INFO,
      RequestDispatcher.FORWARD_QUERY_STRING,
      org.apache.catalina.servlet4preview.RequestDispatcher.FORWARD_MAPPING};

    private static final int SPECIALS_FIRST_FORWARD_INDEX = 6;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new wrapped request around the specified servlet request.
     *
     * @param request The servlet request being wrapped
     * @param context The target context for the wrapped request
     * @param crossContext {@code true} if the wrapped request will be a
     *                     cross-context request, otherwise {@code false}
     */
    public ApplicationHttpRequest(HttpServletRequest request, Context context,
                                  boolean crossContext) {

        super(request);
        this.context = context;
        this.crossContext = crossContext;
        setRequest(request);

    }

    // ----------------------------------------------------- Instance Variables

    /**
     * The context for this request.
     */
    protected final Context context;

    /**
     * The context path for this request.
     */
    protected String contextPath = null;

    /**
     * If this request is cross context, since this changes session access
     * behavior.
     */
    protected final boolean crossContext;

    /**
     * The current dispatcher type.
     */
    protected DispatcherType dispatcherType = null;

    /**
     * The request parameters for this request.  This is initialized from the
     * wrapped request.
     */
    protected Map<String, String[]> parameters = null;

    /**
     * Have the parameters for this request already been parsed?
     */
    private boolean parsedParams = false;

    /**
     * The path information for this request.
     */
    protected String pathInfo = null;

    /**
     * The query parameters for the current request.
     */
    private String queryParamString = null;

    /**
     * The query string for this request.
     */
    protected String queryString = null;

    /**
     * The current request dispatcher path.
     */
    protected Object requestDispatcherPath = null;

    /**
     * The request URI for this request.
     */
    protected String requestURI = null;

    /**
     * The servlet path for this request.
     */
    protected String servletPath = null;

    /**
     * The mapping for this request.
     */
    private ServletMapping mapping = null;

    /**
     * The currently active session for this request.
     */
    protected Session session = null;

    /**
     * Special attributes.
     */
    protected final Object[] specialAttributes = new Object[specials.length];

    // ------------------------------------------------- ServletRequest Methods

    @Override
    public ServletContext getServletContext() {
        if (context == null) {
            return null;
        }
        return context.getServletContext();
    }

    /**
     * Override the getAttribute() method of the wrapped request.
     *
     * @param name Name of the attribute to retrieve
     */
    @Override
    public Object getAttribute(String name) {

        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
            return dispatcherType;
        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
            if ( requestDispatcherPath != null ){
                return requestDispatcherPath.toString();
            } else {
                return null;
            }
        }

        int pos = getSpecial(name);
        if (pos == -1) {
            return getRequest().getAttribute(name);
        } else {
            if ((specialAttributes[pos] == null) &&
                    (specialAttributes[SPECIALS_FIRST_FORWARD_INDEX] == null) &&
                    (pos >= SPECIALS_FIRST_FORWARD_INDEX)) {
                // If it's a forward special attribute, and null, it means this
                // is an include, so we check the wrapped request since
                // the request could have been forwarded before the include
                return getRequest().getAttribute(name);
            } else {
                return specialAttributes[pos];
            }
        }

    }

    /**
     * Override the getAttributeNames() method of the wrapped
     * request.
     */
    @Override
    public Enumeration<String> getAttributeNames() {
        return (new AttributeNamesEnumerator());
    }

    /**
     * Override the removeAttribute() method of the
     * wrapped request.
     *
     * @param name Name of the attribute to remove
     */
    @Override
    public void removeAttribute(String name) {

        if (!removeSpecial(name))
            getRequest().removeAttribute(name);

    }

    /**
     * Override the setAttribute() method of the
     * wrapped request.
     *
     * @param name Name of the attribute to set
     * @param value Value of the attribute to set
     */
    @Override
    public void setAttribute(String name, Object value) {

        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
            dispatcherType = (DispatcherType)value;
            return;
        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
            requestDispatcherPath = value;
            return;
        }

        if (!setSpecial(name, value)) {
            getRequest().setAttribute(name, value);
        }

    }

    /**
     * Return a RequestDispatcher that wraps the resource at the specified
     * path, which may be interpreted as relative to the current request path.
     *
     * @param path Path of the resource to be wrapped
     */
    @Override
    public RequestDispatcher getRequestDispatcher(String path) {

        if (context == null)
            return (null);

        // If the path is already context-relative, just pass it through
        if (path == null)
            return (null);
        else if (path.startsWith("/"))
            return (context.getServletContext().getRequestDispatcher(path));

        // Convert a request-relative path to a context-relative one
        String servletPath =
            (String) getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
        if (servletPath == null)
            servletPath = getServletPath();

        // Add the path info, if there is any
        String pathInfo = getPathInfo();
        String requestPath = null;

        if (pathInfo == null) {
            requestPath = servletPath;
        } else {
            requestPath = servletPath + pathInfo;
        }

        int pos = requestPath.lastIndexOf('/');
        String relative = null;
        if (pos >= 0) {
            relative = requestPath.substring(0, pos + 1) + path;
        } else {
            relative = requestPath + path;
        }

        return (context.getServletContext().getRequestDispatcher(relative));

    }

    /**
     * Override the getDispatcherType() method of the wrapped request.
     *
     */
    @Override
    public DispatcherType getDispatcherType() {
        return dispatcherType;
    }

    // --------------------------------------------- HttpServletRequest Methods

    /**
     * Override the getContextPath() method of the wrapped
     * request.
     */
    @Override
    public String getContextPath() {

        return (this.contextPath);

    }

    /**
     * Override the getParameter() method of the wrapped request.
     *
     * @param name Name of the requested parameter
     */
    @Override
    public String getParameter(String name) {

        parseParameters();

        String[] value = parameters.get(name);
        if (value == null) {
            return null;
        }
        return value[0];

    }

    /**
     * Override the getParameterMap() method of the
     * wrapped request.
     */
    @Override
    public Map<String, String[]> getParameterMap() {

        parseParameters();
        return (parameters);

    }

    /**
     * Override the getParameterNames() method of the
     * wrapped request.
     */
    @Override
    public Enumeration<String> getParameterNames() {

        parseParameters();
        return Collections.enumeration(parameters.keySet());
    }

    /**
     * Override the getParameterValues() method of the
     * wrapped request.
     *
     * @param name Name of the requested parameter
     */
    @Override
    public String[] getParameterValues(String name) {

        parseParameters();
        return parameters.get(name);

    }

    /**
     * Override the getPathInfo() method of the wrapped request.
     */
    @Override
    public String getPathInfo() {

        return (this.pathInfo);

    }

    /**
     * Override the getPathTranslated() method of the wrapped
     * request.
     */
    @Override
    public String getPathTranslated() {
        if (getPathInfo() == null || getServletContext() == null) {
            return null;
        }

        return getServletContext().getRealPath(getPathInfo());
    }

    /**
     * Override the getQueryString() method of the wrapped
     * request.
     */
    @Override
    public String getQueryString() {

        return (this.queryString);

    }

    /**
     * Override the getRequestURI() method of the wrapped
     * request.
     */
    @Override
    public String getRequestURI() {

        return (this.requestURI);

    }

    /**
     * Override the getRequestURL() method of the wrapped
     * request.
     */
    @Override
    public StringBuffer getRequestURL() {

        StringBuffer url = new StringBuffer();
        String scheme = getScheme();
        int port = getServerPort();
        if (port < 0)
            port = 80; // Work around java.net.URL bug

        url.append(scheme);
        url.append("://");
        url.append(getServerName());
        if ((scheme.equals("http") && (port != 80))
            || (scheme.equals("https") && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        url.append(getRequestURI());

        return (url);

    }

    /**
     * Override the getServletPath() method of the wrapped
     * request.
     */
    @Override
    public String getServletPath() {

        return (this.servletPath);

    }

    @Override
    public ServletMapping getServletMapping() {
        return mapping;
    }

    /**
     * Return the session associated with this Request, creating one
     * if necessary.
     */
    @Override
    public HttpSession getSession() {
        return (getSession(true));
    }

    /**
     * Return the session associated with this Request, creating one
     * if necessary and requested.
     *
     * @param create Create a new session if one does not exist
     */
    @Override
    public HttpSession getSession(boolean create) {

        if (crossContext) {

            // There cannot be a session if no context has been assigned yet
            if (context == null)
                return (null);

            // Return the current session if it exists and is valid
            if (session != null && session.isValid()) {
                return (session.getSession());
            }

            HttpSession other = super.getSession(false);
            if (create && (other == null)) {
                // First create a session in the first context: the problem is
                // that the top level request is the only one which can
                // create the cookie safely
                other = super.getSession(true);
            }
            if (other != null) {
                Session localSession = null;
                try {
                    localSession =
                        context.getManager().findSession(other.getId());
                    if (localSession != null && !localSession.isValid()) {
                        localSession = null;
                    }
                } catch (IOException e) {
                    // Ignore
                }
                if (localSession == null && create) {
                    localSession =
                        context.getManager().createSession(other.getId());
                }
                if (localSession != null) {
                    localSession.access();
                    session = localSession;
                    return session.getSession();
                }
            }
            return null;

        } else {
            return super.getSession(create);
        }

    }

    /**
     * Returns true if the request specifies a JSESSIONID that is valid within
     * the context of this ApplicationHttpRequest, false otherwise.
     *
     * @return true if the request specifies a JSESSIONID that is valid within
     * the context of this ApplicationHttpRequest, false otherwise.
     */
    @Override
    public boolean isRequestedSessionIdValid() {

        if (crossContext) {

            String requestedSessionId = getRequestedSessionId();
            if (requestedSessionId == null)
                return false;
            if (context == null)
                return false;
            Manager manager = context.getManager();
            if (manager == null)
                return false;
            Session session = null;
            try {
                session = manager.findSession(requestedSessionId);
            } catch (IOException e) {
                // Ignore
            }
            if ((session != null) && session.isValid()) {
                return true;
            } else {
                return false;
            }

        } else {
            return super.isRequestedSessionIdValid();
        }
    }

    @Override
    public PushBuilder newPushBuilder() {
        return new ApplicationPushBuilder(this);
    }

    // -------------------------------------------------------- Package Methods

    /**
     * Recycle this request
     */
    public void recycle() {
        if (session != null) {
            session.endAccess();
        }
    }

    /**
     * Set the context path for this request.
     *
     * @param contextPath The new context path
     */
    void setContextPath(String contextPath) {

        this.contextPath = contextPath;

    }

    /**
     * Set the path information for this request.
     *
     * @param pathInfo The new path info
     */
    void setPathInfo(String pathInfo) {

        this.pathInfo = pathInfo;

    }

    /**
     * Set the query string for this request.
     *
     * @param queryString The new query string
     */
    void setQueryString(String queryString) {

        this.queryString = queryString;

    }

    /**
     * Set the request that we are wrapping.
     *
     * @param request The new wrapped request
     */
    void setRequest(HttpServletRequest request) {

        super.setRequest(request);

        // Initialize the attributes for this request
        dispatcherType = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
        requestDispatcherPath = request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);

        // Initialize the path elements for this request
        contextPath = request.getContextPath();
        pathInfo = request.getPathInfo();
        queryString = request.getQueryString();
        requestURI = request.getRequestURI();
        servletPath = request.getServletPath();
        if (request instanceof org.apache.catalina.servlet4preview.http.HttpServletRequest) {
            mapping = ((org.apache.catalina.servlet4preview.http.HttpServletRequest) request).getServletMapping();
        } else {
            mapping = (new ApplicationMapping(null)).getServletMapping();
        }
    }

    /**
     * Set the request URI for this request.
     *
     * @param requestURI The new request URI
     */
    void setRequestURI(String requestURI) {

        this.requestURI = requestURI;

    }

    /**
     * Set the servlet path for this request.
     *
     * @param servletPath The new servlet path
     */
    void setServletPath(String servletPath) {

        this.servletPath = servletPath;

    }

    /**
     * Parses the parameters of this request.
     *
     * If parameters are present in both the query string and the request
     * content, they are merged.
     */
    void parseParameters() {

        if (parsedParams) {
            return;
        }

        parameters = new ParameterMap<>();
        parameters.putAll(getRequest().getParameterMap());
        mergeParameters();
        ((ParameterMap<String,String[]>) parameters).setLocked(true);
        parsedParams = true;
    }

    /**
     * Save query parameters for this request.
     *
     * @param queryString The query string containing parameters for this
     *                    request
     */
    void setQueryParams(String queryString) {
        this.queryParamString = queryString;
    }

    void setMapping(ServletMapping mapping) {
        this.mapping = mapping;
    }

    // ------------------------------------------------------ Protected Methods

    /**
     * Is this attribute name one of the special ones that is added only for
     * included servlets?
     *
     * @param name Attribute name to be tested
     */
    protected boolean isSpecial(String name) {

        for (int i = 0; i < specials.length; i++) {
            if (specials[i].equals(name))
                return true;
        }
        return false;

    }

    /**
     * Get a special attribute.
     *
     * @return the special attribute pos, or -1 if it is not a special
     *         attribute
     */
    protected int getSpecial(String name) {
        for (int i = 0; i < specials.length; i++) {
            if (specials[i].equals(name)) {
                return (i);
            }
        }
        return (-1);
    }

    /**
     * Set a special attribute.
     *
     * @return true if the attribute was a special attribute, false otherwise
     */
    protected boolean setSpecial(String name, Object value) {
        for (int i = 0; i < specials.length; i++) {
            if (specials[i].equals(name)) {
                specialAttributes[i] = value;
                return true;
            }
        }
        return false;
    }

    /**
     * Remove a special attribute.
     *
     * @return true if the attribute was a special attribute, false otherwise
     */
    protected boolean removeSpecial(String name) {
        for (int i = 0; i < specials.length; i++) {
            if (specials[i].equals(name)) {
                specialAttributes[i] = null;
                return true;
            }
        }
        return false;
    }

    /**
     * Merge the two sets of parameter values into a single String array.
     *
     * @param values1 First set of values
     * @param values2 Second set of values
     */
    private String[] mergeValues(String[] values1, String[] values2) {

        ArrayList<Object> results = new ArrayList<>();

        if (values1 == null) {
            // Skip - nothing to merge
        } else {
            for (String value : values1) {
                results.add(value);
            }
        }

        if (values2 == null) {
            // Skip - nothing to merge
        } else {
            for (String value : values2) {
                results.add(value);
            }
        }

        String values[] = new String[results.size()];
        return results.toArray(values);
    }

    // ------------------------------------------------------ Private Methods

    /**
     * Merge the parameters from the saved query parameter string (if any), and
     * the parameters already present on this request (if any), such that the
     * parameter values from the query string show up first if there are
     * duplicate parameter names.
     */
    private void mergeParameters() {

        if ((queryParamString == null) || (queryParamString.length() < 1))
            return;

        // Parse the query string from the dispatch target
        Parameters paramParser = new Parameters();
        MessageBytes queryMB = MessageBytes.newInstance();
        queryMB.setString(queryParamString);

        // TODO
        // - Should only use body encoding if useBodyEncodingForURI is true
        // - Otherwise, should use URIEncoding
        // - The problem is that the connector is not available...

        String encoding = getCharacterEncoding();
        Charset charset = null;
        if (encoding != null) {
            try {
                charset = B2CConverter.getCharset(encoding);
                queryMB.setCharset(charset);
            } catch (UnsupportedEncodingException e) {
                // Fall-back to default (ISO-8859-1)
                charset = StandardCharsets.ISO_8859_1;
            }
        }

        paramParser.setQuery(queryMB);
        paramParser.setQueryStringCharset(charset);
        paramParser.handleQueryParameters();

        // Insert the additional parameters from the dispatch target
        Enumeration<String> dispParamNames = paramParser.getParameterNames();
        while (dispParamNames.hasMoreElements()) {
            String dispParamName = dispParamNames.nextElement();
            String[] dispParamValues = paramParser.getParameterValues(dispParamName);
            String[] originalValues = parameters.get(dispParamName);
            if (originalValues == null) {
                parameters.put(dispParamName, dispParamValues);
                continue;
            }
            parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
        }
    }

    // ----------------------------------- AttributeNamesEnumerator Inner Class

    /**
     * Utility class used to expose the special attributes as being available
     * as request attributes.
     */
    protected class AttributeNamesEnumerator implements Enumeration<String> {

        protected int pos = -1;
        protected final int last;
        protected final Enumeration<String> parentEnumeration;
        protected String next = null;

        public AttributeNamesEnumerator() {
            int last = -1;
            parentEnumeration = getRequest().getAttributeNames();
            for (int i = specialAttributes.length - 1; i >= 0; i--) {
                if (getAttribute(specials[i]) != null) {
                    last = i;
                    break;
                }
            }
            this.last = last;
        }

        @Override
        public boolean hasMoreElements() {
            return ((pos != last) || (next != null)
                    || ((next = findNext()) != null));
        }

        @Override
        public String nextElement() {
            if (pos != last) {
                for (int i = pos + 1; i <= last; i++) {
                    if (getAttribute(specials[i]) != null) {
                        pos = i;
                        return (specials[i]);
                    }
                }
            }
            String result = next;
            if (next != null) {
                next = findNext();
            } else {
                throw new NoSuchElementException();
            }
            return result;
        }

        protected String findNext() {
            String result = null;
            while ((result == null) && (parentEnumeration.hasMoreElements())) {
                String current = parentEnumeration.nextElement();
                if (!isSpecial(current)) {
                    result = current;
                }
            }
            return result;
        }

    }

}


text:
package com.app.ui.user.panelControl.view;

import java.util.Iterator;
import java.util.List;

import org.ocpsoft.prettytime.PrettyTime;

import com.app.domain.model.types.Notificacion;
import com.app.domain.model.types.Persona;
import com.app.presenter.event.AppEducacionalEvent.CloseOpenWindowsEvent;
import com.app.presenter.event.AppEducacionalEvent.NotificationsCountUpdatedEvent;
import com.app.presenter.event.AppEducacionalEventBus;
import com.app.ui.AppUI;
import com.app.ui.components.NotificacionCreateWindow;
import com.app.ui.components.SparklineChart;
import com.app.ui.components.TopGrossingMoviesChart;
import com.app.ui.components.TopSixTheatersChart;
import com.app.ui.components.TopTenMoviesTable;
import com.app.ui.user.notificaciones.presenter.NotificacionesPresenter;
import com.app.ui.user.panelControl.presenter.PanelControlPresenter;
import com.google.common.eventbus.Subscribe;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Responsive;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ValoTheme;

/**
 * @author David
 *
 */
public class PanelControlView extends Panel implements View {

	/**
	 *
	 */
	private static final long serialVersionUID = 3179977221799819013L;
	public static final String EDIT_ID = "dashboard-edit";
	public static final String TITLE_ID = "dashboard-title";

	private static PanelControlPresenter presenter;

	private Label titleLabel;
	private NotificationsButton notificationsButton;
	private NotificationCreateButton notificationCreateButton;
	private CssLayout dashboardPanels;
	private final VerticalLayout root;
	private Window notificationsWindow;

	public PanelControlView() {
		presenter = PanelControlPresenter.getInstance();
		addStyleName(ValoTheme.PANEL_BORDERLESS);
		setSizeFull();
		AppEducacionalEventBus.register(this);

		root = new VerticalLayout();
		root.setSizeFull();
		root.setMargin(true);
		root.addStyleName("appeducacional-view");
		setContent(root);
		Responsive.makeResponsive(root);

		root.addComponent(buildHeader());

		root.addComponent(buildSparklines());

		Component content = buildContent();
		root.addComponent(content);
		root.setExpandRatio(content, 1);

		// All the open sub-windows should be closed whenever the root layout
		// gets clicked.
		root.addLayoutClickListener(new LayoutClickListener() {
			/**
			 *
			 */
			private static final long serialVersionUID = 7042531802982092911L;

			@Override
			public void layoutClick(final LayoutClickEvent event) {
				AppEducacionalEventBus.post(new CloseOpenWindowsEvent());
			}
		});
	}

	private Component buildSparklines() {
		CssLayout sparks = new CssLayout();
        sparks.addStyleName("sparks");
        sparks.setWidth("100%");
        Responsive.makeResponsive(sparks);

        SparklineChart s = new SparklineChart("Traffic", "K", "",
        		new SolidColor("#3090F0"), 22, 20, 80);
        sparks.addComponent(s);

        s = new SparklineChart("Revenue / Day", "M", "$",
        		new SolidColor("#98DF58"), 8, 89, 150);
        sparks.addComponent(s);

        s = new SparklineChart("Checkout Time", "s", "",
        		new SolidColor("#F9DD51"), 10, 30, 120);
        sparks.addComponent(s);

        s = new SparklineChart("Theater Fill Rate", "%", "",
        		 new SolidColor("#EC6464"), 50, 34, 100);
        sparks.addComponent(s);

        return sparks;
	}

	private Component buildHeader() {
		HorizontalLayout header = new HorizontalLayout();
		header.addStyleName("viewheader");
		header.setSpacing(true);

		titleLabel = new Label("Panel de Control");
		titleLabel.setId(TITLE_ID);
		titleLabel.setSizeUndefined();
		titleLabel.addStyleName(ValoTheme.LABEL_H1);
		titleLabel.addStyleName(ValoTheme.LABEL_NO_MARGIN);
		header.addComponent(titleLabel);

		notificationsButton = buildNotificationsButton();
		notificationCreateButton = buildNotificationCreateButton();
		HorizontalLayout tools = new HorizontalLayout(notificationsButton,notificationCreateButton);
		tools.setSpacing(true);
		tools.addStyleName("toolbar");
		header.addComponent(tools);

		return header;
	}

	private NotificationsButton buildNotificationsButton() {
		NotificationsButton result = new NotificationsButton();
		result.addClickListener(new ClickListener() {
			/**
			 *
			 */
			private static final long serialVersionUID = 7959321831705470982L;

			@Override
			public void buttonClick(final ClickEvent event) {
				openNotificationsPopup(event);
			}
		});
		return result;
	}

	private NotificationCreateButton buildNotificationCreateButton() {
		NotificationCreateButton result = new NotificationCreateButton();
		result.addClickListener(new ClickListener() {
			/**
			 *
			 */
			private static final long serialVersionUID = 7959321831705470982L;

			@Override
			public void buttonClick(final ClickEvent event) {
				NotificacionesPresenter presenter = NotificacionesPresenter.getInstance();
				Notificacion notificacion = presenter.create();
				NotificacionCreateWindow window =
						new NotificacionCreateWindow(notificacion, presenter);
				AppUI.getCurrent().addWindow(window);
			}
		});
		return result;
	}

	private Component buildContent() {
		dashboardPanels = new CssLayout();
		dashboardPanels.addStyleName("appeducacional-panels");
		Responsive.makeResponsive(dashboardPanels);

		dashboardPanels.addComponent(buildTopGrossingMovies());
		dashboardPanels.addComponent(buildNotes());
		dashboardPanels.addComponent(buildTop10TitlesByRevenue());
		dashboardPanels.addComponent(buildPopularMovies());

		return dashboardPanels;
	}

	private Component buildTopGrossingMovies() {
		TopGrossingMoviesChart topGrossingMoviesChart = new TopGrossingMoviesChart();
		topGrossingMoviesChart.setSizeFull();
		return createContentWrapper(topGrossingMoviesChart);
	}

	private Component buildNotes() {
		TextArea notes = new TextArea("Notes");
		String value = "Remember to:\n· Zoom in and out in the Sales view\n· Filter the transactions and drag a set of them to the Reports tab\n· Create a new report\n· Change the schedule of the movie theater";
		if (!(presenter.getCurrentPerson().getNotas() == null || presenter.getCurrentPerson().getNotas().length() == 0) )
			value = presenter.getCurrentPerson().getNotas();
		notes.setValue(value);
		notes.setSizeFull();
		notes.addStyleName(ValoTheme.TEXTAREA_BORDERLESS);
		Component panel = createContentWrapper(notes);
		panel.addStyleName("notes");
		return panel;
	}

	private Component buildTop10TitlesByRevenue() {
		Component contentWrapper = createContentWrapper(new TopTenMoviesTable());
		contentWrapper.addStyleName("top10-revenue");
		return contentWrapper;
	}

	private Component buildPopularMovies() {
		return createContentWrapper(new TopSixTheatersChart());
	}

	private Component createContentWrapper(final Component content) {
		final CssLayout slot = new CssLayout();
		slot.setWidth("100%");
		slot.addStyleName("appeducacional-panel-slot");

		CssLayout card = new CssLayout();
		card.setWidth("100%");
		card.addStyleName(ValoTheme.LAYOUT_CARD);

		HorizontalLayout toolbar = new HorizontalLayout();
		toolbar.addStyleName("appeducacional-panel-toolbar");
		toolbar.setWidth("100%");

		Label caption = new Label(content.getCaption());
		caption.addStyleName(ValoTheme.LABEL_H4);
		caption.addStyleName(ValoTheme.LABEL_COLORED);
		caption.addStyleName(ValoTheme.LABEL_NO_MARGIN);
		content.setCaption(null);

		MenuBar tools = new MenuBar();
		tools.addStyleName(ValoTheme.MENUBAR_BORDERLESS);
		if ( content instanceof TextArea ){
			MenuItem save = tools.addItem("", FontAwesome.SAVE,new Command() {

				/**
				 *
				 */
				private static final long serialVersionUID = 1L;

				@Override
				public void menuSelected(MenuItem selectedItem) {
					String notes = ((TextArea)content).getValue();
					Persona p = presenter.getCurrentPerson();
					p.setNotas(notes);
					presenter.savePerson(p);
				}
			});
			save.setStyleName("icon-only");
		}

		MenuItem max = tools.addItem("", FontAwesome.EXPAND, new Command() {

			/**
			 *
			 */
			private static final long serialVersionUID = -1943034390434178282L;

			@Override
			public void menuSelected(final MenuItem selectedItem) {
				if (!slot.getStyleName().contains("max")) {
					selectedItem.setIcon(FontAwesome.COMPRESS);
					toggleMaximized(slot, true);
				} else {
					slot.removeStyleName("max");
					selectedItem.setIcon(FontAwesome.EXPAND);
					toggleMaximized(slot, false);
				}
			}
		});
		max.setStyleName("icon-only");
		MenuItem root = tools.addItem("", FontAwesome.COG, null);
		root.addItem("Configure", new Command() {
			/**
			 *
			 */
			private static final long serialVersionUID = 6850093122298654078L;

			@Override
			public void menuSelected(final MenuItem selectedItem) {
				Notification.show("Not implemented in this demo");
			}
		});
		root.addSeparator();
		root.addItem("Close", new Command() {
			/**
			 *
			 */
			private static final long serialVersionUID = 2993982684259298243L;

			@Override
			public void menuSelected(final MenuItem selectedItem) {
				Notification.show("Not implemented in this demo");
			}
		});

		toolbar.addComponents(caption, tools);
		toolbar.setExpandRatio(caption, 1);
		toolbar.setComponentAlignment(caption, Alignment.MIDDLE_LEFT);

		card.addComponents(toolbar, content);
		slot.addComponent(card);
		return slot;
	}

	private void openNotificationsPopup(final ClickEvent event) {
		VerticalLayout notificationsLayout = new VerticalLayout();
		notificationsLayout.setMargin(true);
		notificationsLayout.setSpacing(true);

		Label title = new Label("Notificaciones no leídas");
		title.addStyleName(ValoTheme.LABEL_H3);
		title.addStyleName(ValoTheme.LABEL_NO_MARGIN);
		notificationsLayout.addComponent(title);
		List<Notificacion> notifications = presenter.getListNotificacionesNoLeidas();

		AppEducacionalEventBus.post(new NotificationsCountUpdatedEvent());

		for (Notificacion notification : notifications) {
			VerticalLayout notificationLayout = new VerticalLayout();
			notificationLayout.addStyleName("notification-item");
			PrettyTime prettyTime = new PrettyTime(getLocale());
			String titulo = "";
			if (notification.getEmisor().equals("Profesor")){
				titulo = notification.getProfesor().getNombre()
						+ " " + notification.getProfesor().getApellidos() + " " +
						FontAwesome.BULLHORN.getHtml() + " " +
						(notification.getTitulo().length() > 30 ?
								notification.getTitulo().substring(0,30) :
									notification.getTitulo());
			}else{
				titulo = notification.getPadreMadreOTutor().getNombre()
						+ " " + notification.getPadreMadreOTutor().getApellidos()
						+ " " + FontAwesome.BULLHORN.getHtml() + " " +
						(notification.getTitulo().length() > 30 ?
								notification.getTitulo().substring(0,30) :
									notification.getTitulo());
			}
			Label titleLabel = new Label(titulo);
			titleLabel.setContentMode(ContentMode.HTML);
			titleLabel.addStyleName("notification-title");
			Label timeLabel = new Label(prettyTime.format(notification.getFecha()));
			timeLabel.addStyleName("notification-time");
			String contenido = notification.getContenido().length() > 35 ?
					notification.getContenido().substring(0,35) :
						notification.getContenido();
			Label contentLabel = new Label(contenido);
			contentLabel.addStyleName("notification-content");
			contentLabel.setContentMode(ContentMode.HTML);

			notificationLayout.addComponents(titleLabel, timeLabel,
					contentLabel);
			notificationsLayout.addComponent(notificationLayout);
		}

		HorizontalLayout footer = new HorizontalLayout();
		footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);
		footer.setWidth("100%");
		Button showAll = new Button("Ver Notificaciones",
				new ClickListener() {
					/**
					 *
					 */
					private static final long serialVersionUID = 5594631503767611801L;

					@Override
					public void buttonClick(final ClickEvent event) {
						notificationsWindow.close();
						AppUI.getCurrent().getNavigator().navigateTo("notificaciones");
					}
				});
		showAll.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
		showAll.addStyleName(ValoTheme.BUTTON_SMALL);
		footer.addComponent(showAll);
		footer.setComponentAlignment(showAll, Alignment.TOP_CENTER);
		notificationsLayout.addComponent(footer);

		if (notificationsWindow == null) {
			notificationsWindow = new Window();
			notificationsWindow.setWidth(300.0f, Unit.PIXELS);
			notificationsWindow.addStyleName("notifications");
			notificationsWindow.setClosable(false);
			notificationsWindow.setResizable(false);
			notificationsWindow.setDraggable(false);
			notificationsWindow.setCloseShortcut(KeyCode.ESCAPE, null);
			notificationsWindow.setContent(notificationsLayout);
		}

		if (!notificationsWindow.isAttached()) {
			notificationsWindow.setPositionY(event.getClientY()
					- event.getRelativeY() + 40);
			getUI().addWindow(notificationsWindow);
			notificationsWindow.focus();
		} else {
			notificationsWindow.close();
		}
	}

	@Override
	public void enter(final ViewChangeEvent event) {
		notificationsButton.updateNotificationsCount(null);
	}

	/*
	 * @Override public void dashboardNameEdited(final String name) {
	 * titleLabel.setValue(name); }
	 */

	private void toggleMaximized(final Component panel, final boolean maximized) {
		for (Iterator<Component> it = root.iterator(); it.hasNext();) {
			it.next().setVisible(!maximized);
		}
		dashboardPanels.setVisible(true);

		for (Iterator<Component> it = dashboardPanels.iterator(); it.hasNext();) {
			Component c = it.next();
			c.setVisible(!maximized);
		}

		if (maximized) {
			panel.setVisible(true);
			panel.addStyleName("max");
		} else {
			panel.removeStyleName("max");
		}
	}

	public static final class NotificationsButton extends Button {
		/**
		 *
		 */
		private static final long serialVersionUID = 2993136376885547514L;
		private static final String STYLE_UNREAD = "unread";
		public static final String ID = "dashboard-notifications";

		public NotificationsButton() {
			setIcon(FontAwesome.BELL);
			setId(ID);
			addStyleName("notifications");
			addStyleName(ValoTheme.BUTTON_ICON_ONLY);
			AppEducacionalEventBus.register(this);
		}

		@Subscribe
		public void updateNotificationsCount(
				final NotificationsCountUpdatedEvent event) {
			setUnreadCount(presenter.getNotificacionesNoLeidas());
		}

		public void setUnreadCount(final int count) {
			setCaption(String.valueOf(count));

			String description = "Notifications";
			if (count > 0) {
				addStyleName(STYLE_UNREAD);
				description += " (" + count + " unread)";
			} else {
				removeStyleName(STYLE_UNREAD);
			}
			setDescription(description);
		}
	}

	public static final class NotificationCreateButton extends Button {
		/**
		 *
		 */
		private static final long serialVersionUID = 2993136376885547514L;
		public static final String ID = "dashboard-notifications";

		public NotificationCreateButton() {
			setIcon(FontAwesome.SEND);
			setId(ID);
			addStyleName("notifications");
			addStyleName(ValoTheme.BUTTON_ICON_ONLY);
			AppEducacionalEventBus.register(this);
		}

	}

}


text:
<?php

namespace ChillDev\Bundle\ViewHelpersBundle\Tests\PathResolver\Transformer;

use PHPUnit_Framework_TestCase;

use ChillDev\Bundle\ViewHelpersBundle\PathResolver\Transformer\CustomTransformer;

/**
 * @author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
 * @copyright 2013 © by Rafał Wrzeszcz - Wrzasq.pl.
 * @version 0.1.5
 * @since 0.1.5
 * @package ChillDev\Bundle\ViewHelpersBundle
 */
class CustomTransformerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     * @version 0.1.5
     * @since 0.1.5
     */
    public function transform()
    {
        $prefix = 'foo/';
        $path = 'bar';

        $transformer = new CustomTransformer($prefix);

        $this->assertEquals($prefix . $path, $transformer->transform($path), 'CustomTransformer::transform() should prepand path with base URL.');
    }
}


text:
layout: post
title: "Whiskey Review: Oban (14 Year)"
excerpt: "Pop Culture"
categories: popculture
comments: false
share: true
---

![](https://img.thewhiskyexchange.com/540/obnob.14yo.jpg)

There are five main regions where scotches come from: Speyside (north area), Highland (well, that is in the north area as well), Lowlands (south area), Islay (the isles south of Scotland), and Cambeltown (a freaky little area in the butt of Scotland). As said earlier, each region has their own thing. So to completely explode scotch, we much try a quaff from each of these regions, don't you think?

So my first review was of The Balvenie Doublewood 12 yr; that is a Speyside drink.

My second review was of Laphroiag 10 yr; that is from Islay.

This one is from the Highland region (a very similar region to Speyside) and this one is a crowd pleasure to say the least:

The Oban 14 yr!!!!

If you never have heard of Oban, well wake the hell up!! Sure, it is not as prevalent as a Glenlivet or MaCallan, but if you want any sort of rep in the whiskey world, you have to tie one of these on before you get some street cred.

Let's look at some of the tasting notes:

Nose: Fruity and smoky. Yes, that sounds like a bit of a dichotomy, but imagine roasting a pear on an open flame. Doesn't sound so unusual now, huh? A real zesty, salty, and citrus-like aroma fills your nasal canal with a light jab of toffee

Taste: Rich and fruity. Well, what do you expect, it tastes like it smells. The citrus flavor covers your mouth, mostly pear and orange tones, and fills your palette with joy. There are subtle hints of smoke and caramel mixed in there for balance, but the taste it primarily like there is an Anjou crammed under your tongue.

Finish: The fruity aspects make way for the toffee and sea salt aftertaste upon exhaling. But don't you worry, that fruit sensation is still there, but just it is polity letting the more briny aspects partake as well. Oban leaves your mouth happy, making you want more.

This is a great libation for those who are new to the scotch game; it is not too peaty to scare the lesser palettes away, but is not a bubblegum fruity drink that doesn't really represent the sophisticated taste of scotch. In other words, Oban is well balanced across the board; sweet, fruity, toffee, salty, spicy, smoky, and all of those other tastes that I cannot pick up but experts say that are in there.

Now I know the Oban 14 is not the cheapest of scotches; I have seen it from $14-$25 a pour!! $25? Say what? But don't worry, your local Total Wine or Bevmo will probably have this guy for around $70; not so bad considering the cost of a dram of this stuff at your local bar represents a typical $100 bottle.

So buy one of these if ~$70 is in your wheelhouse. I promise you won't be disappointed.


text:
import { env } from "../../../../y_environment/env"

import { newGetVersionsRemote } from "../infra/remote/get_versions"

import { FindAllVersionInfra } from "../infra"

export function newFindAllVersionInfra(): FindAllVersionInfra {
    return {
        version: env.version,
        versionsURL: env.isProduction ? "/versions.txt" : "/root/versions.txt",
        get: newGetVersionsRemote(),
        config: {
            takeLongtimeThreshold: { delay_millisecond: 300 },
        },
    }
}


text:
namespace wi {

HttpRequest *SdlHttpService::NewRequest(HttpResponseHandler *phandler) {
    return new SdlHttpRequest(phandler);
}

void SdlHttpService::SubmitRequest(HttpRequest *preq) {
    SdlHttpRequest *preqT = (SdlHttpRequest *)preq;
    preqT->Submit();
}

void SdlHttpService::ReleaseRequest(HttpRequest *preq) {
    SdlHttpRequest *preqT = (SdlHttpRequest *)preq;
    preqT->Release();
}

} // namespace wi


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2016-2022 Armel Soro

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<resources>
    <string name="maoni_app_name">Maoni デモ</string>
    <string name="maoni_settings_activity_name">Maoni デモ設定</string>
    <string name="feedback">フィードバック</string>
    <string name="title_activity_maoni_sample_main">Maoni デモ</string>
    <string name="main_activity_text"><![CDATA[これは、既存アプリ内からユーザーのフィードバックを収集するために使用することができる、すぐに使えるマテリアルデザインのアクティビティを提供する軽量ライブラリ、Maoni のデモアプリケーションです。
\n
他の類似のライブラリとは異なり、Maoni は、現在のアクティビティのスクリーンショットをキャプチャすることが、コールバックで操作することができます。
\n\n
下のフローティング アクション ボタンをタッチすると、Maoni のアクティビティを開きます。
\n\n
詳細については http://github.com/rm3l/maoni をご覧ください。    ]]></string>
    <string name="action_about">アプリついて</string>
    <string name="default_email_addr">some.one@somewhe.re</string>
    <string name="send_feedback_activity_title">フィードバックを送信</string>
    <string name="send_feedback_activity_intro"><![CDATA[        こんにちは! このアプリが気に入っていただけましたか? お聞かせください。
        \n\n
        注: Maoniはほぼすべてカスタマイズできます。
    ]]></string>
    <string name="feedback_content_hint">貴重なご意見をお聞かせください。</string>
    <string name="include_app_logs">アプリケーションログを添付</string>
    <string name="include_app_screenshot">画面のキャプチャを添付</string>
    <string name="touch_edit_screenshot">タップすると、プレビューして、注釈を記入します</string>
    <string name="content_error_message">これはユーザーに表示する、カスタム エラー メッセージです</string>
    <string name="screenshot_hint">これは、画面キャプチャの横に表示して、理由を説明するために役立つと思われるカスタム メッセージです。</string>
    <string name="email_address">メールアドレス</string>
    <string name="an_extra_text_area">追加のテキストエリア</string>
    <string name="edittext_hint_write_something_here">テキスト編集のヒント。ここに何かを書きます。</string>
    <string name="an_extra_radiogroup">追加のラジオ グループ</string>
    <string name="rg_1">RG 1</string>
    <string name="rg_2">RG 2</string>
    <string name="rg_3">RG 3</string>
    <string name="send_maoni_email">メールで送信 (maoni メール)</string>
    <string name="send_maoni_github">Github イシューとして送信 (maoni github)</string>
    <string name="send_maoni_jira">JIRA イシューとして送信 (maoni jira)</string>
    <string name="send_maoni_slack">"Slack に送信 (maoni slack)"</string>
    <string name="how_to_send_feedback">あなたのフィードバックを送信しますか?</string>
    <string name="action_settings">設定</string>
    <string name="action_bottom_sheet">Bottom Sheet</string>
</resources>