text:
"use strict";

var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

/**
 * Determines if the provided object is a navigation command.
 * A navigation command is anything with a navigate method.
 * @param {object} obj The item to check.
 * @return {boolean}
 */
exports.isNavigationCommand = isNavigationCommand;

function isNavigationCommand(obj) {
  return obj && typeof obj.navigate === "function";
}

/**
* Used during the activation lifecycle to cause a redirect.
*
* @class Redirect
* @constructor
* @param {String} url The url to redirect to.
*/

var Redirect = exports.Redirect = (function () {
  function Redirect(url) {
    _classCallCheck(this, Redirect);

    this.url = url;
    this.shouldContinueProcessing = false;
  }

  _prototypeProperties(Redirect, null, {
    navigate: {

      /**
      * Called by the navigation pipeline to navigate.
      *
      * @method navigate
      * @param {Router} appRouter - a router which should redirect
      */

      value: function navigate(appRouter) {
        (this.router || appRouter).navigate(this.url, { trigger: true, replace: true });
      },
      writable: true,
      configurable: true
    }
  });

  return Redirect;
})();

Object.defineProperty(exports, "__esModule", {
  value: true
});


text:
Motion Planning Pipeline Tutorial
==================================

In MoveIt!, the motion planners are setup to plan paths. However, there are often
times when we may want to pre-process the motion planning request or post-process
the planned path (e.g. for time parameterization). In such cases, we use
the planning pipeline which chains a motion planner with pre-processing and post-processing
stages. The pre and post-processing stages, called planning request adapters, can
be configured by name from the ROS parameter server. In this tutorial, we will
run you through the C++ code to instantiate and call such a planning pipeline.

.. tutorial-formatter:: ../planning_pipeline_tutorial.cpp

The entire code
^^^^^^^^^^^^^^^
The entire code can be seen :codedir:`here in the moveit_pr2 github project<planning>`.

Compiling the code
^^^^^^^^^^^^^^^^^^
Follow the `instructions for compiling code from source <http://moveit.ros.org/install/>`_.

The launch file
^^^^^^^^^^^^^^^
The entire launch file is `here <https://github.com/ros-planning/moveit_tutorials/tree/kinetic-devel/doc/pr2_tutorials/planning/launch/planning_pipeline_tutorial.launch>`_ on github. All the code in this tutorial can be compiled and run from the moveit_tutorials package that you have as part of your MoveIt! setup.

Running the code
^^^^^^^^^^^^^^^^

Roslaunch the launch file to run the code directly from moveit_tutorials::

 roslaunch moveit_tutorials motion_planning_api_tutorial.launch

Expected Output
^^^^^^^^^^^^^^^

In Rviz, we should be able to see three trajectories being replayed eventually:

 1. The robot moves its right arm to the pose goal in front of it,
 2. The robot moves its right arm to the joint goal to the side,
 3. The robot moves its right arm back to the original pose goal in front of it,

redpajama_set_name: RedPajamaGithub


text:
window::mouse::mouse()
{
    memset(_buttons, 0, sizeof(_buttons));
}

void window::mouse::begin_frame()
{
    for(int i=0;i<static_cast<int>(button::last);++i)
    {
        _buttons[i].went_up = false;
        _buttons[i].went_down = false;
    }

    _cur_delta.zero();
    _scroll_delta.zero();
}

void window::mouse::on_event(button b, bool pressed)
{
    if(b == button::unknown) return; //safety check

    button_state& state = _buttons[static_cast<int>(b)];

    if(pressed && !state.pressed)
        state.went_down = true;
    else if(!pressed && state.pressed)
        state.went_up = true;
    state.pressed = pressed;
}

void window::mouse::on_event(double xpos, double ypos)
{
    position pos(xpos, ypos);

    _cur_delta = _cur_pos - pos;
    _cur_pos = pos;
}

void window::mouse::on_event(float xdelta, float ydelta)
{
    delta dt(xdelta, ydelta);

    _scroll_delta = dt;
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>libri on lou1306</title>
    <link>https://lou1306.github.io/tags/libri/</link>
    <description>Recent content in libri on lou1306</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>it</language>
    <lastBuildDate>Fri, 04 Mar 2016 11:40:29 +0100</lastBuildDate>

    <atom:link href="https://lou1306.github.io/tags/libri/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Libri!</title>
      <link>https://lou1306.github.io/libri/</link>
      <pubDate>Fri, 04 Mar 2016 11:40:29 +0100</pubDate>

      <guid>https://lou1306.github.io/libri/</guid>
      <description>Qui tengo traccia dei libri che leggo :)</description>
    </item>

  </channel>
</rss>


text:
package xworker.lang.text;

public interface JsonDataFormater {
	public String format(Object data, String ident);

	public Object parse(String json);
}


text:
//
// csvfilter, Copyright (c) 2015, plnu
//

#include "binaryOperator.h"

#include <sstream>
#include <string.h>
#include <assert.h>

/**
 *
 * @brief Constructor.
 *
 * Create a new NumericBinaryOperator node for the parse tree.
 *
 * @param op   The token for the operator. Must be a '-', '*' or '/'
 * @param lhs  The expression that was on the left hand of the operator
 * @param rhs  The expression that was on the right hand of the operator
 *
 */
NumericBinaryOperator::NumericBinaryOperator(ConstLexTokenRef op,
                                             ParseTreeRef lhs,
                                             ParseTreeRef rhs)
    :op_(op), lhs_(lhs), rhs_(rhs), result_(Variant::error("Undefined")) {
    assert(op_->type() == LexToken::TYPE_MINUS ||
           op_->type() == LexToken::TYPE_TIMES ||
           op_->type() == LexToken::TYPE_DIVIDE);
}

/**
 * @brief Destructor.
 *
 *
 */
NumericBinaryOperator::~NumericBinaryOperator() {

}

ParseTree::NodeType NumericBinaryOperator::validateTypes(ParseError& err) {
    NodeType ret = validateOperandType(lhs_, err);
    if (ret != NODE_TYPE_ERROR) {
        ret = validateOperandType(rhs_, err);
    }
    return ret;
}

bool NumericBinaryOperator::setType(NodeType t, ParseError& err) {
    bool success = true;
    if (t != NODE_TYPE_NUMBER) {
        success = false;
        std::stringstream msg;
        msg << "Cannot coerce expression into a " << t;
        err = ParseError(msg.str(),
                         Range(lhs_->position().begin,
                               rhs_->position().end));
    }
    return success;
}

VariantRef NumericBinaryOperator::eval(const LineParser& line,
                                       NodeType typeHint) const {
    VariantRef l = lhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef r = rhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef ret = result_;

    if (l->type() == Variant::ERROR) {
        ret = l;
    } else if (r->type() == Variant::ERROR) {
        ret = r;
    } else if (l->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Left hand side of operator at " << op_->position().begin
            << ": expected number, got " << l->type();
        result_->resetToError(msg.str());
    } else if (r->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Right hand side of operator at " << op_->position().begin
            << ": expected number, got " << r->type();
        result_->resetToError(msg.str());
    } else {
        switch (op_->type()) {
        case LexToken::TYPE_MINUS:
            result_->resetToNumber(l->numberVal() - r->numberVal());
            break;
        case LexToken::TYPE_TIMES:
            result_->resetToNumber(l->numberVal() * r->numberVal());
            break;
        case LexToken::TYPE_DIVIDE:
            result_->resetToNumber(l->numberVal() / r->numberVal());
            break;
        default:
            // should never happen - this function only handles numeric
            // operators
            abort();
            break;
        }
    }
    return ret;
}

void NumericBinaryOperator::stream(std::ostream& out) {
    out << "(" << op_->value() << " ";
    lhs_->stream(out);
    out << " ";
    rhs_->stream(out);
    out << "):" << NODE_TYPE_NUMBER;
}

bool NumericBinaryOperator::canBeNumber(const LineParser& line) const {
    return true;
}

Range NumericBinaryOperator::position() const {
    return Range(lhs_->position().begin, rhs_->position().end);
}

ParseTree::NodeType NumericBinaryOperator::validateOperandType(
    ParseTreeRef op,
    ParseError& err) {

    NodeType t = op->validateTypes(err);
    if (t == NODE_TYPE_UNKNOWN) {
        if (!op->setType(NODE_TYPE_NUMBER, err)) {
            t = NODE_TYPE_ERROR;
        }
    } else if (t != NODE_TYPE_NUMBER &&
               t != NODE_TYPE_ERROR) {
        op->setType(NODE_TYPE_NUMBER, err); // this will set the errText
        t = NODE_TYPE_ERROR;
    }
    return t;
}

/**
 *
 * @brief Constructor.
 *
 * Create a new LogicalBinaryOperator node for the parse tree.
 *
 * @param op   The token for the operator. Must be a '&&' or '||'
 * @param lhs  The expression that was on the left hand of the operator
 * @param rhs  The expression that was on the right hand of the operator
 *
 */
LogicalBinaryOperator::LogicalBinaryOperator(ConstLexTokenRef op,
                                             ParseTreeRef lhs,
                                             ParseTreeRef rhs)
    :op_(op), lhs_(lhs), rhs_(rhs) {
    assert(op_->type() == LexToken::TYPE_AND ||
           op_->type() == LexToken::TYPE_OR);
}

LogicalBinaryOperator::~LogicalBinaryOperator() {

}

ParseTree::NodeType LogicalBinaryOperator::validateTypes(ParseError& err) {
    NodeType ret = validateOperandType(lhs_, err);
    if (ret != NODE_TYPE_ERROR) {
        ret = validateOperandType(rhs_, err);
    }
    return ret;
}

bool LogicalBinaryOperator::setType(NodeType t, ParseError& err) {
    bool success = true;
    if (t != NODE_TYPE_BOOL) {
        success = false;
        std::stringstream msg;
        msg << "Cannot coerce expression into a " << t;
        err = ParseError(msg.str(), position());
    }
    return success;
}

VariantRef LogicalBinaryOperator::eval(const LineParser& line,
                                       NodeType typeHint) const {
    VariantRef ret;
    if (op_->type() == LexToken::TYPE_AND) {
        VariantRef l = lhs_->eval(line, NODE_TYPE_BOOL);
        if (l->type() == Variant::ERROR) {
            ret = l;
        } else if (l->type() != Variant::BOOLEAN) {
            std::stringstream msg;
            msg << "Left hand side of operator at " << op_->position().begin
                << ": expected boolean, got " << l->type();
            ret = Variant::error(msg.str());
        } else if (l->booleanVal() == false) {
            ret = l;
        } else {
            VariantRef r = rhs_->eval(line, NODE_TYPE_BOOL);
            if (r->type() == Variant::ERROR) {
                ret = r;
            } else if (r->type() != Variant::BOOLEAN) {
                std::stringstream msg;
                msg << "Right hand side of operator at "
                    << op_->position().begin
                    << ": expected boolean, got " << r->type();
                ret = Variant::error(msg.str());
            } else {
                ret = r;
            }
        }
    } else if (op_->type() == LexToken::TYPE_OR) {
        VariantRef l = lhs_->eval(line, NODE_TYPE_BOOL);
        if (l->type() == Variant::ERROR) {
            ret = l;
        } else if (l->type() != Variant::BOOLEAN) {
            std::stringstream msg;
            msg << "Left hand side of operator at " << op_->position().begin
                << ": expected boolean, got " << l->type();
            ret = Variant::error(msg.str());
        } else if (l->booleanVal() == true) {
            ret = l;
        } else {
            VariantRef r = rhs_->eval(line, NODE_TYPE_BOOL);
            if (r->type() == Variant::ERROR) {
                ret = r;
            } else if (r->type() != Variant::BOOLEAN) {
                std::stringstream msg;
                msg << "Right hand side of operator at "
                    << op_->position().begin
                    << ": expected boolean, got " << r->type();
                ret = Variant::error(msg.str());
            } else {
                ret = r;
            }
        }
    }

    return ret;
}

