text:
Apache Spark Analysis
=====================

This tutorial will show you how to:

1. Use GeoMesa with `Apache Spark <http://spark.apache.org/>`__.
2. Write custom Scala code for GeoMesa to generate histograms and
   spatial densities of `GDELT <http://www.gdeltproject.org/>`__ event
   data.

Background
----------

`Apache Spark <http://spark.apache.org>`__ is a "fast and general engine
for large-scale data processing". Spark presents an abstraction called a
Resilient Distributed Dataset (RDD) that facilitates expressing
transformations, filters, and aggregations, and efficiently executes the
computation across a distributed set of resources. Spark manages the
lineage of a block of transformed data so that if a node goes down,
Spark can restart the computation for just the missing blocks.

GeoMesa has support for executing Spark jobs over data stored in
GeoMesa. You can initialize a Spark RDD using standard CQL queries and
by passing standard CQL functions to transform the data. In the spirit
of the obligatory Word Count map-reduce example, we demonstrate two
geospatial spins on word count. First, counting features by time
resolution to compute a time series of spatial data, and second,
aggregating by grid cell to rapidly generate density plots. Apache Spark
enables us to express these transformations easily and succinctly.

Prerequisites
-------------

.. warning::

    You will need access to a Hadoop |hadoop_version| installation with Yarn as well as an Accumulo |accumulo_version| database.

    You will need to have ingested GDELT data using GeoMesa. Instructions are available in :doc:`geomesa-examples-gdelt`.

You will also need:

-  a `Spark <http://spark.apache.org/>`__ 1.5.0 or later distribution (see below)
-  an Accumulo user that has appropriate permissions to query your data
-  `Java JDK 8 <http://www.oracle.com/technetwork/java/javase/downloads/index.html>`__,
-  `Apache Maven <http://maven.apache.org/>`__ 3.2.2 or better
-  a `git <http://git-scm.com/>`__ client

Spark Distribution
------------------

Spark does not provide a Scala 2.11 (required for GeoMesa) distribution directly. Instead, you have to
build Spark from source. You can follow the instructions `here <http://spark.apache.org/docs/latest/building-spark.html>`__,
with Scala 2.11 details `here <http://spark.apache.org/docs/latest/building-spark.html#building-for-scala-211>`__.

.. warning::

    Ensure that you are using Spark 1.5.0 or later

GeoMesa works best with Spark running on Yarn - as such, you need to have an available Hadoop with Yarn
installation alongside your Spark distribution. We will use ``spark-submit`` to run our jobs on the cluster.

Set Up Tutorial Code
--------------------

Clone the geomesa project and build it, if you haven't already:

.. code-block:: bash

    $ git clone https://github.com/locationtech/geomesa.git
    $ cd geomesa
    $ mvn clean install

This is needed to install the GeoMesa JAR files in your local Maven
repository. For more information see the :doc:`../developer/index`.

The code in this tutorial is written in
`Scala <http://scala-lang.org/>`__, as is much of GeoMesa itself.

Count Events by Day of Year
---------------------------

You will need to have ingested some
`GDELT <http://www.gdeltproject.org/>`__ data as described in :doc:`geomesa-examples-gdelt`.
We have an example analysis in the class
``geomesa-compute/src/main/scala/org/locationtech/geomesa/compute/spark/analytics/CountByDay.scala``.

The code goes as follows.

First, we get a handle to a GeoMesa data store and construct a CQL query
for our bounding box.

.. code-block:: scala

    val params = Map(
      "instanceId" -> "instance",
      "zookeepers" -> "zoo1,zoo2,zoo3",
      "user"       -> "user",
      "password"   -> "*****",
      "auths"      -> "USER,ADMIN",
      "tableName"  -> "geomesa_catalog")

    val ds = DataStoreFinder.getDataStore(params)
    val q = new Query("event", ECQL.toFilter(filter))

Next, initialize an ``RDD[SimpleFeature]`` using ``GeoMesaSpark``.

.. code-block:: scala

    val sc = new SparkContext(GeoMesaSpark.init(new SparkConf(true), ds))
    val queryRDD = GeoMesaSpark.rdd(new Configuration, sc, params, q, None)

Finally, we construct our computation which consists of extracting the
``SQLDATE`` from each ``SimpleFeature`` and truncating it to the day
resolution.

.. code-block:: scala

    val dayAndFeature = queryRDD.mapPartitions { iter =>
      val df = new SimpleDateFormat("yyyyMMdd")
      val ff = CommonFactoryFinder.getFilterFactory2
      val exp = ff.property("SQLDATE")
      iter.map { f => (df.format(exp.evaluate(f).asInstanceOf[java.util.Date]), f) }
    }

Then, we group by the day and count up the number of events in each
group.

.. code-block:: scala

    val groupedByDay = dayAndFeature.groupBy { case (date, _) => date }
    val countByDay = groupedByDay.map { case (date, iter) => (date, iter.size) }
    countByDay.collect().foreach(println)

Run the Tutorial Code
^^^^^^^^^^^^^^^^^^^^^

Edit the file ``geomesa-compute/src/main/scala/org/locationtech/geomesa/compute/spark/analytics/CountByDay.scala``
so that the parameter map points to your cloud instance. Ensure that the ``filter`` covers
a valid range of your GDELT data.

Re-build the GeoMesa Spark jar to pick up the changes:

.. code-block:: bash

    $ mvn clean install -pl geomesa-compute

Now, we can submit the job to our Yarn cluster using ``spark-submit``:

.. code-block:: bash

    $ /path/to/spark/bin/spark-submit --master yarn-client                  \
        --num-executors 40 --executor-cores 4 --deploy-mode client          \
        --class org.locationtech.geomesa.compute.spark.analytics.CountByDay \
        geomesa-compute/target/geomesa-compute-<version>-shaded.jar

You should see a lot of Spark logging, and then the counts:

.. code-block:: bash

    (20140126,3)
    (20140127,33)
    (20140128,34)
    ...

Parallel Computation of Spatial Event Densities
-----------------------------------------------

In the second demonstration, we compute densities of our feature by
discretizing the spatial domain and counting occurrences of the feature
in each grid cell. We use `GeoHashes <http://geohash.org>`__ as our
discretization of the world so that we can configure the resolution of
our density by setting the number of bits in the GeoHash.

This code is does not exist in GeoMesa; it's left as an exercise for the reader.

First, start with a similar ``RDD[SimpleFeature]`` as before but expand
the bounding box.

.. code-block:: scala

    val f = ff.bbox("geom", -180, -90, 180, 90, "EPSG:4326")
    val q = new Query("event", f)

    val queryRDD = GeoMesaSpark.rdd(new Configuration, sc, params, q, None)

Project (in the relational sense) the ``SimpleFeature`` to a 2-tuple of
``(GeoHash, 1)``.

.. code-block:: scala

    val discretized = queryRDD.map { f =>
       (geomesa.utils.geohash.GeoHash(f.getDefaultGeometry.asInstanceOf[Point], 25), 1)
    }

Then, group by grid cell and count the number of features per cell.

.. code-block:: scala

    val density = discretized
       .groupBy { case (gh, _)    => gh }
       .map     { case (gh, iter) => (gh.bbox.envelope, iter.size) }

    density.collect.foreach(println)

The resulting density plot is visualized below.

.. figure:: _static/img/tutorials/2014-08-05-spark/gdelt-global-density.png


text:
const passport = require('passport');
const League = require('../models/League');
const User = require('../models/User');

module.exports = (app) => {
  app.get('/app/user', (req, res) => {
    const userId = req.session.passport.user;
    User.findById(userId, (err, user) => {
      League.find({ ['players.player']: userId })
      .populate('players.player')
      .exec((err, leagues) => {
        const hydratedLeaguesUser = Object.assign({}, user.toObject(), { leagues });
        res.send(hydratedLeaguesUser);
      });
    });
  });
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Pastum\Component\PAMI\Message\Action;

/**
 * Lists avaiable manager actions.
 */
class ListCommandsAction extends ActionMessage
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct('ListCommands');
    }
}


text:
define(["dojo/_base/kernel","dojo/_base/lang","dojo/_base/window","dojo/_base/declare",
		"dojo/_base/fx","dojo/_base/connect","dojo/_base/array","dojo/_base/sniff",
		"dojo/window","dojo/dom","dojo/dom-class","dojo/dom-geometry","dojo/dom-construct",
		"dijit/_TemplatedMixin","dijit/_Widget","dijit/BackgroundIframe","dojo/dnd/Moveable",
		"./ContentPane","./ResizeHandle","dojo/text!./resources/FloatingPane.html"], function(
	kernel, lang, winUtil, declare, baseFx, connectUtil, arrayUtil,
	has, windowLib, dom, domClass, domGeom, domConstruct, TemplatedMixin, Widget, BackgroundIframe,
	Moveable, ContentPane, ResizeHandle, template){

kernel.experimental("dojox.layout.Dock");

var Dock = declare("dojox.layout.Dock",[Widget, TemplatedMixin],{
	// summary:
	//		A widget that attaches to a node and keeps track of incoming / outgoing FloatingPanes
	//		and handles layout

	templateString: '

',

	// _docked: [private] Array
	//		array of panes currently in our dock
	_docked: [],

	_inPositioning: false,

	autoPosition: false,

	addNode: function(refNode){
		// summary:
		//		Insert a dockNode reference into the dock

		var div = domConstruct.create('li', null, this.containerNode),
			node = new DockNode({
				title: refNode.title,
				paneRef: refNode
			}, div)
		;
		node.startup();
		return node;
	},

	startup: function(){

		if (this.id == "dojoxGlobalFloatingDock" || this.isFixedDock) {
			// attach window.onScroll, and a position like in presentation/dialog
			this.connect(window, 'onresize', "_positionDock");
			this.connect(window, 'onscroll', "_positionDock");
			if(has("ie")){
				this.connect(this.domNode, "onresize", "_positionDock");
			}
		}
		this._positionDock(null);
		this.inherited(arguments);

	},

	_positionDock: function(/* Event? */e){
		if(!this._inPositioning){
			if(this.autoPosition == "south"){
				// Give some time for scrollbars to appear/disappear
				setTimeout(lang.hitch(this, function() {
					this._inPositiononing = true;
					var viewport = windowLib.getBox();
					var s = this.domNode.style;
					s.left = viewport.l + "px";
					s.width = (viewport.w-2) + "px";
					s.top = (viewport.h + viewport.t) - this.domNode.offsetHeight + "px";
					this._inPositioning = false;
				}), 125);
			}
		}
	}

});

var DockNode = declare("dojox.layout._DockNode",[Widget, TemplatedMixin],{
	// summary:
	//		dojox.layout._DockNode is a private widget used to keep track of
	//		which pane is docked.

	// title: String
	//		Shown in dock icon. should read parent iconSrc?
	title: "",

	// paneRef: Widget
	//		reference to the FloatingPane we reprasent in any given dock
	paneRef: null,

	templateString:
		'
'+
			''+
			'${title}'+
		'
',

	restore: function(){
		// summary:
		//		remove this dock item from parent dock, and call show() on reffed floatingpane
		this.paneRef.show();
		this.paneRef.bringToTop();
		this.destroy();
	}
});

return Dock;
});


