text:
Animations are exciting, and get things moving.  But they suffer from one big
drawback: they have no memory!  Every new frame of the program starts over, with
only one number: how many seconds since the start.  You can build animations for
simple motion, where you can immediately describe what it's like at any point as
an expression involving time.  But animations break down when you want something
that acts in a less predictable way.

Think about a ball bouncing around in a room.  Can you write an expression that
says exactly where the ball will be at any point in time?  It's not easy!  But
if you know the position and direction the ball is moving, you can figure out
where it should go next.  This is an example of something that's *hard* to
describe as a function of time, but *easier* to describe the changes happening
in each moment.

We now want to describe programs that have *state*, or memory.  In CodeWorld,
the simplest programs with state are called simulations.

Parts of a Simulation
=====================

Pictures and animations were described by a single thing: for a pictures, it was
a picture.  For animations, it was a function mapping numbers to pictures.  But
a simulation is actually built out of *three* separate (but related) parts.
Here they are:

Part 1: Initial state
---------------------

The first part of a simulation is often called `initial`, and it tells you how
the simulation is when it starts.

Part 2: Step function
---------------------

The next part of a simulation is often called `step`, and it tells you how the
simulation changes when time passes.

Part 3: Picture function
------------------------

The final part of a simulation is often called `picture`, and it tells you how the
simulation should be presented on the screen as a `Picture`.

All three of these parts share some data called the "world", which records
everything you want to *remember* about the simulation as it happens.

Building Simulations
====================

It may sound complicated, but let's jump in and look at an example:

    program          = simulationOf(initial, step, picture)
    initial(rs)      = (5, 0)
    step((x, y), dt) = (x - y * dt, y + x * dt)
    picture(x, y)    = translated(rectangle(1, 1), x, y)

In this case, the "world" is a point: the location of an object.  The step
function is the heart of any simulation.  Here, it changes the `x` and `y`
coordinates to move the object, by amounts that depend on where the object is
now.  When the object is near the top of the screen, so `y` is a large number,
it's pushed to the left.  Conversely, when it's near the bottom and `y` is
negative, it's pushed to the right.  When it's near the right, so `x` is a large
number, it's pushed up.  When `x` is negative on the left side, it's pushed
down.

This still leaves `initial`, which tells us that the object starts at (5,0), and
`picture`, which says the object looks like a square, and appears at the
position in the world.

Can you guess what this will look like?  Try it and find out!

Simulations are a lot like science experiments.  You get to describe the rules
for how things change at each moment in time, but the overall behavior of the
system can still surprise you!

Choosing a World
----------------

The world type is the first big choice you make when building a simulation.  In
the simulation above, the world was a point.  When you write your own simulations,
though, the world type can be whatever you choose.  The world type is your answer
to this question:  What do I need to *remember* for the simulation to continue.

Think of these possibilities:
* Do you need to remember the *locations* of things?
* Do you need to remember the *speed* things are moving?
* Do you need to remember the *direction* things are moving?
* Do you need to remember the *angle* of something that turns?

Anything you need to remember will go into your world type.  Let's look at some
examples.

### Simulations with one number ###

The simplest kind of state is a single number.  Let's build a simulation to move
a box across the screen.  You could have done this with an animation, but this
makes a good starting point to learn how things work with simulations.

    program     = simulationOf(initial, step, picture)
    initial(rs) = -10
    step(x, dt) = x + dt
    picture(x)  = translated(solidRectangle(1, 1), x, 0)

The world, in thic coordinate, is the x coordinate of the box.  That's the only
thing you need to remember!  Why not the y coordinate?  Because it is always
zero, so it doesn't change.

Now that we know what the world looks like, let's examine the three parts of
this simulation.  The initial x coordinate is -10, meaning the box starts on the
left edge of the screen.  When time passes, the amount of time passed is added to
the x coordinate, to produce a new x coordinate.  So the x coordinate will
increase at a rate of one unit for every one second.  The program looks like a
box, translated by the x coordinate, and 0 in the y direction.

Try this out, and verify that it does what you expect.

* Can you modify the code to move the box up?  What about left or down?
* Can you modify the code to use rotation instead of translation?
* Can you change the speed at which the box moves?  (Hint: use multiplication.)

### Simulations with multiple numbers ###

Adding a second number to the state lets you describe different kinds of change
at the same time.  Let's try to make a rolling wheel, which will need to move
(translation) and turn (rotation) at the same time.  In the state, we'll need
both an x coordinate, and an angle of rotation.

    program = simulationOf(initial, step, picture)
    initial(rs) = (-10, 0)
    step((x, angle), dt) = (x + dt, angle - 60 * dt)
    picture(x, angle) = translated(rotated(wheel, angle), x, 0)
    wheel = circle(1) & solidRectangle(2, 1/4) & solidRectangle(1/4, 2)

The initial world has an x coordinate of -10, and an angle of zero.  As time
passes, the x coordinate increases by one unit per second, but the angle of
rotation decreases by 60 degrees per second.  The screen looks like a wheel,
rotated by the angle, and translated by the current x coordinate.

* What happens if you add `60 * dt` instead of subtracting?
* What goes wrong if you use a different number for degrees per second?

If you were wondering, the angle of 60 was chosen by experimenting!  The right
speed for rotation depends on how fast the wheel is moving in the x direction
and the size of the wheel.  Here, a little math would tell you that the right
answer is 180 divided by pi, or about 57.3 degrees.  But 60 is close enough!

### Invisible state ###

So far, everything that has been part of the world has been visible in the
picture.  That's not always true, though!  In fact, it's rarely true for more
advanced animations.  Some things need to be remembered to draw to the screen,
but other things - like speeds, time remaining, etc. - need to be remembered
only because they affect how other things change in the future.

This simple animation shows a baseball flying through the air.  While only
the x position and y position are needed to *draw* the simulation, the y
speed also changes, and needs to be remembered.

    program = simulationOf(initial, step, picture)
    initial(rs) = (-9, -9, 15)
    step((x, y, vy), dt) = (x + 6 * dt, y + vy * dt, vx, vy - 10 * dt)
    picture(x, y, vy) = translated(solidCircle(1/2), x, y)

As you can see, the velocity in the y direction, `vy`, starts at 15 units per
second upward.  But as time passes, it decreases, until eventually it becomes
negative, and the ball falls back down again.

* What would happen if the ball started at a different position?
* How would you change the effect of gravity to simulate a ball on the moon?

Simulating Physics
==================

One of the most common things to do with simulations is simulate physics.
To do this, we'll want to make some observations about the physical world.

Position and Velocity
---------------------

The first of these observations was made by Isaac Newton, who first described
many of the foundations of physics as we understand them today.

> *Newton's First Law of Motion*: Every object persists in its state of rest
> or uniform motion in a straight line unless it is compelled to change that
> state by forces impressed on it.

