text:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('class.TicketPage.php');
$page = new TicketPage('Burning Flipside - Tickets');

$page->addWellKnownJS(JS_BOOTSTRAP_FH);
$page->addWellKnownCSS(CSS_BOOTSTRAP_FH);
$page->addJS('js/secondary.js');
$page->addJS('https://www.google.com/recaptcha/api.js');

$page->body = 'There are no secondary ticket sales this year.';
$page->printPage();
die();

$minor = '

Important Information About Minors At Burning Flipside

Your ticket request indicates that you are brining a minor child to Burning Flipside. If this is a mistake please hit
                the correct button below and fix your request. If this is not a mistake and you are bringing minor children to Burning Flipside
                then you must read the content below.

For the protection of minor children and in accordance with Texas law, any minor child attending this event must be accompanied
                        by someone with legal authority to make decisions for the child.

A minor is anyone under the age of 18.

You must bring proper documentation to demonstrate your authority to make decisions for the child. For the child: physical copies of
                        birth certificate, passport, or other official document. For the parent: photo ID. An electronic copy of your documentation will be
                        stored along with the signed event waiver.

A special affidavit process is also available. See below:

If you do not with to bring irreplaceable documents to Burning Flipside you may bring a notorized affidavit. NOTE: Many
                parents consider this process much easier and quicker at Gate.

Download a copy of the affidavit below

Print out the affidavit.

Bring the affidavit, along with your child\'s birth certificate and/or passport, to a Public Notary.

Have the affidavit notarized.

Put your other documents away and bring the notarized affidavit to Flipside with you.

Present the affidavit to the Gate staff with the minor\'s ticket and your legal ID. Gate will keep the affidavit for Flipside\'s records.

                <input type="checkbox" id="minor_affirm" onchange="minor_affirm_clicked()"> I have read and understand the above policies.

                <button type="button" class="btn btn-default" data-dismiss="modal">Oops! I don\'t have any children attending the event!</button>
                <button id="minor_dialog_continue" type="button" class="btn btn-primary" data-dismiss="modal" disabled>Continue</button>

';

if($page->user === null)
{
    $page->printPage();
    die();
}

$maxTotalTickets = $page->ticketSettings['max_tickets_per_request'];

$ticketDataTable = \Tickets\DB\TicketsDataTable::getInstance();
$currentTickets = $ticketDataTable->read(new \Tickets\DB\TicketDefaultFilter($page->user->mail));
$numberOfCurrentTickets = count($currentTickets);
if($currentTickets === false)
{
    $numberOfCurrentTickets = 0;
}

if($numberOfCurrentTickets >= $maxTotalTickets)
{
    $page->body .= '
You currently have '.$numberOfCurrentTickets.' tickets registered to you. This means you cannot purchase any additional tickets using this system.
';
    $page->printPage();
    die();
}

$ticketTypeDataTable = \DataSetFactory::getDataTableByNames('tickets', 'TicketTypes');
$ticketTypes = $ticketTypeDataTable->read();
$ticketTypeCount = count($ticketTypes);
for($i = 0; $i < $ticketTypeCount; $i++)
{
    $type = $ticketTypes[$i];
    $type['count'] = 0;
    $ticketTypes[$type['typeCode']] = $type;
    unset($ticketTypes[$i]);
}

if($numberOfCurrentTickets != 0)
{
    for($i = 0; $i < $numberOfCurrentTickets; $i++)
    {
        $ticket = $currentTickets[$i];
        $ticketTypes[$ticket['type']]['count']++;
        if($ticketTypes[$ticket['type']]['count'] >= $ticketTypes[$ticket['type']]['max_per_request'])
        {
            $page->addNotification('You already have the maximum available '.$ticketTypes[$ticket['type']]['description'].' tickets and will not be able to order any more.', TicketPage::NOTIFICATION_WARNING, false);
        }
    }
}

$secondaryTable = \DataSetFactory::getDataTableByNames('tickets', 'SecondaryRequests');
$requests = $secondaryTable->read(new \Data\Filter('mail eq "'.$page->user->mail.'"'));
if(!empty($requests))
{
    $page->body .= '
You have registered the maximum number of requests. You can reprint your request form here.
';
    $page->printPage();
    die();
}

$secondaryTotalCount = 0;
$validTicketArray = $secondaryTable->read(false, array('valid_tickets'));
$validTicketArrayCount = count($validTicketArray);
for($i = 0; $i < $validTicketArrayCount; $i++)
{
    $tmp = json_decode($validTicketArray[$i]['valid_tickets']);
    $secondaryTotalCount += count($tmp);
}
if($secondaryTotalCount > $page->ticketSettings['secondaryTicketCount'])
{
    $page->body .= 'There have been too many requests. Sorry, we may open up more tickets later.';
    $page->printPage();
    die();
}

$page->body .= '

    <form id="questions">
        First you must answer a series of questions to prove you have read the Burning Flipside '.$page->ticketSettings['year'].' survival guide. You can locate the guide wwwUrl.'/sg" target="_blank">here.

        <button type="button" id="submitAnswer" class="btn btn-primary">Submit Answers</button>
    </form>
<form id="request" tabindex="-1" aria-hidden="true" style="display:none;" data-ticketcount="'.$numberOfCurrentTickets.'">

        First Name:

            <input class="form-control" id="givenName" name="givenName" type="text" required data-toggle="tooltip" data-placement="top" title="This is the first name for the mailing address." value="'.$page->user->givenName.'"/>

        Last Name:

            <input class="form-control" id="sn" name="sn" type="text" required data-toggle="tooltip" data-placement="top" title="This is the last name for the mailing address."  value="'.$page->user->sn.'"/>

        Email:

            <input class="form-control" type="text" name="mail" id="mail" readonly data-toggle="tooltip" data-placement="top" title="This is the email address used for futher communications. This email address has been set and confirmed by your profile. If you need to use a different email address please edit your profile."  value="'.$page->user->mail.'"/>

        Country:

            <select class="form-control bfh-countries" id="c" name="c" data-country="'.$page->user->c.'" required data-toggle="tooltip" data-placement="top" title="The Country for the mailing address."></select>

        Street Address:

            <textarea class="form-control" required id="street" name="street" rows="2" data-toggle="tooltip" data-placement="top" title="The street address for the mailing address.">'.$page->user->postalAddress.'</textarea>

        Postal/Zip Code:

            <input class="form-control" required id="zip" name="zip" type="text" data-toggle="tooltip" data-placement="top" title="The zip or postal code for the mailing address."  value="'.$page->user->postalCode.'"/>

        City:

            <input class="form-control" required id="l" name="l" type="text" data-toggle="tooltip" data-placement="top" title="The city for the mailing address."  value="'.$page->user->l.'"/>

        State:

            <select class="form-control bfh-states" required data-country="c" id="st" name="st" type="text" data-toggle="tooltip" data-placement="top" title="The state/province/or other subdivision of the country for the mailing address." data-state="'.$page->user->st.'"></select>

                Age
                First Name
                Last Name
                Ticket Cost

';
foreach($ticketTypes as $type)
{
    if($type['count'] >= $type['max_per_request'])
    {
        continue;
    }
    $ticketId = $type['typeCode'].'_1';
    $page->body.='

                <input type="checkbox" id="enable_'.$ticketId.'" class="form-control"/>
                '.$type['description'].'

                        <input type="text" id="ticket_first_'.$ticketId.'" name="ticket_first_'.$ticketId.'" class="form-control"/>

                        <input type="text" id="ticket_last_'.$ticketId.'" name="ticket_last_'.$ticketId.'" class="form-control"/>

                $'.$type['cost'].'

';
    if($type['count'] == 0)
    {
        $ticketId = $type['typeCode'].'_2';
        $page->body.='

                <input type="checkbox" id="enable_'.$ticketId.'" class="form-control"/>
                '.$type['description'].'
                <input type="text" id="ticket_first_'.$ticketId.'" name="ticket_first_'.$ticketId.'" class="form-control"/>
                <input type="text" id="ticket_last_'.$ticketId.'" name="ticket_last_'.$ticketId.'" class="form-control"/>
                $'.$type['cost'].'

';
    }
}
$page->body.='

                Ticket Subtotal:

    <button type="submit" name="submit" class="btn btn-primary" id="submitRequest">Submit Request</button>
</form>
'.$minor;

// vim: set tabstop=4 shiftwidth=4 expandtab:


text:
namespace extensions {

class SharedModuleInfo : public Extension::ManifestData {
 public:
  SharedModuleInfo();
  virtual ~SharedModuleInfo();

  bool Parse(const Extension* extension, base::string16* error);

  struct ImportInfo {
    std::string extension_id;
    std::string minimum_version;
  };

  // Utility functions.
  static void ParseImportedPath(const std::string& path,
                                std::string* import_id,
                                std::string* import_relative_path);
  static bool IsImportedPath(const std::string& path);

  // Functions relating to exporting resources.
  static bool IsSharedModule(const Extension* extension);
  static bool IsExportAllowed(const Extension* extension,
                              const std::string& relative_path);

  // Functions relating to importing resources.
  static bool ImportsExtensionById(const Extension* extension,
                                   const std::string& other_id);
  static bool ImportsModules(const Extension* extension);
  static const std::vector<ImportInfo>& GetImports(const Extension* extension);

 private:
  // This extension exports the following resources to other extensions.
  URLPatternSet exported_set_;

  // Optional list of module imports of other extensions.
  std::vector<ImportInfo> imports_;
};

// Parses all import/export keys in the manifest.
class SharedModuleHandler : public ManifestHandler {
 public:
  SharedModuleHandler();
  virtual ~SharedModuleHandler();

  virtual bool Parse(Extension* extension, base::string16* error) OVERRIDE;
  virtual bool Validate(const Extension* extension,
                        std::string* error,
                        std::vector<InstallWarning>* warnings) const OVERRIDE;

 private:
  virtual const std::vector<std::string> Keys() const OVERRIDE;
};

}  // namespace extensions

#endif  // EXTENSIONS_COMMON_MANIFEST_HANDLERS_SHARED_MODULE_INFO_H_

redpajama_set_name: RedPajamaGithub


text:
package controllers.common;

import model.AbstractTile;
import model.Board;
import model.Piece;
import view.BoardView;

/**
 * Move handling the movement of a piece on the board into another location on the board
 * @author hejohnson
 * @author dfontana
 * @author awharrison
 */
public class MovePieceOnBoardMove implements IMove{
	/**Board whose pieces are being moved about**/
	Board board;
	/** Piece being dragged in the board **/
	Piece p;
	/**Tile that was clicked (destination tile)**/
	AbstractTile sourceTile;
	/**Location the piece was originally in - row**/
	int originalRow;
	/**Location the piece was originally in - col**/
	int originalCol;
	/**Location the piece will be placed in - row**/
	int rOffset;
	/**Location the piece will be placed in - col**/
	int cOffset;
	/**Updates the view of the board**/
	BoardView bv;