void LogicalBinaryOperator::stream(std::ostream& out) {
    out << "(" << op_->value() << " ";
    lhs_->stream(out);
    out << " ";
    rhs_->stream(out);
    out << "):" << NODE_TYPE_BOOL;
}

bool LogicalBinaryOperator::canBeNumber(const LineParser& line) const {
    return false;
}

Range LogicalBinaryOperator::position() const {
    return Range(lhs_->position().begin, rhs_->position().end);
}

ParseTree::NodeType LogicalBinaryOperator::validateOperandType(
    ParseTreeRef op,
    ParseError& err) {

    NodeType t = op->validateTypes(err);
    if (t != NODE_TYPE_BOOL && t != NODE_TYPE_ERROR) {
        std::stringstream msg;
        msg << "The arguments to '" << op_->value() << "' must be boolean, not "
            << t;
        err = ParseError(msg.str(), op_->position(), op->position());
        t = NODE_TYPE_ERROR;
    }
    return t;
}

/**
 *
 * @brief Constructor.
 *
 * Create a new ComparisonBinaryOperator node for the parse tree.
 *
 * @param op   The token for the operator. Must be a '<', '<=', '==', '!=',
 *             '>=' or '>'
 * @param lhs  The expression that was on the left hand of the operator
 * @param rhs  The expression that was on the right hand of the operator
 *
 */
ComparisonBinaryOperator::ComparisonBinaryOperator(ConstLexTokenRef op,
                                                   ParseTreeRef lhs,
                                                   ParseTreeRef rhs)
    :op_(op), lhs_(lhs), rhs_(rhs), result_(Variant::error("uninitialised")) {
    assert(op_->type() == LexToken::TYPE_LT  ||
           op_->type() == LexToken::TYPE_LTE ||
           op_->type() == LexToken::TYPE_EQ  ||
           op_->type() == LexToken::TYPE_NEQ ||
           op_->type() == LexToken::TYPE_GT  ||
           op_->type() == LexToken::TYPE_GTE);

}

ComparisonBinaryOperator::~ComparisonBinaryOperator() {

}

ParseTree::NodeType ComparisonBinaryOperator::validateTypes(
    ParseError& err) {
    NodeType l;
    NodeType r;
    NodeType ret = NODE_TYPE_BOOL;
    if ( (l = lhs_->validateTypes(err)) == NODE_TYPE_ERROR ||
         (r = rhs_->validateTypes(err))  == NODE_TYPE_ERROR ) {
        ret = NODE_TYPE_ERROR;
    } else if (l != NODE_TYPE_UNKNOWN &&
               l != NODE_TYPE_STRING &&
               l != NODE_TYPE_NUMBER) {
        std::stringstream msg;
        msg << "The arguments to '" << op_->value()
            << "' must be strings or numbers, not " << l;
        err = ParseError(msg.str(), op_->position(), lhs_->position());
        ret = NODE_TYPE_ERROR;
    } else if (r != NODE_TYPE_UNKNOWN &&
               r != NODE_TYPE_STRING &&
               r != NODE_TYPE_NUMBER) {
        std::stringstream msg;
        msg << "The arguments to '" << op_->value()
            << "' must be strings or numbers, not " << l;
        err = ParseError(msg.str(), op_->position(), rhs_->position());
        ret = NODE_TYPE_ERROR;
    } else if (l == NODE_TYPE_UNKNOWN && r == NODE_TYPE_UNKNOWN) {
        // This is ok, we just can't predict the types of the operators at parse
        // time
    } else if (l == NODE_TYPE_UNKNOWN) {
        if (!lhs_->setType(r, err)) {
            ret = NODE_TYPE_ERROR;
        }
    } else if (r == NODE_TYPE_UNKNOWN) {
        if (!rhs_->setType(l, err)) {
            ret = NODE_TYPE_ERROR;
        }
    } else if (l != r) {
        std::stringstream msg;
        msg << "'" << op_->value()
            << "' expects arguments of the same type (got a " << l
            << " and a " << r << ")";
        err = ParseError(msg.str(), op_->position(), position());
        ret = NODE_TYPE_ERROR;
    } else {
        // we're ok
    }

    return ret;
}

bool ComparisonBinaryOperator::setType(NodeType t, ParseError& err) {
    bool success = true;
    if (t != NODE_TYPE_BOOL) {
        success = false;
        std::stringstream msg;
        msg << "Cannot coerce expression into a " << t;
        err = ParseError(msg.str(), position());
    }
    return success;
}

VariantRef ComparisonBinaryOperator::eval(const LineParser& line,
                                          NodeType typeHint) const {
    VariantRef ret;
    if (lhs_->canBeNumber(line) && rhs_->canBeNumber(line)) {
        ret = evalComparisonNumber(line, typeHint);
    } else {
        ret = evalComparisonString(line, typeHint);
    }
    return ret;
}

void ComparisonBinaryOperator::stream(std::ostream& out) {
    out << "(" << op_->value() << " ";
    lhs_->stream(out);
    out << " ";
    rhs_->stream(out);
    out << "):" << NODE_TYPE_BOOL;
}

bool ComparisonBinaryOperator::canBeNumber(const LineParser& line) const {
    return false;
}

Range ComparisonBinaryOperator::position() const {
    return Range(lhs_->position().begin, rhs_->position().end);
}

/**
 * @brief Evaluate a comparison operator using strings
 *
 * Apply a comparison operator, assuming the operands are strings.
 *
 * @see BinaryOperator::evalComparison
 *
 * @param line      The current line from the csv file
 * @param typeHint  Ignored
 *
 * @return  The result of the operation, or an error.
 *
 */
VariantRef ComparisonBinaryOperator::evalComparisonString(
    const LineParser& line,
    NodeType typeHint) const {

    VariantRef l = lhs_->eval(line, NODE_TYPE_STRING);
    VariantRef r = rhs_->eval(line, NODE_TYPE_STRING);
    VariantRef ret = result_;

    if (l->type() == Variant::ERROR) {
        ret = l;
    } else if (r->type() == Variant::ERROR) {
        ret = r;
    } else if (l->type() != Variant::STRING) {
        std::stringstream msg;
        msg << "Left hand side of operator at " << op_->position().begin
            << ": expected string, got " << l->type();
        result_->resetToError(msg.str());
    } else if (r->type() != Variant::STRING) {
        std::stringstream msg;
        msg << "Right hand side of operator at " << op_->position().begin
            << ": expected string, got " << l->type();
        result_->resetToError(msg.str());
    } else {
        switch (op_->type()) {
        case LexToken::TYPE_LT:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) < 0);
            break;
        case LexToken::TYPE_LTE:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) <= 0);
            break;
        case LexToken::TYPE_EQ:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) == 0);
            break;
        case LexToken::TYPE_NEQ:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) != 0);
            break;
        case LexToken::TYPE_GT:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) > 0);
            break;
        case LexToken::TYPE_GTE:
            result_->resetToBoolean(strcmp(l->charVal(), r->charVal()) >= 0);
            break;
        default:
            // it's not a comparison operator
            abort();
            break;
        }
    }
    return ret;
}

/**
 * @brief Evaluate a comparison operator using numbers
 *
 * Apply a comparison operator, assuming the operands are numbers.
 *
 * @see BinaryOperator::evalComparison
 *
 * @param line      The current line from the csv file
 * @param typeHint  Ignored
 *
 * @return  The result of the operation, or an error.
 *
 */
VariantRef ComparisonBinaryOperator::evalComparisonNumber(
    const LineParser& line,
    NodeType typeHint) const {
    VariantRef l = lhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef r = rhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef ret = result_;
    if (l->type() == Variant::ERROR) {
        ret = l;
    } else if (r->type() == Variant::ERROR) {
        ret = r;
    } else if (l->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Left hand side of operator at " << op_->position().begin
            << ": expected number, got " << l->type();
        result_->resetToError(msg.str());
    } else if (r->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Right hand side of operator at " << op_->position().begin
            << ": expected number, got " << l->type();
        result_->resetToError(msg.str());
    } else {
        switch (op_->type()) {
        case LexToken::TYPE_LT:
            result_->resetToBoolean(l->numberVal() < r->numberVal());
            break;
        case LexToken::TYPE_LTE:
            result_->resetToBoolean(l->numberVal() <= r->numberVal());
            break;
        case LexToken::TYPE_EQ:
            result_->resetToBoolean(l->numberVal() == r->numberVal());
            break;
        case LexToken::TYPE_NEQ:
            result_->resetToBoolean(l->numberVal() != r->numberVal());
            break;
        case LexToken::TYPE_GT:
            result_->resetToBoolean(l->numberVal() > r->numberVal());
            break;
        case LexToken::TYPE_GTE:
            result_->resetToBoolean(l->numberVal() >= r->numberVal());
            break;
        default:
            // it's not a comparison operator
            abort();
            break;
        }
    }
    return ret;
}

/**
 *
 * @brief Constructor.
 *
 * Create a new PlusBinaryOperator node for the parse tree.
 *
 * @param op   The token for the operator. Must be a '+'
 * @param lhs  The expression that was on the left hand of the operator
 * @param rhs  The expression that was on the right hand of the operator
 *
 */
PlusBinaryOperator::PlusBinaryOperator(ConstLexTokenRef op,
                                       ParseTreeRef lhs,
                                       ParseTreeRef rhs)
    :op_(op),
     lhs_(lhs),
     rhs_(rhs),
     calculatedType_(NODE_TYPE_UNKNOWN),
     result_(Variant::error("Uninitialised")),
     addBuf_(nullptr),
     addBufLen_(0) {
    assert(op_->type() == LexToken::TYPE_PLUS);
}

PlusBinaryOperator::~PlusBinaryOperator() {
    delete[] addBuf_;
}

ParseTree::NodeType PlusBinaryOperator::validateTypes(
    ParseError& err) {
    NodeType l;
    NodeType r;

    NodeType ret = NODE_TYPE_UNKNOWN;
    if ( (l = lhs_->validateTypes(err)) == NODE_TYPE_ERROR ||
         (r = rhs_->validateTypes(err))  == NODE_TYPE_ERROR ) {
        ret = NODE_TYPE_ERROR;
    } else if (l != NODE_TYPE_UNKNOWN &&
               l != NODE_TYPE_STRING &&
               l != NODE_TYPE_NUMBER) {
        std::stringstream msg;
        msg << "Arguments to + should be strings or numbers, not " << l << ")";
        err = ParseError(msg.str(), op_->position(), lhs_->position());
        ret = NODE_TYPE_ERROR;
    } else if (r != NODE_TYPE_UNKNOWN &&
               r != NODE_TYPE_STRING &&
               r != NODE_TYPE_NUMBER) {
        std::stringstream msg;
        msg << "Arguments to + should be strings or numbers, not " << r << ")";
        err = ParseError(msg.str(), op_->position(), rhs_->position());
        ret = NODE_TYPE_ERROR;
    } else if (l == NODE_TYPE_UNKNOWN && r == NODE_TYPE_UNKNOWN) {
        // This is ok, we just can't predict the types of the operators at parse
        // time
    } else if (l == NODE_TYPE_UNKNOWN) {
        if (!lhs_->setType(r, err)) {
            ret = NODE_TYPE_ERROR;
        } else {
            ret = r;
        }
    } else if (r == NODE_TYPE_UNKNOWN) {
        if (!rhs_->setType(l, err)) {
            ret = NODE_TYPE_ERROR;
        } else {
            ret = l;
        }
    } else if (l != r) {
        std::stringstream msg;
        msg << "The + operator expects its arguments to be the same type, "
            << "got a " << l << " and a " << r;
        err = ParseError(msg.str(), op_->position(), position());
        ret = NODE_TYPE_ERROR;
    } else {
        ret = l;
    }

    if (ret != NODE_TYPE_ERROR) {
        calculatedType_ = ret;
    }

    return ret;
}