Another way of putting this is that the *state* of an object consists of both
its position, and its velocity.  You can make this observation yourself: when
you throw a ball, your hand is pushing the ball; but when you let go, you are
no longer pushing the ball forward.  Does it stop right away?  No!  The ball
keeps its current velocity, and keeps on moving until something else happens
to stop it.

What this means is that any time you have an object moving with physics in a
simulation, you should start out thinking about both *position* and *velocity*
of that object as part of the state.

The last example above already did for this for movement in the y direction.
But we could rewrite it to keep track of velocity in the x direction, as well.

    program = simulationOf(initial, step, picture)
    initial(rs) = (-9, -9, 6, 15)
    step((x, y, vx, vy), dt) = (x + vx * dt, y + vy * dt, vx, vy - 10 * dt)
    picture(x, y, vx, vy) = translated(solidCircle(1/2), x, y)

This simulation does the same thing as the one before it, but notice how we've
taken the constant `6`, and moved it from the code for the `step` function to a
part of the state.  That is an acknowledgement that although the velocity in x
is always 6 at the moment, there's no reason it couldn't be something different!

Gravity
-------

This section is still in progress.

Other Forces
------------

This section is still in progress.

Designing With Simulation
=========================

This section is still in progress.

Horizontal Composition
----------------------

This section is still in progress.

Vertical Composition
--------------------

This section is still in progress.


text:
"""
This module implements BaseNeutronClient for the Tempest rest client
and configures the api tests with scenarios targeting the Neutron API.
"""

from tempest_lib import exceptions
import testscenarios

from neutron.tests.api import base_v2
from neutron.tests.tempest import test as t_test

# Required to generate tests from scenarios.  Not compatible with nose.
load_tests = testscenarios.load_tests_apply_scenarios

class TempestRestClient(base_v2.BaseNeutronClient):

    @property
    def client(self):
        if not hasattr(self, '_client'):
            manager = t_test.BaseTestCase.get_client_manager()
            self._client = manager.network_client
        return self._client

    @property
    def NotFound(self):
        return exceptions.NotFound

    def _cleanup_network(self, id_):
        try:
            self.delete_network(id_)
        except self.NotFound:
            pass

    def create_network(self, **kwargs):
        network = self._create_network(**kwargs)
        self.test_case.addCleanup(self._cleanup_network, network.id)
        return network

    def _create_network(self, **kwargs):
        # Internal method - use create_network() instead
        body = self.client.create_network(**kwargs)
        return base_v2.AttributeDict(body['network'])

    def update_network(self, id_, **kwargs):
        body = self.client.update_network(id_, **kwargs)
        return base_v2.AttributeDict(body['network'])

    def get_network(self, id_, **kwargs):
        body = self.client.show_network(id_, **kwargs)
        return base_v2.AttributeDict(body['network'])

    def get_networks(self, **kwargs):
        body = self.client.list_networks(**kwargs)
        return [base_v2.AttributeDict(x) for x in body['networks']]

    def delete_network(self, id_):
        self.client.delete_network(id_)

class TestApiWithRestClient(base_v2.BaseTestApi):
    scenarios = [('tempest', {'client': TempestRestClient()})]

redpajama_set_name: RedPajamaGithub


text:
package com.github.msoliter.iroh.examples.network;

import com.github.msoliter.iroh.container.annotations.Component;
import com.github.msoliter.iroh.examples.network.NetworkServiceConfiguration.NetworkAPI;

@Component
public class NetworkServiceTestConfiguration {

    @Component(override = true)
    public NetworkAPI stubNetworkApi() {
        return new NetworkAPI() {
            public void send(Object object) {

            }

            public Object receive() {
                return null;
            }
        };
    }
}


text:
define([
	'dojo/i18n!../../nls/messages',
	'dojo/topic',
	"dojo/_base/declare",
	"gform/controller/actions/_ActionMixin"

], function (messages, topic, declare, _ActionMixin) {

	return declare([_ActionMixin], {
		messageModule: "actions.createCollection",
		getMessages: function () {
			return messages;
		},
		execute: function () {
			var entity = this.ctrl.editor.getPlainValue();
			topic.publish("/new", {source: this,  store: "/mdbcollection",value:{db:entity.name}});
		}
	});
});


text:
/**
 * User Service
 * @module
 */
const Path = require('path');
const Hoek = require('@hapi/hoek');
const NSError = require('errors/nserror');
const Repository = require('plugins/repository');
const Auth = require('plugins/auth');
const Mailer = require('plugins/mailer');
const Config = require('config');

const internals = {};

internals.andActive = (query, active) => (active ? query.andWhere('active', true) : query);

/**
 * Counts the number of users
 * @async
 * @param {Object} [criteria] search criteria
 * @returns {Promise<number>} the number of users
 */
exports.count = async function(criteria = {}) {
    const query = internals.andActive(Repository.User.query(), criteria.active);

    return (await Repository.User.count(criteria, query)).count;
};

/**
 * Retrieves all users
 * @param {(number|string|Object)} [criteria] search criteria
 * @returns {Promise<User[]>} all retrieved users
 */
exports.list = function(criteria = {}) {
    return internals.andActive(
        Repository.User.findAll(criteria).omit(['password']),
        criteria.active
    );
};

/**
 * Retrieves a user by its id
 * @async
 * @param {number} id the user id
 * @returns {Promise<User>} the retrieved user
 */
exports.findById = async function(id) {
    const user = await Repository.User.findOne(id)
        .omit(['password'])
        .withGraphFetched('roles');

    if (!user) {
        throw NSError.RESOURCE_NOT_FOUND();
    }

    return user;
};

/**
 * Retrieves a user by its username
 * @async
 * @param {string} username the username
 * @returns {Promise<User>} the retrieved user
 */
exports.findByUserName = async function(username) {
    const user = await Repository.User.query()
        .findOne({ username })
        .omit(['password'])
        .withGraphFetched('roles');

    if (!user) {
        throw NSError.RESOURCE_NOT_FOUND();
    }

    return user;
};

/**
 * Retrieves user entities by name
 * @param {string} name the name of the user
 * @returns {Promise<User[]>} the retrieved users
 */
exports.findByName = function(name) {
    // same name can exist on multiple users
    return Repository.User.query()
        .where('name', name)
        .omit(['password']);
};

/**
 * Retrieves a user by its email
 * @async
 * @param {string} email the user email
 * @returns {Promise<User>} the retrieved user
 */
exports.findByEmail = async function(email) {
    const user = await Repository.User.query()
        .findOne({ email })
        .omit(['password']);

    if (!user) {
        throw NSError.RESOURCE_NOT_FOUND();
    }

    return user;
};

/**
 * Saves a user
 * @param {User} entity the user to save
 * @returns {Promise<User>} the added user
 */