	/**
	 * Creates the move
	 * @param board - board whose pieces are being manipulated
	 * @param tile - tile that was pressed (destination)
	 * @param p - piece that is being moved
	 * @param rOffset - offset of row where the piece wants to be placed
	 * @param cOffset - offset of col where the piece wants to be placed
	 * @param bv - view of the board being drawn
	 */
	public MovePieceOnBoardMove (Board board, AbstractTile tile, Piece p, int rOffset, int cOffset, BoardView bv) {
		this.board = board;
		this.sourceTile = tile;
		this.p = p;
		this.rOffset = rOffset;
		this.cOffset = cOffset;
		this.bv = bv;
	}

	/**
	 * The move is done by clearing the preview, storing the location of the piece,
	 * removing the piece from the board, placing the piece back on the board in the offset
	 * location, and then setting the dragged piece of the board to null.
	 * @return true if the move was made.
	 */
	public boolean doMove() {
		if (isValid()) {
			this.originalRow = p.getOriginRow();
			this.originalCol = p.getOriginCol();
			board.putPieceOnBoard(p, sourceTile.getRow()+rOffset, sourceTile.getCol()+cOffset);
			board.setDraggedPiece(null);

			//Redraw
			board.clearPiecePreview();
			bv.redraw();
			bv.repaint();
			return true;
		}
		return false;
	}

	/**
	 * Checks to see if the piece passed in is not null (hence being dragged from the board). If so,
	 * it checks if the piece will fit where it is trying to go. If both
	 * check out, the move is valid.
	 * @return boolean - true if the move can be made
	 */
	public boolean isValid() {
		if(this.p != null){
			if(board.willFit(p, sourceTile.getRow()+rOffset, sourceTile.getCol()+cOffset)){
				return true;
			}
		}
		return false;
	}

	/**
	 * Undoes the move by removing the piece and restoring it to the location it was
	 * previously at on the board
	 * @return true - the move can always be undone
	 */
	public boolean undo() {
		board.removePiece(p);
		board.putPieceOnBoard(p, originalRow, originalCol);

		//Redraw
		board.clearPiecePreview();
		bv.redraw();
		bv.repaint();
		return true;
	}

	/**
	 * Redoes the move, but instead of just setting dragged to null, it removes the piece
	 * since the mouse event can't do that for it.
	 * @return true if the move could be made again
	 */
	@Override
	public boolean redo() {
		this.originalRow = p.getOriginRow();
		this.originalCol = p.getOriginCol();
		board.removePiece(p);
		board.putPieceOnBoard(p, sourceTile.getRow()+rOffset, sourceTile.getCol()+cOffset);
		board.setDraggedPiece(null);

		//Redraw
		board.clearPiecePreview();
		bv.redraw();
		bv.repaint();
		return true;
	}
}


text:
<link href="{{ site.github.url }}/tables.css" rel="stylesheet" />

# Main features of `Chymyst Core`

