text:
This section presents all the steps to model an [Aggregate](https://martinfowler.com/bliki/DDD_Aggregate.html), as defined in Domain-Driven Design, using [Akka Persistence Typed](https://doc.akka.io/docs/akka/2.6/typed/persistence.html) and following the [[CQRS|ES_CQRS]] principles embraced by Lagom. While Akka Persistence Typed provides an API for building event-sourced actors, the same does not necessarily apply for CQRS Aggregates. To build CQRS applications, we need to use a few rules to our design.

We use a simplified shopping cart example to guide you through the process. You can find a full-fledged shopping cart sample on our [samples repository](https://github.com/lagom/lagom-samples/tree/1.6.x/shopping-cart/shopping-cart-scala).

## Encoding the model

Start by defining your model in terms of Commands, Events, and State.

### Modelling the State

The state of the shopping cart is defined as following:

@[shopping-cart-state](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

Note that we are modeling it using a case class `ShoppingCart`, and there is a `checkedOutTime` that can be set when transitioning from one state (open shopping cart) to another (checked-out shopping cart). As we will see later, each state encodes the commands it can handle, which events it can persist, and to which other states it can transition.

> **Note**: This is not the recommended technique, though. Whenever your model goes through different state transitions, the recommendation is to have a trait and extensions of it for each state. See examples in the [style guide for Akka Persistence Typed](https://doc.akka.io/docs/akka/2.6/typed/persistence-style.html).

### Modelling Commands and Replies

Next, we define the commands that we can send to it.

Each command defines a [reply](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#replies) through a `replyTo: ActorRef[R]` field where `R` is the reply that will be sent back to the caller. Replies are used to communicate back if a command was accepted or rejected or to read the aggregate data (ie: read-only commands). It is also possible to have a mix of both. For example, if the command succeeds, it returns some updated data; if it fails, it returns a rejected message. Or you can have commands without replies (ie: fire-and-forget). This is a less common pattern in CQRS Aggregate modeling though and not covered in this example.

@[shopping-cart-commands](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

In Akka Typed, it's not possible to return an exception to the caller. All communication between the actor and the caller must be done via the `replyTo:ActorRef[R]` passed in the command. Therefore, if you want to signal a rejection, you most have it encoded in your reply protocol.

The replies used by the commands above are define like this:

@[shopping-cart-replies](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

Here there are two different kinds of replies: `Confirmation` used when we want to modify the state. A modification request can be `Accepted` or `Rejected`. The `Summary` is used when we want to read the state of the shopping cart.

> **Note**: Keep in mind that `Summary` is not the shopping cart itself, but the representation we want to expose to the external world. It's a good practice to keep the internal state of the aggregate private because it allows the internal state, and the exposed API to evolve independently.

### Modelling Events

Next, we define the events that our model will persist. The events must extend Lagom's [`AggregateEvent`](api/com/lightbend/lagom/scaladsl/persistence/AggregateEvent.html). This is important for tagging events. We will cover this topic a little further.

@[shopping-cart-events](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

### Defining Commands Handlers

Once you define your protocol in terms of Commands, Replies, Events, and State, you need to specify the business rules of your model. The command handlers define how to handle each incoming command, which validations must be applied, and finally, which events will be persisted if any.

You can encode it in different ways. The [recommended style](https://doc.akka.io/docs/akka/2.6/typed/persistence-style.html#command-handlers-in-the-state) is to add the command handlers in your state classes. For `ShoppingCart`, we can define the command handlers based on the two possible states:

@[shopping-cart-command-handlers](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

> **Note**: of course, it is possible to organize the command handlers in a way that you consider more convenient for your use case, but we recommend the `onCommand` pattern since it can help to keep the logic for each command well isolated.

Command handlers are the meat of the model. They encode the business rules of your model and act as a guardian of the model consistency. The command handler must first validate that the incoming command can be applied to the current model state. In case of successful validation, one or more event expressing the mutations are persisted. Once the events are persisted, they are applied to the state producing a new valid state.

Because an Aggregate is intended to model a consistency boundary, it's not recommended validating commands using data that is not available in scope. Any decision should be solely based on the data passed in the commands and the state of the Aggregate. Any external call should be considered a smell because it means that the Aggregate is not in full control of the invariants it's supposed to be protecting.

There are two ways of sending back a reply: using `Effect.reply` and `Effect.persist(...).thenReply`. The first one is available directly on `Effect` and should be used when you reply without persisting any event. In this case, you can use the available state in scope because it's guaranteed not to have changed. The second variant should be used when you have persisted one or more events. The updated state is then available to you on the function used to define the reply.

You may run side effects inside the command handler. Please refer to [Akka documentation](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#effects-and-side-effects) for detailed information.

### Defining the Event Handlers

The event handlers are used to mutate the state of the Aggregate by applying the events to it. Event handlers must be pure functions as they will be used when instantiating the Aggregate and replaying the event journal. Similar to the command handlers, a [recommended style](https://doc.akka.io/docs/akka/2.6/typed/persistence-style.html#command-handlers-in-the-state) is to add them in the state classes.

@[shopping-cart-state-event-handlers](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

### EventSourcingBehaviour - gluing the bits together

With all the model encoded, the next step is to glue all the pieces together, so we can let it run as an Actor. To do that, define an `EventSourcedBehavior`. It's recommended to define an `EventSourcedBehavior` using `withEnforcedReplies` when modeling a CQRS Aggregate. Using [enforced replies](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#replies) requires command handlers to return a `ReplyEffect` forcing the developers to be explicit about replies.

@[shopping-cart-create-behavior](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

The `EventSourcedBehavior.withEnforcedReplies` has four fields to be defined: `persistenceId`, `emptyState`, `commandHandler` and `eventHandler`.

The `persistenceId` defines the id that will be used in the event journal. The id is composed of a name (for example, `entityContext.entityTypeKey.name`) and a business id (for example, `entityContext.entityId`). These two values will be concatenated using a `"|"` by default (for example, `"ShoppingCart|123456"`). See [Akka's documentation](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#persistenceid) for more details.

> **Note**: The `entityContext` that appears in scope here will be introduced when covering `ClusterSharding` later in this guide.

The `emptyState` is the state used when the journal is empty. It's the initial state:

@[shopping-cart-empty-state](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

The `commandHandler` is a function `(State, Command) => ReplyEffect[Event, State]`. In this example, it's being defined using the `applyCommand` on the passed state. Equally, the `eventHandler` is a function `(State, Event) => Event` and defined in the passed state.

### Changing behavior -- Finite State Machines

If you are familiar with general Akka Actors, you are probably aware that after processing a message, you should return the next behavior to be used. With Akka Persistence Typed this happens differently. Command handlers and event handlers are all dependent on the current state, therefore can you change behavior by returning a new state in the event handler. Consult the [Akka documentation](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#changing-behavior) for more insight on this topic.

### Tagging the events -- Akka Persistence Query considerations

Events are persisted in the event journal and are primarily used to replay the state of the Aggregate each time it needs to be instantiated. However, in CQRS, we also want to consume those same events and generate read-side views or publish them in a message broker (eg: Kafka) for external consumption.

To be able to consume the events on the read-side, the events must be tagged. This is done using the `AggregateEventTag` utility. It's recommended to shard the tags so they can be consumed in a distributed fashion by Lagom's [[Read-Side Processor|ReadSide]] and [[Topic Producers|MessageBrokerApi#Implementing-a-topic]]. Although not recommended, it's also possible to not shard the events as explained [[here|ReadSide#Event-tags]].

This example splits the tags into 10 shards and defines the event tagger in the companion object of `ShoppingCart.Event`. Note that the tag name must be stable, as well as the number of shards. These two values can't be changed later without migrating the journal.

@[shopping-cart-events-object](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

The `AggregateEventTag` is a Lagom class used by Lagom's [Read-Side Processor|ReadSide]] and [[Topic Producers|MessageBrokerApi#Implementing-a-topic]], however Akka Persistence Typed expects a function `Event => Set[String]`. Therefore, we need to use an adapter to transform Lagom's `AggregateEventTag` to the required Akka tagger function.

@[shopping-cart-create-behavior-with-tagger](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

### Configuring snapshots

Snapshotting is a common optimization to avoid replaying all the events since the beginning.

You can define snapshot rules in two ways: by predicate and by counter. Both can be combined. The example below uses a counter to illustrate the APIs. You can find more details on the [Akka documentation](https://doc.akka.io/docs/akka/2.6/typed/persistence-snapshot.html).

@[shopping-cart-create-behavior-with-snapshots](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

## Akka Cluster Sharding

Lagom uses [Akka Cluster Sharding](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html) to distribute the Aggregates across all the nodes and guarantee that, at any single time, there is only one instance of a given Aggregate loaded in memory over the whole cluster.

### Creating the Aggregate instance

The Aggregate needs to be initialized on the `ClusterSharding` before its use. That process won't create any specific Aggregate instance, and it will only create the Shard Regions and prepare it to be used (read more about Shard Regions in the [Akka Cluster Sharding](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html) docs).

> **Note**: In Akka Cluster, the term to refer to a sharded actor is _entity_, so a sharded Aggregate can also be referred to as an Aggregate Entity.

In the companion object of `ShoppingCart`, define an `EntityTypeKey` and factory method to initialize the `EventSourcedBehavior` for the Shopping Cart Aggregate. The `EntityTypeKey` has a name to identify this model in the cluster uniquely. It's also typed on `ShoppingCart.Command` which is the type of messages that the Aggregate can receive:

@[shopping-cart-entity-type-key](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

The `EntityTypeKey` has as name to uniquely identify this model in the cluster. It should be typed on `ShoppingCartCommand` which is the type of the messages that the Shopping Cart can receive.

In the companion object of `ShoppingCart`, define the `EntityTypeKey` and factory method to initialize the `EventSourcedBehavior` for the Shopping Cart Aggregate.

@[shopping-cart-apply-behavior-creation](code/docs/home/scaladsl/persistence/ShoppingCart.scala)

> **Note**: [Akka style guide](https://doc.akka.io/docs/akka/2.6/typed/style-guide.html) recommends having an `apply` factory method in the companion object and making the constructor private.

Finally, initialize the Aggregate on the `ClusterSharding` using the `typedKey` and the `behavior`. Lagom provides an instance of the `clusterSharding` extension through dependency injection for your convenience. Initializing an entity should be done only once and, in the case of Lagom Aggregates it is typically done in the `LagomApplication`:

@[shopping-cart-loader](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

### Getting instances of the Aggregate Entity

To access instances of the Aggregate (which may be running locally or remotely on the cluster), you should inject the `ClusterSharding` on your service:

@[shopping-cart-service-impl](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

And then you can instantiate an `EntityRef` using the method `entityRef`. In our case, the `EntityRef` is typed to only accept `ShoppingCart.Command`s.

@[shopping-cart-entity-ref](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

To locate the correct actor across the cluster, you need to specify the `EntityTypeKey` we used to initialize the entity and the `id` for the instance we need. Akka Cluster will create the required actor in one node on the cluster or reuse the existing instance if the actor has already been created and is still alive.

The `EntityRef` is similar to an `ActorRef` but denotes the actor is sharded. Interacting with an `EntityRef` implies the messages exchanged with the actor may need to travel over the wire to another node.

#### Considerations on using `ask` pattern

Since we want to send commands to the Aggregate and these commands declare a reply we will need to use the [`ask` pattern](https://doc.akka.io/docs/akka/2.6/typed/interaction-patterns.html#request-response).

The code we introduced above creates an `EntityRef` from inside the `ShoppingCartServiceImpl` meaning we are calling the actor (the `EntityRef`) from outside the `ActorSystem`. `EntityRef` provides an `ask()` overload out of the box meant to be used from outside actors which is the situation we're in.

@[shopping-cart-service-call](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

So we declare an implicit `timeout` and then invoke `ask` (which uses the timeout implicitly). The `ask` method accepts a function of `ActorRef[Res] => M` in which `Res` is the expected response type and `M` is the message being sent to the actor. The `ask` method will create an instance of `ActorRef[Res]` that can be use to build the outgoing message (command). Once the response is sent to `ActorRef[Res]`, Akka will complete the returned `Future[Res]` with the response (in this case `Future[ShoppingCartSummary]`).

@[shopping-cart-service-view](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

Finally, we operate over the `cartSummary` normally (in this case, we map it to a different type). The `convertShoppingCart` is like:

@[shopping-cart-service-map](code/docs/home/scaladsl/persistence/ShoppingCartLoader.scala)

> **Note**: Again, we are keeping the internal state of the Aggregate isolated from the exposed service API so they can evolve independently.

### Configuring number of shards

Akka recommends, as a rule of thumb, that the number of shards should be a factor ten higher than the planned maximum number of cluster nodes. It doesn't have to be exact. Fewer shards than the number of nodes will result in that some nodes will not host any shards. Too many shards will result in less efficient management of the shards, e.g. rebalancing overhead, and increased latency because the coordinator is involved in the routing of the first message for each shard.

See the [Akka Cluster Sharding documentation](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html#shard-allocation) for details on how to configure the number of shards.

### Configuring Entity passivation

Keeping all the Aggregates in memory all the time is inefficient. Instead, use the Entity passivation feature, then sharded entities (the Aggregates) are removed from the cluster when they've been unused for some time.

Akka supports both [programmatic passivation](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html#passivation) and [automatic passivation](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html#automatic-passivation). The default values for automatic passivation are generally good enough.

## Data Serialization

The messages (commands, replies) and the durable classes (events, state snapshots) need to be serializable to be sent over the wire across the cluster or be stored on the database. Akka recommends [Jackson-based serializers](https://doc.akka.io/docs/akka/2.6/serialization-jackson.html) --preferably JSON, but CBOR is also supported-- as a good default in most cases. On top of Akka serializers, Lagom makes it easy to add [[Play-JSON serialization|SerializationPlayJson]] support, which may be more familiar to some Scala developers.

In [Akka Persistence Typed](https://doc.akka.io/docs/akka/2.6/typed/persistence.html), in particular, and when you adopt CQRS/ES practices, commands will include a `replyTo: ActorRef[Reply]` field. This `replyTo` field will be used on your code to send a `Reply` back, as shown in the examples above. Serializing an `ActorRef[T]` requires using the Akka Jackson serializer, meaning you cannot use Play-JSON to serialize commands.

The limitation to use Akka Jackson for Command messages doesn't apply to other messages like events, snapshots, or even replies. Each type Akka needs to serialize may use a different serializer.

Read more about the serialization setup and configuration in the [[serialization|Serialization]] section.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;

namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        private readonly TodoContext _context;

        public TodoController(TodoContext context)
        {
            _context = context;
        }

        [HttpGet]
        public IEnumerable<TodoItem> GetAll()
        {
            return _context.TodoItems.ToList();
        }

        [HttpGet("{id}", Name = "GetTodo")]
        public IActionResult GetById(int id)
        {
            var item = _context.TodoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
            {
                return NotFound();
            }

            return new ObjectResult(item);
        }

        [HttpPost]
        public IActionResult Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            _context.TodoItems.Add(item);
            _context.SaveChanges();

            return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
        }

        [HttpPut("{id}")]
        public IActionResult Update(long id, [FromBody] TodoItem item)
        {
            if (item == null || item.Id != id)
            {
                return BadRequest();
            }

            var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id);
            if (todo == null)
            {
                return NotFound();
            }

            todo.Done = item.Done;
            todo.Name = item.Name;

            _context.TodoItems.Update(todo);
            _context.SaveChanges();

            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(long id)
        {
            var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id);
            if (todo == null)
            {
                return NotFound();
            }

            _context.TodoItems.Remove(todo);
            _context.SaveChanges();
            return NoContent();
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

	<title>Message Log</title>
	<link rel="stylesheet" type="text/css" href="../assets/msg_sniffer.css" />

<form style="margin:0px; padding:0px;">

XML Message History

					<select style="width:150px;" id="sniffer_Origin" onchange="SnifferDisplay.changedOrigin(this)">
						<option value="ALL" selected="selected">All Views</option>
					</select>
					<select style="width:150px;" style="margin-left:0px;" id="sniffer_CommChannel" onchange="SnifferDisplay.changedChannel(this)">
						<option value="ALL">All Cells</option>
					</select>
					<select style="width:250px;" id="sniffer_ChannelAction" onchange="SnifferDisplay.changedAction(this)">
						<option value="ALL" selected="selected">All Actions</option>
					</select>

	<input type="button" style="float: right; margin-right: 15px; width:70px;" value="Clear" onclick="SnifferDisplay.ClearLog()"/>
	<input type="button" style="margin:0px 5px; width:70px;" value="Refresh" onclick="SnifferDisplay.refresh()"/>

</form>

sent

rcvd

action

cell

			called by origin @
			T+1


text:
//Provides control sap.ui.unified.Calendar.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/LocaleData', 'sap/ui/model/type/Date', 'sap/ui/unified/calendar/CalendarUtils',
               './Calendar', './calendar/Header', './calendar/Month', './calendar/DatesRow', './calendar/MonthPicker', './calendar/YearPicker', 'sap/ui/unified/calendar/CalendarDate', './library'],
               function(jQuery, Control, LocaleData, Date1, CalendarUtils, Calendar, Header, Month, DatesRow, MonthPicker, YearPicker, CalendarDate, library) {
	"use strict";

	/*
	* Inside the CalendarDateInterval CalendarDate objects are used. But in the API JS dates are used.
	* So conversion must be done on API functions.
	*/

	/**
	 * Constructor for a new CalendarDateInterval.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * Calendar with dates displayed in one line.
	 * @extends sap.ui.unified.Calendar
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.30.0
	 * @alias sap.ui.unified.CalendarDateInterval
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var CalendarDateInterval = Calendar.extend("sap.ui.unified.CalendarDateInterval", /** @lends sap.ui.unified.CalendarDateInterval.prototype */ { metadata : {

		library : "sap.ui.unified",
		properties : {

			/**
			 * Start date of the Interval
			 */
			startDate : {type : "object", group : "Data"},

			/**
			 * number of days displayed
			 * on phones the maximum rendered number of days is 8.
			 */
			days : {type : "int", group : "Appearance", defaultValue : 7},

			/**
			 * If set the day names are shown in a separate line.
			 * If not set the day names are shown inside the single days.
			 * @since 1.34.0
			 */
			showDayNamesLine : {type : "boolean", group : "Appearance", defaultValue : true},

			/**
			 * If set, the month- and yearPicker opens on a popup
			 * @since 1.34.0
			 */
			pickerPopup : {type : "boolean", group : "Appearance", defaultValue : false}

		}
	}});

	CalendarDateInterval.prototype.init = function(){

		Calendar.prototype.init.apply(this, arguments);

		var oMonthPicker = this.getAggregation("monthPicker");
		oMonthPicker.setColumns(0);
		oMonthPicker.setMonths(3); // default for 7 days
		oMonthPicker.attachEvent("pageChange", _handleMonthPickerPageChange, this);

		var oYearPicker = this.getAggregation("yearPicker");
		oYearPicker.setColumns(0);
		oYearPicker.setYears(3); // default for 7 days
		oYearPicker.attachEvent("pageChange", _handleYearPickerPageChange, this);

		this._iDaysMonthHead = 35; // if more than this number of days, month names are displayed on top of days

	};

	/**
	* If more than this number of days are displayed, start and end month are displayed on the button
	* @returns {number}
	* @protected
	*/
   CalendarDateInterval.prototype._getDaysLarge = function() {
	   return 10;
   };

	CalendarDateInterval.prototype._createMonth = function(sId){

		var oMonth = new DatesRow(sId);

		return oMonth;

	};

	CalendarDateInterval.prototype.setStartDate = function(oStartDate){

		CalendarUtils._checkJSDateObject(oStartDate);

		if (jQuery.sap.equal(this.getStartDate(), oStartDate)) {
			return this;
		}

		var iYear = oStartDate.getFullYear();
		CalendarUtils._checkYearInValidRange(iYear);

		var oCalStartDate = CalendarDate.fromLocalJSDate(oStartDate, this.getPrimaryCalendarType());
		if (CalendarUtils._isOutside(oCalStartDate, this._oMinDate, this._oMaxDate)) {
			throw new Error("Date must be in valid range (minDate and maxDate); " + this);
		}

		var oMinDate = this.getMinDate();
		if (oMinDate && oStartDate.getTime() < oMinDate.getTime()) {
			jQuery.sap.log.warning("startDate < minDate -> minDate as startDate set", this);
			oStartDate = new Date(oMinDate.getTime());
		}

		var oMaxDate = this.getMaxDate();
		if (oMaxDate && oStartDate.getTime() > oMaxDate.getTime()) {
			jQuery.sap.log.warning("startDate > maxDate -> maxDate as startDate set", this);
			oStartDate = new Date(oMaxDate.getTime());
		}

		this.setProperty("startDate", oStartDate, true);
		oCalStartDate = CalendarDate.fromLocalJSDate(oStartDate, this.getPrimaryCalendarType());
		this._oStartDate = oCalStartDate;

		var oDatesRow = this.getAggregation("month")[0];
		oDatesRow.setStartDate(oStartDate);

		this._updateHeader(oCalStartDate);

		var oDate = this._getFocusedDate(true).toLocalJSDate();
		if (!oDatesRow.checkDateFocusable(oDate)) {
			//focused date not longer visible -> focus start date  (but don't set focus)
			this._setFocusedDate(oCalStartDate);
			oDatesRow.displayDate(oStartDate);
		}

		return this;

	};

	// needs to be overwritten because differently implemented in Calendar
	/**
	 * Gets current value of property startDate.
	 *
	 * Start date of the Interval
	 * @returns {object} JavaScript date object for property startDate
	 */
	CalendarDateInterval.prototype.getStartDate = function(){

		return this.getProperty("startDate");

	};

	CalendarDateInterval.prototype.setDays = function(iDays){

		this.setProperty("days", iDays, true);

		iDays = this._getDays(); // to use phone limit

		var oDatesRow = this.getAggregation("month")[0];
		oDatesRow.setDays(iDays);

		if (!this.getPickerPopup()) {
			var oMonthPicker = this.getAggregation("monthPicker");
			var iMonths = Math.ceil(iDays / 3);
			if (iMonths > 12) {
				iMonths = 12;
			}
			oMonthPicker.setMonths(iMonths);

			var oYearPicker = this.getAggregation("yearPicker");
			var iYears = Math.floor(iDays / 2);
			if (iYears > 20) {
				iYears = 20;
			}
			oYearPicker.setYears(iYears);
		}

		var oStartDate = this._getStartDate();
		this._updateHeader(oStartDate);

		if (this.getDomRef()) {
			if (iDays > this._getDaysLarge()) {
				this.$().addClass("sapUiCalIntLarge");
			}else {
				this.$().removeClass("sapUiCalIntLarge");
			}

			if (iDays > this._iDaysMonthHead) {
				this.$().addClass("sapUiCalIntHead");
			}else {
				this.$().removeClass("sapUiCalIntHead");
			}
		}

		return this;

	};

	CalendarDateInterval.prototype._getDays = function(){

		var iDays = this.getDays();

		// in phone mode max 8 days are displayed
		if (sap.ui.Device.system.phone && iDays > 8) {
			return 8;
		} else {
			return iDays;
		}

	};

	CalendarDateInterval.prototype.setShowDayNamesLine = function(bShowDayNamesLine){

		this.setProperty("showDayNamesLine", bShowDayNamesLine, true);

		var oDatesRow = this.getAggregation("month")[0];
		oDatesRow.setShowDayNamesLine(bShowDayNamesLine);

		return this;

	};

	CalendarDateInterval.prototype._getShowMonthHeader = function(){

		var iDays = this._getDays();
		if (iDays > this._iDaysMonthHead) {
			return true;
		}else {
			return false;
		}

	};

	/**
	* @param {boolean} [bForceRecalculate] Indicates if it's called within the startDate property setter and therefore
	* needs to be recalculated
	* @private
	* @returns {sap.ui.unified.calendar.CalendarDate} the date
	*/
	CalendarDateInterval.prototype._getFocusedDate = function(bForceRecalculate){

		if (!this._oFocusedDate || bForceRecalculate) {
			this._oFocusedDate = null;
			Calendar.prototype._getFocusedDate.apply(this, arguments);
			var oStartDate = this.getStartDate();
			var oDatesRow = this.getAggregation("month")[0];
			if (!oStartDate) {
				// use focused date as start date
				this._setStartDate(this._oFocusedDate, false, true);
			}else if (!oDatesRow.checkDateFocusable(this._oFocusedDate.toLocalJSDate())) {
				this._oFocusedDate = CalendarDate.fromLocalJSDate(oStartDate, this.getPrimaryCalendarType());
			}
		}

		return this._oFocusedDate;

	};

	/**
	 * Setter for property months.
	 *
	 * Property months is not supported in sap.ui.unified.CalendarDateInterval control.
	 *
	 * @protected
	 * @param {int} [iMonths] months
	 * @name sap.ui.unified.CalendarDateInterval#setMonths
	 * @function
	 */
	CalendarDateInterval.prototype.setMonths = function(iMonths){

		if (iMonths == 1) {
			return this.setProperty("months", iMonths, false); // rerender
		} else {
			throw new Error("Property months not supported " + this);
		}

	};

	/**
	 * Setter for property firstDayOfWeek.
	 *
	 * Property firstDayOfWeek is not supported in sap.ui.unified.CalendarDateInterval control.
	 *
	 * @protected
	 * @param {int} [iFirstDayOfWeek] first day of the week
	 * @name sap.ui.unified.CalendarDateInterval#setFirstDayOfWeek
	 * @function
	 */
	CalendarDateInterval.prototype.setFirstDayOfWeek = function(iFirstDayOfWeek){

		if (iFirstDayOfWeek == -1) {
			return this.setProperty("firstDayOfWeek", iFirstDayOfWeek, false); // rerender
		} else {
			throw new Error("Property firstDayOfWeek not supported " + this);
		}

	};

	/**
	* Focuses given date.
	* @param {Date} oDate a JavaScript date
	* @return {sap.ui.unified.Calendar} this for method chaining
	*/
	CalendarDateInterval.prototype.focusDate = function(oDate){

		var oDatesRow = this.getAggregation("month")[0];
		if (!oDatesRow.checkDateFocusable(oDate)) {
			this._focusDateExtend(CalendarDate.fromLocalJSDate(oDate, this.getPrimaryCalendarType()), true, true);
		}

		Calendar.prototype.focusDate.apply(this, arguments);

		return this;

	};

	/**
	 * Overrides the Calendar#_focusDateExtend in order to handle the focused date in a custom way.
	 *
	 * Set start date according to new focused date. If focused date is not in current rendered date interval
	 * new focused date should have the same position like the old one
	 *
	 * @param {sap.ui.unified.calendar.CalendarDate} oDate the date to focus
	 * @param {boolean} bOtherMonth determines whether the function is called due navigation outside the visible
	 * date range
	 * @param {boolean} bNoEvent hint to skip firing startDateChange event. If set to true,
	 * the parent is supposed to take care for firing.
	 * @returns {boolean} whether the parent should fire the startDateChange event
	 * @private
	 */
	CalendarDateInterval.prototype._focusDateExtend = function(oDate, bOtherMonth, bNoEvent) {
		if (bOtherMonth) {
			var oOldFocusedDate = this._getFocusedDate();
			var oOldStartDate = this._getStartDate();
			var iDay = CalendarUtils._daysBetween(oOldFocusedDate, oOldStartDate);
			var oNewStartDate = new CalendarDate(oDate, this.getPrimaryCalendarType());
			oNewStartDate.setDate(oNewStartDate.getDate() - iDay);
			this._setStartDate(oNewStartDate, false, true);

			if (!bNoEvent) {
				return true; // fire startDateChange event in caller at end of processing
			}
		}

		return false;

	};

	/**
	 * @param {sap.ui.unified.calendar.CalendarDate} oDate
	 * @private
	*/
	CalendarDateInterval.prototype._setMinMaxDateExtend = function(oDate){

		if (this._oStartDate) {
			// check if still in valid range
			if (this._oStartDate.isBefore(this._oMinDate)) {
				jQuery.sap.log.warning("start date < minDate -> minDate will be start date", this);
				this._setStartDate(new CalendarDate(this._oMinDate, this.getPrimaryCalendarType()), true, true);
			} else {
				var oEndDate = new CalendarDate(this._oStartDate);
				oEndDate.setDate(oEndDate.getDate() + this._getDays() - 1);
				if (oEndDate.isAfter(this._oMaxDate)) {
					jQuery.sap.log.warning("end date > maxDate -> start date will be changed", this);
					var oStartDate = new CalendarDate(this._oMaxDate);
					oStartDate.setDate(oStartDate.getDate() - this._getDays() + 1);
					this._setStartDate(oStartDate, true, true);
				}
			}
		}

	};

	CalendarDateInterval.prototype.setPickerPopup = function(bPickerPopup){

		this.setProperty("pickerPopup", bPickerPopup, true);

		var oMonthPicker = this.getAggregation("monthPicker");
		var oYearPicker = this.getAggregation("yearPicker");

		if (bPickerPopup) {
			oMonthPicker.setColumns(3);
			oMonthPicker.setMonths(12);
			oYearPicker.setColumns(4);
			oYearPicker.setYears(20);
		} else {
			oMonthPicker.setColumns(0);
			oMonthPicker.setMonths(6);
			oYearPicker.setColumns(0);
			oYearPicker.setYears(6);
		}

		return this;

	};

	/**
	* @param {sap.ui.unified.calendar.CalendarDate} oDate
	* @param {boolean} bCheckMonth
	* @private
	*/
	CalendarDateInterval.prototype._togglePrevNext = function(oDate, bCheckMonth){

		if (this._iMode > 1 || (this._iMode == 1 && this.getPickerPopup())) {
			return Calendar.prototype._togglePrevNext.apply(this, arguments);
		}

		var iYearMax = this._oMaxDate.getYear();
		var iYearMin = this._oMinDate.getYear();
		var iMonthMax = this._oMaxDate.getMonth();
		var iMonthMin = this._oMinDate.getMonth();
		var iDateMin = this._oMinDate.getDate();
		var iDateMax = this._oMaxDate.getDate();
		var oHeader = this.getAggregation("header");
		var iDays = this._getDays();
		var iYear;
		var oStartDate;
		var oEndDate;
		var iMonth;
		var iDate;

		if (this._iMode == 1 && !bCheckMonth) {
			// in line month picker don't disable buttons
			var oMonthPicker = this.getAggregation("monthPicker");
			var iMonths = oMonthPicker.getMonths();
			var iStartMonth = oMonthPicker.getStartMonth();
			var iEndMonth = iStartMonth + iMonths - 1;
			iYear = oDate.getYear();

			if (iStartMonth == 0 || (iYear == iYearMin && iStartMonth <= iMonthMin)) {
				oHeader.setEnabledPrevious(false);
			} else {
				oHeader.setEnabledPrevious(true);
			}

			if (iEndMonth > 10 || (iYear == iYearMax && iEndMonth >= iMonthMax)) {
				oHeader.setEnabledNext(false);
			} else {
				oHeader.setEnabledNext(true);
			}

			return;
		}

		oStartDate = this._getStartDate();
		oEndDate = new CalendarDate(oStartDate, this.getPrimaryCalendarType());
		oEndDate.setDate(oEndDate.getDate() + iDays - 1);

		if (CalendarUtils._isOutside(oDate, oStartDate,oEndDate)) {
			// date outside visible range
			oStartDate = new CalendarDate(oDate, this.getPrimaryCalendarType());
			oEndDate = new CalendarDate(oStartDate, this.getPrimaryCalendarType());
			oEndDate.setDate(oEndDate.getDate() + iDays - 1);
		}

		iYear = oStartDate.getYear();
		iMonth = oStartDate.getMonth();
		iDate = oStartDate.getDate();

		if (iYear < iYearMin ||
				(iYear == iYearMin &&
						(!bCheckMonth || iMonth < iMonthMin || (iMonth == iMonthMin && iDate <= iDateMin)))) {
			oHeader.setEnabledPrevious(false);
		}else {
			oHeader.setEnabledPrevious(true);
		}

		iYear = oEndDate.getYear();
		iMonth = oEndDate.getMonth();
		iDate = oEndDate.getDate();

		if (iYear > iYearMax ||
				(iYear == iYearMax &&
						(!bCheckMonth || iMonth > iMonthMax || (iMonth == iMonthMax && iDate >= iDateMax)))) {
			oHeader.setEnabledNext(false);
		} else {
			oHeader.setEnabledNext(true);
		}

	};

  /**
	* Shifts startDate and focusedDate according to given amount of time.
	*
	* @param {sap.ui.unified.calendar.CalendarDate} oStartDate start date
	* @param {sap.ui.unified.calendar.CalendarDate} oFocusedDate focused date
	* @param {int} iDays number of days to shift. Positive values will shift forward, negative - backward.
	* @private
	*/
	CalendarDateInterval.prototype._shiftStartFocusDates = function(oStartDate, oFocusedDate, iDays){
		oStartDate.setDate(oStartDate.getDate() + iDays);
		oFocusedDate.setDate(oFocusedDate.getDate() + iDays);
		this._setFocusedDate(oFocusedDate);
		this._setStartDate(oStartDate, true);
	};

	CalendarDateInterval.prototype._handlePrevious = function(oEvent){

		var oFocusedDate = new CalendarDate(this._getFocusedDate(), this.getPrimaryCalendarType());
		var oMonthPicker = this.getAggregation("monthPicker");
		var oYearPicker = this.getAggregation("yearPicker");
		var oStartDate =  new CalendarDate(this._getStartDate(),  this.getPrimaryCalendarType());
		var iDays = this._getDays();

		switch (this._iMode) {
		case 0: // day picker
			this._shiftStartFocusDates(oStartDate, oFocusedDate, (iDays * -1));
			break;

		case 1: // month picker
			if (oMonthPicker.getMonths() < 12) {
				oMonthPicker.previousPage();
				this._togglePrevNext(oFocusedDate);
			} else {
				oFocusedDate.setYear(oFocusedDate.getYear() - 1);
				var bFireStartDateChange = this._focusDateExtend(oFocusedDate, true, false);
				this._setFocusedDate(oFocusedDate);
				this._updateHeader(oFocusedDate);
				this._setDisabledMonths(oFocusedDate.getYear());

				if (bFireStartDateChange) {
					this.fireStartDateChange();
				}
			}
			break;

		case 2: // year picker
			oYearPicker.previousPage();
			this._togglePrevNexYearPicker();
			break;
			// no default
		}

	};

	CalendarDateInterval.prototype._handleNext = function(oEvent){

		var oFocusedDate = new CalendarDate(this._getFocusedDate(),  this.getPrimaryCalendarType());
		var oMonthPicker = this.getAggregation("monthPicker");
		var oYearPicker = this.getAggregation("yearPicker");
		var oStartDate = new CalendarDate(this._getStartDate(), this.getPrimaryCalendarType());
		var iDays = this._getDays();

		switch (this._iMode) {
		case 0: // day picker
			this._shiftStartFocusDates(oStartDate, oFocusedDate, iDays);
			break;

		case 1: // month picker
			if (oMonthPicker.getMonths() < 12) {
				oMonthPicker.nextPage();
				this._togglePrevNext(oFocusedDate);
			} else {
				oFocusedDate.setYear(oFocusedDate.getYear() + 1);
				var bFireStartDateChange = this._focusDateExtend(oFocusedDate, true, false);
				this._setFocusedDate(oFocusedDate);
				this._updateHeader(oFocusedDate);
				this._setDisabledMonths(oFocusedDate.getYear());

				if (bFireStartDateChange) {
					this.fireStartDateChange();
				}
			}
			break;

		case 2: // year picker
			oYearPicker.nextPage();
			this._togglePrevNexYearPicker();
			break;
			// no default
		}

	};

	/**
	*
	* @param {sap.ui.unified.calendar.CalendarDate} oDate
	* @returns {int[]} the displayed months
	* @private
	*/
	CalendarDateInterval.prototype._getDisplayedMonths = function(oDate){

		var aMonths = [];
		var iMonth = oDate.getMonth();
		var iDays = this._getDays();

		aMonths.push(iMonth);
		if (iDays > this._getDaysLarge()) {
			// of only a few days displayed, there is not enough space for 2 Months in Button
			var oEndDate = new CalendarDate(oDate, this.getPrimaryCalendarType());
			oEndDate.setDate(oEndDate.getDate() + iDays - 1);
			var iEndMonth = oEndDate.getMonth();
			while (iMonth != iEndMonth) {
				iMonth = (iMonth + 1) % 12;
				aMonths.push(iMonth);
			}
		}

		return aMonths;

	};

	CalendarDateInterval.prototype._getDisplayedSecondaryMonths = function(sPrimaryCalendarType, sSecondaryCalendarType){

		var iDays = this._getDays();
		var oStartDate = new CalendarDate(this._getStartDate(), sSecondaryCalendarType);
		var iStartMonth = oStartDate.getMonth();

		var oEndDate = new CalendarDate(oStartDate, this.getPrimaryCalendarType());
		oEndDate.setDate(oEndDate.getDate() + iDays - 1);
		oEndDate = new CalendarDate(oEndDate, sSecondaryCalendarType);
		var iEndMonth = oEndDate.getMonth();

		return {start: iStartMonth, end: iEndMonth};

	};

	CalendarDateInterval.prototype._openPickerPopup = function(oPicker){

		if (!this._oPopup) {
			jQuery.sap.require("sap.ui.core.Popup");
			this._oPopup = new sap.ui.core.Popup();
			this._oPopup.setAutoClose(true);
			this._oPopup.setAutoCloseAreas([this.getDomRef()]);
			this._oPopup.setDurations(0, 0); // no animations
			this._oPopup._oCalendar = this;
			this._oPopup.attachClosed(_handlePopupClosed, this);
			this._oPopup.onsapescape = function(oEvent) {
				this._oCalendar.onsapescape(oEvent);
			};
		}

		this._oPopup.setContent(oPicker);

		var oHeader = this.getAggregation("header");
		var eDock = sap.ui.core.Popup.Dock;
		this._oPopup.open(0, eDock.CenterTop, eDock.CenterBottom, oHeader, null, "flipfit", true);

	};

	/**
	 * Sets given start date as date in local.
	 *
	 * @param {sap.ui.unified.calendar.CalendarDate} oStartDate Date that should be taken to create the local JavaScript date.
	 * E.g. if the date is Dec 21th 1981, the local date (CEST) would be Dec 21th, 1981 00:00:00 GMT +02:00
	 * @param bSetFocusDate if true, sets this date as focused date
	 * @param bNoEvent describes whether the startDateChange event was previously thrown
	 * @private
	*/
	CalendarDateInterval.prototype._setStartDate = function (oStartDate, bSetFocusDate, bNoEvent) {

		var oMaxDate = new CalendarDate(this._oMaxDate, this.getPrimaryCalendarType());
		oMaxDate.setDate(oMaxDate.getDate() - this._getDays() + 1);
		if (oMaxDate.isBefore(this._oMinDate)) {
			// min and max smaller than interval
			oMaxDate = new CalendarDate(this._oMinDate);
			oMaxDate.setDate(oMaxDate.getDate() + this._getDays() - 1);
		}

		if (oStartDate.isBefore(this._oMinDate)) {
			oStartDate = new CalendarDate(this._oMinDate, this.getPrimaryCalendarType());
		}else if (oStartDate.isAfter(oMaxDate)) {
			oStartDate = oMaxDate;
		}

		var oLocaleDate = oStartDate.toLocalJSDate();
		this.setProperty("startDate", oLocaleDate, true);
		this._oStartDate = oStartDate;

		var oDatesRow = this.getAggregation("month")[0];
		oDatesRow.setStartDate(oLocaleDate);

		this._updateHeader(oStartDate);

		if (bSetFocusDate) {
			var oDate = this._getFocusedDate().toLocalJSDate();
			if (!oDatesRow.checkDateFocusable(oDate)) {
				//focused date not longer visible -> focus start date
				this._setFocusedDate(oStartDate);
				oDatesRow.setDate(oLocaleDate);
			}else {
				oDatesRow.setDate(oDate);
			}
		}

		if (!bNoEvent) {
			this.fireStartDateChange();
		}

	};

	/**
	* Gets the start date as CalendarDate (timezone agnostic)
	*
	* E.g. if the date is Dec 21th 1981, the result date would be Dec 21th, 1981 00:00:00 GMT
	* @private
	 *@returns {sap.ui.unified.calendar.CalendarDate} the date
	*/

	CalendarDateInterval.prototype._getStartDate = function(){

		if (!this._oStartDate) {
			// no start date set, use focused date
			this._oStartDate = this._getFocusedDate();
		}

		return this._oStartDate;

	};

	function _handlePopupClosed(oEvent) {

		this._closedPickers();

	}

	function _handleMonthPickerPageChange(oEvent) {

		var oFocusedDate = new CalendarDate(this._getFocusedDate(), this.getPrimaryCalendarType());
		this._togglePrevNext(oFocusedDate);

	}

	function _handleYearPickerPageChange(oEvent) {

		this._togglePrevNexYearPicker();

	}

	return CalendarDateInterval;

}, /* bExport= */ true);


text:
package edu.berkeley.ground.postgres.dao;

import com.google.common.collect.ImmutableMap;
import edu.berkeley.ground.common.exception.GroundException;
import edu.berkeley.ground.common.util.IdGenerator;
import edu.berkeley.ground.postgres.dao.core.PostgresEdgeDao;
import edu.berkeley.ground.postgres.dao.core.PostgresEdgeVersionDao;
import edu.berkeley.ground.postgres.dao.core.PostgresGraphDao;
import edu.berkeley.ground.postgres.dao.core.PostgresGraphVersionDao;
import edu.berkeley.ground.postgres.dao.core.PostgresNodeDao;
import edu.berkeley.ground.postgres.dao.core.PostgresNodeVersionDao;
import edu.berkeley.ground.postgres.dao.core.PostgresStructureDao;
import edu.berkeley.ground.postgres.dao.core.PostgresStructureVersionDao;
import edu.berkeley.ground.postgres.dao.usage.PostgresLineageEdgeDao;
import edu.berkeley.ground.postgres.dao.usage.PostgresLineageEdgeVersionDao;
import edu.berkeley.ground.postgres.dao.usage.PostgresLineageGraphDao;
import edu.berkeley.ground.postgres.dao.usage.PostgresLineageGraphVersionDao;
import edu.berkeley.ground.postgres.dao.version.PostgresTagDao;
import edu.berkeley.ground.postgres.dao.version.PostgresVersionHistoryDagDao;
import edu.berkeley.ground.postgres.dao.version.PostgresVersionSuccessorDao;
import edu.berkeley.ground.postgres.dao.version.mock.TestPostgresItemDao;
import edu.berkeley.ground.postgres.dao.version.mock.TestPostgresRichVersionDao;
import edu.berkeley.ground.postgres.dao.version.mock.TestPostgresVersionDao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.After;
import org.junit.Before;
import play.db.Database;
import play.db.Databases;

public class PostgresTest extends DaoTest {

  private static final String DROP_SCRIPT = "dist/db/drop_postgres.sql";
  private static final String CREATE_SCHEMA_SCRIPT = "dist/db/postgres.sql";

  public PostgresTest() throws GroundException {

  }

  @Before
  public void setup() throws IOException, InterruptedException, GroundException {
    Database dbSource = Databases.createFrom(
      "org.postgresql.Driver",
      "jdbc:postgresql://localhost:5432/test",
      ImmutableMap.of(
        "username", "test",
        "password", "test"
      ));

    IdGenerator idGenerator = new IdGenerator(0, 1, false);

    PostgresTest.dbSource = dbSource;
    PostgresTest.idGenerator = idGenerator;

    PostgresTest.postgresVersionDao = new TestPostgresVersionDao(dbSource, idGenerator);
    PostgresTest.versionSuccessorDao = new PostgresVersionSuccessorDao(dbSource, idGenerator);
    PostgresTest.versionHistoryDagDao = new PostgresVersionHistoryDagDao(dbSource, idGenerator);
    PostgresTest.postgresItemDao = new TestPostgresItemDao(dbSource, idGenerator);
    PostgresTest.tagDao = new PostgresTagDao(dbSource);

    PostgresTest.postgresRichVersionDao = new TestPostgresRichVersionDao(dbSource, idGenerator);
    PostgresTest.structureDao = new PostgresStructureDao(dbSource, idGenerator);
    PostgresTest.structureVersionDao = new PostgresStructureVersionDao(dbSource, idGenerator);
    PostgresTest.edgeDao = new PostgresEdgeDao(dbSource, idGenerator);
    PostgresTest.edgeVersionDao = new PostgresEdgeVersionDao(dbSource, idGenerator);
    PostgresTest.graphDao = new PostgresGraphDao(dbSource, idGenerator);
    PostgresTest.graphVersionDao = new PostgresGraphVersionDao(dbSource, idGenerator);
    PostgresTest.nodeDao = new PostgresNodeDao(dbSource, idGenerator);
    PostgresTest.nodeVersionDao = new PostgresNodeVersionDao(dbSource, idGenerator);
    PostgresTest.lineageEdgeDao = new PostgresLineageEdgeDao(dbSource, idGenerator);
    PostgresTest.lineageEdgeVersionDao = new PostgresLineageEdgeVersionDao(dbSource, idGenerator);
    PostgresTest.lineageGraphDao = new PostgresLineageGraphDao(dbSource, idGenerator);
    PostgresTest.lineageGraphVersionDao = new PostgresLineageGraphVersionDao(dbSource, idGenerator);

    runScript(DROP_SCRIPT);
    runScript(CREATE_SCHEMA_SCRIPT);
  }

  @After
  public void tearDown() throws IOException, InterruptedException, GroundException {
    dbSource.shutdown();
  }

  private static void runScript(String script) {
    try {
      boolean autoCommitState = dbSource.getConnection().getAutoCommit();
      dbSource.getConnection().setAutoCommit(false);
      StatementExecutor exec = new StatementExecutor(dbSource.getConnection());
      PostgresTest.runScript(script, exec::execute);
      dbSource.getConnection().setAutoCommit(autoCommitState);
    } catch (SQLException ex) {
      throw new RuntimeException(ex);
    }
  }

  private static class StatementExecutor {

    private final Connection conn;

    StatementExecutor(Connection conn) {
      this.conn = conn;
    }

    void execute(String statement) {
      try {
        Statement sqlStatement = conn.createStatement();
        sqlStatement.execute(statement);
      } catch (SQLException e) {
        String message = e.getMessage();
        if (message.contains("already exists") || message
                                                    .contains("current transaction is aborted")) {
          System.out.println("Warn: statement [" + statement + "] causes: " + e.getMessage());
          // ignore errors caused by type already existing
        } else {
          throw new RuntimeException(e);
        }
      }
    }
  }

}


text:
angular.module("ct.ui.router.extras", [ 'ui.router' ]);

//define(['angularAMD'], function (angularAMD) {

  var app = angular.module("ct.ui.router.extras");
  app.service("$deepStateRedirect", function ($rootScope, $state) {
    var lastSubstate = {};
    var lastParams = {};
    var deepStateRedirectsByName = {};

    var REDIRECT = "Redirect", ANCESTOR_REDIRECT = "AncestorRedirect";

    function computeDeepStateStatus(state) {
      var name = state.name;
      if (deepStateRedirectsByName.hasOwnProperty(name))
        return deepStateRedirectsByName[name];
      recordDeepStateRedirectStatus(name);
    }

    function recordDeepStateRedirectStatus(stateName) {
      var state = $state.get(stateName);
      if (state && state.deepStateRedirect === true) {
        deepStateRedirectsByName[stateName] = REDIRECT;
        if (lastSubstate[stateName] === undefined)
          lastSubstate[stateName] = stateName;
      }

      var lastDot = stateName.lastIndexOf(".");
      if (lastDot != -1) {
        var parentStatus = recordDeepStateRedirectStatus(stateName.substr(0, lastDot));
        if (parentStatus) {
          deepStateRedirectsByName[stateName] = ANCESTOR_REDIRECT;
        }
      }
      return deepStateRedirectsByName[stateName] || false;
    }

    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
      function shouldRedirect() {
        var deepStateStatus = computeDeepStateStatus(toState);
        var substate = lastSubstate[toState.name];
        // We're changing directly to one of the redirect (tab) states and we have a last substate recorded
        return deepStateStatus === REDIRECT && substate && substate != toState.name ? true : false;
      }

      if (shouldRedirect()) { // send them to the last known state for that tab
        event.preventDefault();
        $state.go(lastSubstate[toState.name], lastParams[toState.name]);
      }

    });

    $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
      var deepStateStatus = computeDeepStateStatus(toState);
      if (deepStateStatus) {
        _.each(lastSubstate, function (deepState, redirectState) {
          if (toState.name == deepState || toState.name.indexOf(redirectState + ".") != -1) {
            lastSubstate[redirectState] = toState.name;
            lastParams[redirectState] = angular.copy(toParams);
          }
        });
      }
    });
  });

  app.run(function ($deepStateRedirect) {
    // Make sure $deepStateRedirect is instantiated
  });

//  return app;
//});

$StickyStateProvider.$inject = [ '$stateProvider' ];
function $StickyStateProvider($stateProvider, $logProvider) {
  // Holds all the states which are inactivated.  Inactivated states can be either sticky states, or descendants of sticky states.
  var inactiveStates = {}; // state.name -> (state)
  var stickyStates = {}; // state.name -> true
  var $state;

  // Called by $stateProvider.registerState();
  // registers a sticky state with $stickyStateProvider
  this.registerStickyState = function (state) {
    stickyStates[state.name] = state;
    // console.log("Registered sticky state: ", state);
  };

  this.$get = [ '$rootScope', '$state', '$injector', '$log', function ($rootScope, $state, $injector, $log) {
    // Each inactive states is either a sticky state, or a child of a sticky state.
    // This function finds the closest ancestor sticky state, then find that state's parent.
    // Map all inactive states to their closest parent-to-sticky state.
    function mapInactives() {
      var mappedStates = {};
      for (var name in inactiveStates) {
        var state = inactiveStates[name];
        var parParents = getStickyStateStack(state);
        for (var i = 0; i < parParents.length; i++) {
          var parent = parParents[i].parent;
          mappedStates[parent.name] = mappedStates[parent.name] || [];
          mappedStates[parent.name].push(state);
        }
      }
      return mappedStates;
    }

    // Given a state, returns all ancestor states which are sticky.
    // Walks up the view's state's ancestry tree and locates each ancestor state which is marked as sticky.
    // Returns an array populated with only those ancestor sticky states.
    function getStickyStateStack(state) {
      var stack = [];
      if (!state) return stack;
      do {
        if (state.sticky) stack.push(state);
        state = state.parent;
      } while (state);
      stack.reverse();
      return stack;
    }

    // Used by processTransition to determine if what kind of sticky state transition this is.
    // returns { from: (bool), to: (bool) }
    function getStickyTransitionType(fromPath, toPath, keep) {
      if (fromPath[keep] === toPath[keep]) return { from: false, to: false };
      var stickyFromState = keep < fromPath.length && fromPath[keep].self.sticky;
      var stickyToState = keep < toPath.length && toPath[keep].self.sticky;
      return { from: stickyFromState, to: stickyToState };
    }

    // Returns a sticky transition type necessary to enter the state.
    // Transition can be: reactivate, updateStateParams, or enter

    // Note: if a state is being reactivated but params dont match, we treat
    // it as a Exit/Enter, thus the special "updateStateParams" transition.
    // If a parent inactivated state has "updateStateParams" transition type, then
    // all descendant states must also be exit/entered, thus the first line of this function.
    function getEnterTransition(state, stateParams, ancestorParamsChanged) {
      if (ancestorParamsChanged) return "updateStateParams";
      var inactiveState = inactiveStates[state.self.name];
      if (!inactiveState) return "enter";
      if (inactiveState.locals == null || inactiveState.locals.globals == null) debugger;
      var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams);
      // $log.debug("getEnterTransition: " + state.name + (paramsMatch ? ": reactivate" : ": updateStateParams"));
      return paramsMatch ? "reactivate" : "updateStateParams";
    }

    // Given a state and (optional) stateParams, returns the inactivated state from the inactive sticky state registry.
    function getInactivatedState(state, stateParams) {
      var inactiveState = inactiveStates[state.name];
      if (!inactiveState) return null;
      if (!stateParams) return inactiveState;
      var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams);
      return paramsMatch ? inactiveState : null;
    }

    // Duplicates logic in $state.transitionTo, primarily to find the pivot state (i.e., the "keep" value)
    function equalForKeys(a, b, keys) {
      if (!keys) {
        keys = [];
        for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
      }

      for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
      }
      return true;
    }

    var stickySupport = {
      getInactiveStates: function () {
        var states = [];
        angular.forEach(inactiveStates, function (state) {
          states.push(state);
        });
        return states;
      },
      getInactiveStatesByParent: function () {
        return mapInactives();
      },
      // Main API for $stickyState, used by $state.
      // Processes a potential transition, returns an object with the following attributes:
      // {
      //    inactives: Array of all states which will be inactive if the transition is completed. (both previously and newly inactivated)
      //    enter: Enter transition type for all added states.  This is a sticky array to "toStates" array in $state.transitionTo.
      //    exit: Exit transition type for all removed states.  This is a sticky array to "fromStates" array in $state.transitionTo.
      // }
      processTransition: function (transition) {
        // This object is returned
        var result = { inactives: [], enter: [], exit: [], keep: 0 };
        var fromPath = transition.fromState.path,
            fromParams = transition.fromParams,
            toPath = transition.toState.path,
            toParams = transition.toParams;
        var keep = 0, state = toPath[keep];

        while (state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams)) {
          state = toPath[++keep];
          if (state != null && state.ownParams == null)
            debugger;
        }

//                    if (keep <= 0) return result;
        result.keep = keep;

        var idx, deepestUpdatedParams, deepestReactivate, reactivatedStatesByName = {}, pType = getStickyTransitionType(fromPath, toPath, keep);
        var ancestorUpdated = false; // When ancestor params change, treat reactivation as exit/enter

        // Calculate the "enter" transitions for new states in toPath
        // Enter transitions will be either "enter", "reactivate", or "updateStateParams" where
        //   enter: full resolve, no special logic
        //   reactivate: use previous locals
        //   updateStateParams: like 'enter', except exit the inactive state before entering it.
        for (idx = keep; idx < toPath.length; idx++) {
          var enterTrans = !pType.to ? "enter" : getEnterTransition(toPath[idx], transition.toParams, ancestorUpdated);
          ancestorUpdated = (ancestorUpdated || enterTrans == 'updateStateParams');
          result.enter[idx] = enterTrans;
          // If we're reactivating a state, make a note of it, so we can remove that state from the "inactive" list
          if (enterTrans == 'reactivate')
            deepestReactivate = reactivatedStatesByName[toPath[idx].name] = toPath[idx];
          if (enterTrans == 'updateStateParams')
            deepestUpdatedParams = toPath[idx];
        }
        deepestReactivate = deepestReactivate ? deepestReactivate.self.name + "." : "";
        deepestUpdatedParams = deepestUpdatedParams ? deepestUpdatedParams.self.name + "." : "";

        // Inactive states, before the transition is processed, mapped to the parent to the sticky state.
        var inactivesByParent = mapInactives();

        // Locate currently and newly inactive states (at pivot and above) and store them in the output array 'inactives'.
        for (idx = 0; idx < keep; idx++) {
          var inactiveChildren = inactivesByParent[fromPath[idx].self.name];
          for (var i = 0; inactiveChildren && i < inactiveChildren.length; i++) {
            var child = inactiveChildren[i];
            // Don't organize state as inactive if we're about to reactivate it.
            if (!reactivatedStatesByName[child.name] &&
                (!deepestReactivate || (child.self.name.indexOf(deepestReactivate) !== 0)) &&
                (!deepestUpdatedParams || (child.self.name.indexOf(deepestUpdatedParams) !== 0)))
              result.inactives.push(child);
          }
        }

        // Calculate the "exit" transition for states not kept, in fromPath.
        // Exit transition can be one of:
        //   exit: standard state exit logic
        //   inactivate: register state as an inactive state
        for (idx = keep; idx < fromPath.length; idx++) {
          var exitTrans = "exit";
          if (pType.from) {
            // State is being inactivated, note this in result.inactives array
            result.inactives.push(fromPath[idx]);
            exitTrans = "inactivate";
          }
          result.exit[idx] = exitTrans;
        }

//      $log.debug("processTransition: " , result);
        return result;
      },

      // Adds a state to the inactivated sticky state registry.
      stateInactivated: function (state) {
        // Keep locals around.
        inactiveStates[state.self.name] = state;
        // Notify states they are being Inactivated (i.e., a different
        // sticky state tree is now active).
        if (state.self.onInactivate)
          $injector.invoke(state.self.onInactivate, state.self, state.locals.globals);
      },

      // Removes a previously inactivated state from the inactive sticky state registry
      stateReactivated: function (state) {
        if (inactiveStates[state.self.name]) {
          delete inactiveStates[state.self.name];
        }
        if (state.locals == null || state.locals.globals == null) debugger;
        if (state.self.onReactivate)
          $injector.invoke(state.self.onReactivate, state.self, state.locals.globals);
      },

      // Exits all inactivated descendant substates when the ancestor state is exited.
      // When transitionTo is exiting a state, this function is called with the state being exited.  It checks the
      // registry of inactivated states for descendants of the exited state and also exits those descendants.  It then
      // removes the locals and de-registers the state from the inactivated registry.
      stateExiting: function (exiting, exitQueue, onExit) {
        var substatePrefix = exiting.self.name + "."; // All descendant states will start with this prefix
        var exitingNames = {};
        angular.forEach(exitQueue, function (state) {
          exitingNames[state.self.name] = true;
        });
        for (var name in inactiveStates) {
          // TODO: Might need to run the inactivations in the proper depth-first order?
          if (!exitingNames[name] && name.indexOf(substatePrefix) === 0) { // inactivated state's name starts with the prefix.
            $log.debug("Exiting " + name + " because it's a substate of " + substatePrefix + " and wasn't found in ", exitingNames);
            var inactiveExiting = inactiveStates[name];
            if (inactiveExiting.self.onExit)
              $injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals);
            inactiveExiting.locals = null;
            delete inactiveStates[name];
          }
        }
        if (onExit)
          $injector.invoke(onExit, exiting.self, exiting.locals.globals);
        exiting.locals = null;
        delete inactiveStates[exiting.self.name];
      },

      // Removes a previously inactivated state from the inactive sticky state registry
      stateEntering: function (entering, params, onEnter) {
        var inactivatedState = getInactivatedState(entering);
        if (inactivatedState && !getInactivatedState(entering, params)) {
          var savedLocals = entering.locals;
          this.stateExiting(inactivatedState);
          entering.locals = savedLocals;
        }

        if (onEnter)
          $injector.invoke(onEnter, entering.self, entering.locals.globals);
      }
    };

    return stickySupport;
  }];
}

angular.module("ct.ui.router.extras").provider("$stickyState", $StickyStateProvider);

var _StickyState; // internal reference to $stickyStateProvider
var internalStates = {}; // Map { statename -> InternalStateObj } holds internal representation of all states
var root, // Root state, internal representation
    pendingTransitions = [], // One transition may supercede another.  This holds references to all pending transitions
    pendingRestore, // The restore function from the superceded transition
    inactivePseudoState; // This pseudo state holds all the inactive states' locals (resolved state data, such as views etc)

// Creates a blank surrogate state
function SurrogateState(type) {
  return {
    resolve: { },
    locals: {
      globals: root && root.locals && root.locals.globals
    },
    views: { },
    self: { },
    ownParams: [],
    surrogateType: type
  };
}

// Grab a copy of the $stickyState service for use by the transition management code
angular.module("ct.ui.router.extras").run(["$stickyState", function ($stickyState) { _StickyState = $stickyState; }]);

angular.module("ct.ui.router.extras").config(
    [ "$provide", "$stateProvider", '$stickyStateProvider',
      function ($provide, $stateProvider, $stickyStateProvider) {
        // inactivePseudoState (__inactives) holds all the inactive locals (resolved states data: views, etc)
        //
        // __inactives needs to reference root.locals.globals.  At this time, root.locals.globals isn't populated
        // so copy a reference to root.locals onto __inactives.locals (then when ui-router populates root.locals.globals
        // it also populates __inactives.locals.globals.  Likewise, this means inactive states are stored on the
        // root state's locals, hmmm that might not be great.
        var pState = {
          self: {  name: '__inactives'  },
          onEnter: function() { inactivePseudoState.locals.globals = root.locals.globals; }
        };
        inactivePseudoState = angular.extend(new SurrogateState("__inactives"), pState);

        // Need access to the internal 'root' state object.  Get it by decorating the StateBuilder parent function.
        $stateProvider.decorator('parent', function (state, parentFn) {
          if (!root) {
            // This code gets run only once
            root = parentFn({}); // StateBuilder.parent({}) returns the root internal state object
            inactivePseudoState.parent = root; // Hook pseudoState.parent up to the root state
            inactivePseudoState.locals = root.locals;
          }
          return parentFn(state);
        });

        $stateProvider.decorator('path', function (state, parentFn) {
          // Capture each internal state representations
          internalStates[state.self.name] = state;
          // Register the ones marked as "sticky"
          if (state.self.sticky === true) {
            $stickyStateProvider.registerStickyState(state.self);
          }
          // Add a fake root node to each state's path to hold the inactive states' locals
          var realPath = [], temp = parentFn(state); // call parent path function, which returns an array of states
          angular.forEach(temp, function (pathElem) {
            // paths are constructed from the parent paths
            if (pathElem !== inactivePseudoState) {
              realPath.push(pathElem);
            }
          });
          // Return a fake path with the first element being the inactivePseudState
          return [ inactivePseudoState ].concat(realPath);
        });

        $provide.decorator("$state", ['$delegate', '$log', function ($state, $log) {
          var realTransitionTo = $state.transitionTo;
          $state.transitionTo = function (to, toParams, options) {
            var idx = pendingTransitions.length;
            if (pendingRestore) {
              pendingRestore();
              $log.debug("Restored paths from pending transition");
            }

            // Custom transitionTo logic here
            var fromState = $state.$current, fromParams = $state.params;
            var rel = options.relative || $state.$current; // Not sure if/when $state.$current is appropriate here.
            var toStateSelf = $state.get(to, rel); // exposes findState relative path functionality, returns state.self
            var savedToStatePath, savedFromStatePath, stickyTransitions;
            var reactivated = [], exited = [], terminalReactivatedState;

            function debugTransition(transition) {
              function message(path, index, state) {
                return (path[index] ? path[index].toUpperCase() + ": " + state.self.name : "(" + state.self.name + ")");
              }

              var inactiveLogVar = map(transition.inactives, function (state) {
                return state.self.name
              });
              var enterLogVar = map(toState.path, function (state, index) {
                return message(transition.enter, index, state);
              });
              var exitLogVar = map(fromState.path, function (state, index) {
                return message(transition.exit, index, state);
              });
              $log.debug("exit: ", exitLogVar);
              $log.debug("enter: ", enterLogVar);
              $log.debug("After transition, inactives: ", inactiveLogVar);
            }

            var noop = function () {
            };
            var restore = function () {
              if (savedToStatePath) {
                toState.path = savedToStatePath;
                savedToStatePath = null;
              }

              if (savedFromStatePath) {
                fromState.path = savedFromStatePath;
                savedFromStatePath = null;
              }

              angular.forEach(restore.restoreFunctions, function (restoreFunction) {
                restoreFunction();
              });
              restore = noop;
              pendingRestore = null;
              pendingTransitions.splice(idx, 1); // Remove this transition from the list
            };
            restore.restoreFunctions = [];
            restore.addRestoreFunction = function addRestoreFunction(fn) {
              this.restoreFunctions.push(fn);
            };

            function stateReactivatedSurrogatePhase1(state) {
              var surrogate = angular.extend(new SurrogateState("reactivate_p1"), { locals: state.locals });
              surrogate.self = angular.extend({}, state.self);
              return surrogate;
            }

            function stateReactivatedSurrogatePhase2(state) {
              var surrogate = angular.extend(new SurrogateState("reactivate_p2"), state);
              surrogate.self = angular.extend({}, state.self);
              surrogate.self.onEnter = function () {
                // ui-router sets locals on the surrogate to a blank locals (because we gave it nothing to resolve)
                // Re-set it back to the already loaded state.locals here.
                surrogate.locals = state.locals;
                _StickyState.stateReactivated(state);
              };
              return surrogate;
            }

            function stateInactivatedSurrogate(state) {
              var surrogate = new SurrogateState("inactivate");
              surrogate.self = angular.extend({}, state.self);
              surrogate.self.onExit = function () {
                _StickyState.stateInactivated(state);
              };
              return surrogate;
            }

            function stateEnteredSurrogate(state, toParams) {
              var oldOnEnter = state.self.onEnter;
              state.self.onEnter = function () {
                _StickyState.stateEntering(state, toParams, oldOnEnter);
              };
              restore.addRestoreFunction(function () {
                state.self.onEnter = oldOnEnter;
              });

              return state;
            }

            function stateExitedSurrogate(state) {
              var oldOnExit = state.self.onExit;
              state.self = angular.extend({}, state.self);
              state.self.onExit = function () {
                _StickyState.stateExiting(state, exited, oldOnExit);
              };
              restore.addRestoreFunction(function () {
                state.self.onExit = oldOnExit;
              });

              return state;
            }

            // if (!toStateSelf) defugger;
            if (toStateSelf) {
              var toState = internalStates[toStateSelf.name]; // have the state, now grab the internal state representation
              if (!toState) debugger;
              if (toState) {
                savedToStatePath = toState.path;
                savedFromStatePath = fromState.path;

                var currentTransition = {toState: toState, toParams: toParams || {}, fromState: fromState, fromParams: fromParams || {}};
                var msg = currentTransition.fromState.self.name + ": " +
                    angular.toJson(currentTransition.fromParams) + ": " +
                    " -> " +
                    currentTransition.toState.self.name + ": " +
                    angular.toJson(currentTransition.toParams);
                $log.debug("Current transition: ", msg);

                pendingTransitions.push(currentTransition);
                pendingRestore = restore;
                stickyTransitions = _StickyState.processTransition(currentTransition);
                debugTransition(stickyTransitions);

                var surrogateToPath = toState.path.slice(0, stickyTransitions.keep);
                var surrogateFromPath = fromState.path.slice(0, stickyTransitions.keep);

                // Rebuild root.inactiveLocals each time...
                for (var name in inactivePseudoState.locals) {
                  delete inactivePseudoState.locals[name];
                }
                for (var i = 0; i < stickyTransitions.inactives.length; i++) {
                  var iLocals = stickyTransitions.inactives[i].locals;
                  for (name in iLocals) {
                    if (iLocals.hasOwnProperty(name) && name.indexOf("@") != -1) {
                      inactivePseudoState.locals[name] = iLocals[name]; // Add all inactive views not already included.
                    }
                  }
                }

                angular.forEach(stickyTransitions.enter, function (value, idx) {
                  var surrogate;
                  if (value === "reactivate") {
                    surrogate = stateReactivatedSurrogatePhase1(toState.path[idx]);
                    // Add surrogate to ToPath again and FromPath.
                    // This is to get ui-router to add the surrogate locals to the protoypal locals object
                    surrogateToPath.push(surrogate);
                    surrogateFromPath.push(surrogate);  // so toPath[i] === fromPath[i]
                    reactivated.push(stateReactivatedSurrogatePhase2(toState.path[idx]));
                    terminalReactivatedState = surrogate;
                  } else if (value === "updateStateParams") {
                    surrogate = stateEnteredSurrogate(toState.path[idx]);
                    surrogateToPath.push(surrogate);
                    terminalReactivatedState = surrogate;
                  } else if (value === "enter") {
                    surrogateToPath.push(stateEnteredSurrogate(toState.path[idx]));
                  }
                });

                angular.forEach(stickyTransitions.exit, function (value, idx) {
                  var exiting = fromState.path[idx];
                  if (value === "inactivate") {
                    surrogateFromPath.push(stateInactivatedSurrogate(exiting));
                    exited.push(exiting);
                  } else if (value === "exit") {
                    surrogateFromPath.push(stateExitedSurrogate(exiting));
                    exited.push(exiting);
                  }
                });

                if (reactivated.length) {
                  angular.forEach(reactivated, function (surrogate) {
                    // Add surrogate for reactivated to ToPath again, this time without a matching FromPath entry
                    // This is to get ui-router to call the surrogate's onEnter callback.
                    surrogateToPath.push(surrogate);
                  });
                }

                if (terminalReactivatedState) {
                  var prefix = terminalReactivatedState.self.name + ".";
                  var inactiveStates = _StickyState.getInactiveStates();
                  var inactiveOrphans = [];
                  inactiveStates.forEach(function (exiting) {
                    if (exiting.self.name.indexOf(prefix) === 0) {
                      $log.debug("exitable: ", exiting.self.name);
                      inactiveOrphans.push(exiting);
                    }
                  });
                  inactiveOrphans.sort();
                  inactiveOrphans.reverse();
                  surrogateFromPath = surrogateFromPath.concat(map(inactiveOrphans, function (exiting) {
                    return stateExitedSurrogate(exiting)
                  }));
                  exited = exited.concat(inactiveOrphans);
                }

                toState.path = surrogateToPath;
                fromState.path = surrogateFromPath;

                var pathMessage = function (state) {
                  return (state.surrogateType ? state.surrogateType + ":" : "") + state.self.name;
                };
                $log.debug("SurrogateFromPath: ", map(surrogateFromPath, pathMessage));
                $log.debug("SurrogateToPath: ", map(surrogateToPath, pathMessage));
              }
            }

            var transitionPromise = realTransitionTo.apply($state, arguments);
            transitionPromise.then(function transitionSuccess(state) {
              restore();
              $log.debug("Current state: " + state.name + ", inactives: ", map(_StickyState.getInactiveStates(), function (s) {
                return s.self.name
              }));
            }, function transitionFailed(err) {
              if (err.message !== "transition prevented"
                  && err.message !== "transition aborted"
                  && err.message !== "transition superceded") {
                $log.debug("transition failed", err);
                console.log(err.stack);
              }
              restore();
            })
          };
          return $state;
        }]);
      }]);

//define(['angularAMD'], function (angularAMD) {
  angular.module('ct.ui.router.extras').provider('$futureState', function _futureStateProvider($stateProvider, $urlRouterProvider) {
    var stateFactories = {}, futureStates = {}, futureUrlFragments = {};
    var transitionPending = false, resolveFunctions = [], initPromise, initDone = false;
    var provider = this;

    // This function registers a promiseFn, to be resolved before the url/state matching code
    // will reject a route.  The promiseFn is injected/executed using the runtime $injector.
    // The function should return a promise.
    // When all registered promises are resolved, then the route is re-sync'ed.

    // Example: function($http) {
    //  return $http.get('//server.com/api/DynamicFutureStates').then(function(data) {
    //    angular.forEach(data.futureStates, function(fstate) { $futureStateProvider.futureState(fstate); });
    //  };
    // }
    this.addResolve = function (promiseFn) {
      resolveFunctions.push(promiseFn);
    };

    // Register a state factory function for a particular future-state type.  This factory, given a future-state object,
    // should create a ui-router state.
    // The factory function is injected/executed using the runtime $injector.  The future-state is injected as 'futureState'.

    // Example:
    //    $futureStateProvider.stateFactory('test', function(futureState) {
    //      return {
    //        name: futureState.stateName,
    //        url: futureState.pathFragment,
    //        template: '<h3>Future State Template</h3>',
    //        controller: function() {
    //          console.log("Entered state " + futureState.stateName);
    //        }
    //      }
    //    });
    this.stateFactory = function (futureStateType, factory) {
      stateFactories[futureStateType] = factory;
    };

    this.futureState = function (futureState) {
      futureStates[futureState.stateName] = futureState;
      futureUrlFragments[futureState.urlPrefix] = futureState;
    };

    function futureState_otherwise($injector, $location) {
      var resyncing = false;
      var $log = $injector.get("$log");

      var otherwiseFunc = function otherwiseFunc($state) {
        $log.debug("Unable to map " + $location.path());
        $location.url("/");
      };

      var lazyLoadMissingState = function lazyLoadMissingState($rootScope, $urlRouter, $state) {
        if (!initDone) {
          // Asynchronously load state definitions, then resync URL
          initPromise().then(function initialResync() {
            resyncing = true;
            $urlRouter.sync();
            resyncing = false;
          });
          initDone = true;
          return;
        }

        var futureState = serviceObject.findFutureState({ url: $location.path() });
        if (!futureState) {
          return $injector.invoke(otherwiseFunc);
        }

        transitionPending = true;
        // Config loaded.  Asynchronously lazy-load state definition from URL fragment, if mapped.
        serviceObject.lazyLoadState(futureState).then(function lazyLoadedStateCallback(state) {
          // TODO: Should have a specific resolve value that says 'dont register a state because I already did'
          if (state)
            $stateProvider.state(state);
          resyncing = true;
          $urlRouter.sync();
          resyncing = false;
          transitionPending = false;
        }, function lazyLoadStateAborted() {
          transitionPending = false;
          $state.go("top");
        });
      };
      if (transitionPending) return;

      var nextFn = resyncing ? otherwiseFunc : lazyLoadMissingState;
      return $injector.invoke(nextFn);
    }
    $urlRouterProvider.otherwise(futureState_otherwise);

    var serviceObject = {
      config: function () {
        return initPromise();
      },
      findFutureState: undefined,
      lazyLoadState: undefined
    };

    this.$get = function futureStateProvider_get($injector, $state, $q, $rootScope, $urlRouter, $log) {

      /* options is an object with at least a name or url attribute */
      serviceObject.findFutureState = function findFutureState(options) {
        if (options.name) {
          var nameComponents = options.name.split(/\./);
          while (nameComponents.length) {
            var stateName = nameComponents.join(".");
            if ($state.get(stateName))
              return null; // State is already defined; nothing to do
            if (futureStates[stateName])
              return futureStates[stateName];
            nameComponents.pop();
          }
        }

        if (options.url) {
          var urlComponents = options.url.split(/\//);
          while (urlComponents.length) {
            var urlPrefix = urlComponents.join("/");
            if (futureUrlFragments[urlPrefix])
              return futureUrlFragments[urlPrefix];
            urlComponents.pop();
          }
        }
      };

      serviceObject.init = function init() {
        $rootScope.$on("$stateNotFound", function futureState_notFound(event, unfoundState, fromState, fromParams) {
          if (transitionPending) return;
          $log.debug("event, unfoundState, fromState, fromParams", event, unfoundState, fromState, fromParams);

          var futureState = serviceObject.findFutureState({ name: unfoundState.to });
          if (futureState == null) return;

          event.preventDefault();
          transitionPending = true;

          var promise = serviceObject.lazyLoadState(futureState);
          promise.then(function (state) {
            // TODO: Should have a specific resolve value that says 'dont register a state because I already did'
            if (state)
              $stateProvider.state(state);
            $state.go(unfoundState.to, unfoundState.toParams);
            transitionPending = false;
          }, function (error) {
            console.log("failed to lazy load state ", error);
            $state.go(fromState, fromParams);
            transitionPending = false;
          });
        });

        // Do this better.  Want to load remote config once, before everything else
        if (!initPromise) {
          var promises = [];
          _.each(resolveFunctions, function(promiseFn) {
            promises.push($injector.invoke(promiseFn));
          });
          initPromise = _.once(function flattenFutureStates() {
            var allPromises = $q.all(promises);
            return allPromises.then(function(data) {
              return _.flatten(data);
            })
          });
        }

        initPromise().then(function buildRealStates(futureStates) {
          $log.debug("Loaded initial future state configuration", futureStates);

          // Get futureStates of future states from user code.
          angular.forEach(futureStates, function(futureState) {
            provider.futureState(futureState);
          });
          $urlRouter.sync();
        });
      };

      serviceObject.lazyLoadState = function lazyLoadState(futureState) {
        if (!futureState) {
          var deferred = $q.defer();
          deferred.reject("No lazyState passed in " + futureState);
          return deferred.promise;
        }

        var state = {
          name: futureState.stateName,
          template: undefined,
          url: futureState.pathFragment + "/",
          resolve: {},
          data: {}
        };

        var type = futureState.type;
        var factory = stateFactories[type];
        if (!factory) throw Error("No state factory for futureState.type: " + (futureState && futureState.type));
        return $injector.invoke(factory, factory, { futureState: futureState });
      };

      return serviceObject;
    }
  });

  angular.module('ct.ui.router.extras').run(function test_futureStateServiceInit($futureState) {
    $futureState.init();
  });

//  return app;
//});

var forEach = angular.forEach;

var map = function (collection, callback) {
  var result = [];
  angular.forEach(collection, function (item) {
    result.push(callback(item));
  });
  return result;
};

"use strict";
function ngloadStateFactory($q, futureState) {
  var ngloadDeferred = $q.defer();

  require([ "ngload!" + futureState.url , 'ngload', 'angularAMD'],  function ngloadCallback(module, ngload, angularAMD) {
    angularAMD.processQueue();
    ngloadDeferred.resolve(module);
  });

  var state = {
    name: futureState.stateName,
    template: "<div ui-view></div>",
    url: futureState.pathFragment + "/",
    resolve: {
      ngapp: function() { return ngloadDeferred.promise }
    }
  };

  return $q.when(state);
}
"use strict";
var iframeStateFactory = function($q, futureState) {
  var state = {
    name: futureState.stateName,
    template: "<iframe src='" + futureState.url + "'></iframe>",
    url: futureState.pathFragment
  };
  return $q.when(state);
};


text:
<?php

include_once "../../class/Carrega.class.php";

include "../Session.php";
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Painel de Controle - Tô Dentro IFSul</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="../../plugins/font-awesome-4.5.0/font-awesome-4.5.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="../../plugins/ionicons-2.0.1/ionicons-2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="../../plugins/select2/select2.min.css">

    <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">

      <?php
            if ($_SESSION['tipo_usuario']==3 || $_SESSION['tipo_usuario']==4)
            {
              include '../inc/topo_full.php';
            }
            else
            {
              include '../inc/topo_basic.php';
            }
            include '../inc/menutime.php';
      ?>

Monitorias

Edição de monitorias

                <?php

                  $id = $_POST["id"];

                  if (isset($_POST["editar"]))
                  {
                    $edit = new Monitorias();
                    $comp = $edit->EditarMonitorias($id);

                    if ($edit != null)
                    {
                ?>
                <form class="form-horizontal" id="form" method="post" action="CrudMonitorias.php">

                        Curso:

<?php echo $comp->curso; ?>

                          </select>

                        Disciplina:

 <?php echo $comp->disciplina; ?>

                      <?php
                      if ($_SESSION['tipo_usuario']==3 || $_SESSION['tipo_usuario']==4)
                      {
                      ?>

                        Status:

                          <select class="form-control select2" name="status" id="status" style="width:100%;" data-toggle="tooltip" title="Campo Obrigatório!" required>
                            <option value=""></option>
                            <?php
                                $staSelect = new Select();
                                $staSelect->statusSelect($comp->status);
                            ?>
                          </select>

                      <?php
                      }
                      else
                      {
                      ?>

                        Status:

                          <input type="text" class="form-control" value="SOB AVALIAÇÃO!" disabled>
                          <input type="hidden" name="status" value="1">

                      <?php
                      }
                      ?>

                          Semestre:

                            <select class="form-control select2" id="semestre" name="semestre" style="width: 100%;" data-toggle="tooltip" title="Campo Obrigatório!" required>
                              <option value=""></option>
                              <?php $semestreSelect = new Select();
                                    $semestreSelect->semestreSelect($comp->semestre);
                              ?>
                            </select>

                           Sala:

                              <select class="form-control select2" name="sala" id="sala" style="width: 100%;" data-toggle="tooltip" title="Campo Obrigatório!" required>
                                 <option value=""></option>
                                 <?php $localSelect = new Select();
                                       $localSelect->localSelect($comp->sala);
                                 ?>
                             </select>

                            Informações adicionais:

                               <textarea class="form-control" name="info" rows="4" placeholder="Digite aqui..." data-toggle="tooltip" title="Campo Obrigatório!" required><?php echo $comp->info; ?></textarea>

                    <input type="hidden" name="id" value="<?php echo $comp->id; ?>"/>
                    <button type="submit" name="atualizar" value="atualizar" class="btn btn-success btn-flat btn-block"> Atualizar </button>

                    <button type="button" name="cancelar" value="cancelar" onclick="javascript:history.back()'" class="btn btn-default btn-flat btn-block btn-sm"> Cancelar </button>

                </form>

      <?php
            }
          }
      ?>
      <?php
        include '../inc/footer.html';
        include '../inc/style_page.html';
      ?>


text:
package errors

import (
	"encoding/json"
	"fmt"
	"strings"
)

// Errors hold a collection of errors returned by a response.
type Errors struct {
	Err []error `json:"error"`
}

func (e *Errors) Error() string {
	if len(e.Err) == 1 {
		return fmt.Sprintf("1 error occurred:\n  %s", e.Err[0])
	}

	errors := make([]string, len(e.Err))
	for i, err := range e.Err {
		errors[i] = fmt.Sprintf("  %s", err)
	}

	return fmt.Sprintf("%d errors occurred:\n%s", len(e.Err), strings.Join(errors, "\n"))
}

// AppendStrings appends a slice of strings to *Errors.Err.
func (e *Errors) AppendStrings(errorStrings []string) {
	for _, s := range errorStrings {
		e.Err = append(e.Err, fmt.Errorf(s))
	}
}

// UnmarshalJSON unmarshals errors into Errors object.
func (e *Errors) UnmarshalJSON(b []byte) error {
	var eCol struct {
		E struct {
			E []string `json:"error"`
		} `json:"errors"`
	}
	var eObj struct {
		E struct {
			E string `json:"error,omitempty"`
		} `json:"errors,omitempty"`
	}
	var err error

	// If error is wrapped in an array
	if err = json.Unmarshal(b, &eCol); err == nil {
		e.AppendStrings(eCol.E.E)
		return nil
	}

	// If error is wrapped in an object
	if err = json.Unmarshal(b, &eObj); err == nil {
		e.AppendStrings([]string{eObj.E.E})
		return nil
	}

	return err
}

// MarshalJSON marshals Errors into its JSON representation.
func (e *Errors) MarshalJSON() ([]byte, error) {
	if len(e.Err) == 1 {
		return json.Marshal(map[string]interface{}{
			"errors": map[string]interface{}{
				"error": (*e).Err[0],
			},
		})
	}

	return json.Marshal(map[string]interface{}{
		"errors": map[string]interface{}{
			"error": *e,
		},
	})
}


text:
<?php

namespace Heyday\Beam\Command;

use Heyday\Beam\Config\BeamConfiguration;
use Heyday\Beam\Utils;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class MakeChecksumsCommand
 * @package Heyday\Beam\Command
 */
class MakeChecksumsCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('makechecksums')
            ->setDescription('Generate a checksums file')
            ->addOption(
                'path',
                'p',
                InputOption::VALUE_OPTIONAL,
                'The path to scan and make the checksums file in',
                getcwd()
            )
            ->addOption(
                'checksumfile',
                'c',
                InputOption::VALUE_OPTIONAL,
                'Filename to save the file with',
                'checksums.json'
            )
            ->addConfigOption();
    }
    /**
     * @param  InputInterface  $input
     * @param  OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = realpath($input->getOption('path'));

        $config = BeamConfiguration::parseConfig($this->getConfig($input, $path));

        $checksums = Utils::checksumsFromFiles(
            Utils::getAllowedFilesFromDirectory($config['exclude'], $path),
            $path
        );

        $jsonfile = rtrim($path, '/') . '/' . $input->getOption('checksumfile');

        file_put_contents(
            $jsonfile . '.gz',
            Utils::checksumsToGz($checksums)
        );
    }
}


text:
namespace mojo {

template <>
struct StructTraits<service_manager::mojom::IdentityDataView,
                    service_manager::Identity> {
  static const std::string& name(const service_manager::Identity& identity) {
    return identity.name();
  }
  static const std::string& user_id(const service_manager::Identity& identity) {
    return identity.user_id();
  }
  static const std::string& instance(
      const service_manager::Identity& identity) {
    return identity.instance();
  }
  static bool Read(service_manager::mojom::IdentityDataView data,
                   service_manager::Identity* out) {
    std::string name, user_id, instance;
    if (!data.ReadName(&name))
      return false;

    if (!data.ReadUserId(&user_id))
      return false;

    if (!data.ReadInstance(&instance))
      return false;

    *out = service_manager::Identity(name, user_id, instance);
    return true;
  }
};

}  // namespace mojo

#endif  // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_IDENTITY_STRUCT_TRAITS_H_


text:
namespace XNet
{

// data are provided in network byte order

class Socket
{
private:
protected:
	Socket();
public:
	virtual ~Socket() {}

	virtual void Send(uint32_t host, uint16_t port, const void* data, size_t length) = 0;
	virtual void* Receive(uint32_t& host, uint16_t& port, size_t& length) = 0;
};

class SocketProvider
{
private:
public:
	SocketProvider();
	virtual ~SocketProvider() {}

	// bindPort is provided in network byte order
	virtual Socket* NewSocket(uint16_t bindPort) = 0;
	virtual uint32_t ResolveHost(const std::string& hostname) = 0;
	virtual std::string ReverseLookup(uint32_t host) = 0;
};

}

#endif


text:
package com.ppcxy.common.base;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 */
@ContextConfiguration({"classpath:spring-common-test.xml"})
@Transactional(transactionManager = "transactionManager")
@Rollback
public abstract class BaseIT extends AbstractTransactionalJUnit4SpringContextTests {

    @PersistenceContext
    protected EntityManager entityManager;

    public void clear() {
        flush();
        entityManager.clear();
    }

    public void flush() {
        entityManager.flush();
    }

    protected String nextRandom() {
        return System.currentTimeMillis() + RandomStringUtils.randomNumeric(5);
    }

}