exports.add = function(entity) {
    return Repository.tx(Repository.User.model, async txUserRepository => {
        const getHash = Auth.crypt(entity.password);
        const getEqualUsers = txUserRepository
            .query()
            .where('username', entity.username)
            .orWhere('email', entity.email);

        const [equalUsers, hash] = await Promise.all([getEqualUsers, getHash]);

        if (equalUsers.length !== 0) {
            throw NSError.RESOURCE_DUPLICATE();
        }

        entity.password = hash;
        entity.active = false;

        return txUserRepository.add(entity);
    });
};

/**
 * Updates an existing user
 * @param {number} id the id of the user to update
 * @param {User} entity the user to update
 * @returns {Promise<User>} the updated user
 */
exports.update = function(id, entity) {
    return Repository.tx(Repository.User.model, async txUserRepository => {
        const getUserByID = txUserRepository.findOne(id);
        const getEqualUsers =
            entity.username || entity.email
                ? txUserRepository
                      .query()
                      .skipUndefined()
                      .where('username', entity.username)
                      .orWhere('email', entity.email)
                : Promise.resolve([]);

        const [user, equalUsers] = await Promise.all([getUserByID, getEqualUsers]);

        if (!user) {
            throw NSError.RESOURCE_NOT_FOUND();
        }

        // username or email is already taken, we should not update
        if (equalUsers.length > 0 && equalUsers.some(equalUser => equalUser.id !== user.id)) {
            throw NSError.RESOURCE_DUPLICATE();
        }

        Hoek.merge(user, Hoek.clone(entity, { shallow: Repository.User.model.updateFields }));

        if (entity.password) {
            user.password = await Auth.crypt(entity.password);
        }

        return txUserRepository.update(user);
    });
};

/**
 * Authenticates a user
 * @async
 * @param {string} username the user username
 * @param {string} password the user password
 * @param {boolean|number|string} expiresIn expressed in seconds or a string describing a time span or false if token never expires
 * @returns {Promise<string>} the authentication token
 */
exports.authenticate = async function(username, password, expiresIn) {
    const user = await Repository.User.query().findOne({ username });

    if (!user || !user.active) {
        throw NSError.AUTH_INVALID_CREDENTIALS();
    }

    const result = await Auth.compare(password, user.password);

    if (!result) {
        throw NSError.AUTH_INVALID_CREDENTIALS();
    }

    return Auth.getToken({ id: user.id }, expiresIn);
};

/**
 * Removes a user
 * @param {number} id the user id
 * @returns {Promise} resolved if the transaction was committed with success
 */
exports.delete = function(id) {
    return Repository.tx(Repository.User.model, async txUserRepository => {
        const user = await txUserRepository.findOne(id);

        if (!user) {
            throw NSError.RESOURCE_NOT_FOUND();
        }

        if (user.active) {
            throw NSError.RESOURCE_STATE();
        }

        const count = await txUserRepository.remove(id);

        if (count !== 1) {
            throw NSError.RESOURCE_DELETE();
        }

        return;
    });
};

/**
 * Sends a password reset email
 * @param {string} host host the server host requesting password reset email
 * @param {string} email the user email address
 */
exports.sendPasswordResetEmail = async function(host, email) {
    // look for active user, if disabled can not reset password
    const user = await Repository.User.query().findOne({ email, active: true });

    if (!user) {
        throw NSError.RESOURCE_NOT_FOUND('Email address not found');
    }

    const token = await Auth.getToken(
        { id: user.id },
        Config.auth.passwordResetIn,
        Auth.token.PASSWORD_RESET
    );

    await Mailer.sendMail({
        from: Config.mail.address.passwordReset,
        to: email,
        subject: 'Noire Server Password Reset',
        template: 'password-reset',
        context: {
            url: `${Path.join(host, Config.mail.url.passwordReset)}?token=${token}`
        }
    });
};


text:
import actionlib
import control_msgs.msg
import rospy

CLOSED_POS = 0.0  # The position for a fully-closed gripper (meters).
OPENED_POS = 0.10  # The position for a fully-open gripper (meters).
ACTION_SERVER = 'gripper_controller/gripper_action'

class Gripper(object):
    """Gripper controls the robot's gripper.
    """
    MIN_EFFORT = 35  # Min grasp force, in Newtons
    MAX_EFFORT = 100  # Max grasp force, in Newtons

    def __init__(self):
        self._client = actionlib.SimpleActionClient(ACTION_SERVER, control_msgs.msg.GripperCommandAction)
        self._client.wait_for_server(rospy.Duration(10))

    def open(self):
        """Opens the gripper.
        """
        goal = control_msgs.msg.GripperCommandGoal()
        goal.command.position = OPENED_POS
        self._client.send_goal_and_wait(goal, rospy.Duration(10))

    def close(self, max_effort=MAX_EFFORT):
        """Closes the gripper.

        Args:
            max_effort: The maximum effort, in Newtons, to use. Note that this
                should not be less than 35N, or else the gripper may not close.
        """
        goal = control_msgs.msg.GripperCommandGoal()
        goal.command.position = CLOSED_POS
        goal.command.max_effort = max_effort
        self._client.send_goal_and_wait(goal, rospy.Duration(10))


text:
Advantages of microkernels
==========================

There are quite a lot of advantages (and disadvantages!) to microkernels, a few of which will be covered here.

Modularity and customizability
------------------------------

Monolithic kernels are, well, monolithic. They do not allow as fine-grained control as microkernels. This is due to many essential components being "hard-coded" into the kernel, and thus requiring modifications to the kernel itself (e.g., device drivers).

Microkernels are very modular by nature. You can replace, reload, modify, change, and remove modules, on runtime, without even touching the kernel.

Modern monolithic kernels try to solve this issue using kernel modules but still often require the system to reboot.

Security
--------

Microkernels are undoubtedly more secure than monolithic kernels. The minimality principle of microkernels is a direct consequence of the principle of least privilege, according to which all components should have only the privileges absolutely needed to provide the needed functionality.

Many security-critical bugs in monolithic kernels stem from services and drivers running unrestricted in kernel mode, without any form of protection.

In other words: **in monolithic kernels, drivers can do whatever, without restrictions, when running in ring 0**.

Fewer crashes
-------------

When compared to microkernels, Monolithic kernels tend to be crash-prone. A crashed driver in a Monolithic kernel can crash the whole system whereas with a microkernel there is a separation of concerns which allows the system to handle any crash safely.

In Linux we often see errors with drivers dereferencing bad pointers which ultimately results in kernel panics.

[There is very good documentation in MINIX about how this can be addressed by a microkernel.]

[There is very good documentation in MINIX about how this can be addressed by a microkernel.]: http://wiki.minix3.org/doku.php?id=www:documentation:reliability


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-108.js
 * @description Object.defineProperties - 'P' is accessor property, P.configurable is true and properties.configurable is false
 */