`Chymyst Core` implements Join Calculus similarly to [JoCaml](http://jocaml.inria.fr), with some extensions in both syntax and semantics.

## Concise declarative syntax

`Chymyst Core` provides an embedded Scala DSL for chemical machine definitions.
Example code looks like this:

```scala
import io.chymyst.jc._

val s = m[Int] // Declare a non-blocking molecule `s`.
val c = b[Int, Int] // Declare a blocking molecule `c`.
site( // Declare a reaction site with default settings.
  go { case s(x) + c(y, reply) ⇒
    s(x + y); reply(x)
  }
)
s(1) // Emit non-blocking molecule `s` with value `1`.

```

As a baseline reference, the most concise syntax for JC is available in [JoCaml](http://jocaml.inria.fr), which uses a modified OCaml compiler.
The equivalent reaction definition in JoCaml looks like this:

```ocaml
def s(x) & c(y) =  // declare a reaction site as well as molecules s and c
   s(x + y) & reply x to c
spawn s(1)  // emit non-blocking molecule s with value 1

```

In the JoCaml syntax, `s` and `c` are declared implicitly, together with the reaction, and type inference fixes the types of their values.
Implicit declaration of molecule emitters ("channels") is not possible in `Chymyst` because Scala macros cannot insert new top-level name declarations into the code.
For this reason, `Chymyst` requires explicit declarations of molecule types (for example, `val c = b[Int, Int]`).

Unlike JoCaml, `Chymyst` does not introduce new keywords such as `spawn` or `reply`/`to`.

## Compile-time checks for blocking molecules

Reactions that consume a blocking molecule are required to send a reply corresponding to that blocking molecule.
This requirement applies separately to each consumed blocking molecule.

`Chymyst` generates a compile-time error if

- a reaction consumes a blocking molecule but does not have code that sends a reply, for example

```scala
// The `reply` emitter is not used at all.
go { case a(x) + f(_, reply) ⇒ a(x + 1) }

```

- a reaction has code that sends a reply but this code is not run unconditionally, for example

```scala
// This code will not emit a reply when `x < 0`.
go { case a(x) + f(_, reply) ⇒ if (x >= 0) reply(x) else a(0) }

```

- a reaction has code that uses a reply emitter within a closure, or manipulates it as a value that could be used outside the reaction, for example

```scala
// Store the `reply` emitter in a data structure.
go { case a(x) + f(_, reply) ⇒ queue.add(reply); reply(x) }
// This code might reply more than once, or not at all,
// because the reply is sent from within a closure.
go { case c(n) + g(_, reply) ⇒ (1 to n).map(i ⇒ reply(i)) }

```

These compile-time checks are intended to help programmers avoid common errors associated with blocking molecules.

## Arbitrary input patterns

In `Chymyst`'s Scala DSL, a reaction's input patterns is a `case` clause in a partial function.
Within the limits of the Scala syntax, reactions can define arbitrary input patterns.

### Unrestricted pattern matching

Reactions can use pattern matching expressions as well as guard conditions for selecting molecule values:

```scala
val c = m[Option[Int]]
val d = m[(String, List[String])]

go { case c(Some(x)) + d( s@("xyz", List(p, q, r)) )
      if x > 0 && p.length > q.length ⇒
      // Reaction will start only if the patterns match and the condition holds.
      // Reaction body can use pattern variables `x`, `s`, `p`, `q`, `r`.
}

```

### Nonlinear input patterns

Reactions can use repeated input molecules ("nonlinear" input patterns):

```scala
val c = m[Int]

go { case c(x) + c(y) + c(z) if x > y && y > z ⇒ c(x - y + z) }

```

Some concurrent algorithms are more easily expressed using repeated input molecules, although reactions may be scheduled more slowly.
Static optimizations are used to optimize the performance of the reaction scheduler for such situations.

### Nonlinear blocking replies

A reaction can consume any number of blocking molecules at once, and each blocking molecule has its own reply.

For example, the following reaction consumes 3 blocking molecules `f`, `f`, `g` and exchanges the values caried by the two `f` molecules:

```scala
val f = b[Int, Int]
val g = b[Unit, Unit]

// Synchronous rendez-vous with exchange of values.
go { case f(x1, replyF1) + f(x2, replyF2) + g(_, replyG) ⇒
   replyF1(x2); replyF2(x1); replyG()
}

```

This reaction is impossible to write using JoCaml-style syntax `reply x to f`:
In that syntax, we cannot identify which of the copies of `f` should receive which reply value.
If JoCaml supported nonlinear input patterns, we could do this in JoCaml syntax:

```ocaml
def f(x1) + f(x2) + g() =>
  reply x2 to f; reply x1 to f; reply () to g

```

However, this code cannot specify that the reply value `x2` should be sent to the process that emitted `f(x1)` rather than to the process that emitted `f(x2)`.

## Reactions are values

Reactions are not merely `case` clauses in code; they are locally scoped values of type `Reaction`.
The `go()` call is a macro that creates reaction values:

```scala
val c = m[Int]
val reaction: Reaction = go { case c(x) ⇒ println(x) }
// Declare a reaction, but do not activate anything yet.

```

Users can build reaction sites incrementally, by constructing, say, an array of `n` reaction values, where `n` is a run-time parameter.
Then a reaction site can be activated using the resulting array of reaction values.

```scala
// Declare reactions, but do not activate anything yet.
val reactions: Seq[Reaction] = ???
// Create a reaction site and activate all reactions.
site(reactions: _*)

```

Reactions and reaction sites are immutable once declared and activated.
It is impossible to add more reactions to an already created reaction site, or to modify a reaction that has already been defined.

Since molecule emitters are local values, one can also define `n` different molecules, where `n` is a run-time parameter.
There is no limit on the number of reactions in one reaction site, and no limit on the number of different molecules.

However, input molecules, input patterns, and guard conditions for each reaction must be defined statically.
It is impossible to define a reaction that consumes `n` input molecules, where `n` is a run-time parameter.

## Timeouts for blocking molecules

Emitting a blocking molecule will block forever if no reactions consume that molecule.
When this behavior is not desirable, the code can time out on that blocking call:

```scala
val f = b[Unit, Int]

site(...) // define some reactions that consume f

val result: Option[Int] = f.timeout()(200 millis)
// will return None on timeout

```

If the timeout occurs, the blocking molecule does not receive any reply value.

At this point, there can be two possibilities:

- no reaction consuming `f()` was able to start so far
- a reaction consuming `f()` already started but did not yet send a reply value

If no reaction was able to start so far, the timeout on `f()` will cause `Chymyst` to remove the relevant copy of `f()` from the chemical soup,
so that no reaction would attempt to send a reply that the caller is no longer waiting for.

If a reaction already started, it is too late to remove the copy of `f()` from the soup.
The reaction will proceed to send a reply even though the caller is no longer waiting for it.

In some cases, it may be necessary for the reaction to know that the caller has timed out.
The reply action can check whether the timeout occurred because the reply emitter returns a `Boolean` value:

```scala
val f = b[Unit, Int]
go { f(_, reply) ⇒
// Attempt to reply with `123`; return `false` if caller timed out.
  val status = reply(123)
  if (!status) ??? // caller timed out, maybe need to clean up, etc.
}

```

## Static analysis for correctness and optimization

`Chymyst` uses the `go()` macro for gathering extensive information about the user's reaction code.
This information is used to perform static analysis of reactions, both at compile time and at "early" run time (after creating reaction sites but before any reactions are activated).
Thus `Chymyst` is able to detect some classes of deadlock or livelock automatically:

```scala
val a = m[Int]
val c = m[Unit]

// Does not compile: "Unconditional livelock due to a(x)"
go { case a(x) ⇒ c(); a(x+1) }

```

The static analysis is used to enforce constraints such as the uniqueness of the reply to blocking molecules:

```scala
val a = m[Int]
val f = b[Unit, Int]

// Does not compile: "Blocking molecules should receive unconditional reply"
go { case f(_, r) + a(x) ⇒ if (x > 0) r(x) }

// Compiles successfully because the reply is always sent.
go { case f(_, r) + a(x) ⇒ if (x > 0) r(x) else r(-x) }

```

Common cases of invalid chemical definitions are flagged either at compile time, or as run-time errors that occur after defining a reaction site and before starting any processes.
Other errors are flagged at run time, such as:

- a molecule was emitted without defining any reaction site for that molecule
- a reaction cannot start because its thread pool was shut down
- a reaction produced an exception and failed to send a reply

The results of static analysis are also used to optimize the scheduling of reactions at run time.
For instance, reactions are scheduled significantly faster if they have no cross-molecule guard conditions.

## Thread pools

`Chymyst` implements fine-grained threading control.
Each reaction site and each reaction can be run on a different, separate thread pool if required.
The user can control the number of threads in thread pools.

```scala
val tp1 = FixedPool(1)
val tp8 = BlockingPool(8)

site(tp8)( // reaction site runs on tp8
  go { case a(x) => ... } onThreads tp1, // this reaction runs on tp1
  go { ... } // all other reactions run on tp8
 )

```

The thread pools of class `BlockingPool` are called "blocking" because they will automatically adjust the number of active threads if blocking operations occur.
So, blocking operations do not decrease the degree of parallelism.

Thread pools also include features for thread priority control.

## Graceful shutdown

When a `Chymyst`-based program needs to exit, it can shut down the thread pools that run reactions.

```scala
val tp = BlockingPool(8)

// define reactions and run them

tp.shutdownNow() // all reactions running on `tp` will stop

```

## Non-deterministic choice

Whenever a molecule can start several reactions, the reaction is chosen arbitrarily.

Whenever a reaction can consume several different copies of input molecules, the actually consumed copies are chosen arbitrarily.

## Pipelined molecules

Some reactions consume molecules in such a way that the reaction scheduler only needs to examine a single molecule instance in order to decide whether reactions can start.
`Chymyst` automatically detects such molecules and implements an ordered queue for storing the molecule instances.
Such molecules are called "pipelined"; reactions with these molecules are scheduled faster and more deterministically.

## Fault tolerance

Reactions marked as fault-tolerant will be automatically restarted if exceptions are thrown.

## Debugging

The execution of reactions can be traced via logging levels per reaction site.
Due to automatic naming of molecules and static analysis, debugging can print information about reaction flow in a visual way.


text:
package com.eaw1805.battles.field.test;

import com.eaw1805.battles.field.FieldBattleProcessor;
import com.eaw1805.battles.field.utils.MapUtils;
import com.eaw1805.battles.field.visibility.FieldBattleVisibilityProcessor;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.battles.field.FieldBattleMap;
import com.eaw1805.data.model.battles.field.FieldBattlePosition;
import com.eaw1805.data.model.battles.field.FieldBattleSector;
import com.eaw1805.data.model.battles.field.enumerations.FormationEnum;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class FieldBattleVisibilityProcessorTest {

    private FieldBattleVisibilityProcessor visibilityProcessor;
    private FieldBattleProcessor fbProcessor;
    private FieldBattleMap fbMap;
    private Brigade brigade0;
    private Brigade brigade1;
    private Brigade brigadeObstacle0;
    private Brigade brigadeObstacle1;

    @Before
    public void setUp() throws Exception {

        brigade0 = new Brigade();
        brigade0.setBrigadeId(0);
        brigade0.setFormationEnum(FormationEnum.LINE);
        brigade1 = new Brigade();
        brigade1.setBrigadeId(1);
        brigade1.setFormationEnum(FormationEnum.LINE);
        brigadeObstacle0 = new Brigade();
        brigadeObstacle0.setBrigadeId(700);
        brigadeObstacle0.setFormationEnum(FormationEnum.SKIRMISH);
        brigadeObstacle1 = new Brigade();
        brigadeObstacle1.setBrigadeId(701);
        brigadeObstacle1.setFormationEnum(FormationEnum.LINE);

        fbMap = new FieldBattleMap(10, 5);
        for (FieldBattleSector sector : MapUtils.getAllSectors(fbMap)) {
            sector.setAltitude(1);
        }
        fbProcessor = mock(FieldBattleProcessor.class);
        when(fbProcessor.getFbMap()).thenReturn(fbMap);
        when(fbProcessor.findSide(brigade0)).thenReturn(0);
        when(fbProcessor.findSide(brigade1)).thenReturn(1);
        when(fbProcessor.findSide(brigadeObstacle0)).thenReturn(0);
        when(fbProcessor.findSide(brigadeObstacle1)).thenReturn(1);

        visibilityProcessor = new FieldBattleVisibilityProcessor(fbProcessor);
    }

    private void setBrigadePosition(Brigade brigade, int x, int y) {
        brigade.setFieldBattlePosition(new FieldBattlePosition(x, y));
        FieldBattleSector fieldBattleSector = fbMap.getFieldBattleSector(x, y);
        when(fbProcessor.getSector(brigade)).thenReturn(fieldBattleSector);
        when(fbProcessor.getBrigadeInSector(fieldBattleSector)).thenReturn(brigade);
    }

    @Test
    public void testVisible1() {
        setBrigadePosition(brigade0, 2, 1);
        setBrigadePosition(brigadeObstacle0, 4, 2);
        setBrigadePosition(brigade1, 7, 3);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
        assertTrue(visibilityProcessor.visible(brigadeObstacle0, brigade1));
        assertTrue(visibilityProcessor.visible(brigade1, brigadeObstacle0));
        assertTrue(visibilityProcessor.visible(brigade1, brigade0));
    }

    @Test
    public void testVisible2() {
        setBrigadePosition(brigade0, 1, 1);
        setBrigadePosition(brigade1, 7, 4);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testVisible3() {
        setBrigadePosition(brigade0, 4, 3);
        setBrigadePosition(brigade1, 5, 3);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testVisible4() {
        setBrigadePosition(brigade0, 4, 3);
        setBrigadePosition(brigade1, 5, 4);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testVisibleInEdgeOfForest() {
        setBrigadePosition(brigade0, 2, 3);
        setBrigadePosition(brigade1, 7, 3);
        fbMap.getFieldBattleSector(7, 3).setForest(true);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisibleInInnerOfForest() {
        setBrigadePosition(brigade0, 2, 3);
        setBrigadePosition(brigade1, 7, 3);
        fbMap.getFieldBattleSector(6, 3).setForest(true);
        fbMap.getFieldBattleSector(7, 3).setForest(true);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testVisibleInEdgeOfVillage() {
        setBrigadePosition(brigade0, 2, 3);
        setBrigadePosition(brigade1, 7, 3);
        fbMap.getFieldBattleSector(7, 3).setVillage(5);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisibleInInnerOfVillage() {
        setBrigadePosition(brigade0, 2, 3);
        setBrigadePosition(brigade1, 7, 3);
        fbMap.getFieldBattleSector(6, 3).setVillage(5);
        fbMap.getFieldBattleSector(7, 3).setVillage(5);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible1() {
        setBrigadePosition(brigade0, 2, 2);
        setBrigadePosition(brigade1, 7, 2);
        setBrigadePosition(brigadeObstacle1, 5, 2);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible2() {
        setBrigadePosition(brigade0, 1, 1);
        setBrigadePosition(brigade1, 4, 4);
        setBrigadePosition(brigadeObstacle1, 3, 3);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible3() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        setBrigadePosition(brigadeObstacle1, 4, 2);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible4() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setVillage(5);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible5() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setChateau(4);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible6() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setForest(true);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible7() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setWall(3);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible8() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setTown(7);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testNotVisible9() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 4);
        fbMap.getFieldBattleSector(4, 2).setAltitude(2);

        assertFalse(visibilityProcessor.visible(brigade0, brigade1));
    }

    @Test
    public void testVisible() {
        setBrigadePosition(brigade0, 0, 0);
        setBrigadePosition(brigade1, 9, 0);

        fbMap.getFieldBattleSector(9, 0).setAltitude(2);

        assertTrue(visibilityProcessor.visible(brigade0, brigade1));
    }
}


text:
angular.module('kdmediaNet').controller('SearchTbImagemAnuncioController', function($scope, $http, TbImagemAnuncioResource , TbAnuncioResource) {

    $scope.search={};
    $scope.currentPage = 0;
    $scope.pageSize= 10;
    $scope.searchResults = [];
    $scope.filteredResults = [];
    $scope.pageRange = [];
    $scope.numberOfPages = function() {
        var result = Math.ceil($scope.filteredResults.length/$scope.pageSize);
        var max = (result == 0) ? 1 : result;
        $scope.pageRange = [];
        for(var ctr=0;ctr<max;ctr++) {
            $scope.pageRange.push(ctr);
        }
        return max;
    };
    $scope.tbAnuncioList = TbAnuncioResource.queryAll();

    $scope.performSearch = function() {
        $scope.searchResults = TbImagemAnuncioResource.queryAll(function(){
            $scope.numberOfPages();
        });
    };

    $scope.previous = function() {
       if($scope.currentPage > 0) {
           $scope.currentPage--;
       }
    };

    $scope.next = function() {
       if($scope.currentPage < ($scope.numberOfPages() - 1) ) {
           $scope.currentPage++;
       }
    };

    $scope.setPage = function(n) {
       $scope.currentPage = n;
    };

    $scope.performSearch();
});


text:
namespace ParquetColumnTests.Io
{
    using System;
    using System.Collections.Generic;
    using ParquetColumnTests.Column.Page.Mem;
    using ParquetSharp;
    using ParquetSharp.Column;
    using ParquetSharp.Column.Impl;
    using ParquetSharp.Column.Page;
    using ParquetSharp.Example.Data;
    using ParquetSharp.Example.Data.Simple;
    using ParquetSharp.Example.Data.Simple.Convert;
    using ParquetSharp.External;
    using ParquetSharp.IO;
    using ParquetSharp.IO.Api;
    using ParquetSharp.Schema;
    using Xunit;
    using static ParquetSharp.Example.Paper;
    using static ParquetSharp.Schema.PrimitiveType.PrimitiveTypeName;
    using static ParquetSharp.Schema.Type.Repetition;
    using Type = ParquetSharp.Schema.Type;

    public class TestColumnIO
    {
        private static readonly Log LOG = Log.getLog(typeof(TestColumnIO));

        private const string oneOfEach =
          "message Document {\n"
        + "  required int64 a;\n"
        + "  required int32 b;\n"
        + "  required float c;\n"
        + "  required double d;\n"
        + "  required boolean e;\n"
        + "  required binary f;\n"
        + "  required int96 g;\n"
        + "  required fixed_len_byte_array(3) h;\n"
        + "}\n";

        private const string schemaString =
            "message Document {\n"
          + "  required int64 DocId;\n"
          + "  optional group Links {\n"
          + "    repeated int64 Backward;\n"
          + "    repeated int64 Forward;\n"
          + "  }\n"
          + "  repeated group Name {\n"
          + "    repeated group Language {\n"
          + "      required binary Code;\n"
          + "      optional binary Country;\n"
          + "    }\n"
          + "    optional binary Url;\n"
          + "  }\n"
          + "}\n";

        int[][] expectedFSA = new int[][]
        {
            new int[] { 1 },      // 0: DocId
            new int[] { 2, 1 },   // 1: Links.Backward
            new int[] { 3, 2 },   // 2: Links.Forward
            new int[] { 4, 4, 4 },// 3: Name.Language.Code
            new int[] { 5, 5, 3 },// 4: Name.Language.Country
            new int[] { 6, 3 }    // 5: Name.Url
        };

        int[][] expectedFSA2 = new int[][]
        {
            new int[] { 1 },      // 0: DocId
            new int[] { 2, 1, 1 },// 1: Name.Language.Country
        };

        public static readonly string[] expectedEventsForR1 = {
            "startMessage()",
            "DocId.addLong(10)",
            "Links.start()",
            "Links.Forward.addLong(20)",
            "Links.Forward.addLong(40)",
            "Links.Forward.addLong(60)",
            "Links.end()",
            "Name.start()",
            "Name.Language.start()",
            "Name.Language.Code.addBinary(en-us)",
            "Name.Language.Country.addBinary(us)",
            "Name.Language.end()",
            "Name.Language.start()",
            "Name.Language.Code.addBinary(en)",
            "Name.Language.end()",
            "Name.Url.addBinary(http://A)",
            "Name.end()",
            "Name.start()",
            "Name.Url.addBinary(http://B)",
            "Name.end()",
            "Name.start()",
            "Name.Language.start()",
            "Name.Language.Code.addBinary(en-gb)",
            "Name.Language.Country.addBinary(gb)",
            "Name.Language.end()",
            "Name.end()",
            "endMessage()"
        };

        private bool useDictionary;

        [Theory, InlineData(true), InlineData(false)]
        public void testSchema(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            Assert.Equal(schemaString, schema.ToString());
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testReadUsingRequestedSchemaWithExtraFields(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType orginalSchema = new MessageType("schema",
                    new PrimitiveType(REQUIRED, INT32, "a"),
                    new PrimitiveType(OPTIONAL, INT32, "b")
            );
            MessageType schemaWithExtraField = new MessageType("schema",
                    new PrimitiveType(OPTIONAL, INT32, "b"),
                    new PrimitiveType(OPTIONAL, INT32, "a"),
                    new PrimitiveType(OPTIONAL, INT32, "c")
            );
            MemPageStore memPageStoreForOriginalSchema = new MemPageStore(1);
            MemPageStore memPageStoreForSchemaWithExtraField = new MemPageStore(1);
            SimpleGroupFactory groupFactory = new SimpleGroupFactory(orginalSchema);
            writeGroups(orginalSchema, memPageStoreForOriginalSchema, groupFactory.newGroup().append("a", 1).append("b", 2));

            SimpleGroupFactory groupFactory2 = new SimpleGroupFactory(schemaWithExtraField);
            writeGroups(schemaWithExtraField, memPageStoreForSchemaWithExtraField, groupFactory2.newGroup().append("a", 1).append("b", 2).append("c", 3));

            {
                List<Group> groups = new List<Group>();
                groups.AddRange(readGroups(memPageStoreForOriginalSchema, orginalSchema, schemaWithExtraField, 1));
                groups.AddRange(readGroups(memPageStoreForSchemaWithExtraField, schemaWithExtraField, schemaWithExtraField, 1));
                // TODO: add once we have the support for empty projection
                //      groups1.AddRange(readGroups(memPageStore3, schema3, schema2, 1));
                object[][] expected = {
              new object[] { 2, 1, null},
              new object[] { 2, 1, 3},
//          new object[] { null, null}
      };
                validateGroups(groups, expected);
            }
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testReadUsingRequestedSchemaWithIncompatibleField(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType originalSchema = new MessageType("schema",
                    new PrimitiveType(OPTIONAL, INT32, "e"));
            MemPageStore store = new MemPageStore(1);
            SimpleGroupFactory groupFactory = new SimpleGroupFactory(originalSchema);
            writeGroups(originalSchema, store, groupFactory.newGroup().append("e", 4));

            try
            {
                MessageType schemaWithIncompatibleField = new MessageType("schema",
                        new PrimitiveType(OPTIONAL, BINARY, "e")); // Incompatible schema: different type
                readGroups(store, originalSchema, schemaWithIncompatibleField, 1);
                Assert.True(false, "should have thrown an incompatible schema exception");
            }
            catch (ParquetDecodingException e)
            {
                Assert.Equal("The requested schema is not compatible with the file schema. incompatible types: optional binary e != optional int32 e", e.Message);
            }
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testReadUsingSchemaWithRequiredFieldThatWasOptional(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType originalSchema = new MessageType("schema",
                    new PrimitiveType(OPTIONAL, INT32, "e"));
            MemPageStore store = new MemPageStore(1);
            SimpleGroupFactory groupFactory = new SimpleGroupFactory(originalSchema);
            writeGroups(originalSchema, store, groupFactory.newGroup().append("e", 4));

            try
            {
                MessageType schemaWithRequiredFieldThatWasOptional = new MessageType("schema",
                        new PrimitiveType(REQUIRED, INT32, "e")); // Incompatible schema: required when it was optional
                readGroups(store, originalSchema, schemaWithRequiredFieldThatWasOptional, 1);
                Assert.True(false, "should have thrown an incompatible schema exception");
            }
            catch (ParquetDecodingException e)
            {
                Assert.Equal("The requested schema is not compatible with the file schema. incompatible types: required int32 e != optional int32 e", e.Message);
            }
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testReadUsingProjectedSchema(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType orginalSchema = new MessageType("schema",
                    new PrimitiveType(REQUIRED, INT32, "a"),
                    new PrimitiveType(REQUIRED, INT32, "b")
            );
            MessageType projectedSchema = new MessageType("schema",
                    new PrimitiveType(OPTIONAL, INT32, "b")
            );
            MemPageStore store = new MemPageStore(1);
            SimpleGroupFactory groupFactory = new SimpleGroupFactory(orginalSchema);
            writeGroups(orginalSchema, store, groupFactory.newGroup().append("a", 1).append("b", 2));

            {
                List<Group> groups = new List<Group>();
                groups.AddRange(readGroups(store, orginalSchema, projectedSchema, 1));
                object[][] expected = {
                    new object[] {2},
                };
                validateGroups(groups, expected);
            }
        }

        private void validateGroups(List<Group> groups1, object[][] e1)
        {
            IEnumerator<Group> i1 = groups1.GetEnumerator();
            for (int i = 0; i < e1.Length; i++)
            {
                object[] objects = e1[i];
                Assert.True(i1.MoveNext());
                Group next = i1.Current;
                for (int j = 0; j < objects.Length; j++)
                {
                    object @object = objects[j];
                    if (@object == null)
                    {
                        Assert.Equal(0, next.getFieldRepetitionCount(j));
                    }
                    else {
                        Assert.Equal(1, next.getFieldRepetitionCount(j));
                        Assert.Equal(@object, next.getInteger(j, 0));
                    }
                }
            }
        }

        private List<Group> readGroups(MemPageStore memPageStore, MessageType fileSchema, MessageType requestedSchema, int n)
        {
            ColumnIOFactory columnIOFactory = new ColumnIOFactory(true);
            MessageColumnIO columnIO = columnIOFactory.getColumnIO(requestedSchema, fileSchema);
            RecordReaderImplementation<Group> recordReader = getRecordReader(columnIO, requestedSchema, memPageStore);
            List<Group> groups = new List<Group>();
            for (int i = 0; i < n; i++)
            {
                groups.Add(recordReader.read());
            }
            return groups;
        }

        private void writeGroups(MessageType writtenSchema, MemPageStore memPageStore, params Group[] groups)
        {
            ColumnIOFactory columnIOFactory = new ColumnIOFactory(true);
            ColumnWriteStoreV1 columns = newColumnWriteStore(memPageStore);
            MessageColumnIO columnIO = columnIOFactory.getColumnIO(writtenSchema);
            RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
            GroupWriter groupWriter = new GroupWriter(recordWriter, writtenSchema);
            foreach (Group group in groups)
            {
                groupWriter.write(group);
            }
            recordWriter.flush();
            columns.flush();
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testColumnIO(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            log(schema);
            log("r1");
            log(r1);
            log("r2");
            log(r2);

            MemPageStore memPageStore = new MemPageStore(2);
            ColumnWriteStoreV1 columns = newColumnWriteStore(memPageStore);

            ColumnIOFactory columnIOFactory = new ColumnIOFactory(true);
            {
                MessageColumnIO columnIO = columnIOFactory.getColumnIO(schema);
                log(columnIO);
                RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
                GroupWriter groupWriter = new GroupWriter(recordWriter, schema);
                groupWriter.write(r1);
                groupWriter.write(r2);

                recordWriter.flush();
                columns.flush();
                log(columns);
                log("=========");

                RecordReaderImplementation<Group> recordReader = getRecordReader(columnIO, schema, memPageStore);

                validateFSA(expectedFSA, columnIO, recordReader);

                List<Group> records = new List<Group>();
                records.Add(recordReader.read());
                records.Add(recordReader.read());

                int i = 0;
                foreach (Group record in records)
                {
                    log("r" + (++i));
                    log(record);
                }
                Assert.Equal(r1.ToString(), records[0].ToString());
                Assert.Equal(r2.ToString(), records[1].ToString());
            }
            {
                MessageColumnIO columnIO2 = columnIOFactory.getColumnIO(schema2);

                List<Group> records = new List<Group>();
                RecordReaderImplementation<Group> recordReader = getRecordReader(columnIO2, schema2, memPageStore);

                validateFSA(expectedFSA2, columnIO2, recordReader);

                records.Add(recordReader.read());
                records.Add(recordReader.read());

                int i = 0;
                foreach (Group record in records)
                {
                    log("r" + (++i));
                    log(record);
                }
                Assert.Equal(pr1.ToString(), records[0].ToString());
                Assert.Equal(pr2.ToString(), records[1].ToString());
            }
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testOneOfEach(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType oneOfEachSchema = MessageTypeParser.parseMessageType(oneOfEach);
            GroupFactory gf = new SimpleGroupFactory(oneOfEachSchema);
            Group g1 = gf.newGroup()
                .append("a", 1L)
                .append("b", 2)
                .append("c", 3.0f)
                .append("d", 4.0d)
                .append("e", true)
                .append("f", Binary.fromString("6"))
                .append("g", new NanoTime(1234, Epoch.currentTimeMillis() * 1000))
                .append("h", Binary.fromString("abc"));

            testSchema(oneOfEachSchema, new List<Group> { g1 });
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testRequiredOfRequired(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MessageType reqreqSchema = MessageTypeParser.parseMessageType(
                  "message Document {\n"
                + "  required group foo {\n"
                + "    required int64 bar;\n"
                + "  }\n"
                + "}\n");

            GroupFactory gf = new SimpleGroupFactory(reqreqSchema);
            Group g1 = gf.newGroup();
            g1.addGroup("foo").append("bar", 2L);

            testSchema(reqreqSchema, new List<Group> { g1 });
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testOptionalRequiredInteraction(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            for (int i = 0; i < 6; i++)
            {
                Type current = new PrimitiveType(REQUIRED, BINARY, "primitive");
                for (int j = 0; j < i; j++)
                {
                    current = new GroupType(REQUIRED, "req" + j, current);
                }
                MessageType groupSchema = new MessageType("schema" + i, current);
                GroupFactory gf = new SimpleGroupFactory(groupSchema);
                List<Group> groups = new List<Group>();
                Group root = gf.newGroup();
                Group currentGroup = root;
                for (int j = 0; j < i; j++)
                {
                    currentGroup = currentGroup.addGroup(0);
                }
                currentGroup.add(0, Binary.fromString("foo"));
                groups.Add(root);
                testSchema(groupSchema, groups);
            }
            for (int i = 0; i < 6; i++)
            {
                Type current = new PrimitiveType(OPTIONAL, BINARY, "primitive");
                for (int j = 0; j < i; j++)
                {
                    current = new GroupType(REQUIRED, "req" + j, current);
                }
                MessageType groupSchema = new MessageType("schema" + (i + 6), current);
                GroupFactory gf = new SimpleGroupFactory(groupSchema);
                List<Group> groups = new List<Group>();
                Group rootDefined = gf.newGroup();
                Group rootUndefined = gf.newGroup();
                Group currentDefinedGroup = rootDefined;
                Group currentUndefinedGroup = rootUndefined;
                for (int j = 0; j < i; j++)
                {
                    currentDefinedGroup = currentDefinedGroup.addGroup(0);
                    currentUndefinedGroup = currentUndefinedGroup.addGroup(0);
                }
                currentDefinedGroup.add(0, Binary.fromString("foo"));
                groups.Add(rootDefined);
                groups.Add(rootUndefined);
                testSchema(groupSchema, groups);
            }
            for (int i = 0; i < 6; i++)
            {
                Type current = new PrimitiveType(OPTIONAL, BINARY, "primitive");
                for (int j = 0; j < 6; j++)
                {
                    current = new GroupType(i == j ? OPTIONAL : REQUIRED, "req" + j, current);
                }
                MessageType groupSchema = new MessageType("schema" + (i + 12), current);
                GroupFactory gf = new SimpleGroupFactory(groupSchema);
                List<Group> groups = new List<Group>();
                Group rootDefined = gf.newGroup();
                Group rootUndefined = gf.newGroup();
                Group currentDefinedGroup = rootDefined;
                Group currentUndefinedGroup = rootUndefined;
                for (int j = 0; j < 6; j++)
                {
                    currentDefinedGroup = currentDefinedGroup.addGroup(0);
                    if (i < j)
                    {
                        currentUndefinedGroup = currentUndefinedGroup.addGroup(0);
                    }
                }
                currentDefinedGroup.add(0, Binary.fromString("foo"));
                groups.Add(rootDefined);
                groups.Add(rootUndefined);
                testSchema(groupSchema, groups);
            }
        }

        private void testSchema(MessageType messageSchema, List<Group> groups)
        {
            MemPageStore memPageStore = new MemPageStore(groups.Count);
            ColumnWriteStoreV1 columns = newColumnWriteStore(memPageStore);

            ColumnIOFactory columnIOFactory = new ColumnIOFactory(true);
            MessageColumnIO columnIO = columnIOFactory.getColumnIO(messageSchema);
            log(columnIO);

            // Write groups.
            RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
            GroupWriter groupWriter =
                new GroupWriter(recordWriter, messageSchema);
            foreach (Group group in groups)
            {
                groupWriter.write(group);
            }
            recordWriter.flush();
            columns.flush();

            // Read groups and verify.
            RecordReaderImplementation<Group> recordReader =
                getRecordReader(columnIO, messageSchema, memPageStore);
            foreach (Group group in groups)
            {
                Group got = recordReader.read();
                Assert.Equal(group.ToString(), got.ToString());
            }
        }

        private RecordReaderImplementation<Group> getRecordReader(MessageColumnIO columnIO, MessageType schema, PageReadStore pageReadStore)
        {
            RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);

            return (RecordReaderImplementation<Group>)columnIO.getRecordReader(pageReadStore, recordConverter);
        }

        private void log(object o)
        {
            LOG.info(o);
        }

        private void validateFSA<T>(int[][] expectedFSA, MessageColumnIO columnIO, RecordReaderImplementation<T> recordReader)
        {
            log("FSA: ----");
            List<PrimitiveColumnIO> leaves = columnIO.getLeaves();
            for (int i = 0; i < leaves.Count; ++i)
            {
                PrimitiveColumnIO primitiveColumnIO = leaves[i];
                log(Arrays.toString(primitiveColumnIO.getFieldPath()));
                for (int r = 0; r < expectedFSA[i].Length; r++)
                {
                    int next = expectedFSA[i][r];
                    log(" " + r + " -> " + (next == leaves.Count ? "end" : Arrays.toString(leaves[next].getFieldPath())) + ": " + recordReader.getNextLevel(i, r));
                    Assert.Equal(next, recordReader.getNextReader(i, r));
                }
            }
            log("----");
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testPushParser(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MemPageStore memPageStore = new MemPageStore(1);
            ColumnWriteStoreV1 columns = newColumnWriteStore(memPageStore);
            MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
            RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
            new GroupWriter(recordWriter, schema).write(r1);
            recordWriter.flush();
            columns.flush();

            RecordReader<bool> recordReader = columnIO.getRecordReader(memPageStore, new ExpectationValidatingConverter(expectedEventsForR1, schema));
            recordReader.read();

        }

        private ColumnWriteStoreV1 newColumnWriteStore(MemPageStore memPageStore)
        {
            return new ColumnWriteStoreV1(memPageStore,
                ParquetProperties.builder()
                    .withPageSize(800)
                    .withDictionaryPageSize(800)
                    .withDictionaryEncoding(useDictionary)
                    .build());
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testEmptyField(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            MemPageStore memPageStore = new MemPageStore(1);
            ColumnWriteStoreV1 columns = newColumnWriteStore(memPageStore);
            MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
            RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
            recordWriter.startMessage();
            recordWriter.startField("DocId", 0);
            recordWriter.addLong(0);
            recordWriter.endField("DocId", 0);
            recordWriter.startField("Links", 1);
            try
            {
                recordWriter.endField("Links", 1);
                Assert.True(false, "expected exception because of empty field");
            }
            catch (ParquetEncodingException e)
            {
                Assert.Equal("empty fields are illegal, the field should be ommited completely instead", e.Message);
            }
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testGroupWriter(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            List<Group> result = new List<Group>();
            GroupRecordConverter groupRecordConverter = new GroupRecordConverter(schema);
            RecordConsumer groupConsumer = new ConverterConsumer(groupRecordConverter.getRootConverter(), schema);
            GroupWriter groupWriter = new GroupWriter(new RecordConsumerLoggingWrapper(groupConsumer), schema);
            groupWriter.write(r1);
            result.Add(groupRecordConverter.getCurrentRecord());
            groupWriter.write(r2);
            result.Add(groupRecordConverter.getCurrentRecord());
            Assert.Equal(result[0].ToString(), r1.ToString());
            Assert.Equal(result[1].ToString(), r2.ToString());
        }

        [Theory, InlineData(true), InlineData(false)]
        public void testWriteWithGroupWriter(bool useDictionary)
        {
            this.useDictionary = useDictionary;

            string[] expected = new[]
            {
                "[DocId]: 10, r:0, d:0",
                "[Links, Forward]: 20, r:0, d:2",
                "[Links, Forward]: 40, r:1, d:2",
                "[Links, Forward]: 60, r:1, d:2",
                "[Links, Backward]: null, r:0, d:1",
                "[Name, Language, Code]: en-us, r:0, d:2",
                "[Name, Language, Country]: us, r:0, d:3",
                "[Name, Language, Code]: en, r:2, d:2",
                "[Name, Language, Country]: null, r:2, d:2",
                "[Name, Url]: http://A, r:0, d:2",
                "[Name, Url]: http://B, r:1, d:2",
                "[Name, Language, Code]: null, r:1, d:1",
                "[Name, Language, Country]: null, r:1, d:1",
                "[Name, Language, Code]: en-gb, r:1, d:2",
                "[Name, Language, Country]: gb, r:1, d:3",
                "[Name, Url]: null, r:1, d:1",
                "[DocId]: 20, r:0, d:0",
                "[Links, Backward]: 10, r:0, d:2",
                "[Links, Backward]: 30, r:1, d:2",
                "[Links, Forward]: 80, r:0, d:2",
                "[Name, Url]: http://C, r:0, d:2",
                "[Name, Language, Code]: null, r:0, d:1",
                "[Name, Language, Country]: null, r:0, d:1"
            };

            ValidatingColumnWriteStore columns = new ValidatingColumnWriteStore(expected);
            MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
            RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
            GroupWriter groupWriter = new GroupWriter(recordWriter, schema);
            groupWriter.write(r1);
            groupWriter.write(r2);
            recordWriter.flush();
            columns.validate();
            columns.flush();
            columns.close();
        }
    }

    sealed class ValidatingColumnWriteStore : ColumnWriteStore
    {
        private readonly string[] expected;
        int counter = 0;

        public ValidatingColumnWriteStore(string[] expected)
        {
            this.expected = expected;
        }

        public void close()
        {
        }

        public ColumnWriter getColumnWriter(ColumnDescriptor path)
        {
            return new TestColumnWriter(this, path);
        }

        public void validate()
        {
            Assert.Equal(expected.Length, counter);
        }

        public void endRecord()
        {
        }

        public void flush()
        {
        }

        public long getAllocatedSize()
        {
            return 0;
        }

        public long getBufferedSize()
        {
            return 0;
        }

        public string memUsageString()
        {
            return null;
        }

        class TestColumnWriter : ColumnWriter
        {
            readonly ValidatingColumnWriteStore store;
            readonly ColumnDescriptor path;

            public TestColumnWriter(ValidatingColumnWriteStore store, ColumnDescriptor path)
            {
                this.store = store;
                this.path = path;
            }

            private void validate(object value, int repetitionLevel, int definitionLevel)
            {
                string valueString = (value == null) ? "null" : value.ToString();
                string actual = Arrays.toString(path.getPath()) + ": " + valueString + ", r:" + repetitionLevel + ", d:" + definitionLevel;
                Assert.Equal(store.expected[store.counter], actual);
                ++store.counter;
            }

            public void writeNull(int repetitionLevel, int definitionLevel)
            {
                validate(null, repetitionLevel, definitionLevel);
            }

            public void write(Binary value, int repetitionLevel, int definitionLevel)
            {
                validate(value.toStringUsingUTF8(), repetitionLevel, definitionLevel);
            }

            public void write(float value, int repetitionLevel, int definitionLevel)
            {
                validate(value, repetitionLevel, definitionLevel);
            }

            public void write(bool value, int repetitionLevel, int definitionLevel)
            {
                validate(value, repetitionLevel, definitionLevel);
            }

            public void write(int value, int repetitionLevel, int definitionLevel)
            {
                validate(value, repetitionLevel, definitionLevel);
            }

            public void write(long value, int repetitionLevel, int definitionLevel)
            {
                validate(value, repetitionLevel, definitionLevel);
            }

            public void close()
            {
            }

            public long getBufferedSizeInMemory()
            {
                throw new NotSupportedException();
            }

            public void write(double value, int repetitionLevel, int definitionLevel)
            {
                validate(value, repetitionLevel, definitionLevel);
            }
        }
    }
}


text:
<?php

namespace AddressBook\Mapper\Rest;

use AddressBook\Entity\Contact;
use AddressBook\Mapper\ContactMapperInterface;
use Zend\Http\Client;
use Zend\Http\Headers;
use Zend\Http\Request;
use Zend\Stdlib\Hydrator\ClassMethods;

class ContactMapper implements ContactMapperInterface {

    public function findAll()
    {
        $client = new Client();
        $request = new Request();
        $request->setUri('http://localhost:8888/contact');

        $headers = new Headers();
        $headers->addHeaderLine('Accept', 'application/json');
        $request->setHeaders($headers);

        $client->send($request);

        $response = $client->getResponse()->getContent();

        $listContactArray = json_decode($response)['_embedded']['contact'];

        $listContacts = array();

        $hydrator = new ClassMethods();

        foreach ($listContactArray as $contactArray) {
            $contact = new Contact();
            $hydrator->hydrate($contactArray, $contact);

            $listContacts[] = $contact;
        }

        return $listContacts;
    }

    public function findById($id)
    {
        // TODO: Implement findById() method.
    }

    public function deleteById($id)
    {
        // TODO: Implement deleteById() method.
    }

    public function insert(Contact $contact)
    {
        // TODO: Implement insert() method.
    }

    public function update(Contact $contact)
    {
        // TODO: Implement update() method.
    }
}


text:
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
	  xmlns:android="http://schemas.android.com/apk/res/android">

	<item
			android:id="@+id/menu_send"
			android:title="@string/send"
			app:showAsAction="always"/>

</menu>


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var $ = require('npm-zepto');
var React = require('react');
var ReactBootstrap = require('react-bootstrap');
var ButtonGroup = ReactBootstrap.ButtonGroup;
var DropdownButton = ReactBootstrap.DropdownButton;
var MenuItem = ReactBootstrap.MenuItem;
var Button = ReactBootstrap.Button;
var ButtonInput = ReactBootstrap.ButtonInput;
var Overlay = ReactBootstrap.Overlay;
var Popover = ReactBootstrap.Popover;
var Input = ReactBootstrap.Input;

module.exports = React.createClass({
	displayName: 'EditableDiv',

	propTypes: {
		content: React.PropTypes.string.isRequired,
		onChange: React.PropTypes.func.isRequired,
		onImageUpload: React.PropTypes.func,
		onVideoUpload: React.PropTypes.func,
		tooltipPlacement: React.PropTypes.string
	},

	getDefaultProps: function getDefaultProps() {
		return {
			tooltipPlacement: 'auto'
		};
	},

	getInitialState: function getInitialState() {
		// this is anti-pattern but we treat this.props.content as initial content
		return {
			html: this.props.content,
			showImageTooltip: false,
			showVideoTooltip: false
		};
	},

	componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
		this.setState({
			html: nextProps.content
		});
	},

	shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
		return nextProps.content !== this.state.html || nextState.showImageTooltip !== this.state.showImageTooltip || nextState.showVideoTooltip !== this.state.showVideoTooltip;
	},

	_toggleImageTooltip: function _toggleImageTooltip() {
		this.setState({
			showImageTooltip: !this.state.showImageTooltip
		});
	},

	_toggleVideoTooltip: function _toggleVideoTooltip() {
		this.setState({
			showVideoTooltip: !this.state.showVideoTooltip
		});
	},

	_execCommand: function _execCommand(command, arg) {
		document.execCommand(command, false, arg);
	},

	_emitChange: function _emitChange() {
		var editor = this.refs.editor.getDOMNode();
		var newHtml = editor.innerHTML;

		this.setState({ html: newHtml }, (function () {
			this.props.onChange({
				target: {
					value: newHtml
				}
			});
		}).bind(this));
	},

	_onImageSubmit: function _onImageSubmit() {
		var _this = this;

		var files = this.refs.imageInput.getInputDOMNode().files;
		this.props.onImageUpload(files, function (url) {
			_this.refs.editor.getDOMNode().focus();
			_this._execCommand('insertImage', url);
		});
		this._toggleImageTooltip();
	},

	_onVideoSubmit: function _onVideoSubmit() {
		var _this2 = this;

		var files = this.refs.videoInput.getInputDOMNode().files;
		this.props.onVideoUpload(files, function (url) {
			_this2.refs.editor.getDOMNode().focus();
			_this2._execCommand('insertHTML', '<figure><video controls width="400" src="' + url + '">Your browser does not support HTML5 video.</video></figure>');
		});
		this._toggleVideoTooltip();
	},

	render: function render() {
		var _this3 = this;

		// customize css rules here
		var toolbarStyle = { marginBottom: 3 };
		var imgTooltipPlacement = this.props.tooltipPlacement;
		var videoTooltipPlacement = this.props.tooltipPlacement;
		if (imgTooltipPlacement === 'auto') {
			var imgBtn = $('#imgUploadBtn');
			if (imgBtn.length) {
				imgTooltipPlacement = imgBtn.offset().left < 350 ? 'right' : 'left';
			}
		}
		if (videoTooltipPlacement === 'auto') {
			var videoUploadBtn = $('#videoUploadBtn');
			if (videoUploadBtn.length) {
				videoTooltipPlacement = videoUploadBtn.offset().left < 350 ? 'right' : 'left';
			}
		}
		var imageUpload = this.props.onImageUpload === undefined ? null : React.createElement(
			Overlay,
			{
				show: this.state.showImageTooltip,
				onHide: function () {
					return _this3.setState({ showImageTooltip: false });
				},
				placement: imgTooltipPlacement,
				container: this,
				rootClose: true,
				target: function () {
					return _this3.refs.imgUploadBtn.getDOMNode();
				} },
			React.createElement(
				Popover,
				{ id: 'popover', title: 'Image Upload' },
				React.createElement(Input, { type: 'file',
					ref: 'imageInput',
					name: 'file',
					label: 'Select an image to upload'
				}),
				React.createElement(ButtonInput, { type: 'submit', value: 'Submit', onClick: this._onImageSubmit })
			)
		);
		var videoUpload = this.props.onVideoUpload === undefined ? null : React.createElement(
			Overlay,
			{
				show: this.state.showVideoTooltip,
				onHide: function () {
					return _this3.setState({ showVideoTooltip: false });
				},
				placement: videoTooltipPlacement,
				container: this,
				rootClose: true,
				target: function () {
					return _this3.refs.videoUploadBtn.getDOMNode();
				} },
			React.createElement(
				Popover,
				{ id: 'popover', title: 'Video Upload' },
				React.createElement(Input, { type: 'file',
					ref: 'videoInput',
					name: 'file',
					label: 'Select a video to upload'
				}),
				React.createElement(ButtonInput, { type: 'submit', value: 'Submit', onClick: this._onVideoSubmit })
			)
		);
		return React.createElement(
			'div',
			null,
			React.createElement(
				'div',
				{ style: toolbarStyle },
				React.createElement(
					ButtonGroup,
					null,
					React.createElement(
						DropdownButton,
						{ title: React.createElement('i', { className: 'fa fa-paragraph' }), id: 'bg-nested-dropdown' },
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'P') },
							'Paragraph'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'BLOCKQUOTE') },
							'Block Quote'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H1') },
							'Header 1'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H2') },
							'Header 2'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H3') },
							'Header 3'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H4') },
							'Header 4'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H5') },
							'Header 5'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'formatBlock', 'H6') },
							'Header 6'
						)
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'bold') },
						React.createElement('i', { className: 'fa fa-bold' })
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'italic') },
						React.createElement('i', { className: 'fa fa-italic' })
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'underline') },
						React.createElement('i', { className: 'fa fa-underline' })
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'strikeThrough') },
						React.createElement('i', { className: 'fa fa-strikethrough' })
					),
					React.createElement(
						DropdownButton,
						{ title: React.createElement('i', { className: 'fa fa-text-height' }), id: 'bg-nested-dropdown' },
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 1) },
							'1'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 2) },
							'2'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 3) },
							'3'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 4) },
							'4'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 5) },
							'5'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 6) },
							'6'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'fontSize', 7) },
							'7'
						)
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'insertOrderedList') },
						React.createElement('i', { className: 'fa fa-list-ol' })
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'insertUnorderedList') },
						React.createElement('i', { className: 'fa fa-list-ul' })
					),
					React.createElement(
						DropdownButton,
						{ title: React.createElement('i', { className: 'fa fa-align-left' }), id: 'bg-nested-dropdown' },
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'justifyLeft') },
							'Align Left'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'justifyRight') },
							'Align Right'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'justifyCenter') },
							'Align Center'
						),
						React.createElement(
							MenuItem,
							{ onSelect: this._execCommand.bind(this, 'justifyFull') },
							'Align Justify'
						)
					),
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'removeFormat') },
						React.createElement('i', { className: 'fa fa-eraser' })
					),
					React.createElement(
						Button,
						{ ref: 'imgUploadBtn', id: 'imgUploadBtn', onClick: this._toggleImageTooltip },
						React.createElement('i', { className: 'fa fa-picture-o' })
					),
					imageUpload,
					React.createElement(
						Button,
						{ ref: 'videoUploadBtn', id: 'videoUploadBtn', onClick: this._toggleVideoTooltip },
						React.createElement('i', { className: 'fa fa-file-video-o' })
					),
					videoUpload,
					React.createElement(
						Button,
						{ onClick: this._execCommand.bind(this, 'createLink') },
						React.createElement('i', { className: 'fa fa-link' })
					)
				)
			),
			React.createElement('div', _extends({
				ref: 'editor',
				className: 'form-control'
			}, this.props, {
				contentEditable: 'true',
				dangerouslySetInnerHTML: { __html: this.state.html },
				onBlur: function (e) {
					if (e.relatedTarget.id === 'imgUploadBtn' || e.relatedTarget.id === 'videoUploadBtn') {
						e.preventDefault();
						_this3.refs.editor.getDOMNode().focus();
					}
				},
				onInput: this._emitChange }))
		);
	}
});