text:
import {Component, ViewEncapsulation} from "@angular/core";
import {AnalyticsService} from "../core/services/analytics.service";

@Component({
    selector: 'sk-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {

    // noinspection JSUnusedLocalSymbols
    /**
     *  Note: Don't remove the un-used import, as it initializes the service.
     */
    constructor(analyticsService: AnalyticsService) {
    }

}


text:
/*global define,dojo,dojoConfig:true,alert,esri,Modernizr,appGlobals */
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
/** @license
 | Copyright 2015 Esri
 |
 | 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.
 */
//============================================================================================================================//
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-attr",
    "dojo/dom",
    "dojo/on",
    "dojo/_base/array",
    "esri/tasks/query",
    "dojo/promise/all",
    "esri/tasks/QueryTask",
    "esri/graphic",
    "dijit/_WidgetBase",
    "dojo/i18n!application/js/library/nls/localizedStrings",
    "dojo/topic",
    "dijit/form/HorizontalSlider",
    "dijit/form/HorizontalRule",
    "esri/tasks/BufferParameters",
    "dojo/_base/Color",
    "esri/tasks/GeometryService",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol"

], function (declare, lang, domStyle, domAttr, dom, on, array, Query, all, QueryTask, Graphic, _WidgetBase, sharedNls, topic, HorizontalSlider, HorizontalRule, BufferParameters, Color, GeometryService, SimpleLineSymbol, SimpleFillSymbol) {
    // ========================================================================================================================//

    return declare([_WidgetBase], {
        sharedNls: sharedNls, // Variable for shared NLS
        unitValues: [null, null, null, null],

        /**
        * Create buffer around pushpin
        * @param {object} mapPoint Contains the map point on map
        * @param {string} widgetName Contains the name of the functionality from where buffer is created.
        * @memberOf widgets/commonHelper/locatorHelper
        */
        createBuffer: function (mapPoint, widgetName) {
            var params, geometryService, isValid;
            this.carouselContainer.removeAllPod();
            this.carouselContainer.addPod(this.carouselPodData);
            this.removeBuffer();
            geometryService = new GeometryService(appGlobals.configData.GeometryService);
          // Checking the map point or map point is having geometry and if config data has buffer distance.
          //TODO...JH Set bufferDistance from slider value
            //isValid = this._validateRangeFilterValues();
          //if ((mapPoint || mapPoint.geometry) && appGlobals.configData.BufferDistance) {
          //if ((mapPoint || mapPoint.geometry) && isValid) {
            if ((mapPoint || mapPoint.geometry)) {
              var geometry = mapPoint.geometry;
              if (typeof (geometry) === 'undefined') {
                geometry = mapPoint;
              }
              //TODO...JH check out the share options
              //appGlobals.shareOptions.arrBufferDistance[this.workflowCount] = bufferDistance;
              //commented from site-selector...this.featureGeometry[this.workflowCount] = geometry;
              //commented from site-selector...selectedPanel = query('.esriCTsearchContainerSitesSelected')[0];
              // set slider values for various workflows

              slider = dijit.byId("sliderhorizontalSliderContainer");
                sliderDistance = slider.value;

              //////////////////////////
                if (Math.round(sliderDistance) !== 0) {
                  if (geometry && geometry.type === "point") {
                    //setup the buffer parameters
                    params = new BufferParameters();
                    params.distances = [Math.round(sliderDistance)];
                    params.bufferSpatialReference = this.map.spatialReference;
                    params.outSpatialReference = this.map.spatialReference;
                    params.geometries = [geometry];
                    params.unit = GeometryService[this._getDistanceUnit(appGlobals.configData.DistanceUnitSettings.DistanceUnitName)];
                    geometryService.buffer(params, lang.hitch(this, function (geometries) {
                      this.showBuffer(geometries, mapPoint, widgetName);
                    }));
                  } else {
                    topic.publish("hideProgressIndicator");
                  }
                }
                //else {
                //  topic.publish("hideProgressIndicator");
                //  if (document.activeElement) {
                //    document.activeElement.blur();
                //  }
                //  // clear buildings, sites and business tab data
                //  if (this.workflowCount === 0) {
                //    domStyle.set(this.outerDivForPegination, "display", "none");
                //    domConstruct.empty(this.outerResultContainerBuilding);
                //    domConstruct.empty(this.attachmentOuterDiv);
                //    delete this.buildingTabData;
                //  } else if (this.workflowCount === 1) {
                //    domStyle.set(this.outerDivForPeginationSites, "display", "none");
                //    domConstruct.empty(this.outerResultContainerSites);
                //    domConstruct.empty(this.attachmentOuterDivSites);
                //    delete this.sitesTabData;
                //  } else if (this.workflowCount === 2) {
                //    this._clearBusinessData();
                //  }
                //  this.lastGeometry[this.workflowCount] = null;
                //  this.map.graphics.clear();
                //  this.map.getLayer("esriBufferGraphicsLayer").clear();
                //  alert(sharedNls.errorMessages.bufferSliderValue);
                //  this.isSharedExtent = false;
                //}
              //////////////////////////

                //params = new BufferParameters();
                //params.distances = [appGlobals.configData.BufferDistance];
              //TODO...JH Get buffer distance from config...will need to map config values to geom service constants
                //params.unit = GeometryService.UNIT_STATUTE_MILE;
                //params.bufferSpatialReference = this.map.spatialReference;
                //params.outSpatialReference = this.map.spatialReference;
                // Checking the geometry
                //if (mapPoint.geometry) {
                //    params.geometries = [mapPoint.geometry];
                //} else {
                //    params.geometries = [mapPoint];
                //}
                // Ccreating buffer and calling show buffer function.
                //geometryService.buffer(params, lang.hitch(this, function (geometries) {
                //    this.showBuffer(geometries, mapPoint, widgetName);
                //}));
            }
        },

      /**
* get distance unit based on unit selection
* @param {string} input distance unit
* @memberOf widgets/siteLocator/siteLocatorHelper
*/
        _getDistanceUnit: function (strUnit) {
          var sliderUnitValue;
          if (strUnit.toLowerCase() === "miles") {
            sliderUnitValue = "UNIT_STATUTE_MILE";
          } else if (strUnit.toLowerCase() === "feet") {
            sliderUnitValue = "UNIT_FOOT";
          } else if (strUnit.toLowerCase() === "meters") {
            sliderUnitValue = "UNIT_METER";
          } else if (strUnit.toLowerCase() === "kilometers") {
            sliderUnitValue = "UNIT_KILOMETER";
          } else {
            sliderUnitValue = "UNIT_STATUTE_MILE";
          }
          return sliderUnitValue;
        },

        /**
        * Show buffer on map
        * @param {object} geometries of mapPoint
        * @param {object} mapPoint Contains the map point
        * @memberOf widgets/commonHelper/locatorHelper
        */
        showBuffer: function (geometries, mapPoint, widgetName) {
            var bufferSymbol;
            // Checking the geolocation variable in the case of share app.
            if (!appGlobals.shareOptions.sharedGeolocation) {
                this._clearBuffer();
            }
            bufferSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([parseInt(appGlobals.configData.BufferSymbology.LineSymbolColor.split(",")[0], 10), parseInt(appGlobals.configData.BufferSymbology.LineSymbolColor.split(",")[1], 10), parseInt(appGlobals.configData.BufferSymbology.FillSymbolColor.split(",")[2], 10), parseFloat(appGlobals.configData.BufferSymbology.LineSymbolTransparency.split(",")[0], 10)]), 2),
                        new Color([parseInt(appGlobals.configData.BufferSymbology.FillSymbolColor.split(",")[0], 10), parseInt(appGlobals.configData.BufferSymbology.FillSymbolColor.split(",")[1], 10), parseInt(appGlobals.configData.BufferSymbology.LineSymbolColor.split(",")[2], 10), parseFloat(appGlobals.configData.BufferSymbology.FillSymbolTransparency.split(",")[0], 10)]));
            // Adding graphic on map
            try {
              this._addGraphic(this.map.getLayer("tempBufferLayer"), bufferSymbol, geometries[0]);
            } catch (error) {
                alert(sharedNls.errorMessages.unableToDrawBuffer);
                topic.publish("hideProgressIndicator");
                this.zoomToFullRoute = true; /* Changed Code for GitHub issue #182 */
            }
            topic.publish("showProgressIndicator");
            // Querying for layer to find features.
            this._queryLayer(geometries[0], mapPoint, widgetName);
        },

        /**
        * Clear buffer from map
        * @memberOf widgets/commonHelper/locatorHelper
        */
        _clearBuffer: function () {
            if (this.map.getLayer("tempBufferLayer") && this.map.getLayer("tempBufferLayer").graphics.length > 0) {
                this.map.getLayer("tempBufferLayer").clear();
            }
            topic.publish("hideInfoWindow");
            this.isInfowindowHide = true;
            this.zoomToFullRoute = true;
        },

        /**
        * Add graphic layer on map of buffer and set expand
        * @param {object} layer Contains feature layer
        * @param {object} symbol Contains graphic
        * @param {object}point Contains the map point
        * @memberOf widgets/commonHelper/locatorHelper
        */
        _addGraphic: function (layer, symbol, point) {
            var graphic;
            graphic = new Graphic(point, symbol);
            layer.add(graphic);
            this.point = point;
            this.zoomToFullRoute = false;
            // Checking the extent changed variable in the case of shared app to maintain extent on map
            if (window.location.href.toString().split("$extentChanged=").length > 1) {
                // If extent change variable set to be true then set the extent other wise don't do any thing.
                if (this.isExtentSet) {
                    this.map.setExtent(point.getExtent().expand(1.6));
                }
            } else {
                // In normal scenario set extent when graphics is added.
                this.map.setExtent(point.getExtent().expand(1.6));
            }
        },

        /**
        * Query layer URL
        * Create an object of graphic
        * @param {object} geometry of graphic
        * @param {object} mapPoint Contains the map point
        * @param {object} widget name of the functionality from query layer is called.
        * @memberOf widgets/commonHelper/locatorHelper
        */
        _queryLayer: function (geometry, mapPoint, widget) {
            var layerobject, i, deferredArray = [], result = [], widgetName, featuresWithinBuffer = [],
                dist, featureSet = [], isDistanceFound, j, k, routeObject;
            // Validate selectedLayerTitle for querying on each layer configured, for finding facility within the buffer.
            if (widget) {
                widgetName = widget;
            } else {
                widgetName = "unifiedSearch";
            }
            if (this.selectedLayerTitle) {
                // Looping each layer for query
                array.forEach(appGlobals.configData.SearchSettings, lang.hitch(this, function (SearchSettings) {
                    // Checking search display title for getting layer.
                    if (SearchSettings.SearchDisplayTitle === this.selectedLayerTitle) {
                        layerobject = SearchSettings;
                        // Query on layer for facility.
                        this._queryLayerForFacility(layerobject, geometry, deferredArray, result);
                    }
                }));
            } else {
                // Looping on each layer for finding facility within the buffer
                for (i = 0; i < appGlobals.configData.SearchSettings.length; i++) {
                    layerobject = appGlobals.configData.SearchSettings[i];
                    this._queryLayerForFacility(layerobject, geometry, deferredArray, result);
                }
                // Calling deferred list when all query is completed.
                all(deferredArray).then(lang.hitch(this, function (relatedRecords) {
                    // looping the result for getting records and pushing it in a variable for further query
                    for (j = 0; j < result.length; j++) {
                        if (result.length > 0) {
                            this.dateFieldArray = this.getDateField(result[j].records);
                            for (k = 0; k < result[j].records.features.length; k++) {
                                featuresWithinBuffer.push(result[j].records.features[k]);
                            }
                        }
                    }
                    // Looping final array for finding distance from start point and calculating route.
                    for (i = 0; i < featuresWithinBuffer.length; i++) {
                        // Checking the geometry
                        if (mapPoint.geometry) {
                            dist = this.getDistance(mapPoint.geometry, featuresWithinBuffer[i].geometry);
                            isDistanceFound = true;
                        }
                        try {
                            featureSet[i] = featuresWithinBuffer[i];
                            featuresWithinBuffer[i].distance = dist.toString();
                        } catch (err) {
                            alert(sharedNls.errorMessages.falseConfigParams);
                        }
                    }
                    // If distance is calculated from the start point
                    if (isDistanceFound) {
                        featureSet.sort(function (a, b) {
                            return parseFloat(a.distance) - parseFloat(b.distance);
                        });
                        // looping the result data for sorting data by distance
                        array.forEach(result, lang.hitch(this, function (resultSet) {
                            resultSet.records.features.sort(function (a, b) {
                                return parseFloat(a.distance) - parseFloat(b.distance);
                            });
                        }));
                        this.highlightFeature(featureSet[0].geometry);
                        // Changing date format for feature if date field is available.
                        routeObject = { "StartPoint": mapPoint, "EndPoint": featureSet, "Index": 0, "WidgetName": widgetName, "QueryURL": layerobject.QueryURL, "activityData": result };
                        //Calling route function to create route
                        this.showRoute(routeObject);
                    }
                    // Checking result array length, if it is 0 then show message and hide carousel container and remove graphics
                    if (result.length === 0) {
                        alert(sharedNls.errorMessages.facilityNotfound);
                        appGlobals.shareOptions.eventInfoWindowData = null;
                        appGlobals.shareOptions.infoRoutePoint = null;
                        this.removeRouteGraphichOfDirectionWidget();
                        this.removeHighlightedCircleGraphics();
                        if (widgetName !== "unifiedSearch") {
                            this.removeLocatorPushPin();
                        }
                        if (this.carouselContainer) {
                            this.carouselContainer.hideCarouselContainer();
                            this.carouselContainer._setLegendPositionDown();
                        }
                        topic.publish("hideProgressIndicator");
                    }
                }));
            }
        },

        /**
        * Query layer for getting facilty
        * finding route from start point to the nearest feature
        * @param {object} layerobject contains the layer information
        * @param {object} geometry contains the geometry
        * @param {object} deferredArray contains deferred array for further operation
        * @param {object} result array to contain feature data
        * @memberOf widgets/commonHelper/locatorHelper
        */
        _queryLayerForFacility: function (layerobject, geometry, deferredArray, result) {
            var queryTask, queryLayer, layerObject;
            // Checking the query url availability
            if (layerobject.QueryURL) {
                queryTask = new QueryTask(layerobject.QueryURL);
                queryLayer = new Query();
                queryLayer.outFields = ["*"];
                queryLayer.returnGeometry = true;
                // Checking the geometry
                if (geometry) {
                    queryLayer.geometry = geometry;
                }
                layerObject = {};
                // Pushing the query task in deferred array for further query
                deferredArray.push(queryTask.execute(queryLayer, lang.hitch(this, function (records) {
                    layerObject = { "queryURL": layerobject.QueryURL, "records": records };
                    // If feature is available the push data in result.
                    if (records.features.length > 0) {
                        result.push(layerObject);
                    }
                })));
            } else {
                topic.publish("hideProgressIndicator");
            }
        }
    });
});