bool PlusBinaryOperator::setType(NodeType t, ParseError& err) {
    bool success = true;
    if (calculatedType_ == NODE_TYPE_UNKNOWN) {
        if (lhs_->setType(t, err) &&
            rhs_->setType(t, err)) {
            calculatedType_ = t;
        } else {
            success = false;
        }
    } else if (t != calculatedType_) {
        success = false;
        std::stringstream msg;
        msg << "Cannot coerce value into a " << t;
        err = ParseError(msg.str(), position());
    }
    return success;
}

VariantRef PlusBinaryOperator::eval(const LineParser& line,
                                          NodeType typeHint) const {
    VariantRef ret;
    if (calculatedType_ == NODE_TYPE_NUMBER) {
        ret = evalPlusNumber(line, typeHint);
    } else if (calculatedType_ == NODE_TYPE_STRING) {
        ret = evalPlusString(line, typeHint);
    } else if (calculatedType_ == NODE_TYPE_UNKNOWN) {
        if (typeHint == NODE_TYPE_NUMBER) {
            ret = evalPlusNumber(line, typeHint);
        } else if (calculatedType_ == NODE_TYPE_STRING) {
            ret = evalPlusString(line, typeHint);
        } else {
            if (lhs_->canBeNumber(line) && rhs_->canBeNumber(line)) {
                ret = evalPlusNumber(line, typeHint);
            } else {
                ret = evalPlusString(line, typeHint);
            }
        }
    }

    return ret;
}

void PlusBinaryOperator::stream(std::ostream& out) {
    out << "(" << op_->value() << " ";
    lhs_->stream(out);
    out << " ";
    rhs_->stream(out);
    out << "):" << calculatedType_;
}

bool PlusBinaryOperator::canBeNumber(const LineParser& line) const {
    return (calculatedType_ == NODE_TYPE_NUMBER) ||
        ( calculatedType_ == NODE_TYPE_UNKNOWN &&
          lhs_->canBeNumber(line) &&
          rhs_->canBeNumber(line) );
}

Range PlusBinaryOperator::position() const {
    return Range(lhs_->position().begin, rhs_->position().end);
}

/**
 * @brief Apply a plus for strings.
 *
 * Apply a plus operator as string concatenation.
 *
 * @see BinaryOperator::evalPlus
 *
 * @param line      The current line from the csv file
 * @param typeHint  A hint as to the expected return type
 *
 * @return  The result of the operation, or an error.
 *
 */
VariantRef PlusBinaryOperator::evalPlusString(const LineParser& line,
                                          NodeType typeHint) const {
    VariantRef l = lhs_->eval(line, NODE_TYPE_STRING);
    VariantRef r = rhs_->eval(line, NODE_TYPE_STRING);
    VariantRef ret = result_;

    if (l->type() == Variant::ERROR) {
        ret = l;
    } else if (r->type() == Variant::ERROR) {
        ret = r;
    } if (l->type() != Variant::STRING) {
        std::stringstream msg;
        msg << "Left hand side of operator at " << op_->position().begin
            << ": expected string, got " << l->type();
        result_->resetToError(msg.str());
    } else if (r->type() != Variant::STRING) {
        std::stringstream msg;
        msg << "Right hand side of operator at " << op_->position().begin
            << ": expected string, got " << r->type();
        result_->resetToError(msg.str());
    } else {
        int lLen = strlen(l->charVal());
        int rLen = strlen(r->charVal());
        int required = lLen + rLen + 1;
        if (addBufLen_ < required) {
            delete[] addBuf_;
            addBuf_ = new char[required];
        }
        strcpy(addBuf_, l->charVal());
        strcpy(addBuf_ + lLen, r->charVal());
        result_->resetToString(addBuf_);
    }

    return ret;
}

/**
 * @brief Apply a plus for numbers.
 *
 * Apply a plus operator as numeric addition.
 *
 * @see BinaryOperator::evalPlus
 *
 * @param line      The current line from the csv file
 * @param typeHint  A hint as to the expected return type
 *
 * @return  The result of the operation, or an error.
 *
 */
VariantRef PlusBinaryOperator::evalPlusNumber(const LineParser& line,
                                           NodeType typeHint) const {
    VariantRef l = lhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef r = rhs_->eval(line, NODE_TYPE_NUMBER);
    VariantRef ret = result_;

    if (l->type() == Variant::ERROR) {
        ret = l;
    } else if (r->type() == Variant::ERROR) {
        ret = r;
    } else if (l->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Left hand side of operator at " << op_->position().begin
            << ": expected number, got " << l->type();
        result_->resetToError(msg.str());
    } else if (r->type() != Variant::NUMBER) {
        std::stringstream msg;
        msg << "Right hand side of operator at " << op_->position().begin
            << ": expected number, got " << r->type();
        result_->resetToError(msg.str());
    } else {
        result_->resetToNumber(l->numberVal() + r->numberVal());
    }

    return ret;
}


text:
#ifndef DefaultAudioDestinationNode_h
#define DefaultAudioDestinationNode_h

#include "platform/audio/AudioDestination.h"
#include "modules/webaudio/AudioDestinationNode.h"
#include "wtf/OwnPtr.h"

namespace blink {

class AudioContext;
class ExceptionState;

class DefaultAudioDestinationNode FINAL : public AudioDestinationNode {
public:
    static DefaultAudioDestinationNode* create(AudioContext* context)
    {
        return adoptRefCountedGarbageCollectedWillBeNoop(new DefaultAudioDestinationNode(context));
    }

    virtual ~DefaultAudioDestinationNode();

    // AudioNode
    virtual void dispose() OVERRIDE;
    virtual void initialize() OVERRIDE;
    virtual void uninitialize() OVERRIDE;
    virtual void setChannelCount(unsigned long, ExceptionState&) OVERRIDE;

    // AudioDestinationNode
    virtual void startRendering() OVERRIDE;
    virtual unsigned long maxChannelCount() const OVERRIDE;

private:
    explicit DefaultAudioDestinationNode(AudioContext*);
    void createDestination();

    OwnPtr<AudioDestination> m_destination;
    String m_inputDeviceId;
    unsigned m_numberOfInputChannels;
};

} // namespace blink

#endif // DefaultAudioDestinationNode_h


text:
#ifndef GEO_EARTH_ENTERPRISE_SRC_FUSION_PORTABLEGLOBE_SHARED_BOUNDS_TRACKER_H_
#define GEO_EARTH_ENTERPRISE_SRC_FUSION_PORTABLEGLOBE_SHARED_BOUNDS_TRACKER_H_

#include <fstream>  // NOLINT(readability/streams)
#include <string>
#include <vector>
#include <map>
#include <cstdint>
#include "common/base/macros.h"
#include <cstdint>
#include "fusion/portableglobe/shared/packetbundle.h"

namespace fusion_portableglobe {

/**
   The boundary and zoom level information for a channel/layer.
*/
struct channel_info {
  // Channel ID and type
  std::uint16_t channel_id = UINT16_MAX;
  PacketType type;

  // Map tile bounding box
  std::uint32_t top = 0;
  std::uint32_t bottom = UINT32_MAX;
  std::uint32_t left = UINT32_MAX;
  std::uint32_t right = 0;

  // Zoom levels where this channel is available
  std::uint32_t min_level = UINT32_MAX;
  std::uint32_t max_level = 0;

  /**
     Default constructor that creates an empty bounds, where
     bottom > top, left > right, and min_level > max_level.
  */
  channel_info() : channel_id(UINT16_MAX),
                   top(0),
                   bottom(UINT32_MAX),
                   left(UINT32_MAX),
                   right(0),
                   min_level(UINT32_MAX),
                   max_level(0)
  {};

  /**
     Create a channel_info with the given channel_id and type, bounding the
     given row, column, and level.
     @param channel
     @param type
     @param row
     @param column
     @param level
  */
  channel_info(std::uint16_t channel_id,
               PacketType type,
               std::uint32_t row,
               std::uint32_t column,
               std::uint32_t level) :
    channel_id(channel_id),
    type(type),
    top(row), bottom(row),
    left(column), right(column),
    min_level(level), max_level(level)
  {}
};

/**
   A class for tracking the map tile boundaries and zoom levels of a portable file
   as it's being built. Once the globe is finished, the information is saved to
   earth/metadata.json and included in the final *.glb or *.glm file.

   Only the tile boundaries at max_level are stored by the tracker.
 */

class BoundsTracker {
public:

  /// Default constructor
  BoundsTracker();

  /**
     Update the channel_info for the specified channel to be of the given type and
     include qtpath in its bounds.
     @param channel ID of the channel to be updated.
     @param type    The packet type of the channel.
     @param qtpath  The quadtree address to update.
  */
  void update(std::uint16_t channel, PacketType type, const std::string& qtpath);

  /**
     Write current boundary information to the specified JSON file.
     @param filename
  */
  void write_json_file(const std::string& filename) const;

  /**
     Return a const reference to the specified channel_info object.
     Throws a khSimpleException if the channel isn't found.
     @param channel_id
  */
  const channel_info& channel(std::uint16_t channel_id) const;

private:

  // Minimum and maximum zoom level and channel for imagery, terrain, and vector data
  std::map<std::uint16_t, channel_info> channels;

  DISALLOW_COPY_AND_ASSIGN(BoundsTracker);
};

}  // namespace fusion_portableglobe

#endif  // GEO_EARTH_ENTERPRISE_SRC_FUSION_PORTABLEGLOBE_PORTABLEGLOBEBUILDER_H_


text:
function GeolocationPoint(lat, lon) {
    if (lat > 90 || lat < -90 || lon > 180 || lon < -180) {
	throw new RangeError('Latitude must be between -90 and 90 inclusive; Longitude must be between -180 and 180 inclusive.');
    }
    this.latitude = lat;
    this.longitude = lon;
}

module.exports = GeolocationPoint;


text:
<?php

namespace FlowerTest;

use Flower\Test\TestTool;
use FlowerTest\TestAsset\DispatcherTrait;
use Zend\ServiceManager\ServiceManager;
use Zend\View\Model\ViewModel;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2014-11-16 at 04:51:19.
 */
class DispatcherTraitTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DispatcherTrait
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new DispatcherTrait;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Flower\DispatcherTrait::setControllerName
     */
    public function testSetControllerName()
    {
        $this->object->setControllerName('foo');
        $this->assertEquals('foo', TestTool::getPropertyValue($this->object, 'controllerName'));
    }

    /**
     * @covers Flower\DispatcherTrait::setDispatchOptions
     */
    public function testSetDispatchOptions()
    {
        $options = array(
            'foo' => 'bar',
        );
        $this->object->setDispatchOptions($options);
        $this->assertEquals($options, TestTool::getPropertyValue($this->object, 'dispatchOptions'));
    }

    /**
     * シグネチャはいらないね。
     *
     * @covers Flower\DispatcherTrait::setSignature
     */
    public function testSetSignature()
    {
        $signature = array(
            'foo' => 'bar',
        );
        $this->object->setSignature($signature);
        $this->assertEquals($signature, TestTool::getPropertyValue($this->object, 'signature'));
    }

    /**
     * @covers Flower\DispatcherTrait::dispatch
     */
    public function testDispatch()
    {
        $controllerName = 'foo';
        $dispatchOptions = array('a' => 'b');
        $resultModel = new ViewModel;

        $plugin = $this->getMockBuilder('Zend\\Mvc\\Controller\\Plugin\\Forward')
                ->disableOriginalConstructor()->getMock();
        $plugin->expects($this->once())
                ->method('dispatch')
                ->with($this->equalTo($controllerName), $this->equalTo($dispatchOptions))
                ->will($this->returnValue($resultModel));

        $pluginManager = $this->getMock('Zend\\Mvc\\Controller\\PluginManager');
        $pluginManager->expects($this->once())
                ->method('get')
                ->with($this->equalTo('forward'))
                ->will($this->returnValue($plugin));
        $sl = new ServiceManager;
        $sl->setService('ControllerPluginManager', $pluginManager);

        $this->object->setServiceLocator($sl);
        $this->object->setControllerName($controllerName);
        $this->object->setDispatchOptions($dispatchOptions);
        $this->assertSame($resultModel, $this->object->dispatch());
    }
}


text:
import functools

from oslo_config import cfg
from oslo_utils import excutils
from oslo_utils import timeutils
import six

from sahara import conductor as c
from sahara.conductor import resource
from sahara import context
from sahara.utils import general as g

conductor = c.API
CONF = cfg.CONF

event_log_opts = [
    cfg.BoolOpt('disable_event_log',
                default=False,
                help="Disables event log feature.")
]

CONF.register_opts(event_log_opts)

def add_successful_event(instance):
    if CONF.disable_event_log:
        return

    cluster_id = instance.cluster_id
    step_id = get_current_provisioning_step(cluster_id)
    if step_id:
        conductor.cluster_event_add(context.ctx(), step_id, {
            'successful': True,
            'node_group_id': instance.node_group_id,
            'instance_id': instance.instance_id,
            'instance_name': instance.instance_name,
            'event_info': None,
        })

def add_fail_event(instance, exception):
    if CONF.disable_event_log:
        return

    cluster_id = instance.cluster_id
    step_id = get_current_provisioning_step(cluster_id)
    event_info = six.text_type(exception)

    if step_id:
        conductor.cluster_event_add(context.ctx(), step_id, {
            'successful': False,
            'node_group_id': instance.node_group_id,
            'instance_id': instance.instance_id,
            'instance_name': instance.instance_name,
            'event_info': event_info,
        })

def add_provisioning_step(cluster_id, step_name, total):
    if CONF.disable_event_log or not g.check_cluster_exists(cluster_id):
        return

    prev_step = get_current_provisioning_step(cluster_id)
    if prev_step:
        conductor.cluster_provision_step_update(context.ctx(), prev_step)

    step_type = context.ctx().current_instance_info.step_type
    new_step = conductor.cluster_provision_step_add(
        context.ctx(), cluster_id, {
            'step_name': step_name,
            'step_type': step_type,
            'completed': 0,
            'total': total,
            'started_at': timeutils.utcnow(),
        })
    context.current().current_instance_info.step_id = new_step
    return new_step

def get_current_provisioning_step(cluster_id):
    if CONF.disable_event_log or not g.check_cluster_exists(cluster_id):
        return None
    current_instance_info = context.ctx().current_instance_info
    return current_instance_info.step_id

def event_wrapper(mark_successful_on_exit, **spec):
    """"General event-log wrapper

    :param mark_successful_on_exit: should we send success event
    after execution of function

    :param spec: extra specification
    :parameter step: provisioning step name (only for provisioning
    steps with only one event)
    :parameter param: tuple (name, pos) with parameter specification,
    where 'name' is the name of the parameter of function, 'pos' is the
    position of the parameter of function. This parameter is used to
    extract info about Instance or Cluster.
    """

    def decorator(func):
        @functools.wraps(func)
        def handler(*args, **kwargs):
            if CONF.disable_event_log:
                return func(*args, **kwargs)
            step_name = spec.get('step', None)
            instance = _find_in_args(spec, *args, **kwargs)
            cluster_id = instance.cluster_id

            if not g.check_cluster_exists(cluster_id):
                return func(*args, **kwargs)

            if step_name:
                # It's single process, let's add provisioning step here
                add_provisioning_step(cluster_id, step_name, 1)

            try:
                value = func(*args, **kwargs)
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    add_fail_event(instance, e)

            if mark_successful_on_exit:
                add_successful_event(instance)

            return value
        return handler
    return decorator

def _get_info_from_instance(arg):
    if isinstance(arg, resource.InstanceResource):
        return arg
    return None

def _get_info_from_cluster(arg):
    if isinstance(arg, resource.ClusterResource):
        return context.InstanceInfo(arg.id)
    return None

def _get_event_info(arg):
    try:
        return arg.get_event_info()
    except AttributeError:
        return None

def _get_info_from_obj(arg):
    functions = [_get_info_from_instance, _get_info_from_cluster,
                 _get_event_info]

    for func in functions:
        value = func(arg)
        if value:
            return value
    return None

def _find_in_args(spec, *args, **kwargs):
    param_values = spec.get('param', None)

    if param_values:
        p_name, p_pos = param_values
        obj = kwargs.get(p_name, None)
        if obj:
            return _get_info_from_obj(obj)
        return _get_info_from_obj(args[p_pos])

    # If param is not specified, let's search instance in args

    for arg in args:
        val = _get_info_from_instance(arg)
        if val:
            return val

    for arg in kwargs.values():
        val = _get_info_from_instance(arg)
        if val:
            return val

    # If instance not found in args, let's get instance info from context

    return context.ctx().current_instance_info


text:
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using Grpc.AspNetCore.FunctionalTests.Infrastructure;
using Grpc.Net.Client;
using Grpc.Net.Client.Web;
using NUnit.Framework;

namespace Grpc.AspNetCore.FunctionalTests.Web;

public enum GrpcTestMode
{
    Grpc,
    GrpcWeb,
    GrpcWebText
}

public abstract class GrpcWebFunctionalTestBase : FunctionalTestBase
{
    public GrpcTestMode GrpcTestMode { get; }
    public TestServerEndpointName EndpointName { get; }

    protected GrpcWebFunctionalTestBase(GrpcTestMode grpcTestMode, TestServerEndpointName endpointName)
    {
        GrpcTestMode = grpcTestMode;
        EndpointName = endpointName;

#if NET6_0_OR_GREATER
        if (endpointName == TestServerEndpointName.Http3WithTls &&
            !RequireHttp3Attribute.IsSupported(out var message))
        {
            Assert.Ignore(message);
        }
#endif
    }

    protected HttpClient CreateGrpcWebClient()
    {
        var grpcWebHandler = CreateGrpcWebHandlerCore();

        return Fixture.CreateClient(EndpointName, grpcWebHandler);
    }

    protected (HttpMessageHandler handler, Uri address) CreateGrpcWebHandler()
    {
        var grpcWebHandler = CreateGrpcWebHandlerCore();

        return Fixture.CreateHandler(EndpointName, grpcWebHandler);
    }

    private GrpcWebHandler? CreateGrpcWebHandlerCore()
    {
        Version protocol;

        if (EndpointName == TestServerEndpointName.Http1)
        {
            protocol = new Version(1, 1);
        }
#if NET6_0_OR_GREATER
        else if (EndpointName == TestServerEndpointName.Http3WithTls)
        {
            protocol = new Version(3, 0);
        }
#endif
        else
        {
            protocol = new Version(2, 0);
        }

        GrpcWebHandler? grpcWebHandler = null;
        if (GrpcTestMode != GrpcTestMode.Grpc)
        {
            var mode = GrpcTestMode == GrpcTestMode.GrpcWeb ? GrpcWebMode.GrpcWeb : GrpcWebMode.GrpcWebText;
            grpcWebHandler = new GrpcWebHandler(mode)
            {
                HttpVersion = protocol
            };
        }

        return grpcWebHandler;
    }

    protected GrpcChannel CreateGrpcWebChannel()
    {
        var httpClient = CreateGrpcWebClient();
        var channel = GrpcChannel.ForAddress(httpClient.BaseAddress!, new GrpcChannelOptions
        {
            HttpClient = httpClient,
            LoggerFactory = LoggerFactory
        });

        return channel;
    }
}


text:
Rails.application.routes.draw do
  root 'home#index'

  get '/heartbeat', to: 'heart_beat#index'

  get '/auth/auth0/callback', to: 'sessions#auth0_success_callback'
  post '/auth/developer/callback', to: 'sessions#auth0_success_callback'

  get '/auth/failure', to: 'sessions#auth0_failure_callback'
  delete '/sessions', to: 'sessions#destroy'

  post 'events/:type', to: 'events#create', as: 'events'

  resource :feature_reviews, only: %i[new show create] do
    member do
      get 'unlink', to: 'feature_reviews#unlink_ticket'
    end
    post 'link_ticket'
  end

  resources :releases, only: %i[index show]

  resources :unapproved_deployments, only: [:show]

  resources :repositories, only: %i[index create edit update],
                           controller: 'git_repository_locations', as: 'git_repository_locations'

  resources :tokens, only: %i[index create update destroy]

  resources :github_notifications, only: [:create]

  match '/delayed_job' => DelayedJobWeb, anchor: false, via: %i[get post]
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">

test interesting

interesting test


text:
<idea-plugin>
  <actions>
    <action>
      <override-text place="<caret>"/>
    </action>
  </actions>
</idea-plugin>


text:
<!DOCTYPE html>

    <title ng-bind="pageTitle"></title>

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@joshdmiller">
    <meta name="twitter:title" content="ngBoilerplate">
    <meta name="twitter:description" content="Non-Trivial AngularJS Made Easy: Everything you need to kickstart AngularJS projects: a best-practice directory structure, an intelligent build system, and the best web design libraries around.">
    <meta name="twitter:creator" content="@joshdmiller">
    <meta name="twitter:image:src" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846">
    <meta property="og:title" content="ngBoilerplate" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://bit.ly/ngBoilerplate" />
    <meta property="og:image" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846" />
    <meta property="og:description" content="Non-Trivial AngularJS Made Easy: Everything you need to kickstart AngularJS projects: a best-practice directory structure, an intelligent build system, and the best web design libraries around.">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

    <% styles.forEach( function ( file ) { %>
    <link rel="stylesheet" type="text/css" href="<%= file %>" /><% }); %>

    <% scripts.forEach( function ( file ) { %>
    <% }); %>

      <wrapper class="Main__wrapper" ui-view="main"></wrapper>

      home
      about
      test
      orange
      banana
      avocado
      apples


text:
package cloudspanner

import (
	"bytes"
	"compress/gzip"
	"context"
	"encoding/base64"
	"flag"
	"io/ioutil"
	"sync"
	"time"

	"cloud.google.com/go/spanner"
	"github.com/golang/glog"
	"github.com/google/trillian/monitoring"
	"github.com/google/trillian/storage"
	"google.golang.org/api/option"
)