function testcase() {

        var obj = {};

        function get_func() {
            return 10;
        }
        function set_func(value) {
            obj.setVerifyHelpProp = value;
        }

        Object.defineProperty(obj, "foo", {
            get: get_func,
            set: set_func,
            enumerable: true,
            configurable: true
        });

        Object.defineProperties(obj, {
            foo: {
                configurable: false
            }
        });
        return accessorPropertyAttributesAreCorrect(obj, "foo", get_func, set_func, "setVerifyHelpProp", true, false);
    }
runTestCase(testcase);


text:
package chemistry;

/*
To do:

- CompoundSeries class should have a method to determine the products

 */

//example: H2O + CO2
public class CompoundSeries
{
	Compound[] compounds;

	public static void main(String[] args)
	{
//		CompoundSeries test = new CompoundSeries("H2O + CO2");
//		System.out.println(new CompoundSeries("H2O+CO2"));
//		System.out.println(new CompoundSeries("C(OH) + CO2"));
		System.out.println(new CompoundSeries("Calcium + Phosphorus"));
	}

	public CompoundSeries(Compound[] compounds)
	{
		this.compounds = compounds;
	}

	public CompoundSeries(Compound compound1, Compound compound2)
	{
		this(new Compound[] {compound1, compound2});
	}

	public CompoundSeries(String str)
	{
		try
		{
			if(str.replaceAll(" ?\\+ ?", "").equals(str))
				compounds = new Compound[] {new Compound(str)};
			else
			{
				String[] strArray = str.split(" ?\\+ ?");		// matches + with or without spaces

				compounds = new Compound[strArray.length];
				for(int i = 0; i < strArray.length; i++)
					compounds[i] = new Compound(strArray[i]);

//				for(int i = 0; i < compounds.length; i++)
//					System.out.print(compounds[i]);

			}
			System.out.println("new CompoundSeries: "+str);
		}
		catch(Exception e)
		{
			System.err.println("failed to create CompoundSeries: "+str);
		}

	}

	public String toString()
	{
		String out = "";
		for(int i = 0; i < compounds.length; i++)
			out += " + "+compounds[i];
		out = out.substring(3);
		return out;
	}
}


text:
<?php

namespace Hris\FormBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

use Hris\FormBundle\Entity\Field;
use Hris\FormBundle\Entity\FieldGroupset;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Hris\FormBundle\Entity\FieldGroup
 *
 * @Gedmo\Loggable
 * @ORM\Table(name="hris_fieldgroup")
 * @ORM\Entity(repositoryClass="Hris\FormBundle\Entity\FieldGroupRepository")
 */
class FieldGroup
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $uid
     *
     * @Gedmo\Versioned
     * @ORM\Column(name="uid", type="string", length=13, unique=true)
     */
    private $uid;

    /**
     * @var string $name
     *
     * @Gedmo\Versioned
     * @ORM\Column(name="name", type="string", length=64, unique=true)
     */
    private $name;

    /**
     * @var string $description
     *
     * @Gedmo\Versioned
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var Field $field
     *
     * @ORM\ManyToMany(targetEntity="Hris\FormBundle\Entity\Field", inversedBy="fieldGroup")
     * @ORM\JoinTable(name="hris_fieldgroup_members",
     *   joinColumns={
     *     @ORM\JoinColumn(name="fieldgroup_id", referencedColumnName="id", onDelete="CASCADE")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="field_id", referencedColumnName="id", onDelete="CASCADE")
     *   }
     * )
     * @ORM\OrderBy({"name" = "ASC"})
     */
    private $field;

    /**
     * @var FieldGroupset $fieldGroupset
     *
     * @ORM\ManyToMany(targetEntity="Hris\FormBundle\Entity\FieldGroupset", mappedBy="fieldGroup")
     * @ORM\OrderBy({"name" = "ASC"})
     */
    private $fieldGroupset;

    /**
     * @var \DateTime $datecreated
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="datecreated", type="datetime")
     */
    private $datecreated;

    /**
     * @var \DateTime $lastupdated
     *
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(name="lastupdated", type="datetime", nullable=true)
     */
    private $lastupdated;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return FieldGroup
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set uid
     *
     * @param string $uid
     * @return FieldGroup
     */
    public function setUid($uid)
    {
        $this->uid = $uid;

        return $this;
    }

    /**
     * Get uid
     *
     * @return string
     */
    public function getUid()
    {
        return $this->uid;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return FieldGroup
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set datecreated
     *
     * @param \DateTime $datecreated
     * @return FieldGroup
     */
    public function setDatecreated($datecreated)
    {
        $this->datecreated = $datecreated;

        return $this;
    }

    /**
     * Get datecreated
     *
     * @return \DateTime
     */
    public function getDatecreated()
    {
        return $this->datecreated;
    }

    /**
     * Set lastupdated
     *
     * @param \DateTime $lastupdated
     * @return FieldGroup
     */
    public function setLastupdated($lastupdated)
    {
        $this->lastupdated = $lastupdated;

        return $this;
    }

    /**
     * Get lastupdated
     *
     * @return \DateTime
     */
    public function getLastupdated()
    {
        return $this->lastupdated;
    }

    /**
     * Add field
     *
     * @param Field $field
     * @return FieldGroup
     */
    public function addField(Field $field)
    {
        $this->field[$field->getId()] = $field;

        return $this;
    }

    /**
     * Remove field
     *
     * @param Field $field
     */
    public function removeField(Field $field)
    {
        $this->field->removeElement($field);
    }

    /**
     * Get field
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getField()
    {
        return $this->field;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->field = new ArrayCollection();
        $this->fieldGroupset = new ArrayCollection();
        $this->uid = uniqid();
    }

    /**
     * Add fieldGroupset
     *
     * @param FieldGroupset $fieldGroupset
     * @return FieldGroup
     */
    public function addFieldGroupset(FieldGroupset $fieldGroupset)
    {
        $this->fieldGroupset[$fieldGroupset->getId()] = $fieldGroupset;

        return $this;
    }

    /**
     * Remove fieldGroupset
     *
     * @param FieldGroupset $fieldGroupset
     */
    public function removeFieldGroupset(FieldGroupset $fieldGroupset)
    {
        $this->fieldGroupset->removeElement($fieldGroupset);
    }

    /**
     * Get fieldGroupset
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getFieldGroupset()
    {
        return $this->fieldGroupset;
    }

    /**
     * Get Entity verbose name
     *
     * @return string
     */
    public function __toString()
    {
        return $this->name;
    }
}


text:
SET @sName = 'bx_notifications';