text:
/***************************************************************************
**    Sun Aug 27 2006
**    (C) 2006 by Sanjay Nair
**    sanjaysn <at> usc <dot> edu
****************************************************************************/

#ifndef CMESSAGEFACTORY_H
#define CMESSAGEFACTORY_H

#include "cglobal.h"

class CTcpSocket;
class CMessage;

class CMessageFactory {

public:
    ~CMessageFactory();

    static CMessage *createMsg(CTcpSocket *sockP);

private:
  CMessageFactory();

  static UCharBuffer rcvFrom(CTcpSocket *sockP, uint len);
  static CMessage * getStoreMsg(
    const UCharBuffer &header, uint32_t dataLen, CTcpSocket *sockP);

  static CMessage * getGetResMsg(
    const UCharBuffer &header, uint32_t dataLen, CTcpSocket *sockP);

  static string writeToTmpFile(CTcpSocket *sockP, uint32_t dataLen);

};

#endif //CMESSAGEFACTORY_H


text:
using content::UserMetricsAction;
using content::WebContents;

// Maximum number of search results to return in a given search. We should
// eventually remove this.
static const int kMaxSearchResults = 100;
static const char kStringsJsFile[] = "strings.js";
static const char kHistoryJsFile[] = "history.js";

////////////////////////////////////////////////////////////////////////////////
//
// HistoryUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////
class HistoryUIHTMLSource : public ChromeWebUIDataSource {
 public:
  HistoryUIHTMLSource();

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path,
                                bool is_incognito,
                                int request_id) OVERRIDE;

  virtual std::string GetMimeType(const std::string& path) const OVERRIDE;

 private:
  ~HistoryUIHTMLSource();

  DISALLOW_COPY_AND_ASSIGN(HistoryUIHTMLSource);
};

HistoryUIHTMLSource::HistoryUIHTMLSource()
    : ChromeWebUIDataSource(chrome::kChromeUIHistoryFrameHost) {
  AddLocalizedString("loading", IDS_HISTORY_LOADING);
  AddLocalizedString("title", IDS_HISTORY_TITLE);
  AddLocalizedString("newest", IDS_HISTORY_NEWEST);
  AddLocalizedString("newer", IDS_HISTORY_NEWER);
  AddLocalizedString("older", IDS_HISTORY_OLDER);
  AddLocalizedString("searchresultsfor", IDS_HISTORY_SEARCHRESULTSFOR);
  AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS);
  AddLocalizedString("cont", IDS_HISTORY_CONTINUED);
  AddLocalizedString("searchbutton", IDS_HISTORY_SEARCH_BUTTON);
  AddLocalizedString("noresults", IDS_HISTORY_NO_RESULTS);
  AddLocalizedString("noitems", IDS_HISTORY_NO_ITEMS);
  AddLocalizedString("edithistory", IDS_HISTORY_START_EDITING_HISTORY);
  AddLocalizedString("doneediting", IDS_HISTORY_STOP_EDITING_HISTORY);
  AddLocalizedString("removeselected", IDS_HISTORY_REMOVE_SELECTED_ITEMS);
  AddLocalizedString("clearallhistory",
                     IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG);
  AddLocalizedString("deletewarning",
                     IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING);
  AddLocalizedString("actionMenuDescription",
                     IDS_HISTORY_ACTION_MENU_DESCRIPTION);
  AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE);
  AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE);
}

HistoryUIHTMLSource::~HistoryUIHTMLSource() {
}

void HistoryUIHTMLSource::StartDataRequest(const std::string& path,
                                           bool is_incognito,
                                           int request_id) {
  if (path == kStringsJsFile) {
    SendLocalizedStringsAsJSON(request_id);
  } else {
    int idr = path == kHistoryJsFile ? IDR_HISTORY_JS : IDR_HISTORY_HTML;
    SendFromResourceBundle(request_id, idr);
  }
}

std::string HistoryUIHTMLSource::GetMimeType(const std::string& path) const {
  if (path == kStringsJsFile || path == kHistoryJsFile)
    return "application/javascript";

  return "text/html";
}

////////////////////////////////////////////////////////////////////////////////
//
// BrowsingHistoryHandler
//
////////////////////////////////////////////////////////////////////////////////
BrowsingHistoryHandler::BrowsingHistoryHandler()
    : search_text_() {
}

BrowsingHistoryHandler::~BrowsingHistoryHandler() {
  cancelable_search_consumer_.CancelAllRequests();
  cancelable_delete_consumer_.CancelAllRequests();
}