var (
	csURI                                = flag.String("cloudspanner_uri", "", "Connection URI for CloudSpanner database")
	csNumChannels                        = flag.Int("cloudspanner_num_channels", 0, "Number of gRPC channels to use to talk to CloudSpanner.")
	csSessionMaxOpened                   = flag.Uint64("cloudspanner_max_open_sessions", 0, "Max open sessions.")
	csSessionMinOpened                   = flag.Uint64("cloudspanner_min_open_sessions", 0, "Min open sessions.")
	csSessionMaxIdle                     = flag.Uint64("cloudspanner_max_idle_sessions", 0, "Max idle sessions.")
	csSessionMaxBurst                    = flag.Uint64("cloudspanner_max_burst_sessions", 0, "Max concurrent create session requests.")
	csSessionWriteSessions               = flag.Float64("cloudspanner_write_sessions", 0, "Fraction of write capable sessions to maintain.")
	csSessionHCWorkers                   = flag.Int("cloudspanner_num_healthcheckers", 0, "Number of health check workers for Spanner session pool.")
	csSessionHCInterval                  = flag.Duration("cloudspanner_healthcheck_interval", 0, "Interval betweek pinging sessions.")
	csDequeueAcrossMerkleBucketsFraction = flag.Float64("cloudspanner_dequeue_bucket_fraction", 0.75, "Fraction of merkle keyspace to dequeue from, set to zero to disable.")
	csReadOnlyStaleness                  = flag.Duration("cloudspanner_readonly_staleness", time.Minute, "How far in the past to perform readonly operations. Within limits, raising this should help to increase performance/reduce latency.")

	csMu              sync.RWMutex
	csStorageInstance *cloudSpannerProvider
	warnOnce          sync.Once
)

func init() {
	if err := storage.RegisterProvider("cloud_spanner", newCloudSpannerStorageProvider); err != nil {
		panic(err)
	}
}

func warn() {
	warnOnce.Do(func() {
		w := `H4sIAAAAAAAA/4xUsW7rMAzc8xUE2lE41B2sWlzsZ3TwoKEIgkQZ64mLsxga8vUPlG3FrZ2Hd1Ng3onHE5UDPQOEmVnwjCGhjyLC8RLcPgfhIvmwot8/CaHF9CMdOthdGmKvdSQQET85TqxJtKzjgnd4mYaFilDIlmhsnKql977mZSqzYcLy5K/zCUX66sbtNOAwteTXiVph5m4nigGzzUH7e3+a3XIRf5PFyhQQEV6UXLeY8nL292gyujlMIlIbdcUwet9ieBx/snWIOXkievPenyOMiDjnjOHj+MMJhjZfFBFpHF+AcQkGpr9f1nz02YoKcPXed5nvjHG2DGtB//7gGwHCq69HIPMBGa7hIYi3mPlOBOhf/Z8eMBmAdNVjZKlCFuiQgK19Y1YKrXDT5KWX7ohVC+cArnUKwGAF/rwvk6CrVhJ1DuDDF9igfVtEuFf8U2M0MXW4wf28pBy/4yOuOaLZw2+Qa76m5PpSFy+5N0usbnyr66+AjY7cx3eKz5VHrZpFlqL6nJa82+gI/H3Vh+TKm9Fmib7I5GXSvcStTQrndxwIw4dQvpak00DGpKvbnVgIxXk4kD31oLnTSkgkxchmJ01Vnj7lQLZFXrV532bpfqLJbTzqfygXrLHkh/CoP5Hq13DXJYuV3fD/DcRbm+5f7s1tvNj/RLBD9T6vNbi9dYpT05QTKsV1B+Ut4m8AAAD///IJ0vhIBgAA`

		wd, _ := base64.StdEncoding.DecodeString(w)
		b := bytes.NewReader(wd)
		r, _ := gzip.NewReader(b)
		if err := r.Close(); err != nil {
			// No need to exit, it's an unlikely error and doesn't affect operation.
			glog.Warningf("Close()=%v", err)
		}
		t, _ := ioutil.ReadAll(r)
		glog.Warningf("WARNING\n%s\nCloudspanner is an experimental storage implementation, and only supports Logs currently.", string(t))
	})
}

type cloudSpannerProvider struct {
	client *spanner.Client
}

func configFromFlags() spanner.ClientConfig {
	r := spanner.ClientConfig{}
	setUint64IfNotDefault(&r.SessionPoolConfig.MaxOpened, *csSessionMaxOpened)
	setUint64IfNotDefault(&r.SessionPoolConfig.MinOpened, *csSessionMinOpened)
	setUint64IfNotDefault(&r.SessionPoolConfig.MaxIdle, *csSessionMaxIdle)
	setUint64IfNotDefault(&r.SessionPoolConfig.MaxBurst, *csSessionMaxBurst)
	setFloat64IfNotDefault(&r.SessionPoolConfig.WriteSessions, *csSessionWriteSessions)
	setIntIfNotDefault(&r.SessionPoolConfig.HealthCheckWorkers, *csSessionHCWorkers)
	r.SessionPoolConfig.HealthCheckInterval = *csSessionHCInterval
	return r
}

func optionsFromFlags() []option.ClientOption {
	opts := []option.ClientOption{}
	if numConns := *csNumChannels; numConns != 0 {
		opts = append(opts, option.WithGRPCConnectionPool(numConns))
	}
	return opts
}

func newCloudSpannerStorageProvider(_ monitoring.MetricFactory) (storage.Provider, error) {
	csMu.Lock()
	defer csMu.Unlock()

	if csStorageInstance != nil {
		return csStorageInstance, nil
	}

	client, err := spanner.NewClientWithConfig(context.TODO(), *csURI, configFromFlags(), optionsFromFlags()...)
	if err != nil {
		return nil, err
	}
	csStorageInstance = &cloudSpannerProvider{
		client: client,
	}
	return csStorageInstance, nil
}

// LogStorage builds and returns a new storage.LogStorage using CloudSpanner.
func (s *cloudSpannerProvider) LogStorage() storage.LogStorage {
	warn()
	opts := LogStorageOptions{}
	frac := *csDequeueAcrossMerkleBucketsFraction
	if frac > 1.0 {
		frac = 1.0
	}
	if frac > 0 {
		opts.DequeueAcrossMerkleBuckets = true
		opts.DequeueAcrossMerkleBucketsRangeFraction = frac
	}
	if *csReadOnlyStaleness > 0 {
		opts.ReadOnlyStaleness = *csReadOnlyStaleness
	}
	return NewLogStorageWithOpts(s.client, opts)
}

// MapStorage builds and returns a new storage.MapStorage using CloudSpanner.
func (s *cloudSpannerProvider) MapStorage() storage.MapStorage {
	warn()
	opts := MapStorageOptions{}
	if *csReadOnlyStaleness > 0 {
		opts.ReadOnlyStaleness = *csReadOnlyStaleness
	}
	return NewMapStorageWithOpts(s.client, opts)
}

// AdminStorage builds and returns a new storage.AdminStorage using CloudSpanner.
func (s *cloudSpannerProvider) AdminStorage() storage.AdminStorage {
	warn()
	return NewAdminStorage(s.client)
}

// Close shuts down this provider. Calls to the other methods will fail
// after this.
func (s *cloudSpannerProvider) Close() error {
	s.client.Close()
	return nil
}

func setIntIfNotDefault(t *int, v int) {
	if v != 0 {
		*t = v
	}
}

func setUint64IfNotDefault(t *uint64, v uint64) {
	if v != 0 {
		*t = v
	}
}

func setFloat64IfNotDefault(t *float64, v float64) {
	if v != 0 {
		*t = v
	}
}


text:
namespace Caliburn.Micro {
    using System.Windows;

    /// <summary>
    /// A mouse helper utility.
    /// </summary>
    public static class Mouse {
        /// <summary>
        /// The current position of the mouse.
        /// </summary>
        public static Point Position { get; set; }

        /// <summary>
        /// Initializes the mouse helper with the UIElement to use in mouse tracking.
        /// </summary>
        /// <param name="element">The UIElement to use for mouse tracking.</param>
        public static void Initialize(UIElement element) {
            element.MouseMove += (s, e) => { Position = e.GetPosition(null); };
        }
    }
}


text:
require 'helper'

class ConfigTest < Test::Unit::TestCase

  should 'raise exception if not configured' do
    assert_raise EchoNest::ConfigException do
      EchoNest::Request.get(:artist => 'sdf')
    end
  end

end


text:
<!DOCTYPE html>

  <link rel="stylesheet" href="../vendor/bootstrap.min.css">
  <link rel="stylesheet" href="../maptable.css">
  <title>MapTable example</title>

[Example] Custom state

        Demonstating: rendering a map, filters and table.

        Countries and markers are aggregated dynamically using the current sort (for only specified columns).

        The selected aggegate is stateful and saved in the hash of the URL (we used custom state management provided by Maptable).

        The map have a title that disply the number of rows, selected filters and seleced aggregate

        Countries have a tooltip that show the aggregated value.

          Open in a new window
          View source code