text:
@interface UIView (QJKJFrameQuick)

@property CGPoint origin;
@property CGSize size;
@property CGFloat height;
@property CGFloat width;
@property CGFloat top;
@property CGFloat left;
@property CGFloat bottom;
@property CGFloat right;

- (void)sFrame;

@end


text:
package com.khartec.waltz.web.endpoints.extracts;

import com.khartec.waltz.data.application.ApplicationIdSelectorFactory;
import com.khartec.waltz.data.data_type.DataTypeIdSelectorFactory;
import com.khartec.waltz.model.EntityKind;
import com.khartec.waltz.model.IdSelectionOptions;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.khartec.waltz.common.ListUtilities.newArrayList;
import static com.khartec.waltz.data.InlineSelectFieldFactory.mkNameField;
import static com.khartec.waltz.model.EntityLifecycleStatus.REMOVED;
import static com.khartec.waltz.schema.Tables.*;
import static com.khartec.waltz.schema.tables.Application.APPLICATION;
import static com.khartec.waltz.schema.tables.LogicalFlow.LOGICAL_FLOW;
import static com.khartec.waltz.schema.tables.OrganisationalUnit.ORGANISATIONAL_UNIT;
import static com.khartec.waltz.web.WebUtilities.mkPath;
import static com.khartec.waltz.web.WebUtilities.readIdSelectionOptionsFromBody;
import static spark.Spark.post;