void BrowsingHistoryHandler::RegisterMessages() {
  // Create our favicon data source.
  Profile* profile = Profile::FromWebUI(web_ui());
  profile->GetChromeURLDataManager()->AddDataSource(
      new FaviconSource(profile, FaviconSource::FAVICON));

  // Get notifications when history is cleared.
  registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED,
      content::Source<Profile>(profile->GetOriginalProfile()));

  web_ui()->RegisterMessageCallback("getHistory",
      base::Bind(&BrowsingHistoryHandler::HandleGetHistory,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("searchHistory",
      base::Bind(&BrowsingHistoryHandler::HandleSearchHistory,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("removeURLsOnOneDay",
      base::Bind(&BrowsingHistoryHandler::HandleRemoveURLsOnOneDay,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("clearBrowsingData",
      base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData,
                 base::Unretained(this)));
}

void BrowsingHistoryHandler::HandleGetHistory(const ListValue* args) {
  // Anything in-flight is invalid.
  cancelable_search_consumer_.CancelAllRequests();

  // Get arguments (if any).
  int day = 0;
  bool res = ExtractIntegerValue(args, &day);
  DCHECK(res);

  // Set our query options.
  history::QueryOptions options;
  options.begin_time = base::Time::Now().LocalMidnight();
  options.begin_time -= base::TimeDelta::FromDays(day);
  options.end_time = base::Time::Now().LocalMidnight();
  options.end_time -= base::TimeDelta::FromDays(day - 1);

  // Need to remember the query string for our results.
  search_text_ = string16();

  HistoryService* hs =
      Profile::FromWebUI(web_ui())->GetHistoryService(Profile::EXPLICIT_ACCESS);
  hs->QueryHistory(search_text_,
      options,
      &cancelable_search_consumer_,
      base::Bind(&BrowsingHistoryHandler::QueryComplete,
                 base::Unretained(this)));
}

void BrowsingHistoryHandler::HandleSearchHistory(const ListValue* args) {
  // Anything in-flight is invalid.
  cancelable_search_consumer_.CancelAllRequests();

  // Get arguments (if any).
  int month = 0;
  string16 query;
  ExtractSearchHistoryArguments(args, &month, &query);

  // Set the query ranges for the given month.
  history::QueryOptions options = CreateMonthQueryOptions(month);

  // When searching, limit the number of results returned.
  options.max_count = kMaxSearchResults;

  // Need to remember the query string for our results.
  search_text_ = query;
  HistoryService* hs =
      Profile::FromWebUI(web_ui())->GetHistoryService(Profile::EXPLICIT_ACCESS);
  hs->QueryHistory(search_text_,
      options,
      &cancelable_search_consumer_,
      base::Bind(&BrowsingHistoryHandler::QueryComplete,
                 base::Unretained(this)));
}

void BrowsingHistoryHandler::HandleRemoveURLsOnOneDay(const ListValue* args) {
  if (cancelable_delete_consumer_.HasPendingRequests()) {
    web_ui()->CallJavascriptFunction("deleteFailed");
    return;
  }

  // Get day to delete data from.
  int visit_time = 0;
  if (!ExtractIntegerValue(args, &visit_time)) {
    LOG(ERROR) << "Unable to extract integer argument.";
    web_ui()->CallJavascriptFunction("deleteFailed");
    return;
  }
  base::Time::Exploded exploded;
  base::Time::FromTimeT(
      static_cast<time_t>(visit_time)).LocalExplode(&exploded);
  exploded.hour = exploded.minute = exploded.second = exploded.millisecond = 0;
  base::Time begin_time = base::Time::FromLocalExploded(exploded);
  base::Time end_time = begin_time + base::TimeDelta::FromDays(1);

  // Get URLs.
  DCHECK(urls_to_be_deleted_.empty());
  for (ListValue::const_iterator v = args->begin() + 1;
       v != args->end(); ++v) {
    if ((*v)->GetType() != Value::TYPE_STRING)
      continue;
    const StringValue* string_value = static_cast<const StringValue*>(*v);
    string16 string16_value;
    if (!string_value->GetAsString(&string16_value))
      continue;

    urls_to_be_deleted_.insert(GURL(string16_value));
  }

  HistoryService* hs =
      Profile::FromWebUI(web_ui())->GetHistoryService(Profile::EXPLICIT_ACCESS);
  hs->ExpireHistoryBetween(
      urls_to_be_deleted_, begin_time, end_time, &cancelable_delete_consumer_,
      base::Bind(&BrowsingHistoryHandler::RemoveComplete,
                 base::Unretained(this)));
}

void BrowsingHistoryHandler::HandleClearBrowsingData(const ListValue* args) {
#if defined(OS_ANDROID)
  NOTIMPLEMENTED() << "TODO(yfriedman): Upstream the Android version.";
#else
  // TODO(beng): This is an improper direct dependency on Browser. Route this
  // through some sort of delegate.
  Profile* profile = Profile::FromWebUI(web_ui());
  Browser* browser = BrowserList::FindBrowserWithProfile(profile);
  if (browser)
    browser->OpenClearBrowsingDataDialog();
#endif
}

void BrowsingHistoryHandler::QueryComplete(
    HistoryService::Handle request_handle,
    history::QueryResults* results) {

  ListValue results_value;
  base::Time midnight_today = base::Time::Now().LocalMidnight();

  for (size_t i = 0; i < results->size(); ++i) {
    history::URLResult const &page = (*results)[i];
    DictionaryValue* page_value = new DictionaryValue();
    SetURLAndTitle(page_value, page.title(), page.url());

    // Need to pass the time in epoch time (fastest JS conversion).
    page_value->SetInteger("time",
        static_cast<int>(page.visit_time().ToTimeT()));

    // Until we get some JS i18n infrastructure, we also need to
    // pass the dates in as strings. This could use some
    // optimization.

    // Only pass in the strings we need (search results need a shortdate
    // and snippet, browse results need day and time information).
    if (search_text_.empty()) {
      // Figure out the relative date string.
      string16 date_str = TimeFormat::RelativeDate(page.visit_time(),
                                                   &midnight_today);
      if (date_str.empty()) {
        date_str = base::TimeFormatFriendlyDate(page.visit_time());
      } else {
        date_str = l10n_util::GetStringFUTF16(
            IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
            date_str,
            base::TimeFormatFriendlyDate(page.visit_time()));
      }
      page_value->SetString("dateRelativeDay", date_str);
      page_value->SetString("dateTimeOfDay",
          base::TimeFormatTimeOfDay(page.visit_time()));
    } else {
      page_value->SetString("dateShort",
          base::TimeFormatShortDate(page.visit_time()));
      page_value->SetString("snippet", page.snippet().text());
    }
    Profile* profile = Profile::FromWebUI(web_ui());
    page_value->SetBoolean("starred",
        profile->GetBookmarkModel()->IsBookmarked(page.url()));
    results_value.Append(page_value);
  }

  DictionaryValue info_value;
  info_value.SetString("term", search_text_);
  info_value.SetBoolean("finished", results->reached_beginning());

  web_ui()->CallJavascriptFunction("historyResult", info_value, results_value);
}

void BrowsingHistoryHandler::RemoveComplete() {
  urls_to_be_deleted_.clear();

  // Notify the page that the deletion request succeeded.
  web_ui()->CallJavascriptFunction("deleteComplete");
}

void BrowsingHistoryHandler::ExtractSearchHistoryArguments(
    const ListValue* args,
    int* month,
    string16* query) {
  *month = 0;
  Value* list_member;

  // Get search string.
  if (args->Get(0, &list_member) &&
      list_member->GetType() == Value::TYPE_STRING) {
    const StringValue* string_value =
      static_cast<const StringValue*>(list_member);
    string_value->GetAsString(query);
  }

  // Get search month.
  if (args->Get(1, &list_member) &&
      list_member->GetType() == Value::TYPE_STRING) {
    const StringValue* string_value =
      static_cast<const StringValue*>(list_member);
    string16 string16_value;
    if (string_value->GetAsString(&string16_value)) {
      bool converted = base::StringToInt(string16_value, month);
      DCHECK(converted);
    }
  }
}

history::QueryOptions BrowsingHistoryHandler::CreateMonthQueryOptions(
    int month) {
  history::QueryOptions options;

  // Configure the begin point of the search to the start of the
  // current month.
  base::Time::Exploded exploded;
  base::Time::Now().LocalMidnight().LocalExplode(&exploded);
  exploded.day_of_month = 1;

  if (month == 0) {
    options.begin_time = base::Time::FromLocalExploded(exploded);

    // Set the end time of this first search to null (which will
    // show results from the future, should the user's clock have
    // been set incorrectly).
    options.end_time = base::Time();
  } else {
    // Set the end-time of this search to the end of the month that is
    // |depth| months before the search end point. The end time is not
    // inclusive, so we should feel free to set it to midnight on the
    // first day of the following month.
    exploded.month -= month - 1;
    while (exploded.month < 1) {
      exploded.month += 12;
      exploded.year--;
    }
    options.end_time = base::Time::FromLocalExploded(exploded);

    // Set the begin-time of the search to the start of the month
    // that is |depth| months prior to search_start_.
    if (exploded.month > 1) {
      exploded.month--;
    } else {
      exploded.month = 12;
      exploded.year--;
    }
    options.begin_time = base::Time::FromLocalExploded(exploded);
  }

  return options;
}

void BrowsingHistoryHandler::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  if (type != chrome::NOTIFICATION_HISTORY_URLS_DELETED) {
    NOTREACHED();
    return;
  }
  history::URLsDeletedDetails* deletedDetails =
      content::Details<history::URLsDeletedDetails>(details).ptr();
  if (deletedDetails->urls != urls_to_be_deleted_ ||
      deletedDetails->all_history) {
    // Notify the page that someone else deleted from the history.
    web_ui()->CallJavascriptFunction("historyDeleted");
  }
}

////////////////////////////////////////////////////////////////////////////////
//
// HistoryUI
//
////////////////////////////////////////////////////////////////////////////////

HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  web_ui->AddMessageHandler(new BrowsingHistoryHandler());

  HistoryUIHTMLSource* html_source = new HistoryUIHTMLSource();

  // Set up the chrome://history-frame/ source.
  Profile* profile = Profile::FromWebUI(web_ui);
  profile->GetChromeURLDataManager()->AddDataSource(html_source);
}

// static
const GURL HistoryUI::GetHistoryURLWithSearchText(const string16& text) {
  return GURL(std::string(chrome::kChromeUIHistoryURL) + "#q=" +
              net::EscapeQueryParamValue(UTF16ToUTF8(text), true));
}

// static
RefCountedMemory* HistoryUI::GetFaviconResourceBytes() {
  return ResourceBundle::GetSharedInstance().
      LoadDataResourceBytes(IDR_HISTORY_FAVICON);
}


text:
> TODO: description

## Usage

```
const ttsLib = require('tts-lib');

// TODO: DEMONSTRATE API
```


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../../../../favicon.ico" />
<title>AbortableHttpRequest - Android SDK | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  android

  android.accessibilityservice

  android.accounts

  android.animation

  android.app

  android.app.admin

  android.app.backup

  android.appwidget

  android.bluetooth

  android.content

  android.content.pm

  android.content.res

  android.database

  android.database.sqlite

  android.drm

  android.gesture

  android.graphics

  android.graphics.drawable

  android.graphics.drawable.shapes

  android.graphics.pdf

  android.hardware

  android.hardware.display

  android.hardware.input

  android.hardware.location

  android.hardware.usb

  android.inputmethodservice

  android.location

  android.media

  android.media.audiofx

  android.media.effect

  android.mtp

  android.net

  android.net.http

  android.net.nsd

  android.net.rtp

  android.net.sip

  android.net.wifi

  android.net.wifi.p2p

  android.net.wifi.p2p.nsd

  android.nfc

  android.nfc.cardemulation

  android.nfc.tech

  android.opengl

  android.os

  android.os.storage

  android.preference

  android.print

  android.print.pdf

  android.printservice

  android.provider

  android.renderscript

  android.sax

  android.security

  android.service.dreams

  android.service.notification

  android.service.textservice

  android.service.wallpaper

  android.speech

  android.speech.tts

  android.support.v13.app

  android.support.v4.accessibilityservice

  android.support.v4.app

  android.support.v4.content

  android.support.v4.content.pm

  android.support.v4.database

  android.support.v4.graphics.drawable

  android.support.v4.hardware.display

  android.support.v4.media

  android.support.v4.net

  android.support.v4.os

  android.support.v4.print

  android.support.v4.text

  android.support.v4.util

  android.support.v4.view

  android.support.v4.view.accessibility

  android.support.v4.widget

  android.support.v7.app

  android.support.v7.appcompat

  android.support.v7.gridlayout

  android.support.v7.media

  android.support.v7.mediarouter

  android.support.v7.view

  android.support.v7.widget

  android.support.v8.renderscript

  android.telephony

  android.telephony.cdma

  android.telephony.gsm

  android.test

  android.test.mock

  android.test.suitebuilder

  android.text

  android.text.format

  android.text.method

  android.text.style

  android.text.util

  android.transition

  android.util

  android.view

  android.view.accessibility

  android.view.animation

  android.view.inputmethod

  android.view.textservice

  android.webkit

  android.widget

  dalvik.bytecode

  dalvik.system

  java.awt.font

  java.beans

  java.io

  java.lang

  java.lang.annotation

  java.lang.ref

  java.lang.reflect

  java.math

  java.net

  java.nio

  java.nio.channels

  java.nio.channels.spi

  java.nio.charset

  java.nio.charset.spi

  java.security

  java.security.acl

  java.security.cert

  java.security.interfaces

  java.security.spec

  java.sql

  java.text

  java.util

  java.util.concurrent

  java.util.concurrent.atomic

  java.util.concurrent.locks

  java.util.jar

  java.util.logging

  java.util.prefs

  java.util.regex

  java.util.zip

  javax.crypto

  javax.crypto.interfaces

  javax.crypto.spec

  javax.microedition.khronos.egl

  javax.microedition.khronos.opengles

  javax.net

  javax.net.ssl

  javax.security.auth

  javax.security.auth.callback

  javax.security.auth.login

  javax.security.auth.x500

  javax.security.cert

  javax.sql

  javax.xml

  javax.xml.datatype

  javax.xml.namespace

  javax.xml.parsers

  javax.xml.transform

  javax.xml.transform.dom

  javax.xml.transform.sax

  javax.xml.transform.stream

  javax.xml.validation

  javax.xml.xpath

  junit.framework

  junit.runner

  org.apache.http

  org.apache.http.auth

  org.apache.http.auth.params

  org.apache.http.client

  org.apache.http.client.entity

  org.apache.http.client.methods

  org.apache.http.client.params

  org.apache.http.client.protocol

  org.apache.http.client.utils

  org.apache.http.conn

  org.apache.http.conn.params

  org.apache.http.conn.routing

  org.apache.http.conn.scheme

  org.apache.http.conn.ssl

  org.apache.http.conn.util

  org.apache.http.cookie

  org.apache.http.cookie.params

  org.apache.http.entity

  org.apache.http.impl

  org.apache.http.impl.auth

  org.apache.http.impl.client

  org.apache.http.impl.conn

  org.apache.http.impl.conn.tsccm

  org.apache.http.impl.cookie

  org.apache.http.impl.entity

  org.apache.http.impl.io

  org.apache.http.io

  org.apache.http.message

  org.apache.http.params

  org.apache.http.protocol

  org.apache.http.util

  org.json

  org.w3c.dom

  org.w3c.dom.ls

  org.xml.sax

  org.xml.sax.ext

  org.xml.sax.helpers

  org.xmlpull.v1

  org.xmlpull.v1.sax2

Interfaces

AbortableHttpRequest

HttpUriRequest

Classes

HttpDelete

HttpEntityEnclosingRequestBase

HttpGet

HttpHead

HttpOptions

HttpPost

HttpPut

HttpRequestBase

HttpTrace

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Methods

| [Expand All]

  Added in API level 1

    public

    interface

AbortableHttpRequest

        org.apache.http.client.methods.AbortableHttpRequest

  Known Indirect Subclasses

              HttpDelete,

              HttpEntityEnclosingRequestBase,

              HttpGet,

              HttpHead,

              HttpOptions,

              HttpPost,

              HttpPut,

              HttpRequestBase,

              HttpTrace

              HttpDelete
              HTTP DELETE method

 The HTTP DELETE method is defined in section 9.7 of
 RFC2616:

 The DELETE method requests that the origin server delete the resource
 identified by the Request-URI.

              HttpEntityEnclosingRequestBase
              Basic implementation of an HTTP request that can be modified.

              HttpGet
              HTTP GET method.

              HttpHead
              HTTP HEAD method.

              HttpOptions
              HTTP OPTIONS method.

              HttpPost
              HTTP POST method.

              HttpPut
              HTTP PUT method.

              HttpRequestBase
              Basic implementation of an HTTP request that can be modified.

              HttpTrace
              HTTP TRACE method.

Class Overview

Interface representing an HTTP request that can be aborted by shutting
 down the underlying HTTP connection.

Summary

Public Methods

        <nobr>
            abstract

            void</nobr>

        <nobr>
        abort()</nobr>

Aborts this http request.

        <nobr>
            abstract

            void</nobr>

        <nobr>
        setConnectionRequest(ClientConnectionRequest connRequest)</nobr>

Sets the ClientConnectionRequest callback that can be
 used to abort a long-lived request for a connection.

        <nobr>
            abstract

            void</nobr>

        <nobr>
        setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger)</nobr>

Sets the ConnectionReleaseTrigger callback that can
 be used to abort an active connection.

Public Methods

        public

        abstract

        void

      abort
      ()

  Added in API level 1

Aborts this http request. Any active execution of this method should
 return immediately. If the request has not started, it will abort after
 the next execution. Aborting this request will cause all subsequent
 executions with this request to fail.

See Also

execute(HttpUriRequest)

execute(org.apache.http.HttpHost, org.apache.http.HttpRequest)

execute(HttpUriRequest, org.apache.http.protocol.HttpContext)

execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext)

        public

        abstract

        void

      setConnectionRequest
      (ClientConnectionRequest connRequest)

  Added in API level 1