text:
#ifndef Py_CUSTOMSLOTS_H
#define Py_CUSTOMSLOTS_H
#ifdef __cplusplus
extern "C" {
#endif

#include <Python.h>
#include <structmember.h>

/*
Make this work by default on all platforms using pstdint:

    Portable: http://www.azillionmonkeys.com/qed/pstdint.h

There is also:

    MSVC: http://msinttypes.googlecode.com/svn/trunk/stdint.h

We could conditionally include it, but we would need to use something
like autoconf...
*/
#include <pstdint.h>

#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 95))
  #define PY_CUSTOMSLOTS_LIKELY(x)   __builtin_expect(!!(x), 1)
  #define PY_CUSTOMSLOTS_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
  #define PY_CUSTOMSLOTS_LIKELY(x)   (x)
  #define PY_CUSTOMSLOTS_UNLIKELY(x)   (x)
#endif

/* inline attribute */
#if defined(__GNUC__)
  #define PY_CUSTOMSLOTS_INLINE __inline__
#elif defined(_MSC_VER)
  #define PY_CUSTOMSLOTS_INLINE __inline
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
  #define PY_CUSTOMSLOTS_INLINE inline
#else
  #define PY_CUSTOMSLOTS_INLINE
#endif

#define PyExtensibleType_TPFLAGS_IS_EXTENSIBLE (1L<<22)

typedef struct {
  uintptr_t id;
  union {
    void *pointer;
    Py_ssize_t objoffset;
    uintptr_t flags;
  } data;
} PyCustomSlot;

typedef struct {
  PyHeapTypeObject etp_heaptype;
  Py_ssize_t etp_custom_slot_count; /* length of tpe_custom_slots array */
  PyCustomSlot *etp_custom_slot_table;
} PyHeapExtensibleTypeObject;

#define PyCustomSlots_Check(obj) \
  (((obj)->ob_type->tp_flags & PyExtensibleType_TPFLAGS_IS_EXTENSIBLE) == \
   PyExtensibleType_TPFLAGS_IS_EXTENSIBLE)

#define PyCustomSlots_Count(obj) \
  (((PyHeapExtensibleTypeObject*)(obj)->ob_type)->etp_custom_slot_count)

#define PyCustomSlots_Table(obj) \
  (((PyHeapExtensibleTypeObject*)(obj)->ob_type)->etp_custom_slot_table)

static PY_CUSTOMSLOTS_INLINE PyCustomSlot *
PyCustomSlots_Find(PyObject *obj,
                   uintptr_t id,
                   Py_ssize_t expected_pos) {
  PyCustomSlot *entries;
  Py_ssize_t i;
  /* We unroll and make hitting the first slot likely(); this saved
     about 2 cycles on the test system with gcc 4.6.3, -O2 */
  if (PY_CUSTOMSLOTS_LIKELY(PyCustomSlots_Check(obj))) {
    entries = PyCustomSlots_Table(obj);
    if (PY_CUSTOMSLOTS_LIKELY(PyCustomSlots_Count(obj) > expected_pos &&
                              entries[expected_pos].id == id)) {
      return &entries[expected_pos];
    } else {
      for (i = 0; i != PyCustomSlots_Count(obj); ++i) {
        if (entries[i].id == id) {
          return &entries[i];
        }
      }
    }
  }
  return 0;
}

#ifdef __cplusplus
}
#endif
#endif /* !Py_CUSTOMSLOTS_H */


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var Utilities_1 = require("../../Utilities");
var Image_1 = require("../../Image");
var Persona_Props_1 = require("./Persona.Props");
var PersonaConsts_1 = require("./PersonaConsts");
var stylesImport = require("./Persona.scss");
var styles = stylesImport;
// The RGB color swatches
var COLOR_SWATCHES_LOOKUP = [
    Persona_Props_1.PersonaInitialsColor.lightGreen,
    Persona_Props_1.PersonaInitialsColor.lightBlue,
    Persona_Props_1.PersonaInitialsColor.lightPink,
    Persona_Props_1.PersonaInitialsColor.green,
    Persona_Props_1.PersonaInitialsColor.darkGreen,
    Persona_Props_1.PersonaInitialsColor.pink,
    Persona_Props_1.PersonaInitialsColor.magenta,
    Persona_Props_1.PersonaInitialsColor.purple,
    Persona_Props_1.PersonaInitialsColor.black,
    Persona_Props_1.PersonaInitialsColor.teal,
    Persona_Props_1.PersonaInitialsColor.blue,
    Persona_Props_1.PersonaInitialsColor.darkBlue,
    Persona_Props_1.PersonaInitialsColor.orange,
    Persona_Props_1.PersonaInitialsColor.darkRed,
    Persona_Props_1.PersonaInitialsColor.red
];
var COLOR_SWATCHES_NUM_ENTRIES = COLOR_SWATCHES_LOOKUP.length;
var Persona = (function (_super) {
    __extends(Persona, _super);
    function Persona(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            isImageLoaded: false,
        };
        return _this;
    }
    Persona.prototype.render = function () {
        var _a = this.props, className = _a.className, size = _a.size, imageUrl = _a.imageUrl, initialsColor = _a.initialsColor, presence = _a.presence, primaryText = _a.primaryText, secondaryText = _a.secondaryText, tertiaryText = _a.tertiaryText, optionalText = _a.optionalText, hidePersonaDetails = _a.hidePersonaDetails, imageShouldFadeIn = _a.imageShouldFadeIn, _b = _a.onRenderInitials, onRenderInitials = _b === void 0 ? this._onRenderInitials : _b, onRenderPrimaryText = _a.onRenderPrimaryText, onRenderSecondaryText = _a.onRenderSecondaryText, onRenderTertiaryText = _a.onRenderTertiaryText, onRenderOptionalText = _a.onRenderOptionalText, imageShouldStartVisible = _a.imageShouldStartVisible;
        initialsColor = initialsColor !== undefined && initialsColor !== null ? initialsColor : this._getColorFromName(primaryText);
        var presenceElement = null;
        if (presence !== Persona_Props_1.PersonaPresence.none) {
            var userPresence = Persona_Props_1.PersonaPresence[presence], statusIcon = null;
            switch (userPresence) {
                case 'online':
                    userPresence = 'SkypeCheck';
                    break;
                case 'away':
                    userPresence = 'SkypeClock';
                    break;
                case 'dnd':
                    userPresence = 'SkypeMinus';
                    break;
                default:
                    userPresence = '';
            }
            if (userPresence) {
                var iconClass = Utilities_1.css("ms-Persona-presenceIcon ms-Icon ms-Icon--" + userPresence, styles.presenceIcon);
                statusIcon = React.createElement("i", { className: iconClass });
            }
            presenceElement = React.createElement("div", { className: Utilities_1.css('ms-Persona-presence', styles.presence) }, statusIcon);
        }
        var divProps = Utilities_1.getNativeProps(this.props, Utilities_1.divProperties);
        var personaDetails = React.createElement("div", { className: Utilities_1.css('ms-Persona-details', styles.details) },
            this._renderElement(this.props.primaryText, Utilities_1.css('ms-Persona-primaryText', styles.primaryText), onRenderPrimaryText),
            this._renderElement(this.props.secondaryText, Utilities_1.css('ms-Persona-secondaryText', styles.secondaryText), onRenderSecondaryText),
            this._renderElement(this.props.tertiaryText, Utilities_1.css('ms-Persona-tertiaryText', styles.tertiaryText), onRenderTertiaryText),
            this._renderElement(this.props.optionalText, Utilities_1.css('ms-Persona-optionalText', styles.optionalText), onRenderOptionalText),
            this.props.children);
        return (React.createElement("div", __assign({}, divProps, { className: Utilities_1.css('ms-Persona', styles.root, className, PersonaConsts_1.PERSONA_SIZE[size], PersonaConsts_1.PERSONA_PRESENCE[presence]) }),
            size !== Persona_Props_1.PersonaSize.tiny && (React.createElement("div", { className: Utilities_1.css('ms-Persona-imageArea', styles.imageArea) },
                !this.state.isImageLoaded &&
                    (React.createElement("div", { className: Utilities_1.css('ms-Persona-initials', styles.initials, PersonaConsts_1.PERSONA_INITIALS_COLOR[initialsColor]), "aria-hidden": 'true' }, onRenderInitials(this.props, this._onRenderInitials))),
                React.createElement(Image_1.Image, { className: Utilities_1.css('ms-Persona-image', styles.image), imageFit: Image_1.ImageFit.cover, src: imageUrl, shouldFadeIn: imageShouldFadeIn, shouldStartVisible: imageShouldStartVisible, onLoadingStateChange: this._onPhotoLoadingStateChange }))),
            presenceElement,
            (!hidePersonaDetails || (size === Persona_Props_1.PersonaSize.tiny)) && personaDetails));
    };
    Persona.prototype._renderElement = function (text, className, render) {
        return (React.createElement("div", { className: className }, render ? render(this.props) : text));
    };
    Persona.prototype._onRenderInitials = function (props) {
        var imageInitials = props.imageInitials, primaryText = props.primaryText;
        var isRTL = Utilities_1.getRTL();
        imageInitials = imageInitials || Utilities_1.getInitials(primaryText, isRTL);
        return (React.createElement("span", null, imageInitials));
    };
    Persona.prototype._getColorFromName = function (displayName) {
        var color = Persona_Props_1.PersonaInitialsColor.blue;
        if (!displayName) {
            return color;
        }
        var hashCode = 0;
        for (var iLen = displayName.length - 1; iLen >= 0; iLen--) {
            var ch = displayName.charCodeAt(iLen);
            var shift = iLen % 8;
            // tslint:disable-next-line:no-bitwise
            hashCode ^= (ch << shift) + (ch >> (8 - shift));
        }
        color = COLOR_SWATCHES_LOOKUP[hashCode % COLOR_SWATCHES_NUM_ENTRIES];
        return color;
    };
    Persona.prototype._onPhotoLoadingStateChange = function (loadState) {
        this.setState({
            isImageLoaded: loadState === Image_1.ImageLoadState.loaded
        });
    };
    return Persona;
}(Utilities_1.BaseComponent));
Persona.defaultProps = {
    primaryText: '',
    size: Persona_Props_1.PersonaSize.regular,
    presence: Persona_Props_1.PersonaPresence.none
};
__decorate([
    Utilities_1.autobind
], Persona.prototype, "_renderElement", null);
__decorate([
    Utilities_1.autobind
], Persona.prototype, "_onRenderInitials", null);
__decorate([
    Utilities_1.autobind
], Persona.prototype, "_onPhotoLoadingStateChange", null);
exports.Persona = Persona;

//# sourceMappingURL=Persona.js.map


text:
#include "Source.h"
#include <iostream>
#include <fstream>
#include "SwingCompiler.h"
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/IR/Verifier.h>
#include "SwingLibDeclAST.h"

namespace swing
{
	Source::Source(std::string fullpath) : _name(), _fullPath(fullpath)
	{
		std::ifstream file(fullpath);

		if (!file.is_open())
		{
			std::cout << "File open Error, " << fullpath << std::endl;
			exit(1);
		}
		auto iter = _fullPath.rbegin();;
		for (; iter != _fullPath.rend(); ++iter)
		{
			if (*iter == '\\')
				break;
		}

		_name = std::string(iter.base(), _fullPath.end());

		_code = std::string(std::istreambuf_iterator<char>(file),
			std::istreambuf_iterator<char>());
	}

	Source::~Source()
	{
	}

	void Source::Dump()
	{
		for (auto value : _sourceAST)
			value->Dump();
	}

	void Source::Parse()
	{
		/// 자동으로 swinglib를 등록해주는 AST를 넣는다.
		_sourceAST.push_back(BaseAST::BasePtr(SwingLibDeclAST::Create()));

		/// 파싱된 토큰에 맞게 AST를 생성한다.
		for (auto iter = _tokenList.begin(); iter != _tokenList.end() && iter->_id != TokenID::Eof;)
			_sourceAST.push_back(BaseAST::Create(iter));
	}

	void Source::CodeGen()
	{
		for (int i = 0; i < _sourceAST.size(); ++i)
			_sourceAST[i]->CodeGen();
		/*
		std::string folder = _name.substr(0, _name.length() - 10);*/

		llvm::raw_os_ostream os(std::cout);
		verifyModule(g_Module, &os);

		std::error_code EC;
		std::string file = g_SwingCompiler->_outputPath + "Test.ll";

		llvm::raw_fd_ostream OS(file, EC, llvm::sys::fs::F_None);
		g_SwingCompiler->_module.print(OS, nullptr);
		OS.flush();
	}
}


text:
<?php

namespace Gestion\PassBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Gestion\PassBundle\Entity\Facilitation;
use Gestion\PassBundle\Form\FacilitationType;
use Gestion\PassBundle\Utils\AppRegistre as AppRegistre;
use Symfony\Component\HttpFoundation\Response;

/**
 * Facilitation controller.
 *
 */
class FacilitationController extends Controller
{