-- TABLES
CREATE TABLE IF NOT EXISTS `bx_notifications_events` (
  `id` int(11) NOT NULL auto_increment,
  `owner_id` int(11) unsigned NOT NULL default '0',
  `type` varchar(255) collate utf8_unicode_ci NOT NULL,
  `action` varchar(255) collate utf8_unicode_ci NOT NULL,
  `object_id` text collate utf8_unicode_ci NOT NULL,
  `object_privacy_view` int(11) NOT NULL default '3',
  `content` text collate utf8_unicode_ci NOT NULL,
  `date` int(11) NOT NULL default '0',
  `active` tinyint(4) NOT NULL default '1',
  PRIMARY KEY  (`id`),
  KEY `owner_id` (`owner_id`)
);

CREATE TABLE IF NOT EXISTS `bx_notifications_events2users` (
  `user_id` int(11) NOT NULL DEFAULT '0',
  `event_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `bx_notifications_handlers` (
  `id` int(11) NOT NULL auto_increment,
  `type` enum('insert','update','delete') NOT NULL DEFAULT 'insert',
  `alert_unit` varchar(64) NOT NULL default '',
  `alert_action` varchar(64) NOT NULL default '',
  `content` text collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE `handler` (`alert_unit`, `alert_action`)
);

INSERT INTO `bx_notifications_handlers`(`type`, `alert_unit`, `alert_action`, `content`) VALUES
('delete', 'profile', 'delete', '');

-- STUDIO PAGE & WIDGET
INSERT INTO `sys_std_pages`(`index`, `name`, `header`, `caption`, `icon`) VALUES
(3, @sName, '_bx_ntfs', '_bx_ntfs', 'bx_notifications@modules/boonex/notifications/|std-pi.png');
SET @iPageId = LAST_INSERT_ID();

SET @iParentPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name` = 'home');
SET @iParentPageOrder = (SELECT MAX(`order`) FROM `sys_std_pages_widgets` WHERE `page_id` = @iParentPageId);
INSERT INTO `sys_std_widgets` (`page_id`, `module`, `url`, `click`, `icon`, `caption`, `cnt_notices`, `cnt_actions`) VALUES
(@iPageId, @sName, '{url_studio}module.php?name=bx_notifications', '', 'bx_notifications@modules/boonex/notifications/|std-wi.png', '_bx_ntfs', '', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_actions";s:6:"params";a:0:{}s:5:"class";s:18:"TemplStudioModules";}');
INSERT INTO `sys_std_pages_widgets` (`page_id`, `widget_id`, `order`) VALUES
(@iParentPageId, LAST_INSERT_ID(), IF(ISNULL(@iParentPageOrder), 1, @iParentPageOrder + 1));


text:
package io.crate.types;

import static io.crate.types.TimeTZParser.parse;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import org.elasticsearch.test.ESTestCase;
import org.junit.Test;

public class TimeTZParserTest extends ESTestCase {

    private static org.hamcrest.Matcher<TimeTZ> isTZ(long value, int zoneOffset) {
        return is(new TimeTZ(value, zoneOffset));
    }

    @Test
    public void test_parse_time_correct_syntax_no_colon() {
        assertThat(parse("12"), isTZ(43200000000L, 0));
        assertThat(parse("12.000001"), isTZ(43200000001L, 0));
        assertThat(parse("1200"), isTZ(43200000000L, 0));
        assertThat(parse("1200.002"), isTZ(43200002000L, 0));
        assertThat(parse("120000"), isTZ(43200000000L, 0));
        assertThat(parse("120000.000003"), isTZ(43200000003L, 0));
    }

    @Test
    public void test_parse_time_correct_syntax_colon() {
        assertThat(parse("12:00"), isTZ(43200000000L, 0));
        assertThat(parse("12:00.999"), isTZ(43200999000L, 0));
        assertThat(parse("12:00:00"), isTZ(43200000000L, 0));
        assertThat(parse("12:00:00.003"), isTZ(43200003000L, 0));
    }

    @Test
    public void test_parse_time_correct_syntax_tz() {
        assertThat(parse("00+12"), isTZ(0L, 12 * 3600));
        assertThat(parse("00+1200"), isTZ(0L, 12 * 3600));
        assertThat(parse("00-12:00"), isTZ(0L, -12 * 3600));
        assertThat(parse("00.0+12"), isTZ(0L, 12 * 3600));
        assertThat(parse("00.0+1200"), isTZ(0L, 12 * 3600));
        assertThat(parse("00.000001  +12:00"), isTZ(1L, 12 * 3600));
    }

    @Test
    public void test_parse_time_range_overflow() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '24:00:00.000001' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 24");
        parse("24:00:00.000001");
    }

    @Test
    public void test_parse_time_unsupported_literal_long() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '234' could not be parsed, unparsed text found at index 2");
        parse("234");
    }

    @Test
    public void test_parse_time_unsupported_literal_floating_point() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '234.9999' could not be parsed, unparsed text found at index 2");
        parse("234.9999");
    }

    @Test
    public void test_parse_time_out_of_range_hh() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '25' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 25");
        parse("25");
    }

    @Test
    public void test_parse_time_out_of_range_hhmm() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '1778' could not be parsed: Invalid value for MinuteOfHour (valid values 0 - 59): 78");
        parse("1778");
    }

    @Test
    public void test_parse_time_out_of_range_hhmmss() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '175978' could not be parsed: Invalid value for SecondOfMinute (valid values 0 - 59): 78");
        parse("175978");
    }

    @Test
    public void test_parse_time_out_of_range_hh_floating_point() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Invalid value for HourOfDay (valid values 0 - 23): 25");
        parse("25.999999");
    }

    @Test
    public void test_parse_time_out_of_range_hhmm_floating_point() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Invalid value for MinuteOfHour (valid values 0 - 59): 78");
        parse("1778.999999");
    }

    @Test
    public void test_parse_time_out_of_range_hhmmss_floating_point() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Text '175978.999999' could not be parsed: Invalid value for SecondOfMinute (valid values 0 - 59): 78");
        parse("175978.999999");
    }

    @Test
    public void test_parse_time() {
        assertThat(parse("04"), isTZ(4 * 60 * 60 * 1000_000L, 0));
        assertEquals(parse("04"), parse("0400"));
        assertEquals(parse("04"), parse("04:00"));
        assertEquals(parse("04"), parse("040000"));
        assertEquals(parse("04"), parse("04:00:00"));
        assertEquals(parse("04"), parse("040000.0"));
        assertEquals(parse("04"), parse("04:00:00.0"));
        assertEquals(parse("04+00"), parse("04:00:00.0+00"));
        assertEquals(parse("04+00"), parse("04:00:00.0+0000"));
        assertEquals(parse("04+00"), parse("04:00:00.0+00:00"));
    }

    @Test
    public void test_format_time() {
        assertThat(TimeTZParser.formatTime(new TimeTZ(14400000000L, 0)), is("04:00:00"));
        assertThat(TimeTZParser.formatTime(new TimeTZ(14400123000L, 0)), is("04:00:00.123"));
        assertThat(TimeTZParser.formatTime(new TimeTZ(14400123666L, 65)), is("04:00:00.123666+00:01:05"));
    }

    @Test
    public void test_format_time_with_tz() {
        assertThat(TimeTZParser.formatTime(new TimeTZ(14400123000L, 123)),
                   is("04:00:00.123+00:02:03"));
        assertThat(TimeTZParser.formatTime(new TimeTZ(14400123666L, 14 * 3600 + 59 * 60)),
                   is("04:00:00.123666+14:59"));
    }
}