Sets the ClientConnectionRequest callback that can be
 used to abort a long-lived request for a connection.
 If the request is already aborted, throws an IOException.

Throws

            IOException

See Also

ClientConnectionManager

ThreadSafeClientConnManager

        public

        abstract

        void

      setReleaseTrigger
      (ConnectionReleaseTrigger releaseTrigger)

  Added in API level 1

Sets the ConnectionReleaseTrigger callback that can
 be used to abort an active connection.
 Typically, this will be the ManagedClientConnection itself.
 If the request is already aborted, throws an IOException.

Throws

            IOException

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android 4.4 r1 —

    About Android  |
    Legal  |
    Support


text:
package com.koch.ambeth.security.privilege.model.impl;

import com.koch.ambeth.security.privilege.model.IPrivilege;
import com.koch.ambeth.security.privilege.model.IPropertyPrivilege;

public final class AllowAllPrivilege extends AbstractPrivilege {
	private static final long serialVersionUID = -7998560841747295166L;

	public static final IPrivilege INSTANCE = new AllowAllPrivilege();

	private static final IPropertyPrivilege allowAllPropertyPrivilege = PropertyPrivilegeImpl
			.create(true, true, true, true);

	private AllowAllPrivilege() {
		super(true, true, true, true, true, null, null);
	}

	@Override
	public IPropertyPrivilege getDefaultPropertyPrivilegeIfValid() {
		return allowAllPropertyPrivilege;
	}

	@Override
	public IPropertyPrivilege getPrimitivePropertyPrivilege(int primitiveIndex) {
		return allowAllPropertyPrivilege;
	}

	@Override
	public IPropertyPrivilege getRelationPropertyPrivilege(int relationIndex) {
		return allowAllPropertyPrivilege;
	}

	@Override
	public boolean isCreateAllowed() {
		return true;
	}

	@Override
	public boolean isReadAllowed() {
		return true;
	}

	@Override
	public boolean isUpdateAllowed() {
		return true;
	}

	@Override
	public boolean isDeleteAllowed() {
		return true;
	}

	@Override
	public boolean isExecuteAllowed() {
		return true;
	}
}


text:
namespace Apache.Ignite.Core.Tests.Deployment
{
    using System;
    using System.CodeDom.Compiler;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;
    using Apache.Ignite.Core.Deployment;
    using Apache.Ignite.Core.Discovery.Tcp;
    using Apache.Ignite.Core.Discovery.Tcp.Static;
    using NUnit.Framework;

    /// <summary>
    /// Tests assembly versioning: multiple assemblies with same name but different version should be supported.
    /// </summary>
    public class PeerAssemblyLoadingVersioningTest
    {
        private static readonly string TempDir = PathUtils.GetTempDirectoryName();

        /// <summary>
        /// Sets up the test.
        /// </summary>
        [SetUp]
        public void SetUp()
        {
            // Copy referenced assemblies.
            foreach (var type in new[] { typeof(Ignition), GetType() })
            {
                var loc = type.Assembly.Location;
                Assert.IsNotNull(loc);
                File.Copy(loc, Path.Combine(TempDir, type.Assembly.GetName().Name + ".dll"));
            }
        }

        /// <summary>
        /// Tears down the test.
        /// </summary>
        [TearDown]
        public void TearDown()
        {
            Directory.Delete(TempDir, true);
        }

        /// <summary>
        /// Tests that multiple versions of same assembly can be used on remote nodes.
        /// </summary>
        [Test]
        public void TestMultipleVersionsOfSameAssembly()
        {
            using (Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain,
                IgniteInstanceName = "peerDeployTest",
                DiscoverySpi = new TcpDiscoverySpi
                {
                    IpFinder = new TcpDiscoveryStaticIpFinder {Endpoints = new[] {"127.0.0.1:47500..47502"}},
                    SocketTimeout = TimeSpan.FromSeconds(0.3)
                }
            }))
            {
                RunClientProcess(CompileClientNode(Path.Combine(TempDir, "PeerTest.exe"), "1.0.1.0"));
                RunClientProcess(CompileClientNode(Path.Combine(TempDir, "PeerTest.exe"), "1.0.2.0"));
            }
        }

        /// <summary>
        /// Runs the client process.
        /// </summary>
        private static void RunClientProcess(string exePath)
        {
            var procStart = new ProcessStartInfo
            {
                FileName = exePath,
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
            };

            var proc = Process.Start(procStart);
            Assert.IsNotNull(proc);

            proc.AttachProcessConsoleReader();

            Assert.IsTrue(proc.WaitForExit(30000));
            Assert.AreEqual(0, proc.ExitCode);

            File.Delete(exePath);
        }

        /// <summary>
        /// Compiles the client node.
        /// </summary>
        private string CompileClientNode(string exePath, string version)
        {
            var netstandard = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");

            var parameters = new CompilerParameters
            {
                GenerateExecutable = true,
                OutputAssembly = exePath,
                ReferencedAssemblies =
                {
                    typeof(Ignition).Assembly.Location,
                    GetType().Assembly.Location,
                    "System.dll",
                    netstandard.Location
                }
            };

            var src = @"
using System;
using System.Reflection;

using Apache.Ignite.Core;
using Apache.Ignite.Core.Deployment;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Tests;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;

[assembly: AssemblyVersion(""" + version + @""")]

class Program
{
    static void Main(string[] args)
    {
        using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration(false, null, true)) {ClientMode = true, PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain,
                DiscoverySpi = new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { ""127.0.0.1:47500..47502"" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }
}))
        {
            var res = ignite.GetCompute().Call(new GridNameFunc());
            if (res != ""peerDeployTest_" + version + @""") throw new Exception(""fail: "" + res);
        }
    }
}