@Service
public class LogicalFlowExtractor extends DirectQueryBasedDataExtractor {

    private static final Field<String> SOURCE_NAME_FIELD = mkNameField(
            LOGICAL_FLOW.SOURCE_ENTITY_ID,
            LOGICAL_FLOW.SOURCE_ENTITY_KIND,
            newArrayList(EntityKind.APPLICATION, EntityKind.ACTOR));

    private static final Field<String> TARGET_NAME_FIELD = mkNameField(
            LOGICAL_FLOW.TARGET_ENTITY_ID,
            LOGICAL_FLOW.TARGET_ENTITY_KIND,
            newArrayList(EntityKind.APPLICATION, EntityKind.ACTOR));

    private final ApplicationIdSelectorFactory applicationIdSelectorFactory = new ApplicationIdSelectorFactory();
    private final DataTypeIdSelectorFactory dataTypeIdSelectorFactory = new DataTypeIdSelectorFactory();

    @Autowired
    public LogicalFlowExtractor(DSLContext dsl) {
        super(dsl);
    }

    @Override
    public void register() {
        post(mkPath("data-extract", "logical-flows"), (request, response) -> {
            IdSelectionOptions options = readIdSelectionOptionsFromBody(request);
            SelectConditionStep<Record> qry = prepareQuery(dsl, options);
            return writeExtract("logical-flows", qry, request, response);
        });
    }

