text:
.. _example-traffic-lights:

================================
Traffic Lights at Intersection
================================

The System
=============

In this tutorial example we will model traffic lights at an intersection. We will simplify the problem as follows:

* There is only one intersection of "North-South" street and "East-West" street.
* Vehicles do not make turns at the intersection. They continue in their original direction, if the traffic light is green.
* The traffic light itself has two states: Red and Green.
* The vehicles arrive at the intersection as poisson process. That is, the interval between two successive vehicles is exponentially distributed. The four directions are considered as Identical Independent Distributions (IID).

**Simulation Objectives**. The parameters to our simplified system are: (a) the time that the light remains green, and (b) the rate at which vehicles arrive. Given these two, we would like to know:

* What is average duration that vehicles have to wait at the intersection?
* What is the average number of vehicles that are waiting at the intersection?

Modeling with SIM.JS
=====================

We will model the traffic lights as :ref:`events-events`. We will have two events, one for the North-South street and another for the East-West Street.

We will model the traffic as **one** :ref:`entity-entity`, that will generate *requests* to cross the intersection. This entity will generate four exponential IID requests (for the vehicles in four directions).

We are interested in measuring the time spent by the vehicles at the intersection. We can consider the number of vehicles waiting at intersection as :ref:`statistics-population` and will use the Population class for recording statistics.

We begin by creating an instance of simulator:

.. code-block:: js

    var sim = new Sim.Sim();

Next we create two events to model the traffic lights and give them descriptive names:

.. code-block:: js

    var trafficLights = [new Sim.Event("North-South Light"),
                         new Sim.Event("East-West Light")];

To monitor the statistics, we create an object of Population class:

.. code-block:: js

    var stats = new Sim.Population("Waiting at Intersection");

Of course, we create a random number generator:

.. code-block:: js

    var random = new Random(SEED);

We will create two entities: one to control the traffic lights, another to generate the vehicle traffic. Lets look at traffic light controller first.

The traffic light controller periodically turns off lights in one direction and turns on the other. This process is repeated indefinitely at interval of GREEN_TIME seconds.

.. code-block:: js

    class LightController extends Sim.Entity {
        currentLight: 0,  // the light that is turned on currently
        start() {
            // Logging
            sim.log(trafficLights[this.currentLight].name + " OFF"
                            + ", " + trafficLights[1 - this.currentLight].name + " ON");
            sim.log("------------------------------------------");

            // turn off the current light
            trafficLights[this.currentLight].clear();

            // turn on the other light.
            // Note the true parameter: the event must "sustain"
            trafficLights[1 - this.currentLight].fire(true);

            // update the currentLight variable
            this.currentLight = 1 - this.currentLight;

            // Repeat every GREEN_TIME interval
            this.setTimer(GREEN_TIME).done(this.start);
        }
    }

Quite a few things are happening here. Lets dissect the code now:

* First we create a JavaScript class (which is mostly interchangeable with prototype) that inherits all the behavior of Sim.Entity, and implements the :func:`start` function. Later on we will use the :func:`Sim.addEntity` function to create ``Entity objects``. Of course, more than one objects can be created from the same ``Entity Prototype`` object (although in this example we create only one entity object).
* When we call the :func:`Sim.addEntity` the simulator kernel adds other functions and attributes to the Entity prototype object. We call this new object as ``Extended Entity Prototype`` object. For example, :func:`this.setTimer` was added by the simulator. Refer to :ref:`entity-prototype` for a complete list of extended functions and attributes. The simulator now creates a new object with the extended entity prototype object as the *prototype*.
* The ``Entity prototype`` object **must** define a *start* function. This function is called by the simulator when the simulation starts.
* Notice that the events are fired with *true* argument, which indicates that the events must remain in 'fired state' until explicitly cleared. The default behavior is that the events fire for an instant only and go back to passive state immediately.
* The :func:`setTimer` function sets a timers for GREEN_TIME duration, and at expiry will call :func:`this.start` function. The setTimer function returns a :ref:`Request <request-main>` object that can be used to modify the request. In this case we attach a callback function that must be called after the timer expires (via the :func:`~Request.done` function).
* We have used :func:`sim.log` function to log the actions to help us debugging.

Moving on to the entity to generate traffic. Lets look at the code first:

.. code-block:: js

    class Traffic extends Sim.Entity {
        start() {
            this.generateTraffic("North", trafficLights[0]); // traffic for North -> South
            this.generateTraffic("South", trafficLights[0]); // traffic for South -> North
            this.generateTraffic("East", trafficLights[1]); // traffic for East -> West
            this.generateTraffic("West", trafficLights[1]); // traffic for West -> East
        },
        generateTraffic: function (direction, light) {
            // Logging
            sim.log("Arrive for " + direction);

            // STATS: record that vehicle as entered the intersection
            stats.enter(this.time());

            // wait on the light.
            // The done() function will be called when the event fires
            // (i.e. the light turns green).
            this.waitEvent(light).done(() => {
                var arrivedAt = this.callbackData;

                // Logging
                sim.log("Leave for " + direction + " (arrived at " + arrivedAt.toFixed(6) + ")");

                // STATS: record that vehicle has left the intersection
                stats.leave(arrivedAt, this.time());
            }).setData(this.time());

            // Repeat for the next car. Call this function again.
            var nextArrivalAt = random.exponential(1.0 / MEAN_ARRIVAL);
            this.setTimer(nextArrivalAt).done(this.generateTraffic, this, [direction, light]);
        }
    }

Lets follow this code:

* As before, we subclass ``Sim.Entity`` and implement a :func:`start` function.
* We also notice that :func:`this.time()`, :func:`this.setTimer` and :func:`this.waitEvent` are added by the simulator to this entity prototype object.
* The :func:`generateTraffic` function generates traffic for one street for one direction. We call this function four times in our start function.
* :func:`this.waitEvent` illustrates the most typical design pattern for requesting resources. The entity first make a request (in this case, wait for the event -- the traffic light -- to fire) which returns a :ref:`Request <request-main>` object. The entities then call the :class:`~Sim.Request` class functions to fine tune the request. Each of these function return the request object back, so the functions can be chained together. In this case we call two functions on request object:
    * :func:`Request.done`. This assigns a callback function which will be called when the request is satisfied. In our case, we use the callback to update the statistics.
    * :func:`Request.setData`. This stores some user data that can be retrieved later from :attr:this.callbackData` attribute within the callback function. In this case, we store the current time (which is the arrival time).
* We have seen the :func:`this.setTimer` earlier too, however, this time we use the complete three-argument form: :attr:`this.setTimer(callbackFn, context, data)`. *callbackFn* is the callback function (this.generateTraffic in our example), *context* is object in whose context this function will be called, and *data* will become argument to the callback function.
* Note that there are two ways to pass data to the callback functions: via the :func:`Request.setData` as :attr:`this.callbackData` or passing data along with callback function which shows up arguments to the callback function. The difference between the two is that the former data will appear for *all* callback functions, whereas the latter will be specific to one callback function only. The following example should explain this:

.. code-block:: js

    this.waitEvent(event)
    .setData('Data to all callback functions')
    .done(fn1, this, 'data to fn1 only')
    .done(fn2, this, 'data to fn2 only')
    .waitUntil(fn3, this, 'data to fn3 only')
    .unlessEvent(fn4, this, 'data to fn4 only');

    fn1 = function(arg) {
        assert(arg == 'data to fn1 only');
        assert(this.callbackData == 'Data to all callback functions');
    }

    fn2 = function(arg) {
        assert(arg == 'data to fn2 only');
        assert(this.callbackData == 'Data to all callback functions');
    }

Having created the entity prototype objects we create the actual entity objects

.. code-block:: js

    sim.addEntity(LightController);
    sim.addEntity(Traffic);

And finally, we start simulation:

.. code-block:: js

    // simulate for SIMTIME time
    sim.simulate(SIMTIME);

`View the complete source code <traffic_lights.js>`_.

Running Simulation
======================
This javascript code can be executed where ever javascript can run. This includes:

* As a script in HTML page on a web browser.
* Via Web browser JavaScript debuggers such as Mozilla Firebug, Safari's Developer tools etc.
* With `Rhino <www.mozilla.org/rhino>`_.
* With ``jrunscript``.
* and so on...

We will run our model as a web page on a web browser. For this we have created the following web page:

.. code-block:: js

    <html>
    <head>
        <title>Tutorial: Simulation of Traffic Lights at Intersection</title>

        <script type="text/javascript" src="sim-0.1.js"></script>
        <script type="text/javascript" src="traffic-light.js"></script>
    </head>
    <body></body>
    </html>

Tracing Simulation Runs
=========================

Having completed the model let us first see that the model is working correctly. We can use the :ref:`debug-log` feature of the simulator to log events and actions.

We have already added the logging support in our code. To enable logging, we use the :func:`Sim.setLogger` function:

.. code-block:: js

    // add these lines before starting simulation
    document.write("<pre>");
    sim.setLogger(function (str) {
        document.write(str);
    }));

Remember to add these lines before the :func:`sim.simulate` function. The *setLogger* function takes as input a 'writer' function that will be invoked to write trace logs. In our case, we output the trace logs to the web document. We have also added the "<pre>" tag so that the output is displayed as well formatted text.

Lets first disable the logging statement in the Traffic function so that we see the output from the LightController entity only. To help in visualization, we have selected rather extreme values with GREEN_TIME = 5 min, MEAN_ARRIVAL = 1 min, SIMTIME = 30 min and SEED = 1234.

We see the following output::

    0.000000   North-South Light OFF, East-West Light ON
    0.000000   ------------------------------------------
    5.000000   East-West Light OFF, North-South Light ON
    5.000000   ------------------------------------------
    10.000000   North-South Light OFF, East-West Light ON
    10.000000   ------------------------------------------
    15.000000   East-West Light OFF, North-South Light ON
    15.000000   ------------------------------------------
    20.000000   North-South Light OFF, East-West Light ON
    20.000000   ------------------------------------------
    25.000000   East-West Light OFF, North-South Light ON
    25.000000   ------------------------------------------
    30.000000   North-South Light OFF, East-West Light ON
    30.000000   ------------------------------------------

This make sense, the lights switch every 5 minutes.

Next we enable the logging statement in the Traffic entity. We show only some selected lines from the output::

    0.000000   North-South Light OFF, East-West Light ON
    0.000000   ------------------------------------------
    0.000000   Arrive for North
    0.000000   Arrive for South
    0.000000   Arrive for East
    0.000000   Arrive for West
    0.000000   Leave for East (arrived at 0.000000)
    0.000000   Leave for West (arrived at 0.000000)
    0.034122   Arrive for North
    0.250816   Arrive for South
    0.819317   Arrive for East
    0.819317   Leave for East (arrived at 0.819317)
    0.912556   Arrive for East
    0.912556   Leave for East (arrived at 0.912556)
    <lines omitted>
    5.000000   East-West Light OFF, North-South Light ON
    5.000000   ------------------------------------------
    5.000000   Leave for North (arrived at 0.000000)
    5.000000   Leave for South (arrived at 0.000000)
    5.000000   Leave for North (arrived at 0.034122)
    5.000000   Leave for South (arrived at 0.250816)
    5.000000   Leave for South (arrived at 2.651636)
    5.000000   Leave for North (arrived at 4.928112)
    5.129310   Arrive for South
    5.129310   Leave for South (arrived at 5.129310)
    5.144233   Arrive for East
    5.194057   Arrive for North
    5.194057   Leave for North (arrived at 5.194057)
    <lines omitted>
    10.000000   North-South Light OFF, East-West Light ON
    10.000000   ------------------------------------------
    10.000000   Leave for East (arrived at 5.144233)
    10.000000   Leave for West (arrived at 5.230096)
    10.000000   Leave for East (arrived at 6.584731)
    10.000000   Leave for East (arrived at 7.645791)
    10.000000   Leave for East (arrived at 8.079168)
    10.000000   Leave for East (arrived at 8.551925)
    10.000000   Leave for West (arrived at 8.709882)
    10.000000   Leave for West (arrived at 9.194689)
    10.000000   Leave for East (arrived at 9.277087)
    10.000000   Leave for West (arrived at 9.963535)
    <lines omitted>

Note the first four arrival lines. Only the East- and West-bound vehicles leave the intersection. Notice also at 5.0 minutes, all the North and South bound vehicles leave intersection as soon as the light turns green. You can follow the logs to verify that our traffic light model is indeed working correctly.

Statistics
============

We are ultimately interested in average statistics of our model. For this problem we would like to know:

* What is average duration that vehicles have to wait at the intersection?
* What is the average number of vehicles that are waiting at the intersection?

We have used the :ref:`statistics-population` statistics to monitor the vehicle traffic at the intersection. :attr:`Population.durationSeries` (which is a :ref:`statistics-time-series`) records the duration for which vehicles wait at the intersection, and :attr:`Population.sizeSeries` (which is a :ref:`statistics-data-series`) records the number of vehicles standing at the intersection.

To output these two statistics, add the following lines after the :func:`sim.simulate` call.

.. code-block:: js

    document.write("Number of vehicles at intersection (average) = "
            + stats.sizeSeries.average().toFixed(3)
            + " (+/- " + stats.sizeSeries.deviation().toFixed(3)
            + ")\n");
    document.write("Time spent at the intersection (average) = "
            + stats.durationSeries.average().toFixed(3)
            + " (+/- " + stats.durationSeries.deviation().toFixed(3)
            + ")\n");

The output for our rather contrived input values is as follows::

    Number of vehicles at intersection (average) = 4.264 (+/- 2.069)
    Time spent at the intersection (average) = 1.361 (+/- 1.830)

Traffic Lights in Action
=============================

You can `play with this simulation model <traffic_lights.html>`_. Try out different values of input parameters and compare the output statistics of model.


text:
package models

import play.api.db.slick.Config.driver.simple._
import oil.FilterByKey

object Database {
  class UserRow(tag: Tag) extends Table[User](tag, "Users") with FilterByKey {
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def age = column[Int]("age")
    def streetAddress = column[String]("street_address")
    def city = column[String]("city")
    def zipCode = column[String]("zip_code")
    def country = column[String]("country")
    def email = column[String]("email")
    def telephoneNumber = column[String]("telephone_number")

    def * = (id.?, age, streetAddress, city, zipCode, country, email, telephoneNumber) <> (User.tupled, User.unapply)

    def filterByKey(key: String): Column[Boolean] = id === key.toInt
  }

  //val Users = new TableQuery(tag => new UserRow(tag))
  val Users = TableQuery[UserRow]
}

redpajama_set_name: RedPajamaGithub


text: export * from './reOrder.component';


text:
package org.wso2.carbon.logging.service.util;

import org.wso2.carbon.core.RegistryResources;

public final class LoggingConstants {

    public static final String LOGGERS = RegistryResources.LOGGING + "loggers/";
    public static final String APPENDERS = RegistryResources.LOGGING + "appenders/";
    public static final String SYSLOG = RegistryResources.LOGGERS + "syslog/SYSLOG_PROPERTIES";
    public static final String CASSANDRA = RegistryResources.LOGGERS + "cassandra/CASSANDRA_PROPERTIES";
    public static final String URL_SEPARATOR = "/";
    public static final String LOGGING_CONF_FILE = "logging-config.xml";
    public static final String SYSLOG_CONF_FILE = "syslog-config.xml";
    public static final String ETC_DIR = "etc";
    public static final String USERNAME_KEY = "username";
    public static final String PASSWORD_KEY = "password";
    public static final String DEFUALT_CLUSTER_NAME = "TestCluster";
    public static final String WSO2_STRATOS_MANAGER = "manager";

	public static final String TENANT_ID = "tenantID";
	public static final String SERVER_NAME = "serverName";
	public static final String APP_NAME = "appName";
	public static final String LOG_TIME = "logTime";
	public static final String PRIORITY = "priority";
	public static final String MESSAGE = "message";
	public static final String LOGGER = "logger";
	public static final String IP = "ip";
	public static final String INSTANCE = "instance";
	public static final String STACKTRACE = "stacktrace";

	public static final String DEFAULT_VERSION ="1.0.0";
    public static final String LOG_FILE_PATTERN = "log.file.pattern";
    public static final String LOG_CONSOLE_PATTERN = "log.console.pattern";
    public static final String LOG_MEMORY_PATTERN = "log.memory.pattern";
    public static final String MEMORY_APPENDER = "MemoryAppender";

    // global system settings
    public static final String SYSTEM_LOG_LEVEL = "wso2carbon.system.log.level";
    public static final String SYSTEM_LOG_PATTERN = "wso2carbon.system.log.pattern";
    public static final String LOG4J_FILE_LAST_MODIFIED = "wso2carbon.system.log.last.modified";

    public static final String LOG4J_FILE_FOUND = "log4j.file.not.found";
    public static final String CONFIG_FILENAME = "cloud-services-desc.xml";
    public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy";
    public static final String WSO2CARBON_CONSOLE_APPENDER = "CARBON_CONSOLE";
    public static final String WSO2CARBON_FILE_APPENDER = "CARBON_LOGFILE";
    public static final String WSO2CARBON_EVENT_APPENDER = "LOGEVENT";
    public static final String WSO2CARBON_MEMORY_APPENDER = "CARBON_MEMORY";
    public static final String WSO2CARBON_SYS_LOG_APPENDER = "CARBON_SYS_LOG";

    public static final int MEMORY_APPENDER_BUFFER_SZ = 200;

    public static final String DATE_FORMATTER = "yyyy-MM-dd";
    public static final String DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss,SSS";
    public static final String GMT = "GMT";

    public static final class SyslogProperties {
        public static final String LOG_INDEX_URL = "log.index.url";
        public static final String SYSLOG_PORT = "syslog.port";
        public static final String REALM = "realm";
        public static final String USER_NAME = "user.name";
        public static final String PASSWORD = "password";
    }

    public static final class HColumn {
        public static final String TENANT_ID = "payload_tenantID";
        public static final String SERVER_NAME = "payload_serverName";
        public static final String APP_NAME = "payload_appName";
        public static final String LOG_TIME = "payload_logTime";
        public static final String LOGGER = "payload_logger";
        public static final String PRIORITY = "payload_priority";
        public static final String MESSAGE = "payload_message";
        public static final String IP = "payload_ip";
        public static final String STACKTRACE = "payload_stacktrace";
        public static final String INSTANCE = "payload_instance";
    }

    public static final class CassandraProperties {
        public static final String URL = "cassandra.host.url";
        public static final String KEYSPACE = "cassandra.keyspace";
        public static final String COLUMN_FAMILY = "cassandra.keyspace.column.family";
        public static final String USER_NAME = "user.name";
        public static final String PASSWORD = "password";
        public static final String IS_CASSANDRA_AVAILABLE = "isCassandraAvailable";
    }

    public static final class LoggerProperties {
        public static final String NAME = "name";
        public static final String LOG_LEVEL = "log.level";
        public static final String ADDITIVITY = "additivity";
    }

    public static final class SyslogConfigProperties {
        public static final String SYSLOG_HOST = "syslogHost";
        public static final String PORT = "port";
        public static final String REALM = "realm";
        public static final String USER_NAME = "userName";
        public static final String PASSWORD = "password";
        public static final String LOG_PATTERN = "logPattern";
        public static final String IS_SYSLOG_ON = "isSyslogOn";
    }

    public static final class LogConfigProperties {
        public static final String DEFAULT_LOGGING_CONFIG_NAMESPACE = "http://wso2.org/projects/carbon/carbon.xml";
        public static final String LOGGING_CONFIG = "loggingConfig";
        public static final String LOG_PROVIDER_CONFIG = "logProviderConfig";
        public static final String LOG_FILE_PROVIDER_CONFIG = "logFileProviderConfig";
        public static final String PROPERTIES = "properties";
        public static final String PROPERTY = "property";
        public static final String PROPERTY_NAME = "name";
        public static final String PROPERTY_VALUE = "value";
        public static final String CLASS_ATTRIBUTE = "class";

    }

    public static final class AppenderProperties {
        public static final String NAME = "name";
        public static final String PATTERN = "pattern";
        public static final String LOG_FILE_NAME = "log.file.name";
        public static final String IS_FILE_APPENDER = "is.file.appender";
        public static final String THRESHOLD = "threshold";
        public static final String FACILITY = "facility";
        public static final String SYS_LOG_HOST = "sys.log.host";
        public static final String IS_SYS_LOG_APPENDER = "is.sys.log.appender";
    }

    public static final class RegexPatterns {
        public static final String HOST_PATTERN = "(\\d+\\.\\d+\\.\\d+\\.\\d+)";
        public static final String CLOSE_BRACKET_PATTERN = "\\]  ";
        public static final String OPEN_BRACKET_PATTERN = "\\[";
        public static final String EXCEPTION_START_PATTERN = "\\sat\\s";
        public static final String SYSLOG_DATE_PATTERN = "\\d{1,2}\\s\\d{2}:\\d{2}:\\d{2}\\s\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}";
        public static final String OPEN_CURLY_BRACES_PATTERN = "\\{";
        public static final String NEW_LINE = "\n";
        public static final String TENANT_PATTERN = "%T";
        public static final String LOG_ERROR = "ERROR";
        public static final String LOG_FATAL = "FATAL";
        public static final String LOG_WARN = "WARN";
        public static final String LOG_INFO = "INFO";
        public static final String LOG_DEBUG = "DEBUG";
        public static final String LOG_TRACE = "TRACE";
        public static final String LOCAL_CARBON_LOG_PATTERN = "wso2carbon.log*";
        public static final String LOG_FILE_DATE_SEPARATOR = "log.";
        public static final String CURRENT_LOG = "0_Current Log";
        public static final String SYSLOG_DOMAIN_PATTERN = ".*?([^.]+\\.[$.]+)";
        public static final String SYS_LOG_FILE_NAME_PATTERN = ".gz";
        public static final String LOG_ERROR_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}ERROR";
        public static final String LOG_WARN_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}WARN";
        public static final String LOG_FATAL_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}FATAL";
        public static final String LOG_DEBUG_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}DEBUG";
        public static final String LOG_TRACE_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}TRACE";
        public static final String LOG_INFO_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}][\\s\\S.*]*\\s{0,2}INFO";
        public static final String LOG_HEADER_PATTERN = "\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2},\\d{2,6}]";
        public static final String ERROR_LINE = "\\] ERROR \\{";
        public static final String LINK_SEPARATOR_PATTERN = "a href=";
        public static final String SYSLOG_DATE_SEPARATOR_PATTERN = "";
        public static final String COLUMN_SEPARATOR_PATTERN = "	";
        public static final String GT_PATTARN = ">";
        public static final String BACK_SLASH_PATTERN = "\"";
    }
}


text:
<!-- dash: REST | Guide | ###:Section -->

# REST Module

## Overview

  Nitrogen's default route handler gives you an easy way to add a no-nonsense
  RESTful handler to a page module. If you need to add a simple a RESTful
  interface without wanting to deal with Webmachine or Cowboy's restful
  handlers, and just use straight up Nitrogen, you can do this trivially.

  Simply stated, if you add `-behaviour(nitrogen_rest).` to a module, instead
  of looking for a `main()` function as the entry point, it will instead expect
  an entry point based on the HTTP request method used.  So a `GET` request
  will look for a `get()` function, and so on.

  Each Entry Point function expects a single argument, `PathInfo`, which is
  exactly yhe same information that would be retrieved from calling
  `wf:path_info()`.

### Request Methods Module Entry Points

   Commonly used Request methods and their corresponding entry points

 *  `GET` :: `get(PathInfo)`
 *  `POST` :: `post(PathInfo)`
 *  `PUT` :: `put(PathInfo)`
 *  `DELETE` :: `delete(PathInfo)`

   Less commonly used Request methods:

 *  `CONNECT` :: `connect(PathInfo)`
 *  `TRACE` :: `trace(PathInfo)`
 *  `OPTIONS` :: `options(PathInfo)`

   (You might notice the pattern here: the HTTP status code is made lower-case
   and converted to an atom, and that is the function called.

### Return values of entry points

   All the above functions are expected to return either a `Body`, which can be
   a typical Nitrogen body (with Nitrogen elements), or a 2-tuple,
   `{StatusCode, Body}`, where StatusCode is the HTTP status code of the
   return. If only a `Body` is returned, the `StatusCode` is the standard 200
   status code.

### See Also

 *  [Route Handler Docs](route.md)

 *  [REST Handler Demo](http://nitrogenproject.com/demos/rest_handler)


text:
/**
 * @fileoverview 百度地图的自定义信息窗口,对外开放。
 * 用户自定义信息窗口的各种样式。例如:border,margin,padding,color,background等
 * 主入口类是InfoBox,
 * 基于Baidu Map API 1.2。
 *
 * @author Baidu Map Api Group
 * @version 1.2
 */
/**
 * @namespace BMap的所有library类均放在BMapLib命名空间下
 */
var BMapLib = window.BMapLib = BMapLib || {};
//常量,infoBox可以出现的位置,此版本只可实现上下两个方向。
var INFOBOX_AT_TOP = 1, INFOBOX_AT_RIGHT = 2, INFOBOX_AT_BOTTOM = 3, INFOBOX_AT_LEFT = 4;
(function() {
    //声明baidu包
    var T, baidu = T = baidu || {version: '1.5.0'};
    baidu.guid = '$BAIDU$';
    //以下方法为百度Tangram框架中的方法,请到http://tangram.baidu.com 查看文档
    (function() {
        window[baidu.guid] = window[baidu.guid] || {};

		baidu.lang = baidu.lang || {};
        baidu.lang.isString = function (source) {
            return '[object String]' == Object.prototype.toString.call(source);
        };
        baidu.lang.isFunction = function (source) {
            return '[object Function]' == Object.prototype.toString.call(source);
        };
        baidu.lang.Event = function (type, target) {
            this.type = type;
            this.returnValue = true;
            this.target = target || null;
            this.currentTarget = null;
        };

        baidu.object = baidu.object || {};
        baidu.extend =
        baidu.object.extend = function (target, source) {
            for (var p in source) {
                if (source.hasOwnProperty(p)) {
                    target[p] = source[p];
                }
            }

            return target;
        };
        baidu.event = baidu.event || {};
        baidu.event._listeners = baidu.event._listeners || [];
        baidu.dom = baidu.dom || {};

        baidu.dom._g = function (id) {
            if (baidu.lang.isString(id)) {
                return document.getElementById(id);
            }
            return id;
        };
        baidu._g = baidu.dom._g;
        baidu.event.on = function (element, type, listener) {
            type = type.replace(/^on/i, '');
            element = baidu.dom._g(element);
            var realListener = function (ev) {
                    // 1. 这里不支持EventArgument,  原因是跨frame的事件挂载
                    // 2. element是为了修正this
                    listener.call(element, ev);
                },
                lis = baidu.event._listeners,
                filter = baidu.event._eventFilter,
                afterFilter,
                realType = type;
            type = type.toLowerCase();
            // filter过滤
            if(filter && filter[type]){
                afterFilter = filter[type](element, type, realListener);
                realType = afterFilter.type;
                realListener = afterFilter.listener;
            }

            // 事件监听器挂载
            if (element.addEventListener) {
                element.addEventListener(realType, realListener, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + realType, realListener);
            }
            // 将监听器存储到数组中
            lis[lis.length] = [element, type, listener, realListener, realType];
            return element;
        };

        baidu.on = baidu.event.on;
        baidu.event.un = function (element, type, listener) {
            element = baidu.dom._g(element);
            type = type.replace(/^on/i, '').toLowerCase();

            var lis = baidu.event._listeners,
                len = lis.length,
                isRemoveAll = !listener,
                item,
                realType, realListener;
            while (len--) {
                item = lis[len];

                if (item[1] === type
                    && item[0] === element
                    && (isRemoveAll || item[2] === listener)) {
                   	realType = item[4];
                   	realListener = item[3];
                    if (element.removeEventListener) {
                        element.removeEventListener(realType, realListener, false);
                    } else if (element.detachEvent) {
                        element.detachEvent('on' + realType, realListener);
                    }
                    lis.splice(len, 1);
                }
            }

            return element;
        };
        baidu.un = baidu.event.un;
        baidu.dom.g = function (id) {
            if ('string' == typeof id || id instanceof String) {
                return document.getElementById(id);
            } else if (id && id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) {
                return id;
            }
            return null;
        };
        baidu.g = baidu.G = baidu.dom.g;
        baidu.dom._styleFixer = baidu.dom._styleFixer || {};
        baidu.dom._styleFilter = baidu.dom._styleFilter || [];
        baidu.dom._styleFilter.filter = function (key, value, method) {
            for (var i = 0, filters = baidu.dom._styleFilter, filter; filter = filters[i]; i++) {
                if (filter = filter[method]) {
                    value = filter(key, value);
                }
            }
            return value;
        };
        baidu.string = baidu.string || {};

        baidu.string.toCamelCase = function (source) {
            //提前判断,提高getStyle等的效率 thanks xianwei
            if (source.indexOf('-') < 0 && source.indexOf('_') < 0) {
                return source;
            }
            return source.replace(/[-_][^-_]/g, function (match) {
                return match.charAt(1).toUpperCase();
            });
        };

        baidu.dom.setStyle = function (element, key, value) {
            var dom = baidu.dom, fixer;

            // 放弃了对firefox 0.9的opacity的支持
            element = dom.g(element);
            key = baidu.string.toCamelCase(key);

            if (fixer = dom._styleFilter) {
                value = fixer.filter(key, value, 'set');
            }

            fixer = dom._styleFixer[key];
            (fixer && fixer.set) ? fixer.set(element, value) : (element.style[fixer || key] = value);

            return element;
        };

         baidu.setStyle = baidu.dom.setStyle;

        baidu.dom.setStyles = function (element, styles) {
            element = baidu.dom.g(element);
            for (var key in styles) {
                baidu.dom.setStyle(element, key, styles[key]);
            }
            return element;
        };
         baidu.setStyles = baidu.dom.setStyles;
        baidu.browser = baidu.browser || {};
        baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || + RegExp['\x241']) : undefined;
        baidu.dom._NAME_ATTRS = (function () {
            var result = {
                'cellpadding': 'cellPadding',
                'cellspacing': 'cellSpacing',
                'colspan': 'colSpan',
                'rowspan': 'rowSpan',
                'valign': 'vAlign',
                'usemap': 'useMap',
                'frameborder': 'frameBorder'
            };

            if (baidu.browser.ie < 8) {
                result['for'] = 'htmlFor';
                result['class'] = 'className';
            } else {
                result['htmlFor'] = 'for';
                result['className'] = 'class';
            }

            return result;
        })();
        baidu.dom.setAttr = function (element, key, value) {
            element = baidu.dom.g(element);
            if ('style' == key){
                element.style.cssText = value;
            } else {
                key = baidu.dom._NAME_ATTRS[key] || key;
                element.setAttribute(key, value);
            }
            return element;
        };
         baidu.setAttr = baidu.dom.setAttr;
        baidu.dom.setAttrs = function (element, attributes) {
            element = baidu.dom.g(element);
            for (var key in attributes) {
                baidu.dom.setAttr(element, key, attributes[key]);
            }
            return element;
        };
        baidu.setAttrs = baidu.dom.setAttrs;
        baidu.dom.create = function(tagName, opt_attributes) {
            var el = document.createElement(tagName),
                attributes = opt_attributes || {};
            return baidu.dom.setAttrs(el, attributes);
        };
        T.undope=true;
    })();

    /**
     * @exports InfoBox as BMapLib.InfoBox
     */

    var InfoBox =
    /**
     * InfoBox类的构造函数
     * @class InfoBox 入口。
     * 可以自定义border,margin,padding,关闭按钮等等。
     * @constructor
         * @param {Map} map Baidu map的实例对象.
         * @param {String} content infoBox中的内容.
         * @param {Json Object} opts 可选的输入参数,非必填项。可输入选项包括:

         * {
"offset" : {Size} infoBox的偏移量
         *
"boxClass" : {String} 定义infoBox的class,
         *
"boxStyle" : {Json} 定义infoBox的style,此项会覆盖boxClass

         *
"closeIconMargin" : {String} 关闭按钮的margin

         *
"closeIconUrl" : {String} 关闭按钮的url地址

         *
"enableAutoPan" : {Boolean} 是否启动自动平移功能

         *
"align" : {Number} 基于哪个位置进行定位,取值为[INFOBOX_AT_TOP,INFOBOX_AT_BOTTOM]

         * }
.
         * @example 参考示例:

         * var infoBox = new BMapLib.InfoBox(map,"百度地图api",{boxStyle:{background:"url('resource/baiduMap/img/tipbox.gif') no-repeat
          center top",width: "200px"},closeIconMargin: "10px 2px 0 0",enableAutoPan: true
          ,alignBottom: false});
     */
        BMapLib.InfoBox = function(map, content, opts) {

        this._content = content || "";
        this._isOpen = false;
        this._map = map;
        this._opts = opts = opts || {};
        this._opts.offset =  opts.offset || new BMap.Size(0,0);
        this._opts.boxClass = opts.boxClass || "infoBox";
        this._opts.boxStyle = opts.boxStyle || {};
        this._opts.closeIconMargin = opts.closeIconMargin || "2px";
        this._opts.closeIconUrl = opts.closeIconUrl || "resource/baiduMap/img/close.png";
        this._opts.enableAutoPan = opts.enableAutoPan  ? true : false;
        this._opts.align = opts.align || INFOBOX_AT_TOP;
    }
    InfoBox.prototype = new BMap.Overlay();
    InfoBox.prototype.initialize = function(map) {
        var me = this;
        var div = this._div = baidu.dom.create('div', {"class": this._opts.boxClass});
        baidu.dom.setStyles(div, this._opts.boxStyle);
        //设置position为absolute,用于定位
        div.style.position = "absolute";
        this._setContent(this._content);

        var floatPane = map.getPanes().floatPane;
        floatPane.style.width = "auto";
        floatPane.appendChild(div);
        //设置完内容后,获取div的宽度,高度
        this._getInfoBoxSize();
        //this._boxWidth = parseInt(this._div.offsetWidth,10);
        //this._boxHeight = parseInt(this._div.offsetHeight,10);
        //阻止各种冒泡事件
        baidu.event.on(div,"onmousedown",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"onmouseover",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"click",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"dblclick",function(e){
            me._stopBubble(e);
        });
        return div;
    }
    InfoBox.prototype.draw = function() {
        this._isOpen && this._adjustPosition(this._point);
    }
    /**
     * 打开infoBox
     * @param {Marker|Point} anchor 要在哪个marker或者point上打开infobox
     * @return none
     *
     * @example 参考示例:

     * infoBox.open();
     */
    InfoBox.prototype.open = function(anchor){
        var me = this,poi;
        if(!this._isOpen) {
            this._map.addOverlay(this);
            this._isOpen = true;
            //延迟10ms派发open事件,使后绑定的事件可以触发。
            setTimeout(function(){
                me._dispatchEvent(me,"open",{"point" : me._point});
            },10);
        }
        if(anchor instanceof BMap.Point){
            poi = anchor;
            //清除之前存在的marker事件绑定,如果存在的话
            this._removeMarkerEvt();
        }else if(anchor instanceof BMap.Marker){
        	//如果当前marker不为空,说明是第二个marker,或者第二次点open按钮,先移除掉之前绑定的事件
        	if(this._marker){
        		this._removeMarkerEvt();
        	}
            poi = anchor.getPosition();
            this._marker = anchor;
            !this._markerDragend && this._marker.addEventListener("dragend",this._markerDragend = function(e){
            	me._point = e.point;
            	me._adjustPosition(me._point);
            	me._panBox();
            	me.show();
            });
             //给marker绑定dragging事件,拖动marker的时候,infoBox也跟随移动
            !this._markerDragging && this._marker.addEventListener("dragging",this._markerDragging = function(){
            	me.hide();
            	me._point = me._marker.getPosition();
                me._adjustPosition(me._point);
            });
        }
        //打开的时候,将infowindow显示
        this.show();
        this._point = poi;
        this._panBox();
        this._adjustPosition(this._point);
    }
    /**
     * 关闭infoBox
     * @return none
     *
     * @example 参考示例:

     * infoBox.close();
     */
    InfoBox.prototype.close = function(){
        if(this._isOpen){
            this._map.removeOverlay(this);
            this._remove();
            this._isOpen = false;
            this._dispatchEvent(this,"close",{"point" : this._point});
        }
    }

	/**
   	 * 打开infoBox时,派发事件的接口
     * @name InfoBox#Open
     * @event
     * @param {Event Object} e 回调函数会返回event参数,包括以下返回值:
     *
{"target : {BMap.Overlay} 触发事件的元素,
     *
"type:{String} 事件类型,
     *
"point:{Point} infoBox的打开位置}
     *
     * @example 参考示例:
     * infoBox.addEventListener("open", function(e) {
     *     alert(e.type);
     * });
     */
   /**
   	 * 关闭infoBox时,派发事件的接口
     * @name InfoBox#Close
     * @event
     * @param {Event Object} e 回调函数会返回event参数,包括以下返回值:
     *
{"target : {BMap.Overlay} 触发事件的元素,
     *
"type:{String} 事件类型,
     *
"point:{Point} infoBox的关闭位置}
     *
     * @example 参考示例:
     * infoBox.addEventListener("close", function(e) {
     *     alert(e.type);
     * });
     */
  /**
     * 启用自动平移
     * @return none
     *
     * @example 参考示例:

     * infoBox.enableAutoPan();
     */
    InfoBox.prototype.enableAutoPan = function(){
        this._opts.enableAutoPan = true;
    }
    /**
     * 禁用自动平移
     * @return none
     *
     * @example 参考示例:

     * infoBox.disableAutoPan();
     */
    InfoBox.prototype.disableAutoPan = function(){
        this._opts.enableAutoPan = false;
    }
    /**
     * 设置infoBox的内容
     * @param {String|HTMLElement} content 弹出气泡中的内容
     * @return none
     *
     * @example 参考示例:

     * infoBox.setContent("百度地图API");
     */
    InfoBox.prototype.setContent = function(content){
      	this._setContent(content);
      	this._getInfoBoxSize();
        this._adjustPosition(this._point);
    }
    /**
     * 设置信息窗的地理位置
     * @param {Point} point 设置position
     * @return none
     *
     * @example 参考示例:

     * infoBox.setPosition(new BMap.Point(116.35,39.911));
     */
    InfoBox.prototype.setPosition = function(poi){
        this._point = poi;
        this._adjustPosition(poi);
        this._removeMarkerEvt();
    }
    /**
     * 获得信息窗的地理位置
     * @param none
     * @return {Point} 信息窗的地理坐标
     *
     * @example 参考示例:

     * infoBox.getPosition();
     */
    InfoBox.prototype.getPosition = function(){
        return this._point;
    }
    /**
     * 返回信息窗口的箭头距离信息窗口在地图
     * 上所锚定的地理坐标点的像素偏移量。
     * @return {Size} Size
     *
     * @example 参考示例:

     * infoBox.getOffset();
     */
    InfoBox.prototype.getOffset = function(){
        return this._opts.offset;
    },
    /**
   	 *@ignore
     * 删除overlay,调用Map.removeOverlay时将调用此方法,
     * 将移除覆盖物的容器元素
     */
    InfoBox.prototype._remove = function(){
        var me = this;
        if(this.domElement && this.domElement.parentNode){
          //防止内存泄露
          baidu.event.un(this._div.firstChild, "click", me._closeHandler());
          this.domElement.parentNode.removeChild(this.domElement);
        }
        this.domElement = null;
        this._isOpen = false;
        this.dispatchEvent("onremove");
    },
    baidu.object.extend(InfoBox.prototype,{
        /**
         * 获取关闭按钮的html
         * @return IMG 关闭按钮的HTML代码
         */
        _getCloseIcon: function(){
            var img = "";
            return img;
        },
        /**
	     * 设置infoBox的内容
	     * @param {String|HTMLElement} content 弹出气泡中的内容
	     * @return none
	     *
	     * @example 参考示例:

	     * infoBox.setContent("百度地图API");
	     */
        _setContent: function(content){
	        if(!this._div){
	            return;
	        }
	        var closeHtml = this._getCloseIcon();
	        //string类型的content
	        if(typeof content.nodeType === "undefined"){
	            this._div.innerHTML = closeHtml + content;
	        }else{
	            this._div.innerHTML = closeHtml;
	            this._div.appendChild(content);
	        }
	        this._content = content;
	        //添加click关闭infobox事件
	        this._addEventToClose();

   	    },
        /**
         * 调整infobox的position
         * @return none
         */
        _adjustPosition: function(poi){
            var pixel = this._getPointPosition(poi);
            var icon = this._marker && this._marker.getIcon();
            switch(this._opts.align){
                case INFOBOX_AT_TOP:
                    if(this._marker){
                        this._div.style.bottom = -(pixel.y - this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height) - this._marker.getOffset().height + 2 + "px";
                    }else{
                        this._div.style.bottom = -(pixel.y - this._opts.offset.height) + "px";
                    }
                    break;
                case INFOBOX_AT_BOTTOM:
                    if(this._marker){
          		        this._div.style.top = pixel.y + this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height + this._marker.getOffset().height + "px";
                    }else{
                        this._div.style.top = pixel.y + this._opts.offset.height + "px";
                    }
                    break;
            }

            if(this._marker){
                this._div.style.left = pixel.x - icon.anchor.width + this._marker.getOffset().width + icon.infoWindowAnchor.width - this._boxWidth / 2 + "px";
            }else{
                this._div.style.left = pixel.x - this._boxWidth / 2 + "px";
            }
        },
        /**
         * 得到infobox的position
         * @return Point  infobox当前的position
         */
        _getPointPosition: function(poi){
            this._pointPosition = this._map.pointToOverlayPixel(poi);
            return this._pointPosition;
        },
        /**
         * 得到infobox的高度跟宽度
         * @return none
         */
        _getInfoBoxSize: function(){
        	this._boxWidth = parseInt(this._div.offsetWidth,10);
        	this._boxHeight = parseInt(this._div.offsetHeight,10);
        },
        /**
         * 添加关闭事件
         * @return none
         */
        _addEventToClose: function(){
            var me = this;
            baidu.event.on(this._div.firstChild, "click", me._closeHandler());
            this._hasBindEventClose = true;
        },
        /**
         * 处理关闭事件
         * @return none
         */
        _closeHandler: function(){
            var me = this;
            return function(e){
                me.close();
            }
        },
        /**
         * 阻止事件冒泡
         * @return none
         */
        _stopBubble: function(e){
            if(e && e.stopPropagation){
                e.stopPropagation();
            }else{
                window.event.cancelBubble = true;
            }
        },
        /**
         * 自动平移infobox,使其在视野中全部显示
         * @return none
         */
        _panBox: function(){
            if(!this._opts.enableAutoPan){
                return;
            }
            var mapH = parseInt(this._map.getContainer().offsetHeight,10),
                mapW = parseInt(this._map.getContainer().offsetWidth,10),
                boxH = this._boxHeight,
                boxW = this._boxWidth;
            //infobox窗口本身的宽度或者高度超过map container
            if(boxH >= mapH || boxW >= mapW){
                return;
            }
            //如果point不在可视区域内
            if(!this._map.getBounds().containsPoint(this._point)){
                this._map.setCenter(this._point);
            }
            var anchorPos = this._map.pointToPixel(this._point),
                panTop,panBottom,panY,
                //左侧超出
                panLeft = boxW / 2 - anchorPos.x,
                //右侧超出
                panRight = boxW / 2 + anchorPos.x - mapW;
            if(this._marker){
                var icon = this._marker.getIcon();
            }
            //基于bottom定位,也就是infoBox在上方的情况
            switch(this._opts.align){
                case INFOBOX_AT_TOP:
                    //上侧超出
                    var h = this._marker ? icon.anchor.height + this._marker.getOffset().height - icon.infoWindowAnchor.height : 0;
                    panTop = boxH - anchorPos.y + this._opts.offset.height + h + 2 ;
                    break;
                case INFOBOX_AT_BOTTOM:
                    //下侧超出
                    var h = this._marker ? -icon.anchor.height + icon.infoWindowAnchor.height + this._marker.getOffset().height + this._opts.offset.height : 0;
                    panBottom = boxH + anchorPos.y - mapH + h + 4;
                    break;
            }

            panX = panLeft > 0 ? panLeft : (panRight > 0 ? -panRight : 0);
            panY = panTop > 0 ? panTop : (panBottom > 0 ? -panBottom : 0);
            this._map.panBy(panX,panY);
        },
        _removeMarkerEvt: function(){
			this._markerDragend && this._marker.removeEventListener("dragend", this._markerDragend);
            this._markerDragging && this._marker.removeEventListener("dragging", this._markerDragging);
            this._markerDragend = this._markerDragging = null;
        },
      	/**
	     * 集中派发事件函数
	     *
	     * @private
	     * @param {Object} instance 派发事件的实例
	     * @param {String} type 派发的事件名
	     * @param {Json} opts 派发事件里添加的参数,可选
	     */
	     _dispatchEvent: function(instance, type, opts) {
	        type.indexOf("on") != 0 && (type = "on" + type);
	        var event = new baidu.lang.Event(type);
	        if (!!opts) {
	            for (var p in opts) {
	                event[p] = opts[p];
	            }
	        }
	        instance.dispatchEvent(event);
	    }
    });
})();


text:
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, ClassVar, Dict, Generic, Iterable, List, Sequence, Tuple, TypeVar

from ..typedefs import Literal
from .typedefs import DataToken

T = TypeVar("T")
U = TypeVar("U")

def _enumerate_starting_at(
    sequence: Sequence[T],
    first_index: int,
) -> Iterable[Tuple[int, T]]:
    """Enumerate only a portion of a sequence, without slicing the sequence.

    Equivalent to enumerate(sequence[first_index:], start=first_index). The built-in enumerate()
    always iterates the entire sequence and only changes the counter's value based on
    the start parameter. In this function, we skip elements with indices in [0, first_index)
    in the sequence, and only iterate over elements with indices in [first_index, len(sequence)).

    Args:
        sequence: arbitrary sequence of values over which to iterate
        first_index: the first index of the sequence to produce in the resulting iterable

    Yields:
        tuples (index, element_at_that_index_in_sequence), analogous to the built-in enumerate()
    """
    for index in range(first_index, len(sequence)):
        yield index, sequence[index]

def _unzip_and_yield_second(iterable: Iterable[Tuple[T, U]]) -> Iterable[U]:
    """Unpack an iterable of tuples and only yield the second element of each tuple."""
    for _, second in iterable:
        yield second

@dataclass(frozen=True)
class AdapterOperation:
    """The record of an action performed on or by an InterpreterAdapter function as part of a trace.

    Actions that can be recorded like this include function calls, function returns, function yields
    (including yields that contain nested generators, whose yields will also be recorded),
    and yields of generators that were passed as inputs to function calls. The kind of action being
    recorded is reflected in the kind attribute, and carries a value suitable to the kind of action
    in the data attribute.

    For example, calling get_tokens_of_type("Foo") would produce an AdapterOperation
    with kind "call", with name "get_tokens_of_type", with unique ID and parent unique IDs
    appropriate for the trace, and with data (("Foo",), {}) representing a (positional_args, kwargs)
    tuple for the function call. For function returns, the data attribute of AdapterOperation
    holds the value returned by the function. For yields of input or output generators, the content
    of the data attribute is determined by the specific circumstances of the function named in
    the name attribute -- e.g. whether the function outputs a generator of generators, etc.

    The parent_uid field allows us to track dependencies across different operations. For example,
    data yielded by a generator-style function will be recorded in AdapterOperations
    of kind "yield" whose parent_uids point to the AdapterOperation of the particular invocation
    of the function that is generating that data.

    When InterpreterAdapter functions consume iterable arguments, the iterable argument in
    the AdapterOperation "call" record is replaced by a placeholder name. As values from such
    an iterable are consumed, those values are recorded in their own AdapterOperation records
    with kind "yield", parent unique ID matching the unique ID of the "call" record, and
    name matching the placeholder name in the "call" record.
    """

    kind: Literal["call", "yield", "return"]
    name: str
    uid: int
    parent_uid: int
    data: Any

@dataclass(frozen=True)
class RecordedTrace(Generic[DataToken]):
    """A complete, immutable recording of the execution of a query via an InterpreterAdapter.

    Includes a linearized sequence of all operations performed during the execution of the query:
    - adapter function calls, yields, and returns;
    - yields of any iterables that were passed as inputs to the adapter functions.

    Traces may record complete executions of queries (i.e. ones where the generators are run
    to completion), and may also be used to record partial executions (e.g. "fetch only 3 results").

    The recording is sufficiently detailed to be used in at least the following use cases:
    - to examine, either manually or through automated tests, a query's execution flow;
    - to "impersonate" an InterpreterAdapter implementation for a given query, allowing bugs in
      the interpreter code to be isolated and reproduced without an InterpreterAdapter;
    - to "impersonate" the interpreter code toward an InterpreterAdapter implementation,
      allowing adapter implementers to test and examine their implementations in isolation from
      the rest of the interpreter code.
    """

    DEFAULT_ROOT_UID: ClassVar[int] = -1

    # AdapterOperations that are part of this trace but do not have a specific parent operation
    # instead get assigned the trace's root_uid value as their parent_uid value.
    root_uid: int = field(init=False, default=DEFAULT_ROOT_UID)
    operations: Tuple[AdapterOperation, ...]

class TraceRecorder(Generic[DataToken]):

    # We expose an immutable (copied) version of the operation log through get_trace().
    # Other attributes are considered public.
    _operation_log: List[AdapterOperation]
    root_uid: int

    def __init__(self) -> None:
        """Initialize the TraceRecorder."""
        self._operation_log = []
        self.root_uid = RecordedTrace[DataToken].DEFAULT_ROOT_UID

    def record_call(
        self,
        operation_name: str,
        parent_uid: int,
        call_args: Tuple[Any, ...],
        call_kwargs: Dict[str, Any],
    ) -> int:
        """Record that a call of the specified function has occurred with the given arguments."""
        uid = len(self._operation_log)
        call_args = deepcopy(call_args)
        call_kwargs = deepcopy(call_kwargs)
        self._operation_log.append(
            AdapterOperation("call", operation_name, uid, parent_uid, (call_args, call_kwargs))
        )
        return uid

    def record_iterable(
        self, operation_name: str, parent_uid: int, iterable: Iterable[T]
    ) -> Iterable[Tuple[int, T]]:
        """Record each data item in the given iterable as a yield with the provided metadata.

        Args:
            operation_name: name to associate with this operation; usually the name of the function
                            whose iterable output is being recorded.
            parent_uid: unique identifier of the parent operation of this operation.
            iterable: iterable to record

        Yields:
            for each piece of data yielded by the input iterable, yields a tuple of:
            - the operation's unique identifier for the yielded data, and
            - the input iterable's yielded data itself.
        """
        for item in iterable:
            item_uid = len(self._operation_log)
            self._operation_log.append(
                AdapterOperation("yield", operation_name, item_uid, parent_uid, deepcopy(item))
            )
            yield item_uid, item

    def record_compound_iterable(
        self,
        operation_name: str,
        parent_uid: int,
        compound_iterable: Iterable[Tuple[U, Iterable[T]]],
    ) -> Iterable[Tuple[int, Tuple[U, Iterable[T]]]]:
        """Record all yields for the given iterable-of-iterables.

        This function is similar to record_iterable() above, but adapted to the needs of
        the InterpreterAdapter's project_neighbors() function, which yields iterables that
        themselves contain iterables. In that case, making an accurate record of the order of
        all yields is a tricky process: the outer iterable and any of the produced inner iterables
        may be actuated with few limitations (essentially just "can't iterate inner iterables that
        haven't been yielded yet").

        This function tracks all yields of the outer iterable, and uses self.record_iterable() to
        track the yields for each produced inner iterable.

        Args:
            operation_name: name to associate with this operation; usually the name of the function
                            whose compound iterable output is being recorded.
            parent_uid: unique identifier of the parent operation of this operation.
            compound_iterable: iterable to record

        Yields:
            for each piece of data yielded by the input compound_iterable, yields a tuple of:
            - the operation's unique identifier for the yielded data, and
            - the input compound_iterable's yielded data itself.
        """
        for item_index, item in enumerate(compound_iterable):
            item_uid = len(self._operation_log)
            iterable_name = f"__output_iterable_{item_index}"
            non_iterable_data, iterable_data = item
            non_iterable_data = deepcopy(non_iterable_data)

            operation_data = (non_iterable_data, iterable_name)
            self._operation_log.append(
                AdapterOperation("yield", operation_name, item_uid, parent_uid, operation_data)
            )

            inner_iterable = _unzip_and_yield_second(
                self.record_iterable(iterable_name, item_uid, iterable_data)
            )
            yield item_uid, (non_iterable_data, inner_iterable)

    def get_trace(self) -> RecordedTrace[DataToken]:
        """Create an immutable trace with all the activity up to this point."""
        return RecordedTrace(tuple(self._operation_log))


text:
'use strict';

angular.module('myApp.dashboard', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/dashboard', {
        templateUrl: 'dashboard/dashboard.html',
        controller: 'DashboardController',
        controllerAs: 'DashboardCtrl'
    });
}])

.controller('DashboardController', ['$scope', '$timeout', 'CommonProp', function ($scope, $timeout, CommonProp) {
            var _self = this;
            if (!CommonProp.getUser()) {
                CommonProp.changeLocation('/login');
            } else {
                this.username = CommonProp.getUser().name;
                this.searchInitiated = false;
                this.articlesLoaded = false;
                this.articles = [];
                $scope.$watch('search.name', function (newVal, oldVal) {
                    if (newVal && !oldVal) {
                        _self.articlesLoaded = false;
                        _self.searchInitiated = true;
                        CommonProp.fetchAllPlanets(newVal).then(function () {
                            _self.articles = CommonProp.getPlanetsData();
                            _self.articlesLoaded = true;
                        });
                    } else {
                        if (!newVal) {
                            _self.articles = [];
                            _self.articlesLoaded = false;
                            _self.searchInitiated = false;
                        }
                    }
                });
            }
}]);


text:
package korolev

import java.util.concurrent.Executors

import korolev.util.{JavaTimerScheduler, Scheduler}

import scala.collection.concurrent.TrieMap
import scala.concurrent.ExecutionContext
import scala.language.higherKinds
import scala.reflect.ClassTag

/**
  * @author Aleksey Fomkin <aleksey.fomkin@gmail.com>
  */
object execution {

  private val schedulerCache = TrieMap.empty[Any, Any]

  implicit val defaultExecutor = ExecutionContext.
    fromExecutorService(Executors.newWorkStealingPool())

  implicit def defaultScheduler[F[+_]: Async]: Scheduler[F] = {
    val async = Async[F]
    val scheduler = schedulerCache.getOrElseUpdate(async, new JavaTimerScheduler[F])
    scheduler.asInstanceOf[Scheduler[F]]
  }
}


text:
<?php
namespace Craft;

class DeprecatedTag_TokenParser extends \Twig_TokenParser
{
	// Properties
	// =========================================================================

	/**
	 * @var string
	 */
	private $_tag;

	// Public Methods
	// =========================================================================

	/**
	 * Constructor
	 *
	 * @param string $tag
	 *
	 * @return DeprecatedTag_TokenParser
	 */
	public function __construct($tag)
	{
		$this->_tag = $tag;
	}

	/**
	 * Parses resource include tags.
	 *
	 * @param \Twig_Token $token
	 *
	 * @return DeprecatedTag_Node
	 */
	public function parse(\Twig_Token $token)
	{
		$lineno = $token->getLine();
		$stream = $this->parser->getStream();

		// Parse until we reach the end of this tag
		while (!$stream->test(\Twig_Token::BLOCK_END_TYPE))
		{
			$stream->next();
		}

		$stream->expect(\Twig_Token::BLOCK_END_TYPE);

		$filename = $stream->getFilename();
		craft()->deprecator->log("{% {$this->_tag} %}", "The {% {$this->_tag} %} tag is no longer necessary. You can remove it from your '{$filename}' template on line {$lineno}.");

		return new \Twig_Node(array(), array(), $lineno, $this->_tag);
	}

	/**
	 * Defines the tag name.
	 *
	 * @return string
	 */
	public function getTag()
	{
		return $this->_tag;
	}
}


text:
<?php

declare(strict_types=1);

namespace LooplineSystems\CloseIoApiWrapper\Exception;

use Fig\Http\Message\StatusCodeInterface;
use LooplineSystems\CloseIoApiWrapper\CloseIoResponse;
use Throwable;

/**
 * This exception is thrown when a Close.io response returns an error.
 *
 * @author Stefano Arlandini <sarlandini@alice.it>
 */
class CloseIoResponseException extends CloseIoException
{
    private const UNKNOWN_ERROR_MESSAGE = 'Unknown error from Close.io REST API.';

    /**
     * @var CloseIoResponse The response that threw the exception
     */
    private $response;

    /**
     * Constructor.
     *
     * @param CloseIoResponse $response The response that threw the exception
     * @param Throwable|null  $previous The previous throwable used for the exception chaining
     */
    public function __construct(CloseIoResponse $response, Throwable $previous = null)
    {
        $this->response = $response;

        parent::__construct($response->getDecodedBody()['error'] ?? self::UNKNOWN_ERROR_MESSAGE, 0, $previous);
    }

    /**
     * A factory method for creating the appropriate exception based on the
     * response from Close.io.
     *
     * @param CloseIoResponse $response The response that threw the exception
     *
     * @return self
     */
    public static function create(CloseIoResponse $response): self
    {
        switch ($response->getHttpStatusCode()) {
            case StatusCodeInterface::STATUS_UNAUTHORIZED:
                return new CloseIoAuthenticationException($response);
            case StatusCodeInterface::STATUS_TOO_MANY_REQUESTS:
                return new CloseIoThrottleException($response);
            case StatusCodeInterface::STATUS_NOT_FOUND:
                return new CloseIoResourceNotFoundException($response);
            case StatusCodeInterface::STATUS_BAD_REQUEST:
                return new CloseIoBadRequestException($response);
            default:
                return new static($response);
        }
    }

    /**
     * Gets the response that threw the exception.
     *
     * @return CloseIoResponse
     */
    public function getResponse(): CloseIoResponse
    {
        return $this->response;
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NodaTime;
using NodaTime.Text;
using System;

namespace TempoDB.Json
{
    public class PeriodConverter : JsonConverter
    {
        private PeriodPattern pattern;

        public PeriodConverter()
        {
            this.pattern = PeriodPattern.NormalizingIsoPattern;
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(Period).IsAssignableFrom(objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (!(value is Period))
            {
                throw new ArgumentException(string.Format("Unexpected value when converting. Expected {0}, got {1}.", typeof(Period).FullName, value.GetType().FullName));
            }

            var period = (Period)value;
            writer.WriteValue(pattern.Format(period));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (objectType != typeof(Period))
                    throw new Exception(string.Format("Cannot convert null value to {0}.", objectType));

                return null;
            }

            var periodText = reader.Value.ToString();
            if (string.IsNullOrEmpty(periodText) && objectType == typeof(Period))
                return null;

            var period = pattern.Parse(periodText).Value;
            return period;
        }
    }
}