public class GridNameFunc : IComputeFunc<string> { public string Invoke() { return Ignition.GetIgnite().Name + ""_"" + GetType().Assembly.GetName().Version; } }
";

            var results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, src);

            Assert.IsEmpty(results.Errors);

            return exePath;
        }
    }
}


text:
(function () {
    'use strict';

    angular.module('dynamicCharts').config(function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise("/inputs");

        $stateProvider
            .state('inputs', {
                url: "/inputs",
                templateUrl: "app/inputs/inputs-main.html"
            });

    });

})();


text:
/* Authors: Darby Lim, Hye-Jong KIM, Ryan Shim, Yong-Ho Na */

#include "../include/planar_libs/planar_kinematics.h"

using namespace robotis_manipulator;
using namespace planar_kinematics;

/*****************************************************************************
** Kinematics Solver
*****************************************************************************/
void SolverUsingGeometry::setOption(const void *arg) {}

Eigen::MatrixXd SolverUsingGeometry::jacobian(Manipulator *manipulator, Name tool_name)
{
  return Eigen::MatrixXd::Identity(6, manipulator->getDOF());
}

void SolverUsingGeometry::solveForwardKinematics(Manipulator *manipulator) {}

bool SolverUsingGeometry::solveInverseKinematics(Manipulator *manipulator, Name tool_name, Pose target_pose, std::vector<JointValue> *goal_joint_value)
{
  return inverseKinematicsSolverUsingGeometry(manipulator, tool_name, target_pose, goal_joint_value);
}