text:
"""

process_file(filename)

  takes templated file .xxx.src and produces .xxx file where .xxx
  is .pyf .f90 or .f using the following template rules:

  '<..>' denotes a template.

  All function and subroutine blocks in a source file with names that
  contain '<..>' will be replicated according to the rules in '<..>'.

  The number of comma-separated words in '<..>' will determine the number of
  replicates.

  '<..>' may have two different forms, named and short. For example,

  named:
   <p=d,s,z,c> where anywhere inside a block '<p>' will be replaced with
   'd', 's', 'z', and 'c' for each replicate of the block.

   <_c>  is already defined: <_c=s,d,c,z>
   <_t>  is already defined: <_t=real,double precision,complex,double complex>

  short:
   <s,d,c,z>, a short form of the named, useful when no <p> appears inside
   a block.

  In general, '<..>' contains a comma separated list of arbitrary
  expressions. If these expression must contain a comma|leftarrow|rightarrow,
  then prepend the comma|leftarrow|rightarrow with a backslash.

  If an expression matches '\\<index>' then it will be replaced
  by <index>-th expression.

  Note that all '<..>' forms in a block must have the same number of
  comma-separated entries.

 Predefined named template rules:
  <prefix=s,d,c,z>
  <ftype=real,double precision,complex,double complex>
  <ftypereal=real,double precision,\\0,\\1>
  <ctype=float,double,complex_float,complex_double>
  <ctypereal=float,double,\\0,\\1>

"""
__all__ = ['process_str', 'process_file']

import os
import sys
import re

routine_start_re = re.compile(r'(\n|\A)((     (\$|\*))|)\s*(subroutine|function)\b', re.I)
routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I)
function_start_re = re.compile(r'\n     (\$|\*)\s*function\b', re.I)

def parse_structure(astr):
    """ Return a list of tuples for each function or subroutine each
    tuple is the start and end of a subroutine or function to be
    expanded.
    """

    spanlist = []
    ind = 0
    while True:
        m = routine_start_re.search(astr, ind)
        if m is None:
            break
        start = m.start()
        if function_start_re.match(astr, start, m.end()):
            while True:
                i = astr.rfind('\n', ind, start)
                if i==-1:
                    break
                start = i
                if astr[i:i+7]!='\n     $':
                    break
        start += 1
        m = routine_end_re.search(astr, m.end())
        ind = end = m and m.end()-1 or len(astr)
        spanlist.append((start, end))
    return spanlist

template_re = re.compile(r"<\s*(\w[\w\d]*)\s*>")
named_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>")
list_re = re.compile(r"<\s*((.*?))\s*>")

def find_repl_patterns(astr):
    reps = named_re.findall(astr)
    names = {}
    for rep in reps:
        name = rep[0].strip() or unique_key(names)
        repl = rep[1].replace(r'\,', '@comma@')
        thelist = conv(repl)
        names[name] = thelist
    return names

def find_and_remove_repl_patterns(astr):
    names = find_repl_patterns(astr)
    astr = re.subn(named_re, '', astr)[0]
    return astr, names

item_re = re.compile(r"\A\\(?P<index>\d+)\Z")
def conv(astr):
    b = astr.split(',')
    l = [x.strip() for x in b]
    for i in range(len(l)):
        m = item_re.match(l[i])
        if m:
            j = int(m.group('index'))
            l[i] = l[j]
    return ','.join(l)

def unique_key(adict):
    """ Obtain a unique key given a dictionary."""
    allkeys = list(adict.keys())
    done = False
    n = 1
    while not done:
        newkey = '__l%s' % (n)
        if newkey in allkeys:
            n += 1
        else:
            done = True
    return newkey

template_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z')
def expand_sub(substr, names):
    substr = substr.replace(r'\>', '@rightarrow@')
    substr = substr.replace(r'\<', '@leftarrow@')
    lnames = find_repl_patterns(substr)
    substr = named_re.sub(r"<\1>", substr)  # get rid of definition templates

    def listrepl(mobj):
        thelist = conv(mobj.group(1).replace(r'\,', '@comma@'))
        if template_name_re.match(thelist):
            return "<%s>" % (thelist)
        name = None
        for key in lnames.keys():    # see if list is already in dictionary
            if lnames[key] == thelist:
                name = key
        if name is None:      # this list is not in the dictionary yet
            name = unique_key(lnames)
            lnames[name] = thelist
        return "<%s>" % name

    substr = list_re.sub(listrepl, substr) # convert all lists to named templates
                                           # newnames are constructed as needed

    numsubs = None
    base_rule = None
    rules = {}
    for r in template_re.findall(substr):
        if r not in rules:
            thelist = lnames.get(r, names.get(r, None))
            if thelist is None:
                raise ValueError('No replicates found for <%s>' % (r))
            if r not in names and not thelist.startswith('_'):
                names[r] = thelist
            rule = [i.replace('@comma@', ',') for i in thelist.split(',')]
            num = len(rule)

            if numsubs is None:
                numsubs = num
                rules[r] = rule
                base_rule = r
            elif num == numsubs:
                rules[r] = rule
            else:
                print("Mismatch in number of replacements (base <%s=%s>)"
                      " for <%s=%s>. Ignoring." %
                      (base_rule, ','.join(rules[base_rule]), r, thelist))
    if not rules:
        return substr

    def namerepl(mobj):
        name = mobj.group(1)
        return rules.get(name, (k+1)*[name])[k]

    newstr = ''
    for k in range(numsubs):
        newstr += template_re.sub(namerepl, substr) + '\n\n'

    newstr = newstr.replace('@rightarrow@', '>')
    newstr = newstr.replace('@leftarrow@', '<')
    return newstr

def process_str(allstr):
    newstr = allstr
    writestr = ''

    struct = parse_structure(newstr)

    oldend = 0
    names = {}
    names.update(_special_names)
    for sub in struct:
        cleanedstr, defs = find_and_remove_repl_patterns(newstr[oldend:sub[0]])
        writestr += cleanedstr
        names.update(defs)
        writestr += expand_sub(newstr[sub[0]:sub[1]], names)
        oldend =  sub[1]
    writestr += newstr[oldend:]

    return writestr