    private SelectConditionStep<Record> prepareQuery(DSLContext dsl, IdSelectionOptions options) {

        Select<Record1<Long>> appIdSelector = applicationIdSelectorFactory.apply(options);

        Condition conditionForDataType = EntityKind.DATA_TYPE.equals(options.entityReference().kind())
                ? LOGICAL_FLOW_DECORATOR.DECORATOR_ENTITY_ID.in(dataTypeIdSelectorFactory.apply(options))
                : DSL.trueCondition();

        Field<Long> sourceFlowId = LOGICAL_FLOW.ID.as("sourceFlowId");
        Field<Long> targetFlowId = LOGICAL_FLOW.ID.as("targetFlowId");

        Select<Record1<Long>> sourceAppFlows = DSL.select(sourceFlowId)
                .from(LOGICAL_FLOW)
                .innerJoin(APPLICATION)
                    .on(LOGICAL_FLOW.SOURCE_ENTITY_ID.eq(APPLICATION.ID))
                .where(LOGICAL_FLOW.SOURCE_ENTITY_KIND.eq(EntityKind.APPLICATION.name()))
                .and(APPLICATION.ID.in(appIdSelector));

        Select<Record1<Long>> targetAppFlows = DSL.select(targetFlowId)
                .from(LOGICAL_FLOW)
                .innerJoin(APPLICATION)
                    .on(LOGICAL_FLOW.TARGET_ENTITY_ID.eq(APPLICATION.ID))
                .where(LOGICAL_FLOW.TARGET_ENTITY_KIND.eq(EntityKind.APPLICATION.name()))
                .and(APPLICATION.ID.in(appIdSelector));

        Field<String> sourceAssetCodeField = DSL
                .when(LOGICAL_FLOW.SOURCE_ENTITY_KIND.eq(EntityKind.APPLICATION.name()),
                        DSL.select(APPLICATION.ASSET_CODE)
                                .from(APPLICATION)
                                .where(APPLICATION.ID.eq(LOGICAL_FLOW.SOURCE_ENTITY_ID)));

        Field<String> sourceOrgUnitNameField = DSL
                .when(LOGICAL_FLOW.SOURCE_ENTITY_KIND.eq(EntityKind.APPLICATION.name()),
                        DSL.select(ORGANISATIONAL_UNIT.NAME)
                                .from(APPLICATION)
                                .innerJoin(ORGANISATIONAL_UNIT)
                                    .on(ORGANISATIONAL_UNIT.ID.eq(APPLICATION.ORGANISATIONAL_UNIT_ID))
                                .where(APPLICATION.ID.eq(LOGICAL_FLOW.SOURCE_ENTITY_ID)));

        Field<String> targetAssetCodeField = DSL
                .when(LOGICAL_FLOW.TARGET_ENTITY_KIND.eq(EntityKind.APPLICATION.name()),
                        DSL.select(APPLICATION.ASSET_CODE)
                                .from(APPLICATION)
                                .where(APPLICATION.ID.eq(LOGICAL_FLOW.TARGET_ENTITY_ID)));

        Field<String> targetOrgUnitNameField = DSL
                .when(LOGICAL_FLOW.TARGET_ENTITY_KIND.eq(EntityKind.APPLICATION.name()),
                        DSL.select(ORGANISATIONAL_UNIT.NAME)
                                .from(APPLICATION)
                                .innerJoin(ORGANISATIONAL_UNIT)
                                    .on(ORGANISATIONAL_UNIT.ID.eq(APPLICATION.ORGANISATIONAL_UNIT_ID))
                                .where(APPLICATION.ID.eq(LOGICAL_FLOW.TARGET_ENTITY_ID)));

        return dsl
                .select(SOURCE_NAME_FIELD.as("Source"),
                        sourceAssetCodeField.as("Source Asset Code"),
                        sourceOrgUnitNameField.as("Source Org Unit"))
                .select(TARGET_NAME_FIELD.as("Target"),
                        targetAssetCodeField.as("Target Asset Code"),
                        targetOrgUnitNameField.as("Target Org Unit"))
                .select(DATA_TYPE.NAME.as("Data Type"))
                .select(ENUM_VALUE.DISPLAY_NAME.as("Authoritativeness"))
                .from(LOGICAL_FLOW)
                .leftJoin(sourceAppFlows)
                    .on(sourceFlowId.eq(LOGICAL_FLOW.ID))
                .leftJoin(targetAppFlows)
                    .on(targetFlowId.eq(LOGICAL_FLOW.ID))
                .join(LOGICAL_FLOW_DECORATOR)
                    .on(LOGICAL_FLOW_DECORATOR.LOGICAL_FLOW_ID.eq(LOGICAL_FLOW.ID)
                        .and(LOGICAL_FLOW_DECORATOR.DECORATOR_ENTITY_KIND.eq(EntityKind.DATA_TYPE.name())))
                .join(DATA_TYPE)
                    .on(DATA_TYPE.ID.eq(LOGICAL_FLOW_DECORATOR.DECORATOR_ENTITY_ID)
                        .and(LOGICAL_FLOW_DECORATOR.DECORATOR_ENTITY_KIND.eq(EntityKind.DATA_TYPE.name())))
                .join(ENUM_VALUE)
                    .on(ENUM_VALUE.KEY.eq(LOGICAL_FLOW_DECORATOR.RATING)
                            .and(ENUM_VALUE.TYPE.eq("AuthoritativenessRating")))
                .where(LOGICAL_FLOW.ENTITY_LIFECYCLE_STATUS.ne(REMOVED.name()))
                .and(conditionForDataType)
                .and(sourceFlowId.isNotNull()
                        .or(targetFlowId.isNotNull()));

    }

}