/*****************************************************************************
** Private
*****************************************************************************/
bool SolverUsingGeometry::inverseKinematicsSolverUsingGeometry(Manipulator *manipulator, Name tool_name, Pose target_pose, std::vector<JointValue>* goal_joint_value)
{
  const double link[3] = {0.120, 0.098, 0.0366};
  JointValue target_angle[7];
  std::vector<JointValue> target_angle_vector;
  double start_x[3], start_y[3];
  double temp_x[3], temp_y[3];
  double goal_x[3], goal_y[3];
  double diff_x[3], diff_y[3];
  Matrix3d goal_orientation;
  double target_pose_length[3];
  double alpha[3];
  double temp_diff[3];

  // Start pose for each set of two joints
  for (uint8_t i=0; i<3; i++)
  {
    start_x[i] = cos(PI*2.0/3.0*i)*(-0.1705);
    start_y[i] = sin(PI*2.0/3.0*i)*(-0.1705);
  }

  // Goal pose for each set of two joints after tool rotation
  for (uint8_t i=0; i<3; i++){
    temp_x[i] = target_pose.kinematic.position(0) + cos(PI*2.0/3.0*i)*(-link[2]);
    temp_y[i] = target_pose.kinematic.position(1) + sin(PI*2.0/3.0*i)*(-link[2]);
  }

  goal_orientation = target_pose.kinematic.orientation;
  if (goal_orientation(0,0) || goal_orientation(0,1) || goal_orientation(0,2)
   || goal_orientation(1,0) || goal_orientation(1,1) || goal_orientation(1,2)
   || goal_orientation(2,0) || goal_orientation(2,1) || goal_orientation(2,2))
  {
    goal_orientation(0,0) = 1;
    goal_orientation(1,1) = 1;
    goal_orientation(2,2) = 1;
  }
  for (uint8_t i=0; i<3; i++)
  {
    goal_x[i] = goal_orientation(0,0)*temp_x[i] + goal_orientation(0,1)*temp_y[i];
    goal_y[i] = goal_orientation(1,0)*temp_x[i] + goal_orientation(1,1)*temp_y[i];
    diff_x[i] = goal_x[i] - start_x[i];
    diff_y[i] = goal_y[i] - start_y[i];
    target_pose_length[i] = sqrt(diff_x[i]*diff_x[i] + diff_y[i]*diff_y[i]);
  }

  // Compute the Length of Position Difference and Target Angle
  for (uint8_t i=0; i<3; i++)
  {
    alpha[i] = acos((target_pose_length[i]*target_pose_length[i] + link[0]*link[0] - link[1]*link[1])
                            / (2*target_pose_length[i]*link[0]));
    temp_diff[i] = sin(-PI*2.0/3.0*i)*diff_x[i] + cos(-PI*2.0/3.0*i)*diff_y[i];
    target_angle[i].position = acos(-temp_diff[i] / target_pose_length[i]) - alpha[i] - PI/4.0;
  }

  // Set Joint Angle
  target_angle_vector.push_back(target_angle[0]);
  target_angle_vector.push_back(target_angle[1]);
  target_angle_vector.push_back(target_angle[2]);

  for (uint8_t i=0; i<3; i++)
  {
    target_angle[i].position += PI/4.0;
    target_angle[i+3].position = acos(-(temp_diff[i] - (-link[0]*cos(target_angle[i].position))) / link[1]) - target_angle[i].position - PI*7.0/12.0;
    target_angle[i+3].position = acos((-sin(PI*2.0/3.0*i)*diff_x[i] + cos(PI*2.0/3.0*i)*diff_y[i]
                              + link[0]*cos(target_angle[i].position)) / -link[1]) - target_angle[i].position - PI*7.0/12.0;
  }

  target_angle_vector.push_back(target_angle[3]);
  target_angle_vector.push_back(target_angle[4]);
  target_angle_vector.push_back(target_angle[5]);

  target_angle[3].position += PI*7.0/12.0;

  target_angle[6].position =  PI/2.0 - target_angle[0].position - target_angle[3].position + PI/3.0;

  target_angle_vector.push_back(target_angle[6]);

  *goal_joint_value = target_angle_vector;
  manipulator->setAllJointValue(target_angle_vector);

  return true;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title ng-bind="title">Authentication Starter</title>

    <link rel="stylesheet" type="text/css" href="assets/css/font-awesome.css" />
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="assets/css/custom.css" />

    <alert-message></alert-message>


text:
// Include all libcat Graphics headers

#include <cat/AllCommon.hpp>

#include <cat/gfx/Scalar.hpp>
#include <cat/gfx/Vector.hpp>
#include <cat/gfx/Matrix.hpp>
#include <cat/gfx/Quaternion.hpp>


text:
package org.apache.axis2.addressing.wsdl;

import junit.framework.TestCase;
import org.apache.axis2.AbstractTestCase;

import javax.wsdl.Definition;
import javax.wsdl.Fault;
import javax.wsdl.Input;
import javax.wsdl.Operation;
import javax.wsdl.Output;
import javax.wsdl.PortType;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;
import java.io.File;
import java.net.URL;
import java.util.List;

public class WSDL11ActionHelperTest extends TestCase {

    String testWSDLFile = "/target/test-resources/wsdl/actionTests.wsdl";

    Definition definition;

    protected void setUp() throws Exception {
        super.setUp();
        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", false);
        reader.setFeature("javax.wsdl.verbose", false);

        URL wsdlFile = new File(AbstractTestCase.basedir + testWSDLFile)
                .toURL();//getClass().getClassLoader().getResource(testWSDLFile);
        definition = reader.readWSDL(wsdlFile.toString());
    }

    // Test DefaultActionPattern (no names in WSDL)
    // Test not required for Fault as Fault elements MUST have naes per the WSDL 1.1 spec
    //    portType=withoutWSAWActionNoName
    // operation=echo
    public void testGenerateInputActionNoNames() {
        String expectedAction =
                "http://ws.apache.org/axis2/actiontest/withoutWSAWActionNoName/echoRequest";
        PortType pt = definition.getPortType(
                new QName("http://ws.apache.org/axis2/actiontest/", "withoutWSAWActionNoName"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Input in = op.getInput();
        String actualAction = WSDL11ActionHelper.getActionFromInputElement(definition, pt, op, in);
        assertEquals(expectedAction, actualAction);
    }

    public void testGenerateOutputActionNoNames() {
        String expectedAction =
                "http://ws.apache.org/axis2/actiontest/withoutWSAWActionNoName/echoResponse";
        PortType pt = definition.getPortType(
                new QName("http://ws.apache.org/axis2/actiontest/", "withoutWSAWActionNoName"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Output out = op.getOutput();
        String actualAction =
                WSDL11ActionHelper.getActionFromOutputElement(definition, pt, op, out);
        assertEquals(expectedAction, actualAction);
    }

    // Test DefaultActionPattern (names explicitly set in WSDL)
    //    portType=withoutWSAWAction
    // operation=echo
    public void testGenerateInputAction() {
        String expectedAction =
                "http://ws.apache.org/axis2/actiontest/withoutWSAWAction/NamedInput";
        PortType pt = definition.getPortType(
                new QName("http://ws.apache.org/axis2/actiontest/", "withoutWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Input in = op.getInput();
        String actualAction = WSDL11ActionHelper.getActionFromInputElement(definition, pt, op, in);
        assertEquals(expectedAction, actualAction);
    }

    public void testGenerateOutputAction() {
        String expectedAction =
                "http://ws.apache.org/axis2/actiontest/withoutWSAWAction/NamedOutput";
        PortType pt = definition.getPortType(
                new QName("http://ws.apache.org/axis2/actiontest/", "withoutWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Output out = op.getOutput();
        String actualAction =
                WSDL11ActionHelper.getActionFromOutputElement(definition, pt, op, out);
        assertEquals(expectedAction, actualAction);
    }

    public void testGenerateFaultAction() {
        String expectedAction =
                "http://ws.apache.org/axis2/actiontest/withoutWSAWAction/echo/Fault/echoFault";
        PortType pt = definition.getPortType(
                new QName("http://ws.apache.org/axis2/actiontest/", "withoutWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Fault fault = op.getFault("echoFault");
        String actualAction =
                WSDL11ActionHelper.getActionFromFaultElement(definition, pt, op, fault);
        assertEquals(expectedAction, actualAction);
    }

    // Test reading wsaw:Action values
    // portType=withWSAWAction
    // operation=echo
    public void testGetWSAWInputAction() {
        String expectedAction = "http://example.org/action/echoIn";
        PortType pt = definition
                .getPortType(new QName("http://ws.apache.org/axis2/actiontest/", "withWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Input in = op.getInput();
        String actualAction = WSDL11ActionHelper.getActionFromInputElement(definition, pt, op, in);
        assertEquals(expectedAction, actualAction);
    }

    public void testGetWSAWOutputAction() {
        String expectedAction = "http://example.org/action/echoOut";
        PortType pt = definition
                .getPortType(new QName("http://ws.apache.org/axis2/actiontest/", "withWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Output out = op.getOutput();
        String actualAction =
                WSDL11ActionHelper.getActionFromOutputElement(definition, pt, op, out);
        assertEquals(expectedAction, actualAction);
    }

    public void testGetWSAWFaultAction() {
        String expectedAction = "http://example.org/action/echoFault";
        PortType pt = definition
                .getPortType(new QName("http://ws.apache.org/axis2/actiontest/", "withWSAWAction"));
        List operations = pt.getOperations();
        Operation op = (Operation) operations.get(0);
        Fault fault = op.getFault("echoFault");
        String actualAction =
                WSDL11ActionHelper.getActionFromFaultElement(definition, pt, op, fault);
        assertEquals(expectedAction, actualAction);
    }
}


text:
<?php

namespace Pair;

/**
 * Singleton class that allows to trace query, API calls and custom events with partial
 * and total execution times.
 */
class Logger {

	/**
	 * Singleton instance.
	 * @var Logger
	 */
	private static $instance = NULL;

	/**
	 * Start time.
	 * @var float
	 */
	private $timeStart;

	/**
	 * Time chrono of last event.
	 * @var float
	 */
	private $lastChrono;

	/**
	 * Full event list.
	 * @var \stdClass[]
	 */
	private $events = array();

	/**
	 * Flag force log disabled.
	 * @var bool
	 */
	private $disabled = FALSE;

	/**
	 * Disabled constructor.
	 */
	private function __construct() {}

	/**
	 * Singleton instance method.
	 *
	 * @return	Logger
	 */
	final public static function getInstance(): Logger {

		if (NULL == self::$instance) {
			self::$instance = new self();
			self::$instance->startChrono();
		}

		return self::$instance;

	}

	/**
	 * Shutdown the log.
	 */
	final public function disable() {

		$this->disabled = TRUE;

	}

	/**
	 * Check that logger can be collected by checking "disabled" flag, cli,
	 * API, router module and Options.
	 *
	 * @return boolean
	 */
	final public function isEnabled(): bool {

		$router = Router::getInstance();

		if ($this->disabled or 'cli' == php_sapi_name() or 'api' == $router->module
				or ('user' == $router->module and 'login' == $router->action)) {
			return FALSE;
		}

		return TRUE;

	}

	/**
	 * Check if the log can appear in the current session.
	 *
	 * @return bool
	 */
	public function canBeShown(): bool {

		// user is defined, could be admin
		if (User::current() and Options::get('show_log')) {

			// get current session
			$session = Session::current();

			// if impersonating, use the former user attribs
			if ($session->hasFormerUser()) {
				$formerUser = $session->getFormerUser();
				return ($formerUser ? $formerUser->admin : FALSE);
			}

			return (bool)User::current()->admin;

		} else {

			return FALSE;

		}

	}

	/**
	 * Starts the time chrono.
	 */
	private function startChrono() {

		$this->timeStart = $this->lastChrono = $this->getMicrotime();

		self::event('Starting Pair framework with base timezone ' . BASE_TIMEZONE);

	}

	/**
	 * Returns current time as float value.
	 *
	 * @return float
	 */
	private function getMicrotime(): float {

		list ($msec, $sec) = explode(' ', microtime());
		$time = ((float)$msec + (float)$sec);
		return $time;

	}

	/**
	 * Adds an event, storing its chrono time.
	 *
	 * @param	string	Event description.
	 * @param	string	Event type notice, query, api, warning or error (default is notice).
	 * @param	string	Optional additional text.
	 * @return	void
	 */
	final public static function event(string $description, string $type='notice', $subtext=NULL): void {

		$self = self::getInstance();

		if (!$self->isEnabled()) return;

		$now = $self->getMicrotime();

		$event				= new \stdClass();
		$event->description = $description;
		$event->type		= $type;
		$event->subtext		= $subtext;
		$event->chrono		= abs($now - $self->lastChrono);

		$self->events[]		= $event;

		$self->lastChrono	= $now;

	}

	/**
	 * AddEvent's proxy for warning event creations.
	 *
	 * @param	string	Event description.
	 */
	final public static function warning(string $description) {

		self::event($description, 'warning');

	}

	/**
	 * AddEvent's proxy for error event creations.
	 *
	 * @param	string	Event description.
	 */
	final public static function error(string $description) {

		self::event($description, 'error');

	}

	/**
	 * Adds an event, storing its chrono time.
	 *
	 * @param	string	Event description.
	 * @param	string	Event type notice, query, api, warning or error (default is notice).
	 * @param	string	Optional additional text.
	 * @return	void
	 * @deprecated		Use static method Logger::event() instead.
	 */
	final public function addEvent(string $description, string $type='notice', $subtext=NULL): void {

		self::event($description, $type, $subtext);

	}

	/**
	 * AddEvent's proxy for warning event creations.
	 *
	 * @param	string	Event description.
	 * @deprecated		Use static method Logger::warning() instead.
	 */
	final public function addWarning(string $description) {

		self::event($description, 'warning');

	}

	/**
	 * AddEvent's proxy for error event creations.
	 *
	 * @param	string	Event description.
	 * @deprecated		Use static method Logger::error() instead.
	 */
	final public function addError(string $description) {

		self::event($description, 'error');

	}

	/**
	 * Returns a formatted event list of all chrono steps.
	 *
	 * @return	string|NULL	HTML code of log list.
	 */
	final public function getEventList(): ?string {

		$app = Application::getInstance();

		if (!$this->isEnabled() or !$this->canBeShown()) {
			return NULL;
		}

		$sum			= 0;
		$log			= '';

		$apiChrono		= 0;
		$queryChrono	= 0;
		$queryCount		= 0;
		$warningCount	= 0;
		$errorCount		= 0;

		$firstError		= FALSE;
		$firstWarning	= FALSE;

		// cookie infos
		$showQueries	= isset($_COOKIE['LogShowQueries']) ? (bool)$_COOKIE['LogShowQueries'] : FALSE;
		$showEvents		= isset($_COOKIE['LogShowEvents'])  ? (bool)$_COOKIE['LogShowEvents']  : FALSE;

		// create a date in timezone of connected user
		$timeStart = new \DateTime('@' . (int)$this->timeStart, new \DateTimeZone(BASE_TIMEZONE));
		if ($app->currentUser and $app->currentUser->areKeysPopulated()) {
			$timeStart->setTimezone($app->currentUser->getDateTimeZone());
		}

		// get memory limit
		$limit = ini_get('memory_limit');

		// get number multiplier
		switch (substr($limit,-1)) {
			case 'G': case 'g': $multiplier = 1073741824;	break;
			case 'M': case 'm': $multiplier = 1048576;		break;
			case 'K': case 'k': $multiplier = 1024;			break;
			default:			$multiplier = 1;			break;
		}

		// convert string memory limit to integer
		$limit = (int)$limit * $multiplier;

		// get current usage and percentual ratio
		$ratio = memory_get_usage() / $limit * 100;

		// alert about risk of "out of memory"
		if (($ratio) > 60) {
			self::warning('Memory usage is ' . round($ratio,0) . '% of limit, will reduce logs');
		}

		foreach ($this->events as $e) {

			// update ratio with current memory usage
			$ratio = memory_get_usage() / $limit * 100;

			// prevent out memory errors by adding just warnings and errors
			if ($ratio > 60 and !in_array($e->type, ['warning','error'])) {
				continue;
			}

			$eventDomId = '';

			switch ($e->type) {

				// external API-call counters
				case 'api':
					$apiChrono += $e->chrono;
					break;

				// SQL queries counters
				case 'query':
					$queryCount++;
					$queryChrono += $e->chrono;
					break;

				// warning counter
				case 'warning':
					$warningCount++;
					if (!$firstWarning) {
						$eventDomId = 'id="logFirstWarning" ';
						$firstWarning = TRUE;
					}
					break;

				// error counter
				case 'error':
					$errorCount++;
					if (!$firstError) {
						$eventDomId = 'id="logFirstError" ';
						$firstError = TRUE;
					}
					break;

			}

			// if it's query, verifies cookie val
			$class = $e->type . (('query'==$e->type and !$showQueries) ? ' hidden' : '');

			$log .=
				'
' .
				'chrono>1 ? ' slow' : '') . '">' . $this->formatChrono($e->chrono) . ' ' .
				htmlspecialchars($e->description) .
				($e->subtext ? ' | ' . htmlspecialchars($e->subtext) . '' : '') . '
';

			$sum += $e->chrono;

		}

		// log header
		$ret = '
';
		$ret.= '
';

		// log date
		$ret.= '
' . $timeStart->format('Y-m-d H:i:s') . '
';

		// external api
		$ret.= $apiChrono ? '
API ' . $this->formatChrono($apiChrono) . '
' : '';

		// database
		$ret.= '

' . $queryCount .' queries
(' . $this->formatChrono($queryChrono) .')

';

		// total time
		$ret.= '
' . $this->formatChrono($sum) .' total
';

		// memory peak
		$ret.= '
' . floor(memory_get_peak_usage()/1024/1024) . ' MB memory
';

		// warnings
		if ($warningCount) {
			$ret.= '' . $warningCount . ' ' . ($warningCount>1 ? 'warnings' : 'warning') . '';
		}

		// errors
		if ($errorCount) {
			$ret.= '' . $errorCount . ' ' . ($errorCount>1 ? 'errors' : 'error') . '';
		}

		// show/hide log button
		if ($showEvents) {
			$ret.= '
Hide
';
		} else {
			$ret.= '
Show
';
		}

		$ret.= '
';

		// log content
		$ret.= '
' . $log . '

';

		return $ret;

	}

	/**
	 * Returns a formatted event list with no header, useful for AJAX purpose.
	 *
	 * @return	string|NULL	HTML code of log list.
	 */
	final public function getEventListForAjax(): ?string {

		$app	= Application::getInstance();
		$router	= Router::getInstance();

		if (!$this->isEnabled() or !$this->canBeShown() or !$router->sendLog()) {
			return NULL;
		}

		$log = '';

		// shows the log
		if (Options::get('show_log') and $app->currentUser->admin) {

			$showQueries = isset($_COOKIE['LogShowQueries']) ? $_COOKIE['LogShowQueries'] : 0;

			foreach ($this->events as $e) {

				// if it's query, verifies cookie val
				$class = $e->type . (('query'==$e->type and !$showQueries) ? ' hidden' : '');

				$log .=
					'
' .
					$this->formatChrono($e->chrono) . ' ' . htmlspecialchars($e->description) .
					($e->subtext ? ' | ' . htmlspecialchars($e->subtext) . '' : '') . '
';

			}

		}

		return $log;

	}

	/**
	 * Choose if use sec or millisec based on amount of time to show (for instance 1.23 s or 345 ms).
	 *
	 * @param	float	Time value to show (in seconds).
	 * @return	string
	 */
	private function formatChrono($chrono): string {

		return ($chrono >= 1) ? round($chrono, 2).' s' : round($chrono*1000) .' ms';

	}

	/**
	 * Returns count of registered error.
	 *
	 * @return	int
	 */
	final public function getErrorCount(): int {

		$count = 0;

		foreach ($this->events as $e) {
			if ('error' == $e->type) $count++;
		}

		return $count;

	}

	/**
	 * Reset events and start chrono again.
	 */
	final public function reset() {

		$this->events = array();
		$this->startChrono();

	}

}


text:
<html>
<head>
    <meta charset="utf-8">
    <title>Gun shoot effect</title>
    <meta name="viewport" content="initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <link href='http://fonts.googleapis.com/css?family=Lato:700|Oswald:400' rel='stylesheet' type='text/css'>
    <style>
        html, body {
            position: absolute;
            width: 100%;
            height: 100%;
            margin: 0 0;
            overflow: hidden;
            background-color: #000;
            font-family: 'Oswald', sans-serif;
            color: #fff;
        }
        ::selection {
          background: transparent;
        }
        ::-moz-selection {
          background: transparent;
        }
        a {
            color: #ff5f5f;
        }
    </style>
</head>

<body>
    <script src="js/dat.gui.js"></script>
    <script src="js/speakUtils.js"></script>
    <script src="js/pixi.js"></script>
    <script src="js/TweenMax.js"></script>

    <script id="shader-fs" type="x-shader/x-fragment">

        precision mediump float;

        varying vec2 vTextureCoord;
        uniform sampler2D uSampler;

        // new texture sampler2D
        uniform sampler2D uOverlay;

        uniform float uAnimation;

        #define PI 3.1415926535

        float rand(vec2 co){
            return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
        }

        void main(void) {

            // assign the the pixel color values to 2 vec4 variables
            vec4 diffuse = texture2D(uSampler, vTextureCoord);
            vec4 overlay = texture2D(uOverlay, vTextureCoord);

            // use mix() which is lerp() in GLSL to interpolate the colors
            vec4 color = mix(diffuse, overlay, uAnimation);

            // output the color
            gl_FragColor = color;

        }
    </script>

    <script>

        var config = {
            animation: 0
        };

        var windowWidth;
        var windowHeight;

        var stats;
        var resources;

        var renderer;
        var stage;

        var sprite;
        var uniforms;

        // assign the fragment shader script text above to the variable fs
        var fs = document.getElementById('shader-fs').textContent;

        // variable to store the scale ratio
        var spriteScale;

        var gui;

        var isPreloaded = false;

        function init() {

            gui = new dat.GUI();

            // add a gui control animation range from 0 to 1
            gui.add(config, 'animation', 0, 1).listen();

            renderer = new PIXI.WebGLRenderer(1, 1);
            stage = stage = new PIXI.Container();
            document.body.appendChild(renderer.view);

            sprite = new PIXI.Sprite(new PIXI.Texture(new PIXI.BaseTexture(resources.base)));

            // add a new PIXI texture with the overlay image
            var overlayTexture = new PIXI.Texture(new PIXI.BaseTexture(resources.overlay));

            // assign a custom shader to the sprite
            sprite.shader = new PIXI.AbstractFilter(null, fs, uniforms = {

                // add the texture to the uniform
                uOverlay: { type: 'sampler2D', value: overlayTexture },

                // add a new uniform for animation
                uAnimation: { type: '1f', value: 0 }
            });

            // set Anchor to the center of the sprite
            sprite.anchor.set(0.5, 0.5);

            stage.addChild(sprite);

            window.onresize = onResize;
            onResize();

            loop();

        }

        function onResize() {
            windowWidth = window.innerWidth;
            windowHeight = window.innerHeight;
            renderer.resize(windowWidth, windowHeight);

            // use the "cover scale" as scale ratio
            spriteScale = Math.max( windowWidth / 1920, windowHeight / 1080);

            // update the sprite scaling
            sprite.scale.set(spriteScale, spriteScale);

            // set the position(anchor) to the screen center
            sprite.position.x = windowWidth / 2;
            sprite.position.y = windowHeight / 2;

            render();
        }

        function loop() {
            requestAnimationFrame(loop);
            render();
        }

        function render() {

            // assign the animation value in the GUI control to the uniform
            uniforms.uAnimation.value = config.animation;

            renderer.render(stage);
        }

        function preload() {
            speakUtils.preload([
                {id: 'base', url: 'images/gun_base.jpg', type: 'image'},
                {id: 'overlay', url: 'images/gun_overlay.jpg', type: 'image'}
            ], function(percent, items) {
                resources = resources || items.contents;
                if(percent == 1 && !isPreloaded) {
                    isPreloaded = true;
                    init();
                }
            });
        }
        preload();

    </script>
</body>
</html>


text:
'use strict';

var chai   = require('chai');
var expect = chai.expect;

var errors = require('lib/common/errors');

var AVFSError = require('lib/common/avfs-error');

describe('common/errors', function () {

  describe('createError()', function () {

    it('should create an error with message and data', function () {
      var error = errors.createError('Fake error', {
        test: true,
        text: 'test'
      });

      expect(error).to.be.an('error');
      expect(error.message).to.equal('Fake error');
      expect(error).to.include.keys(['test', 'text']);
      expect(error.test).to.equal(true);
      expect(error.text).to.equal('test');
    });

  });

  describe('nullCheck()', function () {

    it('should return undefined with valid string', function () {
      expect(errors.nullCheck('test')).to.be.an('undefined');
    });

    it('should throw path:null error with null bytes in string', function () {
      expect(errors.nullCheck.bind(null, '\u0000')).to.throw(AVFSError).with.property('code', 'path:null');
    });

  });

});


text:
#ifndef __itkGroupSpatialObject_h
#define __itkGroupSpatialObject_h

#include <list>

#include "itkSpatialObject.h"

namespace itk
{
/**
 * \class GroupSpatialObject
 * \brief Representation of a group based on the spatial object classes.
 *
 * A GroupSpatialObject represents a group by serving as the parent of
 * the elements of the group.  Since any itk::SpatialObject can have
 * children (see SpatialObject::GetChildren()), this class needs no
 * additional methods.
 * \ingroup ITK-SpatialObjects
 */

template< unsigned int TDimension = 3 >
class ITK_EXPORT GroupSpatialObject:
  public SpatialObject< TDimension >
{
public:

  typedef GroupSpatialObject                      Self;
  typedef SpatialObject< TDimension >             Superclass;
  typedef SmartPointer< Self >                    Pointer;
  typedef SmartPointer< const Self >              ConstPointer;
  typedef double                                  ScalarType;
  typedef typename Superclass::TreeNodeType       TreeNodeType;
  typedef typename TreeNodeType::ChildrenListType TreeNodeChildrenListType;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Method for creation through the object factory. */
  itkTypeMacro(GroupSpatialObject, SpatialObject);

  /**  */
  bool ComputeLocalBoundingBox() const { return false; }
protected:
  GroupSpatialObject(const Self &); //purposely not implemented
  void operator=(const Self &);     //purposely not implemented

  GroupSpatialObject();
  virtual ~GroupSpatialObject();

  /** Method to print the object.*/
  virtual void PrintSelf(std::ostream & os, Indent indent) const;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkGroupSpatialObject.txx"
#endif

#endif // __itkGroupSpatialObject_h


text:
<?php

function newmember_content(&$a) {

	$o = '
' . t('Welcome to Friendica') . '
';

	$o .= '
' . t('New Member Checklist') . '
';

	$o .= '
';

	$o .= t('We would like to offer some tips and links to help make your experience enjoyable. Click any item to visit the relevant page.');

	$o .= '
';

	$o .= '
' . '' . t('On your Settings page -  change your initial password. Also make a note of your Identity Address. This will be useful in making friends.') . '
' . EOL;

	$o .= '
' . '' . t('Review the other settings, particularly the privacy settings. An unpublished directory listing is like having an unlisted phone number. In general, you should probably publish your listing - unless all of your friends and potential friends know exactly how to find you.') . '
' . EOL;

	$o .= '
' . '' . t('Upload a profile photo if you have not done so already. Studies have shown that people with real photos of themselves are ten times more likely to make friends than people who do not.') . '
' . EOL;

	if(in_array('facebook', $a->plugins))
		$o .= '
' . '' . t("Authorise the Facebook Connector if you currently have a Facebook account and we will \x28optionally\x29 import all your Facebook friends and conversations.") . '
' . EOL;

    $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);

	if(! $mail_disabled)
		$o .= '
' . '' .  t('Enter your email access information on your Connector Settings page if you wish to import and interact with friends or mailing lists from your email INBOX') . '
' . EOL;

	$o .= '
' . '' . t('Edit your default profile to your liking. Review the settings for hiding your list of friends and hiding the profile from unknown visitors.') . '
' . EOL;

	$o .= '
' . '' . t('Set some public keywords for your default profile which describe your interests. We may be able to find other people with similar interests and suggest friendships.') . '
' . EOL;

	$o .= '
' . '' . t('Your Contacts page is your gateway to managing friendships and connecting with friends on other networks. Typically you enter their address or site URL in the Add New Contact dialog.') . '
' . EOL;

	$o .= '
' . '' . t('The Directory page lets you find other people in this network or other federated sites. Look for a Connect or Follow link on their profile page. Provide your own Identity Address if requested.') . '
' . EOL;

	$o .= '
' . '' . t('Once you have made some friends, organize them into private conversation groups from the sidebar of your Contacts page and then you can interact with each group privately on your Network page.') . '
' . EOL;

	$o .= '
' . '' . t('Our help pages may be consulted for detail on other program features and resources.') . '
' . EOL;

	$o .= '
';

	return $o;
}


text:
var gumHelper = window.GumHelper;

var buttonStart = document.getElementById('start');
var buttonStartWithTimeout = document.getElementById('startWithTimeout');
var buttonStop = document.getElementById('stop');
var videoContainer = document.getElementById('videoContainer');

buttonStart.addEventListener('click', startStreaming, false);
buttonStartWithTimeout.addEventListener('click', startStreamingWithTimeout, false);
buttonStop.addEventListener('click', stopStreaming, false);

if(navigator.getMedia) {

    buttonStart.disabled = false;

    startStreaming();

} else {

    window.alert('For some reason it looks like your browser does not support getUserMedia');

}

function onStreamingStarted(err, videoElement) {

    if(err) {

        window.alert(err.message);

    } else {

        videoContainer.appendChild(videoElement);
        buttonStart.disabled = true;
        buttonStartWithTimeout.disabled = true;
        buttonStop.disabled = false;

    }

}

function startStreaming() {

    gumHelper.startVideoStreaming(function(err, stream, videoElement, width, height) {

        onStreamingStarted(err, videoElement);

    });

}

function startStreamingWithTimeout() {

    gumHelper.startVideoStreaming(function(err, stream, videoElement, width, height) {

        onStreamingStarted(err, videoElement);

    }, { timeout: 15000 });

}

function stopStreaming() {

    videoContainer.innerHTML = '';
    gumHelper.stopVideoStreaming();

    buttonStart.disabled = false;
    buttonStartWithTimeout.disabled = false;
    buttonStop.disabled = true;

}