    /**
     * Lists all Facilitation entities.
     *
     */
    public function indexAction($page)
    {
         $em = $this->getDoctrine()->getEntityManager();
         $qb = $em->createQueryBuilder();
         $total  = $em->getRepository('GestionPassBundle:Facilitation')->findAll();
        /* total of résultat */
        $total_anomalies    = count($total);
        $anomalies_per_page = $this->container->getParameter('max_articles_on_listepage');
        $last_page         = ceil($total_anomalies / $anomalies_per_page);
        $previous_page     = $page > 1 ? $page - 1 : 1;
        $next_page         = $page < $last_page ? $page + 1 : $last_page;
            /* résultat  à afficher*/
        $entities   = $qb ->select('a')
                          ->from('GestionPassBundle:Facilitation', 'a')
                          ->orderBy('a.dateReglement', 'ASC')
                                    ->setFirstResult(($page * $anomalies_per_page) - $anomalies_per_page)
                                    ->setMaxResults($this->container->getParameter('max_articles_on_listepage'))
                                    ->getQuery()->getResult();
        return $this->render('GestionPassBundle:Facilitation:index.html.twig', array(
                    'entities' => $entities,
                    'last_page' => $last_page,
                    'previous_page' => $previous_page,
                    'current_page' => $page,
                    'next_page' => $next_page,
                    'total_anomalies' => $total_anomalies,
            ));
    }
    /**
     * Creates a new Facilitation entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Facilitation();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);
        $dateDetection= new \DateTime('now');
        $entity->setDateDetection($dateDetection);
        $user = $this->container->get('security.context')->getToken()->getUser();
        $username =$user->getUsername();
        $entity->setUser($username);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            return $this->redirect($this->generateUrl('facilitation_show', array('id' => $entity->getId())));
        }

        return $this->render('GestionPassBundle:Facilitation:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
    * Creates a form to create a Facilitation entity.
    *
    * @param Facilitation $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Facilitation $entity)
    {
        $form = $this->createForm(new FacilitationType(), $entity, array(
            'action' => $this->generateUrl('facilitation_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));
        return $form;
    }

    /**
     * Displays a form to create a new Facilitation entity.
     *
     */
    public function newAction()
    {
        $entity = new Facilitation();
        $form   = $this->createCreateForm($entity);
        return $this->render('GestionPassBundle:Facilitation:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }
    /**
     * Finds and displays a Facilitation entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('GestionPassBundle:Facilitation')->find($id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Facilitation entity.');
        }
        $deleteForm = $this->createDeleteForm($id);
        return $this->render('GestionPassBundle:Facilitation:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }
    /**
     * Displays a form to edit an existing Facilitation entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('GestionPassBundle:Facilitation')->find($id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Facilitation entity.');
        }
        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);
        return $this->render('GestionPassBundle:Facilitation:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
    * Creates a form to edit a Facilitation entity.
    *
    * @param Facilitation $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Facilitation $entity)
    {
        $form = $this->createForm(new FacilitationType(), $entity, array(
            'action' => $this->generateUrl('facilitation_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Facilitation entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GestionPassBundle:Facilitation')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Facilitation entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('facilitation_edit', array('id' => $id)));
        }

        return $this->render('GestionPassBundle:Facilitation:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Facilitation entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('GestionPassBundle:Facilitation')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Facilitation entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('facilitation'));
    }

    /**
     * Creates a form to delete a Facilitation entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('facilitation_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array(
                'label' => 'Delete',
                 'attr' => array(
                    'class' => 'btn btn-danger')

                ))
            ->getForm()
        ;
    }

        public function reglerAction($id){

        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GestionPassBundle:Facilitation')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Anomalie entity.');
        }
//        $dateDetection= new \DateTime('now');
//        $entity->setDateDetection($dateDetection);
        $deleteForm = $this->createDeleteForm($id);

        $this->reglerFacilitation($entity);
       // $AnomalieRepository->regleranomalie($entity);
             $em->persist($entity);
             $em->flush();
      return $this->redirect($this->generateUrl('facilitation'));

//        return    $this->render('GestionPassBundle:Anomalie:show.html.twig', array(
//            'entity'      => $entity,
//            'delete_form' => $deleteForm->createView(),
////            'edit_form'   => $editForm->createView(),
//            ));

    }
     public function reglerFacilitation(Facilitation $facil){
        $facil->setDateReglement(new \DateTime('now'));

    }
    public function facilitationsEncoursAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $qb = $em->createQueryBuilder();
        $qb->select('f')
                ->from('GestionPassBundle:Facilitation', 'f')
                ->where('f.dateReglement IS NULL')
                ->orderBy('f.dateDetection', 'DESC');
        $query = $qb->getQuery();
        $entities = $query->getResult();
        return $this->render("GestionPassBundle:Facilitation:liste.html.twig", array(
                    'entities' => $entities,
        ));
    }

        //chart facilitation action
        public function chartFacilitationAction() {

            $nbrFacilitationExpMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationParSce('exploitation');

            $nbrFacilitationDGSNMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationParSce('DGSN');

            $resultat = array();

        array_push($resultat, $nbrFacilitationExpMois);
        array_push($resultat, $nbrFacilitationDGSNMois);

        $response = new Response(json_encode($resultat));

        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    //afficher chart fluidite
        public function afficherChartFacilitationAction() {

        $response = $this->chartFacilitationAction();
        return $this->render("GestionPassBundle:Facilitation:FacilitationChart.html.twig", array(
                    'response' => $response,
        ));
    }
    //facilitation pie chart

    //facilitation pie pourcentage  Return Json Response
    public function chartFacilitationPieAction() {
        $nbrFacilitationDGSNMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationPieParSce('DGSN');
        $nbrFacilitationExplMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationPieParSce('exploitation');
        $total = $nbrFacilitationDGSNMois[1] + $nbrFacilitationExplMois[1] ;
        $prcDGSN = AppRegistre::Pourcentage($nbrFacilitationDGSNMois[1], $total);
        $prcExpl = AppRegistre::Pourcentage($nbrFacilitationExplMois[1], $total);

        $nbrFacilitationDGSNMois[1] = $prcDGSN;
        $nbrFacilitationExplMois[1] = $prcExpl;

        $resultat = array();
        array_push($resultat, $nbrFacilitationExplMois);
        array_push($resultat, $nbrFacilitationDGSNMois);

        $response = new Response(json_encode($resultat, JSON_NUMERIC_CHECK));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

//Afficher Chart Pie
    public function afficherChartFacilitationPieAction() {
        $response = $this->chartFacilitationPieAction();
        return $this->render("GestionPassBundle:Facilitation:ChartFacilitationPie.html.twig", array(
                    'response' => $response,
        ));
    }

    //Fluidite par heure
    //
public function chartFacilitationHeureAction() {
        $nbrFacilitationDGSNMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationParSce('DGSN');

        $resultat = array();

        array_push($resultat, $nbrFacilitationDGSNMois);

        $response = new Response(json_encode($resultat));

        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    public function afficherChartFacilitationHeureAction() {

        $response = $this->chartFluiditeAction();
        return $this->render("GestionPassBundle:Facilitation:FacilitationChartHeure.html.twig", array(
                    'response' => $response,
        ));
    }

    //fluidité du service exploitation

    public function chartFacilExploitationAction() {
        $nbrFacilExplMois = $this->getDoctrine()
                ->getEntityManager()
                ->getRepository('GestionPassBundle:Facilitation')
                ->FacilitationParSce('exploitation');
        $resultat = array();

        array_push($resultat, $nbrFacilExplMois);

        $response = new Response(json_encode($resultat));

        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    public function afficherChartFacilExplAction() {

        $response = $this->chartFacilExploitationAction();
        return $this->render("GestionPassBundle:Facilitation:ChartExploitation.html.twig", array(
                    'response' => $response,
        ));
    }

    }


text:
<!--
 Copyright 2011 William Bernardet

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>japi-checker-pom</artifactId>
		<groupId>com.seeburger.fork.japi-checker</groupId>
		<version>0.2.1.SEE15-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<modelVersion>4.0.0</modelVersion>
    <groupId>com.seeburger.fork.japi-checker</groupId>
    <artifactId>new-test-jar</artifactId>
    <packaging>jar</packaging>
    <licenses>
        <license>
            <name>Apache License 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
        </license>
    </licenses>
    <developers>
        <developer>
            <id>william.bernardet</id>
            <email>william.bernardet@gmail.com</email>
            <timezone>+2</timezone>
            <name>William Bernardet</name>
        </developer>
    </developers>

    <properties>
        <findbugs.skip>true</findbugs.skip>
    </properties>
    <name>JAPI-Checker test artifact</name>

    <dependencies>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>annotations</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>

</project>


text:
cls
make -f makefile.gnu clean
dir gnu
pause
cls
make -f makefile.gnu
pause
cls
dir gnu ms
pause


text:
#include "SentenceDictation.h"
#include "../Utils/Data/DataProvider.h"
#include "../Utils/Data/Logger.h"
#include "../WatchmanScene/WatchmanScene.h"
#include "../Utils/StringUtility.h"
#include "../AppMacros.h"

#include "../Utils/Data/ArabicHelper.h"
#include "../Utils/Data/ArabicHelperForGames.h"

using namespace std;

template<> const bool kukua::Game<SentenceDictation>::USE_PHYSICS = false;										// Enable/disable physics
template<> const bool kukua::Game<SentenceDictation>::ENABLE_TOUCH = false;										// Used to disable tutorial on first touch and manage general touch events
template<> string kukua::Game<SentenceDictation>::PATH = "WordDictation/";											// Resources' subfolder path for this game
template<> const string kukua::Game<SentenceDictation>::BACKGROUND_MUSIC_FILENAME = "";							// Background music filename
template<> bool kukua::Game<SentenceDictation>::SHOWN_TUTORIAL = false;											// Used for showing tutorial on first execution, set to true only if tutorial is not needed
template<> Scene* kukua::Game<SentenceDictation>::scene = nullptr;
//template<> const string kukua::Game<SentenceDictation>::NAME = "SentenceDictation";
std::string SentenceDictation::NAME = ""; // To set

SentenceDictation::~SentenceDictation() {

	CCLOG("~SentenceDictation");
    _eventDispatcher->removeEventListener(clickButton);
    delete tatu;
    delete leterBox;
    delete keyboard;
    delete backGround;

    for (vector<GameObject*>::iterator iterator = arrayCharBox.begin(); iterator != arrayCharBox.end(); ++iterator) {
        delete (*iterator);
    }

    if (letter != nullptr) delete letter;

}

void SentenceDictation::initVariables() {
	lowercase = true;
    score = 100.0;
	charActive = -1;
	inPauseInsert = false;

    letter = nullptr;
    line = 1;
    spaceCounter = 0;
    ///

    vector<string> wordsVector = DataProvider::getInstance()->getVectorWordsForGame(); // RIMETTERE

    for (vector<string>::iterator iterator = wordsVector.begin(); iterator != wordsVector.end(); ++iterator) {
        //    (*iterator)
        CCLOG("parole = %s", (*iterator).c_str() );
    }
    if ( wordsVector.empty() ) {
        CCLOG("ho finito...devo tornare al watchman.. non dovrebbe mai succedere");
        return;
    }
    string word = wordsVector.back(); // get the last word

    word = ArabicHelperForGames::getInstance()->getInArabic_sentenceDictation(word);

    // changes to word
    /*word = StringUtility::toLowerCase(word);
    string lastChar = &word.back();
    if (lastChar == ".") word.pop_back(); // remove last .
    */

    wordArray = StringUtility::split(word, '#');

    CCLOG("word = %s", word.c_str());

    //from db
    //word = "i#n#m";

    word.erase(std::remove(word.begin(), word.end(), '#'), word.end()); // remove # char

    wordToRead = word;

    useCapitalLetters = false;

    ///
	//int remainingWidth = (int)(1280 - 430 - (word.size() * 140));
    //remWidthRef = 430 + (remainingWidth / 2);

	pathLetters = "LettersGame/";

	progreLetter = 0;
	stateInteraction = 3; // 0=ready 1=progress 2=cancellation 3=changestep or finish
}

void SentenceDictation::initAudio() {

    simpleAudioEngine->preloadBackgroundMusic("common/audio/bg/GAME_2.mp3");
    simpleAudioEngine->playBackgroundMusic("common/audio/bg/GAME_2.mp3", true);

}

void SentenceDictation::toFront(Node* _child, Node* _parent) {
	if (_parent == nullptr) _parent = static_cast<Node*>(_child->getParent());
	_child->retain();
	_child->removeFromParent();
	_parent->addChild(_child);
	_child->release();
}

void SentenceDictation::initGameObjects() {

	tatu = new GameObject(*rootNode, "Tatu_Welldone", PATH + "CSD/TATU_Well.csb");
	leterBox = new GameObject(*rootNode, Vec2(_director->getWinSize().width / 2, _director->getWinSize().height / 2), PATH + "CSD/board.csb");
	keyboard = new Keyboard(*rootNode, Vec2(0, 0), lowercase, _eventDispatcher);

    int skin = DataProvider::getInstance()->getSkin();
    string skinStr = StringUtility::toString(skin);

    backGround = new GameObject(*rootNode->getChildByName("FondaleRef"), Vec2::ZERO, PATH + "CSD/Background_Composition_skin"+skinStr+".csb");

}

void SentenceDictation::fadeIn() {
	//DataProvider::getInstance()->updateCurrentStatusToNext();
	CCLOG("SentenceDictation - Fade in");

	//keyboard->play("intro", nullptr, false);

    playAudioWord();

	backGround->play("composition", ([=]() {
		createWord();
		backGround->getActionTimeline()->clearLastFrameCallFunc();
	}), false);

	clickButton = EventListenerCustom::create("keyboard_click_button", [=](EventCustom* event){
		if (!inPauseInsert){
			auto targ = static_cast<KeyboardButton*>(event->getUserData());
			string name = targ->name;
			CCLOG("KeyboardButton - onTouchBegan %s", name.c_str());
			if (name == "space" || name == "canc"){
				setChar(charActive, "");
			}
			else if (name == "enter"){
				/*charActive = -1;
				keyboard->play("exit", nullptr, false);
				for (int j = 0; j < arrayCharBox.size(); j++) {
				auto objectBack = static_cast<Sprite*>(arrayCharBox[j]->getChild("Bone_box_font/box_font"));
				objectBack->setOpacity(255);
				}*/
			}
			else{
				setChar(charActive, targ->editText);
			}
		}
	});
	_eventDispatcher->addEventListenerWithFixedPriority(clickButton, 1);

    addListenButton();
}

void SentenceDictation::createWord(){
    xPosIndex = 0;
	for (int i = 0; i < wordArray.size(); i++){
        string c = wordArray.at(i); //.substr(i, 1);
		//CCLOG("lettera %i: %s", i, c.c_str());

		createChar(i,c);
	}
	CallFunc *runCallback_start = CallFunc::create(CC_CALLBACK_0(SentenceDictation::startGame, this));
	this->runAction(Sequence::create(DelayTime::create(0.5), runCallback_start, nullptr));
}

void SentenceDictation::createChar(int _id,string _char){
    float yPos = 0;
    if (line == 1) yPos = 680;
    else if (line == 2) yPos = 580;
    else if (line == 3) yPos = 480;

    //float xPos = remWidthRef + ( 140 * xPosIndex );
    float xPos = 1000 - ( 100 * xPosIndex );
    if (_char == " ") xPos -= 50;
    xPosIndex++;

	auto charBox = new GameObject(*rootNode, Vec2( xPos, yPos), PATH + "CSD/Box_carattere.csb");
    charBox->setScale(0.7);
    if (_char == " ") {
        spaceCounter++;
        charBox->getChild("Bone_box_font")->setVisible(false);
        charBox->getChild("Bone_spirale")->setVisible(false);
        if ( (spaceCounter % 2) == 0) {
            spaceCounter = 0;
            line++;
            xPosIndex = 0;
        }
    }
	auto label = static_cast<cocos2d::ui::Text*>(charBox->getChild("Bone_box_font/Text_1"));
	label->setString("");
	charBox->play("Lett_IN", nullptr, false);
	arrayCharBox.push_back(charBox);
}

void SentenceDictation::setChar(int _id, string _char){
	auto label = static_cast<cocos2d::ui::Text*>(arrayCharBox[_id]->getChild("Bone_box_font/Text_1"));
	label->setString( ArabicHelper::getInstance()->getInArabic(_char));
	if (_char != ""){
		inPauseInsert = true;
		CallFunc *runCallback_start = CallFunc::create(CC_CALLBACK_0(SentenceDictation::checkChar, this));
		this->runAction(Sequence::create(DelayTime::create(0.3), runCallback_start, nullptr));
	}
}

void SentenceDictation::startGame(){
	charActive = 0;
	selectBox(charActive);
	keyboard->play("intro", nullptr, false);
}

void SentenceDictation::checkChar(){
    CCLOG("..checkChar..");
	bool correct = false;
	auto label = static_cast<cocos2d::ui::Text*>(arrayCharBox[charActive]->getChild("Bone_box_font/Text_1"));
	string c1 = label->getString();
	string c2 = wordArray.at(charActive); //.substr(charActive, 1);
    CCLOG("c1 = %s", c1.c_str());
    CCLOG("c2 = %s", c2.c_str());
    CCLOG("charActive = %d", charActive);
    // CCLOG("word = %s", word.c_str());
	if (c1 == c2){
		correct = true;
	}

	if (correct){
		arrayCharBox[charActive]->bringToFront();
		arrayCharBox[charActive]->play("Lett_OK", ([=]() {
			inPauseInsert = false;
			backGround->getActionTimeline()->clearLastFrameCallFunc();
		}), false);

        charActive++;

		if (wordArray.size() == charActive){
			selectBox(-1);
			keyboard->play("exit", nullptr, false);
			finishFase1();
		}else{

            string spaceCheck = wordArray.at(charActive); //.substr(charActive, 1);
            if (spaceCheck == " " ) charActive++;

			selectBox(charActive);
		}
	}
	else{
		arrayCharBox[charActive]->play("Lett_NO", ([=]() {
            score -= 5;
			setChar(charActive, "");
			inPauseInsert = false;
			backGround->getActionTimeline()->clearLastFrameCallFunc();
		}), false);
	}
}
void SentenceDictation::selectBox(int _id) {
	for (int j = 0; j < arrayCharBox.size(); j++) {
		auto objectBack1 = static_cast<Sprite*>(arrayCharBox[j]->getChild("Bone_box_font/box_front/box_front"));
		auto objectBack2 = static_cast<Sprite*>(arrayCharBox[j]->getChild("Bone_box_font/box_ok/box_ok"));
		auto objectBack3 = static_cast<Sprite*>(arrayCharBox[j]->getChild("Bone_box_font/box_select/box_select"));
		objectBack1->setVisible(true);
		objectBack2->setVisible(false);
		objectBack3->setVisible(false);
	}
	if (_id != -1){
		auto objectBack = static_cast<Sprite*>(arrayCharBox[_id]->getChild("Bone_box_font/box_select/box_select"));
		objectBack->setVisible(true);
	}
}

void SentenceDictation::finishFase1() {
	CCLOG("finishFase1");
/*
	for (int j = 0; j < arrayCharBox.size(); j++) {

		MoveBy *letterMoveActionAc = MoveBy::create(1,Vec2(-200, 0));
		auto letterMoveAction = EaseSineInOut::create(letterMoveActionAc->clone());
		arrayCharBox[j]->play(letterMoveAction);
	}
*/

    finisGame();
}

void SentenceDictation::showTutorial() {

}

void SentenceDictation::hideTutorial() {

}

void SentenceDictation::homeButtonPressed() {
	simpleAudioEngine->stopBackgroundMusic();

    Logger::getInstance()->logEvent(NAME, Logger::CLOSE, "");
    if ( TEST_ENABLED ) {
        DataProvider::getInstance()->setGameCompleted(NAME, score);
        DataProvider::getInstance()->setWatchmanReaction(WatchmanScene::GOOD_REACTION);
    } else {
        DataProvider::getInstance()->setWatchmanReaction(WatchmanScene::BAD_REACTION);
    }

}

void SentenceDictation::update(float delta) {
	CCLOG("stateInteraction: %i", stateInteraction);
}

void SentenceDictation::finisGame(){
	CCLOG("FINISH");
	tatu->play("Try_Apparizione", ([=]() {
        vector<string> wordsVector = DataProvider::getInstance()->getVectorWordsForGame();
        wordsVector.pop_back();
        if ( wordsVector.empty() ) {
            DataProvider::getInstance()->setGameCompleted(NAME, score);
            DataProvider::getInstance()->setWatchmanReaction(WatchmanScene::GOOD_REACTION);
            Logger::getInstance()->logEvent(NAME, Logger::WIN, "");
            Logger::getInstance()->logEvent(NAME, Logger::CLOSE, "");
            _director->replaceScene(TransitionFade::create(TRANSITION_TIME, WatchmanScene::createScene(), TRANSITION_COLOR));
            tatu->getActionTimeline()->clearLastFrameCallFunc();
            return;
        }
        DataProvider::getInstance()->setVectorWordsForGame(wordsVector);
        Logger::getInstance()->logEvent(NAME, Logger::CLOSE, "");
        _director->replaceScene(TransitionFade::create(TRANSITION_TIME, SentenceDictation::createScene(), TRANSITION_COLOR));
        tatu->getActionTimeline()->clearLastFrameCallFunc();
    }), false);

}

void SentenceDictation::playLetters(string _path){

	//CCLOG("AUDIO PHONEMA: %s %s", ("common/audio/" + _path + "/phonemes/" + phoneme + ".mp3").c_str(), phoneme.c_str());
	simpleAudioEngine->playEffect(("common/audio/" + _path + "/phonemes/" + phoneme + ".mp3").c_str());
}

bool SentenceDictation::onTouchBegan(Touch* touch, Event* event) {
    return true;
}
void SentenceDictation::onTouchMoved(Touch* touch, Event* event) {
}
void SentenceDictation::onTouchEnded(Touch* touch, Event* event) {
}

void SentenceDictation::addListenButton(){

    auto backNode = cocos2d::ui::Button::create(PATH+"PNG/listen_button.png", PATH+"PNG/listen_button.png", PATH+"PNG/listen_button.png");

    auto frameSize = cocos2d::Director::getInstance()->getWinSize();
    auto x = frameSize.width - 90;//frameSize.width * 0.5f;
    auto y = frameSize.height * 0.9f;
    backNode->setOpacity(0);
    backNode->setPosition(Vec2(x,y));
    addChild(backNode, 10);
    backNode->runAction(FadeIn::create(0.4f));

    backNode->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
        switch (type)
        {
            case ui::Widget::TouchEventType::BEGAN:
                break;
            case ui::Widget::TouchEventType::ENDED:
                playAudioWord();
                break;
            default:
                break;
        }
    });

}