text:
.ngh-search-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 250px;
    margin: 50px auto;
}

.ngh-search-result {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}

.ngh-card img {
    max-width: 200px;
}


text:
Ext.define("presentation-feature-list", {
    extend: 'Rally.app.App',
    componentCls: 'app',
    logger: new Rally.technicalservices.Logger(),
    defaults: { margin: 10 },
    items: [
        {xtype:'container',itemId:'settings_box'},
        {xtype:'tsinfolink'}
    ],

    config: {
        defaultSettings: {
            stateMappings: {},
            linkField: 'c_PublishToRoadmapURL',
            publishedField: 'c_PublishToRoadmap',

        }
    },
    modelType: 'PortfolioItem/Features', //cc ,
    linkFieldURL: null,
    modelStates: undefined,
    model: null,
    externalAppSettingsKey: 'technicalServicesRoadmapAppSettings',

    launch: function(){
        Rally.data.ModelFactory.getModel({
            type: this.modelType,
            scope: this,
            success: function(model) {
                this.model = model;
                model.getField('State').getAllowedValueStore().load({
                    scope: this,
                    callback: function(records, operation, success) {
                        if (success){
                            var modelStates = [];
                            Ext.Array.each(records, function(allowedValue) {
                                if (allowedValue.get('StringValue') && allowedValue.get('StringValue').length > 0){
                                    modelStates.push(allowedValue.get('StringValue'));
                                }
                            });
                            this.modelStates = modelStates;
                            if (this.isExternal()){
                               // this.showSettings(this.config)
                                this.getExternalAppSettings(this.externalAppSettingsKey);
                            } else {
                                this.onSettingsUpdate(this.getSettings());
                            }
                        } else {
                            Rally.ui.notify.Notifier.showError({message: Ext.String.format('Unable to load State field values for {0}: [{1}]',this.modelType, operations.error.errors.join(', '))});
                        }
                    }
                });
            },
            failure: function(){
                Rally.ui.notify.Notifier.showError({message: Ext.String.format('Unable to load model type [{0}]',this.modelType)});
            }
        });
    },
    _prepareApp: function(){
        var model = this.model;
        if (model && model.getField(this.linkField) && model.getField(this.linkField).attributeDefinition){
            this.linkFieldURL = model.getField(this.linkField).attributeDefinition.URL;
        }
        this._addProjectPicker();
    },
    _addProjectPicker: function(){

        if (_.isEmpty(this.stateMappings)){
            this.add({
                xtype: 'container',
                itemId: 'ct-no-settings',
                flex: 1,
                style: {
                    textAlign: 'center'
                },
                html: '<b>No states are configured to be displayed.  Please use the App Settings to display at least one State</b>'
            });
            return;
        }
        if (this.down('#ct-no-settings')){
            this.down('#ct-no-settings').destroy();
        }
        this.add({
            xtype: 'rallycombobox',
            storeConfig: {
                autoLoad: true,
                model: 'Project',
                fetch: ['_ref','Name'],
                filters: [{
                    property: 'Parent',
                    value: this.getContext().getProject()._ref
                }],
                remoteSort: false,
                remoteFilter: true
            },
            listeners: {
                scope: this,
                ready: function(cb){
                    this._buildPrettyGrid({project: cb.getValue(), projectScopeDown: true},
                        this.stateMappings);
                },
                change: function(cb){
                    this._buildPrettyGrid({project: cb.getValue(), projectScopeDown: true},
                        this.stateMappings);
                }
            },
            valueField: '_ref',
            displayField: 'Name',
            fieldLabel: 'Select Project'
        });
    },
    _buildPrettyGrid: function(projectContext, stateMappings){

        var state_panels = [];

        _.each(stateMappings, function(obj, state){
            state_panels.push({
                xtype: 'tsfeaturegrid',
                state: state,
                label: obj.label,
                context: projectContext,
                description: obj.description,
                modelName: this.modelType,
                linkField: this.linkField,
                linkFieldURL: this.linkFieldURL,
                publishedField: this.publishedField
            });
        }, this);

        if (this.down('#pretty-pnl')){
            this.down('#pretty-pnl').destroy();
        }

        var pnl = Ext.create('Ext.panel.Panel', {
            itemId: 'pretty-pnl',
            flex: 1,
            border: 0,
            header: this._getHeaderPanel(stateMappings),

            defaults: {
                // applied to each contained panel
                bodyStyle: 'padding:15px'
            },
            layout: {
                // layout-specific configs go here
                type: 'vbox',
                titleCollapse: false,
                animate: true,
               // activeOnTop: true
            },
            scope: this,
            items: state_panels
        });
        this.add(pnl);
    },
    _getHeaderPanel: function(stateMappings){

        var buttons = [];
        _.each(stateMappings, function(obj, key){
            buttons.push({
                xtype: 'button',
                itemId: 'btn-' + key,
                text: obj.label,
                textAlign: 'left',
                cls: 'feature-summary-header',
                flex: 1,
                height: 20,
                listeners: {
                    scope: this,
                    click: this._onButtonClick
                }
            });
        }, this);

        return {
            collapsible: false,
            collapsed: false,
            width: '100%',
            flex: 1,
            padding: 15,
            margin: '5 5 5 5',
            items: buttons,
            cls: 'feature-summary-header'
        };
    },
    _onButtonClick: function(btn){
        this.logger.log('_onButtonClick', btn.itemId);

        var buttons = this.query('button');

        _.each(buttons, function(b){
            var pid = b.itemId.replace('btn-','#pnl-');
            if (this.down(pid) && b.itemId == btn.itemId){
                this.down(pid).expand();
            } else {
                this.down(pid).collapse();
            }
        }, this);
    },
    /********************************************
     /* Overrides for App class
     /*
     /********************************************/
    //getSettingsFields:  Override for App
    getSettingsFields: function() {
        var me = this;

        return [
            {
                name: 'publishedField',
                xtype: 'tsbooleanfieldcombobox',
                fieldLabel: 'Published Field',
                model: this.modelType,
                labelWidth: 200,
                labelAlign: 'right',
                minValue: 0
            },{
                name: 'linkField',
                xtype: 'tsweblinkfieldcombobox',
                model: this.modelType,
                fieldLabel: 'Publish To Roadmap Link Field',
                labelWidth: 200,
                labelAlign: 'right',
                minValue: 0
            },{
                name: 'encodedStateMapping',
                xtype: 'tsmappersettings',
                states: this.modelStates,
                fieldLabel: 'State Mappings',
                margin: 15,
                labelAlign: 'top'
            }
        ];
    },
    isExternal: function(){
        return typeof(this.getAppId()) == 'undefined';
    },
    showSettings: function(options) {
        this._appSettings = Ext.create('Rally.app.AppSettings', Ext.apply({
            fields: this.getSettingsFields(),
            settings: this.getSettings(),
            defaultSettings: this.getDefaultSettings(),
            context: this.getContext(),
            settingsScope: this.settingsScope,
            autoScroll: true
        }, options));

        this._appSettings.on('cancel', this._hideSettings, this);
        this._appSettings.on('save', this._onSettingsSaved, this);
        if (this.isExternal()){
            if (this.down('#settings_box').getComponent(this._appSettings.id)==undefined){
                this.down('#settings_box').add(this._appSettings);
            }
        } else {
            this.hide();
            this.up().add(this._appSettings);
        }
        return this._appSettings;
    },
    _onSettingsSaved: function(settings){
        Ext.apply(this.settings, settings);
        this._hideSettings();
        this.onSettingsUpdate(settings);
    },
    onSettingsUpdate: function (settings){
        this.logger.log('onSettingsUpdate',settings);
        Ext.apply(this, settings);
        this.saveExternalAppSettings(this.externalAppSettingsKey, settings);
        if (!_.isEmpty(settings.encodedStateMapping)){
            this.stateMappings = Ext.JSON.decode(settings.encodedStateMapping);
        } else {
            this.stateMappings = {};
        }
        this._prepareApp();
    },
    saveExternalAppSettings: function(key, settings){

        var prefs = {};
        _.each(settings, function(val, setting_key){
            var pref_key = key + '.' + setting_key;
            prefs[pref_key] = val;
        });

        this.logger.log('SaveExternalAppSettings', key, settings, prefs);
        Rally.data.PreferenceManager.update({
            project: this.getContext().getProject()._ref,
            settings: prefs,
            scope: this,
            success: function(updatedRecords, notUpdatedRecords) {
               this.logger.log('settings saved', key, updatedRecords, notUpdatedRecords);
            }
        });
    },
    getExternalAppSettings: function(key){
        Rally.data.PreferenceManager.load({
            project: this.getContext().getProject()._ref,
            additionalFilters: [{
                property: 'name',
                operator: 'contains',
                value: key
            }],
            scope: this,
            cache: false,
            success: function(prefs) {
                this.logger.log('settings loaded', key, prefs);
                _.each(prefs, function(val, pref_name){
                    if (/\.linkField$/.test(pref_name)){
                        this.linkField = val;
                    }
                    if (/\.publishedField$/.test(pref_name)){
                        this.publishedField = val;
                    }
                    if (/\.encodedStateMapping$/.test(pref_name)){
                        if (val && !_.isEmpty(val)){
                            this.stateMappings = Ext.JSON.decode(val);
                        }
                    }
                }, this);

                this._prepareApp();
            }
        });

    }
});