include_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P<name>[\w\d./\\]+\.src)['\"]", re.I)

def resolve_includes(source):
    d = os.path.dirname(source)
    with open(source) as fid:
        lines = []
        for line in fid:
            m = include_src_re.match(line)
            if m:
                fn = m.group('name')
                if not os.path.isabs(fn):
                    fn = os.path.join(d, fn)
                if os.path.isfile(fn):
                    print('Including file', fn)
                    lines.extend(resolve_includes(fn))
                else:
                    lines.append(line)
            else:
                lines.append(line)
    return lines

def process_file(source):
    lines = resolve_includes(source)
    return process_str(''.join(lines))

_special_names = find_repl_patterns('''
<_c=s,d,c,z>
<_t=real,double precision,complex,double complex>
<prefix=s,d,c,z>
<ftype=real,double precision,complex,double complex>
<ctype=float,double,complex_float,complex_double>
<ftypereal=real,double precision,\\0,\\1>
<ctypereal=float,double,\\0,\\1>
''')

def main():
    try:
        file = sys.argv[1]
    except IndexError:
        fid = sys.stdin
        outfile = sys.stdout
    else:
        fid = open(file, 'r')
        (base, ext) = os.path.splitext(file)
        newname = base
        outfile = open(newname, 'w')

    allstr = fid.read()
    writestr = process_str(allstr)
    outfile.write(writestr)

if __name__ == "__main__":
    main()


text:
package camt

import (
	"encoding/xml"

	"github.com/fgrid/iso20022"
)

type Document02800105 struct {
	XMLName xml.Name                         `xml:"urn:iso:std:iso:20022:tech:xsd:camt.028.001.05 Document"`
	Message *AdditionalPaymentInformationV05 `xml:"AddtlPmtInf"`
}

func (d *Document02800105) AddMessage() *AdditionalPaymentInformationV05 {
	d.Message = new(AdditionalPaymentInformationV05)
	return d.Message
}

// Scope
// The Additional Payment Information message is sent by an account servicing institution to an account owner.
// This message is used to provide additional or corrected information on a payment instruction or statement entry, in order to allow reconciliation.
// Usage
// The Additional Payment Information message provides elements which are usually not reported in a statement or advice (for example full remittance information or identification of parties other than the account servicing institution and the account owner). It complements information about a payment instruction that has already been received, in the form of one or several entries of the original payment instruction.
// The Additional Payment Information message covers one and only one original payment instruction. If several payment instructions need further details, multiple Additional Payment Information messages must be used, one for each of the payment instructions.
// The AdditionalPaymentInformation message may be used as a result of two investigation processes and in a way outlined below.
// - A Claim Non Receipt workflow raised by the creditor or recipient of the payment: This means that the payment instruction has reached the creditor or beneficiary. The account owner needs further details or correct information for its reconciliation processes. The Additional Payment Information can be used to provide the missing information.
// - A Request To Modify Payment workflow raised by the debtor or one of the intermediate agents upstream: When the payment instruction has reached its intended recipient and the modification does not affect the accounting at the account servicing institution, this Additional Payment Information message allows the account owner to receive further particulars or correct information about a payment instruction or an entry passed to its account.
// The Additional Payment Information message cannot be used to trigger a request for modification of a payment instruction activity. A Request To Modify Payment message must be used. In other words, if a debtor or one of intermediate agent (excluding the account servicing institution of the creditor) realises the some information was missing in the original payment instruction, he should not use an Additional Payment Information but instead a Request To Modify Payment message.
// It is assumed that when an account servicing institution sends out an Additional Payment Information message, the institution is fairly confident that this will resolve the case. Therefore it does not need to wait for a Resolution Of Investigation message. Neither does the account owner, or whoever receives the additional information, need to send back a Resolution Of Investigation message. Positive resolution in this case is implicit. Both parties are expected to close the case. In the event that the problem does not go away, a party can re-open the case.
type AdditionalPaymentInformationV05 struct {

	// Identifies the assignment of an investigation case from an assigner to an assignee.
	// Usage: The Assigner must be the sender of this confirmation and the Assignee must be the receiver.
	Assignment *iso20022.CaseAssignment3 `xml:"Assgnmt"`

	// Identifies the investigation case.
	Case *iso20022.Case3 `xml:"Case"`

	// Identifies the underlying payment instruction.
	Underlying *iso20022.UnderlyingTransaction2Choice `xml:"Undrlyg"`

	// Additional information to the underlying payment instruction.
	Information *iso20022.PaymentComplementaryInformation4 `xml:"Inf"`

	// Additional information that cannot be captured in the structured elements and/or any other specific block.
	SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}

func (a *AdditionalPaymentInformationV05) AddAssignment() *iso20022.CaseAssignment3 {
	a.Assignment = new(iso20022.CaseAssignment3)
	return a.Assignment
}

func (a *AdditionalPaymentInformationV05) AddCase() *iso20022.Case3 {
	a.Case = new(iso20022.Case3)
	return a.Case
}

func (a *AdditionalPaymentInformationV05) AddUnderlying() *iso20022.UnderlyingTransaction2Choice {
	a.Underlying = new(iso20022.UnderlyingTransaction2Choice)
	return a.Underlying
}

func (a *AdditionalPaymentInformationV05) AddInformation() *iso20022.PaymentComplementaryInformation4 {
	a.Information = new(iso20022.PaymentComplementaryInformation4)
	return a.Information
}

func (a *AdditionalPaymentInformationV05) AddSupplementaryData() *iso20022.SupplementaryData1 {
	newValue := new(iso20022.SupplementaryData1)
	a.SupplementaryData = append(a.SupplementaryData, newValue)
	return newValue
}


text:
const remoteip = require('remoteip')
const uaParser = require('ua-parser')
const _ = require('lodash')

/**
 * Format log metadata.
 *
 * @param {Request} req
 * @param {Response} res
 */

exports.format = function format(req, res) {
  const data = {}

  // Define category.
  data.category = 'http-request'

  // User
  if (req.user) data.user = _.pick(req.user, 'id', 'email')

  // Client request.
  data.clientRequest = {}

  // User agent informations.
  const parsedUa = uaParser.parse(req.headers['user-agent'])

  data.clientRequest.ua = {
    browser: parsedUa.ua.toString(),
    os: parsedUa.os.toString(),
    device: parsedUa.device.toString(),
  }

  // Client ip.
  data.clientRequest.ip = remoteip.get(req)

  // Request UUID.
  if (req.uuid) data.clientRequest.uuid = req.uuid

  // Query.
  data.clientRequest.qs = _.cloneDeep(req.query)

  // Body.
  data.clientRequest.body = _.cloneDeep(req.body)

  // Headers.
  data.clientRequest.headers = _.clone(req.headers)

  // Path.
  data.clientRequest.path = req.path

  // Status code.
  data.clientRequest.statusCode = res.statusCode

  return data
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: jmolivas
 * Date: 1/16/18
 * Time: 2:22 PM
 */

namespace Drupal\Console\Core\Command\Chain;

use Drupal\Console\Core\Command\Command;
use Drupal\Console\Core\Utils\ChainDiscovery;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class BaseCommand extends Command
{
    /**
     * @var ChainDiscovery
     */
    protected $chainDiscovery;

    /**
     * BaseCommand constructor.
     *
     * @param ChainDiscovery $chainDiscovery
     */
    public function __construct(
        ChainDiscovery $chainDiscovery
    ) {
        $this->chainDiscovery = $chainDiscovery;
        parent::__construct();
        $this->ignoreValidationErrors();
    }

    protected function initialize(
        InputInterface $input,
        OutputInterface $output
    ) {
        parent::initialize($input, $output);

        $options = [];
        foreach ($_SERVER['argv'] as $index => $element) {
            if ($index<2) {
                continue;
            }

            if (substr($element, 0, 2) !== "--") {
                continue;
            }

            $element = substr($element, 2);
            $exploded = explode("=", $element);

            if (!$exploded) {
                $exploded = explode(" ", $element);
            }

            if (count($exploded)>1) {
                $options[trim($exploded[0])] = trim($exploded[1]);
            }
        }

        $file = $input->getOption('file');
        $file = calculateRealPath($file);
        $content = $this->chainDiscovery->getFileContents($file);
        $variables = $this->chainDiscovery->extractInlinePlaceHolderNames($content);

        foreach ($variables as $variable) {
            if (!array_key_exists($variable, $options)) {
                $options[$variable] = null;
            }
        }

        foreach ($options as $optionName => $optionValue) {
            if ($input->hasOption($optionName)) {
                continue;
            }

            $this->addOption(
                $optionName,
                null,
                InputOption::VALUE_OPTIONAL,
                $optionName,
                $optionValue
            );
        }
    }

    protected function getFileOption()
    {
        $input = $this->getIo()->getInput();
        $file = $input->getOption('file');

        if (!$file) {
            $files = array_keys($this->chainDiscovery->getFiles());

            $file = $this->getIo()->choice(
                $this->trans('commands.chain.questions.chain-file'),
                $files
            );
        }

        $file = calculateRealPath($file);
        $input->setOption('file', $file);

        return $file;
    }

    protected function getOptionsAsArray()
    {
        $input = $this->getIo()->getInput();
        $options = [];
        foreach ($input->getOptions() as $option => $value) {
            $options[$option] =  $value;
        }

        return $options;
    }
}


text:
  <xi:include href="irclogs_macros.html" />

Chat Excerpt from ${month}/${day}/${year}

${irclog_table(rows)}


text:
<?php

// include class.secure.php to protect this file and the whole CMS!
if ( defined( 'LEPTON_PATH' ) )
{
	include( LEPTON_PATH . '/framework/class.secure.php' );
} //defined( 'LEPTON_PATH' )
else
{
	$oneback = "../";
	$root    = $oneback;
	$level   = 1;
	while ( ( $level < 10 ) && ( !file_exists( $root . '/framework/class.secure.php' ) ) )
	{
		$root .= $oneback;
		$level += 1;
	} //( $level < 10 ) && ( !file_exists( $root . '/framework/class.secure.php' ) )
	if ( file_exists( $root . '/framework/class.secure.php' ) )
	{
		include( $root . '/framework/class.secure.php' );
	} //file_exists( $root . '/framework/class.secure.php' )
	else
	{
		trigger_error( sprintf( "[ %s ] Can't include class.secure.php!", $_SERVER[ 'SCRIPT_NAME' ] ), E_USER_ERROR );
	}
}
// end include class.secure.php

define('dl_error_add_record',						'
Fout tijdens toevoegen nieuw record

[%s] %s
');
define('dl_error_create_table',					'
Fout tijdens aanmaken nieuwe tabel

[%s] %s
');
define('dl_error_delete_record',				'
Fout tijdens verwijderen record

[%s] %s
');
define('dl_error_delete_table',					'
Fout tijdens verwijderen tabel

[%s] %s
');
define('dl_error_describe_table',				'
Kon de tabel beschrijving niet lezen.

Prompt: %s
');
define('dl_error_empty_directory', 			'Selecteer vanuit de MEDIA map!');
define('dl_error_header',								'class.dirlist.php');
define('dl_error_insert_field',					'
Fout tijdens het invoegen van veld "%s" in tabel.

Prompt: %s
');
define('dl_error_link_by_page_id',			'The filename of the page could not be read from the database.');
define('dl_error_no_error',							'geen fout');
define('dl_error_not_specified',    		'niet gespecificeerd');
define('dl_error_row_empty',						'geen regel in tabel');
define('dl_error_update_record',				'
Fout tijdens het updaten record

[%s] %s
');

define('dl_upgrade_field_exists',				'
Het veld "%s" bestaat nog steeds.
');
define('dl_upgrade_insert_field',				'
Het veld "%s" is succesvol toegevoegd aan de tabel.
');

define('dl_backend_blank',							'Open files in a new window');
define('dl_backend_btn_abort',					'Annuleren');
define('dl_backend_btn_submit',					'Toevoegen');
define('dl_backend_description',    		'Via deze dialoog kun je DirList instellen voor deze pagina rsp. section');
define('dl_backend_exclude',						'Uitsluiten');
define('dl_backend_header',         		'DirList configureren');
define('dl_backend_include',						'Selecteren');
define('dl_backend_text_header',    		'Header voor DirList');
define('dl_backend_text_preselect',			'Je kunt bestanden selecteren of uitsluiten. Geef de bestandstypen (extensies) gescheiden door een komma, bijv.: tif, jpg, gif');
define('dl_backend_text_prefix',    		'Deze tekst wordt getoond na de header en voor de DirList (Prefix)');
define('dl_backend_text_select',				'Map die DirList gebruikt');
define('dl_backend_text_sort',					'Sorteren DirList:');
define('dl_backend_text_suffix',				'Deze tekst wordt getoond aan het einde van de pagina rsp. section (Suffix)');
define('dl_backend_select_directory',		'--> Kies een map!');
define('dl_backend_sortDateAscending',	'op datum, oplopend');
define('dl_backend_sortDateDescending',	'op datum, aflopend');
define('dl_backend_sortFilesAscending',	'op bestandsnaam, oplopend');
define('dl_backend_sortFilesDescending','op bestandsnaam, aflopend');
define('dl_backend_sortSizeAscending',	'op grootte, oplopend');
define('dl_backend_sortSizeDescending',	'op grootte, aflopend');
define('dl_backend_success_update',			'Wijziging succesvol opgeslagen');

define('dl_frontend_empty_directory',		'..');
define('dl_frontend_th_date',						'Gewijzigd');
define('dl_frontend_th_datetime',				'd.m.Y h:i');
define('dl_frontend_th_file',						'Bestandsnaam');
define('dl_frontend_th_size',						'Grootte');

?>