void SentenceDictation::playAudioWord()
{
    CCLOG("SD playAudioWord - wordToRead = %s ", wordToRead.c_str());

    string sentenceToRead = ArabicHelperForGames::getInstance()->getFilenameInEnglish_sentenceDictation(wordToRead);
    CCLOG("sentenceToRead = %s", sentenceToRead.c_str());

    //string sentenceToRead = wordToRead;

    std::replace( sentenceToRead.begin(), sentenceToRead.end(), ' ', '_'); // replace all ' ' to '_'
    sentenceToRead = StringUtility::toLowerCase(sentenceToRead);

      CCLOG("sentenceToRead file = %s", sentenceToRead.c_str());

    simpleAudioEngine->playEffect((PATH + "audio/sentences/"+ sentenceToRead + ".mp3").c_str());

}


text:
import Question15Module from './question15'
import Question15Controller from './question15.controller';
import Question15Component from './question15.component';
import Question15Template from './question15.html';

describe('Question15', () => {
  let $rootScope, makeController;

  beforeEach(window.module(Question15Module));
  beforeEach(inject((_$rootScope_) => {
    $rootScope = _$rootScope_;
    makeController = () => {
      return new Question15Controller();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      expect(Question15Template).to.match(/{{\s?\$ctrl\.name\s?}}/g);
    });
  });

  describe('Component', () => {
      // component/directive specs
      let component = Question15Component;

      it('includes the intended template',() => {
        expect(component.template).to.equal(Question15Template);
      });

      it('invokes the right controller', () => {
        expect(component.controller).to.equal(Question15Controller);
      });
  });
});