text:
The Apache Hadoop software library is a framework that allows for the
distributed processing of large data sets across clusters of computers
using a simple programming model.

This charm deploys a compute / slave node running the NodeManager
and DataNode components of
[Apache Hadoop 2.7.1](http://hadoop.apache.org/docs/r2.7.1/),
which provides computation and storage resources to the platform.

## Usage

This charm is intended to be deployed via one of the
[apache bundles](https://jujucharms.com/u/bigdata-charmers/#bundles).
For example:

    juju quickstart apache-analytics-sql

This will deploy the Apache Hadoop platform with Apache Hive available to
perform SQL-like queries against your data.

You can also manually load and run map-reduce jobs via the plugin charm
included in the bigdata bundles linked above:

    juju scp my-job.jar plugin/0:
    juju ssh plugin/0
    hadoop jar my-job.jar

### Scaling

The compute-slave node is the "workhorse" of the Apache Hadoop platform.
To scale your deployment's performance, you can simply add more compute-slave
units.  For example, to add three mode units:

    juju add-unit compute-slave -n 3

## Monitoring

This charm supports monitoring via Ganglia.  To enable monitoring, you must
do **both** of the following (the order does not matter):

 * Add a relation to the [Ganglia charm][] via the `:master` relation
 * Enable the `ganglia_metrics` config option

You must **also** enable metrics on [yarn-master][] and / or [hdfs-master][]
to initiate the restart of the NodeManager and / or DataNode components for
them to begin collecting metrics.

For example:

    juju add-relation compute-slave ganglia:master
    juju add-relation yarn-master ganglia:master
    juju set compute-slave ganglia_metrics=true
    juju set yarn-master ganglia_metrics=true

## Deploying in Network-Restricted Environments

The Apache Hadoop charms can be deployed in environments with limited network
access. To deploy in this environment, you will need a local mirror to serve
the packages and resources required by these charms.

### Mirroring Packages

You can setup a local mirror for apt packages using squid-deb-proxy.
For instructions on configuring juju to use this, see the
[Juju Proxy Documentation](https://juju.ubuntu.com/docs/howto-proxies.html).

### Mirroring Resources

In addition to apt packages, the Apache Hadoop charms require a few binary
resources, which are normally hosted on Launchpad. If access to Launchpad
is not available, the `jujuresources` library makes it easy to create a mirror
of these resources:

    sudo pip install jujuresources
    juju-resources fetch --all /path/to/resources.yaml -d /tmp/resources
    juju-resources serve -d /tmp/resources

This will fetch all of the resources needed by this charm and serve them via a
simple HTTP server. The output from `juju-resources serve` will give you a
URL that you can set as the `resources_mirror` config option for this charm.
Setting this option will cause all resources required by this charm to be
downloaded from the configured URL.

You can fetch the resources for all of the Apache Hadoop charms
(`apache-hadoop-hdfs-master`, `apache-hadoop-yarn-master`,
`apache-hadoop-hdfs-secondary`, `apache-hadoop-plugin`, etc) into a single
directory and serve them all with a single `juju-resources serve` instance.

## Contact Information

- <bigdata@lists.ubuntu.com>

## Hadoop

- [Apache Hadoop](http://hadoop.apache.org/) home page
- [Apache Hadoop bug trackers](http://hadoop.apache.org/issue_tracking.html)
- [Apache Hadoop mailing lists](http://hadoop.apache.org/mailing_lists.html)
- [Apache Hadoop Juju Charm](http://jujucharms.com/?text=hadoop)

[Ganglia charm]: http://jujucharms.com/ganglia/
[yarn-master]: http://jujucharms.com/apache-hadoop-yarn-master/
[hdfs-master]: http://jujucharms.com/apache-hadoop-hdfs-master/


text:
{% if site.tags != "" %}
{% include collecttags.html %}
{% endif %}