text:
package com.amazonaws.services.storagegateway.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * CreateTapeWithBarcodeInput
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateTapeWithBarcodeRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use the
     * ListGateways operation to return a list of gateways for your account and region.
     *

     */
    private String gatewayARN;
    /**
     *

     * The size, in bytes, of the virtual tape that you want to create.
     *

     * <note>
     *

     * The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     * </note>
     */
    private Long tapeSizeInBytes;
    /**
     *

     * The barcode that you want to assign to the tape.
     *

     * <note>
     *

     * Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     * </note>
     */
    private String tapeBarcode;
    /**
     *

     * True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by Amazon
     * S3. Optional.
     *

     */
    private Boolean kMSEncrypted;
    /**
     *

     * The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value can only
     * be set when KMSEncrypted is true. Optional.
     *

     */
    private String kMSKey;
    /**
     *

     * The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in the S3
     * storage class that is associated with the pool. When you use your backup application to eject the tape, the tape
     * is archived directly into the storage class (Glacier or Deep Archive) that corresponds to the pool.
     *

     *

     * Valid values: "GLACIER", "DEEP_ARCHIVE"
     *

     */
    private String poolId;
    /**
     *

     * A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value pair.
     *

     * <note>
     *

     * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the
     * maximum length for a tag's value is 256.
     *

     * </note>
     */
    private com.amazonaws.internal.SdkInternalList<Tag> tags;

    /**
     *

     * The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use the
     * ListGateways operation to return a list of gateways for your account and region.
     *

     *
     * @param gatewayARN
     *        The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use
     *        the ListGateways operation to return a list of gateways for your account and region.
     */

    public void setGatewayARN(String gatewayARN) {
        this.gatewayARN = gatewayARN;
    }

    /**
     *

     * The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use the
     * ListGateways operation to return a list of gateways for your account and region.
     *

     *
     * @return The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use
     *         the ListGateways operation to return a list of gateways for your account and region.
     */

    public String getGatewayARN() {
        return this.gatewayARN;
    }

    /**
     *

     * The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use the
     * ListGateways operation to return a list of gateways for your account and region.
     *

     *
     * @param gatewayARN
     *        The unique Amazon Resource Name (ARN) that represents the gateway to associate the virtual tape with. Use
     *        the ListGateways operation to return a list of gateways for your account and region.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withGatewayARN(String gatewayARN) {
        setGatewayARN(gatewayARN);
        return this;
    }

    /**
     *

     * The size, in bytes, of the virtual tape that you want to create.
     *

     * <note>
     *

     * The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     * </note>
     *
     * @param tapeSizeInBytes
     *        The size, in bytes, of the virtual tape that you want to create.
 <note>
     *

     *        The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     */

    public void setTapeSizeInBytes(Long tapeSizeInBytes) {
        this.tapeSizeInBytes = tapeSizeInBytes;
    }

    /**
     *

     * The size, in bytes, of the virtual tape that you want to create.
     *

     * <note>
     *

     * The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     * </note>
     *
     * @return The size, in bytes, of the virtual tape that you want to create.
 <note>
     *

     *         The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     */

    public Long getTapeSizeInBytes() {
        return this.tapeSizeInBytes;
    }

    /**
     *

     * The size, in bytes, of the virtual tape that you want to create.
     *

     * <note>
     *

     * The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     * </note>
     *
     * @param tapeSizeInBytes
     *        The size, in bytes, of the virtual tape that you want to create.
 <note>
     *

     *        The size must be aligned by gigabyte (1024*1024*1024 byte).
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withTapeSizeInBytes(Long tapeSizeInBytes) {
        setTapeSizeInBytes(tapeSizeInBytes);
        return this;
    }

    /**
     *

     * The barcode that you want to assign to the tape.
     *

     * <note>
     *

     * Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     * </note>
     *
     * @param tapeBarcode
     *        The barcode that you want to assign to the tape.
 <note>
     *

     *        Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     */

    public void setTapeBarcode(String tapeBarcode) {
        this.tapeBarcode = tapeBarcode;
    }

    /**
     *

     * The barcode that you want to assign to the tape.
     *

     * <note>
     *

     * Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     * </note>
     *
     * @return The barcode that you want to assign to the tape.
 <note>
     *

     *         Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     */

    public String getTapeBarcode() {
        return this.tapeBarcode;
    }

    /**
     *

     * The barcode that you want to assign to the tape.
     *

     * <note>
     *

     * Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     * </note>
     *
     * @param tapeBarcode
     *        The barcode that you want to assign to the tape.
 <note>
     *

     *        Barcodes cannot be reused. This includes barcodes used for tapes that have been deleted.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withTapeBarcode(String tapeBarcode) {
        setTapeBarcode(tapeBarcode);
        return this;
    }

    /**
     *

     * True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by Amazon
     * S3. Optional.
     *

     *
     * @param kMSEncrypted
     *        True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by
     *        Amazon S3. Optional.
     */

    public void setKMSEncrypted(Boolean kMSEncrypted) {
        this.kMSEncrypted = kMSEncrypted;
    }

    /**
     *

     * True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by Amazon
     * S3. Optional.
     *

     *
     * @return True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by
     *         Amazon S3. Optional.
     */

    public Boolean getKMSEncrypted() {
        return this.kMSEncrypted;
    }

    /**
     *

     * True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by Amazon
     * S3. Optional.
     *

     *
     * @param kMSEncrypted
     *        True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by
     *        Amazon S3. Optional.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withKMSEncrypted(Boolean kMSEncrypted) {
        setKMSEncrypted(kMSEncrypted);
        return this;
    }

    /**
     *

     * True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by Amazon
     * S3. Optional.
     *

     *
     * @return True to use Amazon S3 server side encryption with your own AWS KMS key, or false to use a key managed by
     *         Amazon S3. Optional.
     */

    public Boolean isKMSEncrypted() {
        return this.kMSEncrypted;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value can only
     * be set when KMSEncrypted is true. Optional.
     *

     *
     * @param kMSKey
     *        The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value
     *        can only be set when KMSEncrypted is true. Optional.
     */

    public void setKMSKey(String kMSKey) {
        this.kMSKey = kMSKey;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value can only
     * be set when KMSEncrypted is true. Optional.
     *

     *
     * @return The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value
     *         can only be set when KMSEncrypted is true. Optional.
     */

    public String getKMSKey() {
        return this.kMSKey;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value can only
     * be set when KMSEncrypted is true. Optional.
     *

     *
     * @param kMSKey
     *        The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server side encryption. This value
     *        can only be set when KMSEncrypted is true. Optional.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withKMSKey(String kMSKey) {
        setKMSKey(kMSKey);
        return this;
    }

    /**
     *

     * The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in the S3
     * storage class that is associated with the pool. When you use your backup application to eject the tape, the tape
     * is archived directly into the storage class (Glacier or Deep Archive) that corresponds to the pool.
     *

     *

     * Valid values: "GLACIER", "DEEP_ARCHIVE"
     *

     *
     * @param poolId
     *        The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in
     *        the S3 storage class that is associated with the pool. When you use your backup application to eject the
     *        tape, the tape is archived directly into the storage class (Glacier or Deep Archive) that corresponds to
     *        the pool.

     *

     *        Valid values: "GLACIER", "DEEP_ARCHIVE"
     */

    public void setPoolId(String poolId) {
        this.poolId = poolId;
    }

    /**
     *

     * The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in the S3
     * storage class that is associated with the pool. When you use your backup application to eject the tape, the tape
     * is archived directly into the storage class (Glacier or Deep Archive) that corresponds to the pool.
     *

     *

     * Valid values: "GLACIER", "DEEP_ARCHIVE"
     *

     *
     * @return The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in
     *         the S3 storage class that is associated with the pool. When you use your backup application to eject the
     *         tape, the tape is archived directly into the storage class (Glacier or Deep Archive) that corresponds to
     *         the pool.

     *

     *         Valid values: "GLACIER", "DEEP_ARCHIVE"
     */

    public String getPoolId() {
        return this.poolId;
    }

    /**
     *

     * The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in the S3
     * storage class that is associated with the pool. When you use your backup application to eject the tape, the tape
     * is archived directly into the storage class (Glacier or Deep Archive) that corresponds to the pool.
     *

     *

     * Valid values: "GLACIER", "DEEP_ARCHIVE"
     *

     *
     * @param poolId
     *        The ID of the pool that you want to add your tape to for archiving. The tape in this pool is archived in
     *        the S3 storage class that is associated with the pool. When you use your backup application to eject the
     *        tape, the tape is archived directly into the storage class (Glacier or Deep Archive) that corresponds to
     *        the pool.

     *

     *        Valid values: "GLACIER", "DEEP_ARCHIVE"
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withPoolId(String poolId) {
        setPoolId(poolId);
        return this;
    }

    /**
     *

     * A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value pair.
     *

     * <note>
     *

     * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the
     * maximum length for a tag's value is 256.
     *

     * </note>
     *
     * @return A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a
     *         key-value pair.
 <note>
     *

     *         Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and
     *         the following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters,
     *         and the maximum length for a tag's value is 256.
     *

     */

    public java.util.List<Tag> getTags() {
        if (tags == null) {
            tags = new com.amazonaws.internal.SdkInternalList<Tag>();
        }
        return tags;
    }

    /**
     *

     * A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value pair.
     *

     * <note>
     *

     * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the
     * maximum length for a tag's value is 256.
     *

     * </note>
     *
     * @param tags
     *        A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value
     *        pair.
 <note>
     *

     *        Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     *        following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and
     *        the maximum length for a tag's value is 256.
     *

     */

    public void setTags(java.util.Collection<Tag> tags) {
        if (tags == null) {
            this.tags = null;
            return;
        }

        this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags);
    }

    /**
     *

     * A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value pair.
     *

     * <note>
     *

     * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the
     * maximum length for a tag's value is 256.
     *

     * </note>
     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param tags
     *        A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value
     *        pair.
 <note>
     *

     *        Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     *        following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and
     *        the maximum length for a tag's value is 256.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withTags(Tag... tags) {
        if (this.tags == null) {
            setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length));
        }
        for (Tag ele : tags) {
            this.tags.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value pair.
     *

     * <note>
     *

     * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the
     * maximum length for a tag's value is 256.
     *

     * </note>
     *
     * @param tags
     *        A list of up to 50 tags that can be assigned to a virtual tape that has a barcode. Each tag is a key-value
     *        pair.
 <note>
     *

     *        Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the
     *        following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and
     *        the maximum length for a tag's value is 256.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateTapeWithBarcodeRequest withTags(java.util.Collection<Tag> tags) {
        setTags(tags);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGatewayARN() != null)
            sb.append("GatewayARN: ").append(getGatewayARN()).append(",");
        if (getTapeSizeInBytes() != null)
            sb.append("TapeSizeInBytes: ").append(getTapeSizeInBytes()).append(",");
        if (getTapeBarcode() != null)
            sb.append("TapeBarcode: ").append(getTapeBarcode()).append(",");
        if (getKMSEncrypted() != null)
            sb.append("KMSEncrypted: ").append(getKMSEncrypted()).append(",");
        if (getKMSKey() != null)
            sb.append("KMSKey: ").append(getKMSKey()).append(",");
        if (getPoolId() != null)
            sb.append("PoolId: ").append(getPoolId()).append(",");
        if (getTags() != null)
            sb.append("Tags: ").append(getTags());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateTapeWithBarcodeRequest == false)
            return false;
        CreateTapeWithBarcodeRequest other = (CreateTapeWithBarcodeRequest) obj;
        if (other.getGatewayARN() == null ^ this.getGatewayARN() == null)
            return false;
        if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false)
            return false;
        if (other.getTapeSizeInBytes() == null ^ this.getTapeSizeInBytes() == null)
            return false;
        if (other.getTapeSizeInBytes() != null && other.getTapeSizeInBytes().equals(this.getTapeSizeInBytes()) == false)
            return false;
        if (other.getTapeBarcode() == null ^ this.getTapeBarcode() == null)
            return false;
        if (other.getTapeBarcode() != null && other.getTapeBarcode().equals(this.getTapeBarcode()) == false)
            return false;
        if (other.getKMSEncrypted() == null ^ this.getKMSEncrypted() == null)
            return false;
        if (other.getKMSEncrypted() != null && other.getKMSEncrypted().equals(this.getKMSEncrypted()) == false)
            return false;
        if (other.getKMSKey() == null ^ this.getKMSKey() == null)
            return false;
        if (other.getKMSKey() != null && other.getKMSKey().equals(this.getKMSKey()) == false)
            return false;
        if (other.getPoolId() == null ^ this.getPoolId() == null)
            return false;
        if (other.getPoolId() != null && other.getPoolId().equals(this.getPoolId()) == false)
            return false;
        if (other.getTags() == null ^ this.getTags() == null)
            return false;
        if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode());
        hashCode = prime * hashCode + ((getTapeSizeInBytes() == null) ? 0 : getTapeSizeInBytes().hashCode());
        hashCode = prime * hashCode + ((getTapeBarcode() == null) ? 0 : getTapeBarcode().hashCode());
        hashCode = prime * hashCode + ((getKMSEncrypted() == null) ? 0 : getKMSEncrypted().hashCode());
        hashCode = prime * hashCode + ((getKMSKey() == null) ? 0 : getKMSKey().hashCode());
        hashCode = prime * hashCode + ((getPoolId() == null) ? 0 : getPoolId().hashCode());
        hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
        return hashCode;
    }

    @Override
    public CreateTapeWithBarcodeRequest clone() {
        return (CreateTapeWithBarcodeRequest) super.clone();
    }

}


text:
namespace GuiLib
{
    class WidgetImpl
    {
    public:
        explicit WidgetImpl(ATOM aWndClass);
        WidgetImpl();
        virtual ~WidgetImpl();

        void create(const CString aName);
        void set_event_handlers(Widget* aWidget, const WidgetEventHandlers& aEventHandlers);

        DISABLE_COPY_MOVE_SEMANTICS(WidgetImpl);

        Rect get_screen_rect() const;
        void set_screen_rect(const Rect& aRect);

        Size get_size() const;
        void set_size(Size aSize);

        void set_text(CString aName);
        String get_text() const;

        void show();
        void hide();
        bool is_visible() const;

        void set_parent(WidgetImpl& parent);
        boost::optional<Widget&> get_parent() const;

        void set_style(LONG newStyle);
        void add_style(LONG styleToAdd);
        void reset_style(LONG styleToRemove);

        void destroy();

        LRESULT wndproc(UINT aMsg, WPARAM aWP, LPARAM aLP);

        virtual DWORD get_creation_style() const = 0;
        virtual DWORD get_creation_style_ex() const = 0;

    protected:
        void assertWnd() const;
        HWND getHandle()
        {
            GUI_ASSERT(iHandle);
            return iHandle;
        }

        HWND getHandle() const
        {
            GUI_ASSERT(iHandle);
            return iHandle;
        }

    private:
        static LRESULT wndproc_adapter(WidgetImpl* wnd, UINT aMsg, WPARAM aWP, LPARAM aLP);

        void createWindow(ATOM aWndClass, CString aName);
        LONG get_style() const;
        LONG get_style_ex() const;

        LRESULT on_create();
        LRESULT on_destroy();
        LRESULT on_ncdestroy();
        LRESULT on_minmax_info(MINMAXINFO* info);
        LRESULT on_close();

        ATOM regClass();

    private:
        WidgetEventHandlers iEventHandlers;
        Widget* iWidget;

        HWND iHandle;
        SafeVirtualSpace iThunkMem;
        const ATOM iWndClass;
    };
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

const express = require('express');
const _ = require('lodash');
const un_eval = require('un-eval');
const request = require('request-promise-native');
const moment = require('moment');

const processVars = require('../processVars');
const FDevIDs = require('../fdevids')
const highchartsTheme = require('../modules/highcharts/highChartsTheme');

let router = express.Router();

router.get('/factions/influence', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/factions`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                systemDetails: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\faction-influence-chart.component.ts
        const history = responseObject.docs[0].history;
        const allSystems = [];
        history.forEach(element => {
            if (allSystems.indexOf(element.system) === -1) {
                allSystems.push(element.system);
            }
        });
        const series = [];
        history.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        allSystems.forEach(system => {
            const data = [];
            let lastElement;
            history.forEach(element => {
                if (element.system === system) {
                    data.push([
                        Date.parse(element.updated_at),
                        Number.parseFloat((element.influence * 100).toFixed(2))
                    ]);
                    lastElement = element;
                } else {
                    if (element.systems.findIndex(systemElement => {
                        return systemElement.name === system;
                    }) === -1) {
                        data.push([Date.parse(element.updated_at), null]);
                    }
                }
            });
            const latestUpdate = responseObject.docs[0].faction_presence.find(findSystem => {
                return findSystem.system_name === system;
            });
            if (latestUpdate) {
                data.push([
                    Date.parse(latestUpdate.updated_at),
                    Number.parseFloat((lastElement.influence * 100).toFixed(2))
                ]);
            }
            series.push({
                name: system,
                data: data
            });
        });
        let options = {
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Influence'
                }
            },
            title: {
                text: 'Influence Trend'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-infleunce`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/factions/state', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/factions`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                systemDetails: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\faction-state-chart.component.ts
        const history = responseObject.docs[0].history;
        const allSystems = [];
        history.forEach(record => {
            if (allSystems.indexOf(record.system) === -1) {
                allSystems.push(record.system);
            }
        });
        history.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        const series = [];
        const states = Object.keys(FDevIDs.state).filter(state => {
            return state !== 'null';
        }).map(state => {
            return [state, FDevIDs.state[state].name];
        });
        let i = 0;
        states.forEach(state => {
            const data = [];
            allSystems.forEach((system, index) => {
                let previousState = '';
                let timeBegin = 0;
                let timeEnd = 0;
                history.forEach(record => {
                    if (record.system === system) {
                        if (previousState !== record.state) {
                            if (record.state === state[0]) {
                                timeBegin = Date.parse(record.updated_at);
                            }
                            if (previousState === state[0] && record.state !== state[0]) {
                                timeEnd = Date.parse(record.updated_at);
                                data.push({
                                    x: timeBegin,
                                    x2: timeEnd,
                                    y: index
                                });
                            }
                            previousState = record.state;
                        }
                    }
                });
                if (previousState === state[0]) {
                    data.push({
                        x: timeBegin,
                        x2: Date.now(),
                        y: index
                    });
                }
            });
            series.push({
                name: state[1],
                pointWidth: 20,
                data: data
            });
            i++;
        });
        let options = {
            chart: {
                height: 130 + allSystems.length * 40,
                type: 'xrange'
            },
            title: {
                text: 'State Periods'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Systems'
                },
                categories: allSystems,
                reversed: true
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.yCategory}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-state`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/factions/active', (req, res, next) => {
    factionActivePendingRecovering(req, res, next, 'active');
});

router.get('/factions/pending', (req, res, next) => {
    factionActivePendingRecovering(req, res, next, 'pending');
});

router.get('/factions/recovering', (req, res, next) => {
    factionActivePendingRecovering(req, res, next, 'recovering');
});

let factionActivePendingRecovering = async (req, res, next, type) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/factions`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                systemDetails: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\faction-a-p-r-state-chart.component.ts
        let stateType;
        let stateTitle;
        switch (type) {
            case 'active':
                stateType = 'active_states';
                stateTitle = 'Active State';
                break;
            case 'pending':
                stateType = 'pending_states';
                stateTitle = 'Pending State';
                break;
            case 'recovering':
                stateType = 'recovering_states';
                stateTitle = 'Recovering State';
                break;
            default:
                stateType = 'pending_states';
                stateTitle = 'Pending State';
        }
        const allTimeSystems = [];
        const allTimeStates = [];
        const maxStatesConcurrent = [];
        const systems = [];
        const history = responseObject.docs[0].history;
        history.forEach(record => {
            if (allTimeSystems.indexOf(record.system) === -1) {
                allTimeSystems.push(record.system);
            }
        });
        allTimeSystems.forEach((system, index) => {
            const allStates = [];
            let maxStates = 0;
            history.forEach((record, recordIndex, records) => {
                if (record.system === system && record[stateType]) {
                    if (record[stateType].length === 0) {
                        records[recordIndex][stateType].push({
                            state: 'none',
                            trend: 0
                        });
                    }
                    record[stateType].forEach(recordState => {
                        if (allStates.indexOf(recordState.state) === -1) {
                            allStates.push(recordState.state);
                        }
                    });
                    maxStates = record[stateType].length > maxStates ? record[stateType].length : maxStates;
                }
            });
            allTimeStates.push(allStates);
            if (maxStates === 0) {
                maxStates = 1;
            }
            maxStatesConcurrent.push(maxStates);
        });
        history.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        // const series: XRangeChartSeriesOptions[] = [];
        const series = [];
        const states = Object.keys(FDevIDs.state).filter(state => {
            return state !== 'null';
        }).map(state => {
            return [state, FDevIDs.state[state].name];
        });
        const data = {};
        states.forEach(state => {
            data[state[0]] = [];
        });
        allTimeSystems.forEach((system, index) => {
            systems.push(system);
            const previousStates = new Array(maxStatesConcurrent[index]);
            const tempBegin = new Array(maxStatesConcurrent[index]);
            history.filter(record => {
                return record.system === system;
            }).forEach(record => {
                if (record[stateType] && !_.isEqual(record[stateType].map(recordState => {
                    return recordState.state;
                }), previousStates)) {
                    const statesStarting = _.pull(_.difference(record[stateType].map(recordState => {
                        return recordState.state;
                    }), previousStates), undefined, null);
                    const statesEnding = _.pull(_.difference(previousStates, record[stateType].map(recordState => {
                        return recordState.state;
                    })), undefined, null);
                    statesEnding.forEach(state => {
                        const previousStateIndex = previousStates.indexOf(state);
                        data[state].push({
                            x: tempBegin[previousStateIndex],
                            x2: Date.parse(record.updated_at),
                            y: _.sum(maxStatesConcurrent.slice(0, index)) + previousStateIndex,
                            faction: system
                        });
                        previousStates[previousStateIndex] = null;
                    });
                    statesStarting.forEach(state => {
                        for (let i = 0; i < previousStates.length; i++) {
                            if (!previousStates[i]) {
                                previousStates[i] = state;
                                tempBegin[i] = Date.parse(record.updated_at);
                                break;
                            }
                        }
                    });
                }
            });
            previousStates.forEach((state, previousStateIndex) => {
                if (state) {
                    data[state].push({
                        x: tempBegin[previousStateIndex],
                        x2: Date.now(),
                        y: _.sum(maxStatesConcurrent.slice(0, index)) + previousStateIndex,
                        faction: system
                    });
                    previousStates[previousStateIndex] = null;
                }
            });
        });
        states.forEach(state => {
            series.push({
                name: state[1],
                pointWidth: 20,
                data: data[state[0]]
            });
        });
        const tickPositions = [-1];
        for (let i = 0; i < maxStatesConcurrent.length; i++) {
            tickPositions.push(tickPositions[i] + maxStatesConcurrent[i]);
        }
        let options = {
            chart: {
                height: 130 + _.sum(maxStatesConcurrent) * 40,
                type: 'xrange',
                events: {
                    render: function () {
                        var tickAbsolutePositions = this.yAxis[0].tickPositions.map(function (tickPosition) {
                            return +this.yAxis[0].ticks[tickPosition.toString()].gridLine.d.split(' ')[2]
                        }, this);
                        tickAbsolutePositions = [+this.yAxis[0].ticks['-1'].gridLine.d.split(' ')[2]].concat(tickAbsolutePositions);
                        var labelPositions = [];
                        for (var i = 1; i < tickAbsolutePositions.length; i++) {
                            labelPositions.push((tickAbsolutePositions[i] + tickAbsolutePositions[i - 1]) / 2);
                        }

                        systemsRegex.forEach(function (system, index) {
                            this.yAxis[0]
                                .labelGroup.element.childNodes[index]
                                .attributes.y.nodeValue = labelPositions[index] +
                                parseFloat(this.yAxis[0].labelGroup.element.childNodes[index].style['font-size']) / 2;
                        }, this);
                    }
                }
            },
            title: {
                text: `${stateTitle} Periods`
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Systems'
                },
                categories: systems,
                tickPositioner: function () {
                    return tickPositionsRegex;
                },
                startOnTick: false,
                reversed: true,
                labels: {
                    formatter: function () {
                        var chart = this.chart;
                        var axis = this.axis;
                        var label;

                        if (!chart.yaxisLabelIndex) {
                            chart.yaxisLabelIndex = 0;
                        }
                        if (this.value !== -1) {

                            label = axis.categories[chart.yaxisLabelIndex];
                            chart.yaxisLabelIndex++;

                            if (chart.yaxisLabelIndex === maxStatesConcurrentRegex.length) {
                                chart.yaxisLabelIndex = 0;
                            }

                            return label;
                        }
                    },
                },
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.faction}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: un_eval(options).replace('systemsRegex', JSON.stringify(systems)).replace('tickPositionsRegex', JSON.stringify(tickPositions)).replace('maxStatesConcurrentRegex', JSON.stringify(maxStatesConcurrent)),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-${stateType}`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
}

router.get('/factions/happiness', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/factions`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                systemDetails: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\faction-happiness-chart.component.ts
        const history = responseObject.docs[0].history;
        const allSystems = [];
        history.forEach(record => {
            if (allSystems.indexOf(record.system) === -1) {
                allSystems.push(record.system);
            }
        });
        history.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        const series = [];
        const happiness = Object.keys(FDevIDs.happiness).map(happiness => {
            return [happiness, FDevIDs.happiness[happiness].name];
        });
        let i = 0;
        happiness.forEach(happiness => {
            const data = [];
            allSystems.forEach((system, index) => {
                let previousHappiness = '';
                let timeBegin = 0;
                let timeEnd = 0;
                history.forEach(record => {
                    if (record.system === system) {
                        if (previousHappiness !== record.happiness) {
                            if (record.happiness === happiness[0]) {
                                timeBegin = Date.parse(record.updated_at);
                            }
                            if (previousHappiness === happiness[0] && record.happiness !== happiness[0]) {
                                timeEnd = Date.parse(record.updated_at);
                                data.push({
                                    x: timeBegin,
                                    x2: timeEnd,
                                    y: index
                                });
                            }
                            previousHappiness = record.happiness;
                        }
                    }
                });
                if (previousHappiness === happiness[0]) {
                    data.push({
                        x: timeBegin,
                        x2: Date.now(),
                        y: index
                    });
                }
            });
            series.push({
                name: happiness[1],
                pointWidth: 20,
                data: data
            });
            i++;
        });
        let options = {
            chart: {
                height: 130 + allSystems.length * 40,
                type: 'xrange'
            },
            title: {
                text: 'Happiness Periods'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Systems'
                },
                categories: allSystems,
                reversed: true
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.yCategory}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-happiness`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/systems/influence', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/systems`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                factionDetails: 'true',
                factionHistory: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\system-influence-chart.component.ts
        const factionHistory = responseObject.docs[0].faction_history;
        const history = responseObject.docs[0].history;
        const allTimeFactions = [];
        factionHistory.forEach(record => {
            if (allTimeFactions.indexOf(record.faction_name) === -1) {
                allTimeFactions.push(record.faction_name);
            }
        });
        factionHistory.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        const series = [];
        allTimeFactions.forEach(faction => {
            const data = [];
            let lastRecord;
            factionHistory.forEach(record => {
                if (record.faction_name === faction) {
                    data.push([
                        Date.parse(record.updated_at),
                        Number.parseFloat((record.influence * 100).toFixed(2))
                    ]);
                    lastRecord = record;
                } else {
                    const indexInSystem = history.findIndex(element => {
                        return element.updated_at === record.updated_at;
                    });
                    if (indexInSystem !== -1 && history[indexInSystem].factions.findIndex(element => {
                        return element.name_lower === faction.toLowerCase();
                    }) === -1) {
                        data.push([Date.parse(record.updated_at), null]);
                    }
                }
            });
            const latestUpdate = responseObject.docs[0].factions.find(findFaction => {
                return findFaction.name === faction;
            })
            if (latestUpdate) {
                data.push([
                    Date.parse(latestUpdate.faction_details.faction_presence.updated_at),
                    Number.parseFloat((lastRecord.influence * 100).toFixed(2))
                ]);
            }
            series.push({
                name: faction,
                data: data
            });
        });
        let options = {
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Influence'
                }
            },
            title: {
                text: 'Influence Trend'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-infleunce`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/systems/state', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/systems`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                factionDetails: 'true',
                factionHistory: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\system-state-chart.component.ts
        const factionHistory = responseObject.docs[0].faction_history;
        const allTimeFactions = [];
        factionHistory.forEach(record => {
            if (allTimeFactions.indexOf(record.faction_name) === -1) {
                allTimeFactions.push(record.faction_name);
            }
        });
        factionHistory.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        const series = [];
        const states = Object.keys(FDevIDs.state).filter(state => {
            return state !== 'null';
        }).map(state => {
            return [state, FDevIDs.state[state].name];
        });
        let i = 0;
        states.forEach(state => {
            const data = [];
            allTimeFactions.forEach((faction, index) => {
                let previousState = '';
                let timeBegin = 0;
                let timeEnd = 0;
                factionHistory.forEach(record => {
                    if (record.faction_name === faction) {
                        if (previousState !== record.state) {
                            if (record.state === state[0]) {
                                timeBegin = Date.parse(record.updated_at);
                            }
                            if (previousState === state[0] && record.state !== state[0]) {
                                timeEnd = Date.parse(record.updated_at);
                                data.push({
                                    x: timeBegin,
                                    x2: timeEnd,
                                    y: index
                                });
                            }
                            previousState = record.state;
                        }
                    }
                });
                if (previousState === state[0]) {
                    data.push({
                        x: timeBegin,
                        x2: Date.now(),
                        y: index
                    });
                }
            });
            series.push({
                name: state[1],
                pointWidth: 20,
                data: data
            });
            i++;
        });
        let options = {
            chart: {
                height: 130 + allTimeFactions.length * 40,
                type: 'xrange'
            },
            title: {
                text: 'State Periods'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Factions'
                },
                categories: allTimeFactions,
                reversed: true
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.yCategory}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-state`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/systems/active', (req, res, next) => {
    systemActivePendingRecovering(req, res, next, 'active');
});

router.get('/systems/pending', (req, res, next) => {
    systemActivePendingRecovering(req, res, next, 'pending');
});

router.get('/systems/recovering', (req, res, next) => {
    systemActivePendingRecovering(req, res, next, 'recovering');
});

let systemActivePendingRecovering = async (req, res, next, type) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/systems`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                factionDetails: 'true',
                factionHistory: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\system-a-p-r-state-chart.component.ts
        let stateType;
        let stateTitle;
        switch (type) {
            case 'active':
                stateType = 'active_states';
                stateTitle = 'Active State';
                break;
            case 'pending':
                stateType = 'pending_states';
                stateTitle = 'Pending State';
                break;
            case 'recovering':
                stateType = 'recovering_states';
                stateTitle = 'Recovering State';
                break;
            default:
                stateType = 'pending_states';
                stateTitle = 'Pending State';
        }
        const allTimeFactions = [];
        const allTimeStates = [];
        const maxStatesConcurrent = [];
        const factions = [];
        const factionHistory = responseObject.docs[0].faction_history;
        factionHistory.forEach(record => {
            if (allTimeFactions.indexOf(record.faction_name) === -1) {
                allTimeFactions.push(record.faction_name);
            }
        });
        allTimeFactions.forEach((faction, index) => {
            const allStates = [];
            let maxStates = 0;
            factionHistory.forEach((record, recordIndex, records) => {
                if (record.faction_name === faction) {
                    if (record[stateType].length === 0) {
                        records[recordIndex][stateType].push({
                            state: 'none',
                            trend: 0
                        });
                    }
                    record[stateType].forEach(recordState => {
                        if (allStates.indexOf(recordState.state) === -1) {
                            allStates.push(recordState.state);
                        }
                    });
                    maxStates = record[stateType].length > maxStates ? record[stateType].length : maxStates;
                }
            });
            allTimeStates.push(allStates);
            if (maxStates === 0) {
                maxStates = 1;
            }
            maxStatesConcurrent.push(maxStates);
        });
        factionHistory.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        // const series: XRangeChartSeriesOptions[] = [];
        const series = [];
        const states = Object.keys(FDevIDs.state).filter(state => {
            return state !== 'null';
        }).map(state => {
            return [state, FDevIDs.state[state].name];
        });
        const data = {};
        states.forEach(state => {
            data[state[0]] = [];
        });
        allTimeFactions.forEach((faction, index) => {
            factions.push(faction);
            const previousStates = new Array(maxStatesConcurrent[index]);
            const tempBegin = new Array(maxStatesConcurrent[index]);
            factionHistory.filter(record => {
                return record.faction_name === faction;
            }).forEach(record => {
                if (record[stateType] && !_.isEqual(record[stateType].map(recordState => {
                    return recordState.state;
                }), previousStates)) {
                    const statesStarting = _.pull(_.difference(record[stateType].map(recordState => {
                        return recordState.state;
                    }), previousStates), undefined, null);
                    const statesEnding = _.pull(_.difference(previousStates, record[stateType].map(recordState => {
                        return recordState.state;
                    })), undefined, null);
                    statesEnding.forEach(state => {
                        const previousStateIndex = previousStates.indexOf(state);
                        data[state].push({
                            x: tempBegin[previousStateIndex],
                            x2: Date.parse(record.updated_at),
                            y: _.sum(maxStatesConcurrent.slice(0, index)) + previousStateIndex,
                            faction: faction
                        });
                        previousStates[previousStateIndex] = null;
                    });
                    statesStarting.forEach(state => {
                        for (let i = 0; i < previousStates.length; i++) {
                            if (!previousStates[i]) {
                                previousStates[i] = state;
                                tempBegin[i] = Date.parse(record.updated_at);
                                break;
                            }
                        }
                    });
                }
            });
            previousStates.forEach((state, previousStateIndex) => {
                if (state) {
                    data[state].push({
                        x: tempBegin[previousStateIndex],
                        x2: Date.now(),
                        y: _.sum(maxStatesConcurrent.slice(0, index)) + previousStateIndex,
                        faction: faction
                    });
                    previousStates[previousStateIndex] = null;
                }
            });
        });
        states.forEach(state => {
            series.push({
                name: state[1],
                pointWidth: 20,
                data: data[state[0]]
            });
        });
        const tickPositions = [-1];
        for (let i = 0; i < maxStatesConcurrent.length; i++) {
            tickPositions.push(tickPositions[i] + maxStatesConcurrent[i]);
        }
        let options = {
            chart: {
                height: 130 + _.sum(maxStatesConcurrent) * 40,
                type: 'xrange',
                events: {
                    render: function () {
                        var tickAbsolutePositions = this.yAxis[0].tickPositions.map(function (tickPosition) {
                            return +this.yAxis[0].ticks[tickPosition.toString()].gridLine.d.split(' ')[2]
                        }, this);
                        tickAbsolutePositions = [+this.yAxis[0].ticks['-1'].gridLine.d.split(' ')[2]].concat(tickAbsolutePositions);
                        var labelPositions = [];
                        for (var i = 1; i < tickAbsolutePositions.length; i++) {
                            labelPositions.push((tickAbsolutePositions[i] + tickAbsolutePositions[i - 1]) / 2);
                        }

                        factionsRegex.forEach(function (faction, index) {
                            this.yAxis[0]
                                .labelGroup.element.childNodes[index]
                                .attributes.y.nodeValue = labelPositions[index] +
                                parseFloat(this.yAxis[0].labelGroup.element.childNodes[index].style['font-size']) / 2;
                        }, this);
                    }
                }
            },
            title: {
                text: `${stateTitle} Periods`
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Factions'
                },
                categories: factions,
                tickPositioner: function () {
                    return tickPositionsRegex;
                },
                startOnTick: false,
                reversed: true,
                labels: {
                    formatter: function () {
                        var chart = this.chart;
                        var axis = this.axis;
                        var label;

                        if (!chart.yaxisLabelIndex) {
                            chart.yaxisLabelIndex = 0;
                        }
                        if (this.value !== -1) {

                            label = axis.categories[chart.yaxisLabelIndex];
                            chart.yaxisLabelIndex++;

                            if (chart.yaxisLabelIndex === maxStatesConcurrentRegex.length) {
                                chart.yaxisLabelIndex = 0;
                            }

                            return label;
                        }
                    }
                },
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.faction}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: un_eval(options).replace('factionsRegex', JSON.stringify(factions)).replace('tickPositionsRegex', JSON.stringify(tickPositions)).replace('maxStatesConcurrentRegex', JSON.stringify(maxStatesConcurrent)),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-${stateType}`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
}

router.get('/systems/happiness', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/systems`,
            qs: {
                name: req.query.name,
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax,
                factionDetails: 'true',
                factionHistory: 'true'
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\system-happiness-chart.component.ts
        const factionHistory = responseObject.docs[0].faction_history;
        const allTimeFactions = [];
        factionHistory.forEach(record => {
            if (allTimeFactions.indexOf(record.faction_name) === -1) {
                allTimeFactions.push(record.faction_name);
            }
        });
        factionHistory.sort((a, b) => {
            if (a.updated_at  b.updated_at) {
                return 1;
            } else {
                return 0;
            }
        });
        const series = [];
        const happiness = Object.keys(FDevIDs.happiness).map(happiness => {
            return [happiness, FDevIDs.happiness[happiness].name];
        });
        let i = 0;
        happiness.forEach(happiness => {
            const data = [];
            allTimeFactions.forEach((faction, index) => {
                let previousHappiness = '';
                let timeBegin = 0;
                let timeEnd = 0;
                factionHistory.forEach(record => {
                    if (record.faction_name === faction) {
                        if (previousHappiness !== record.happiness) {
                            if (record.happiness === happiness[0]) {
                                timeBegin = Date.parse(record.updated_at);
                            }
                            if (previousHappiness === happiness[0] && record.happiness !== happiness[0]) {
                                timeEnd = Date.parse(record.updated_at);
                                data.push({
                                    x: timeBegin,
                                    x2: timeEnd,
                                    y: index
                                });
                            }
                            previousHappiness = record.happiness;
                        }
                    }
                });
                if (previousHappiness === happiness[0]) {
                    data.push({
                        x: timeBegin,
                        x2: Date.now(),
                        y: index
                    });
                }
            });
            series.push({
                name: happiness[1],
                pointWidth: 20,
                data: data
            });
            i++;
        });
        let options = {
            chart: {
                height: 130 + allTimeFactions.length * 40,
                type: 'xrange'
            },
            title: {
                text: 'Happiness Periods'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Factions'
                },
                categories: allTimeFactions,
                reversed: true
            },
            plotOptions: {
                xrange: {
                    borderRadius: 0,
                    borderWidth: 0,
                    grouping: false,
                    dataLabels: {
                        align: 'center',
                        enabled: true,
                        format: '{point.name}'
                    },
                    colorByPoint: false
                }
            },
            tooltip: {
                headerFormat: '{point.x} - {point.x2}
',
                pointFormat: '\u25CF {series.name}: {point.yCategory}
'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-happiness`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

router.get('/tick', async (req, res, next) => {
    try {
        let requestOptions = {
            url: `${processVars.protocol}://${processVars.host}/api/ebgs/v5/ticks`,
            qs: {
                timeMin: req.query.timeMin,
                timeMax: req.query.timeMax
            },
            json: true,
            resolveWithFullResponse: true
        };
        let response = await request.get(requestOptions);
        let responseObject = {};
        if (response.statusCode === 200) {
            responseObject = response.body;
            if (responseObject.total <= 0) {
                throw new Error(response);
            }
        } else {
            throw new Error(response);
        }
        // Copied over from src\app\charts\tick-chart.component.ts
        const tickData = responseObject;
        const data = [];
        const series = [];
        const firstTick = tickData[tickData.length - 1];
        tickData.forEach(tick => {
            const tickMoment = moment(tick.time);
            const firstTickMoment = moment(firstTick.time);
            const normalisedTime = moment(`${firstTickMoment.format('YYYY-MM-DD')} ${tickMoment.format('HH:mm:ss:SSSZZ')}`, 'YYYY-MM-DD HH:mm:ss:SSSZZ');
            data.push([
                Date.parse(tick.updated_at),
                Date.parse(normalisedTime.toISOString())
            ])
        });
        series.push({
            name: 'Tick',
            data: data
        });
        let options = {
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Time (UTC)'
                },
                type: 'datetime',
                dateTimeLabelFormats: {
                    millisecond: '%H:%M',
                    second: '%H:%M',
                    minute: '%H:%M',
                    hour: '%H:%M',
                    day: '%H:%M',
                    week: '%H:%M',
                    month: '%H:%M',
                    year: '%H:%M'
                }
            },
            tooltip: {
                headerFormat: '{point.key}
',
                pointFormatter: function () {
                    console.log(this);
                    return `<span style="color:${this.color}">●</span> ${this.series.name}: <b>${moment(this.y).utc().format('HH:mm')} UTC</b><br/>`
                }
            },
            title: {
                text: 'Tick Trend'
            },
            series: series,
            exporting: {
                enabled: true,
                sourceWidth: 1200
            }
        };
        let highchartsCurrentTheme = highchartsTheme.HighchartsLightTheme;
        if (req.query.theme === 'dark') {
            highchartsCurrentTheme = highchartsTheme.HighchartsDarkTheme;
        }
        let highchartsRequestOptions = {
            url: `http://localhost:7801/`,
            formData: {
                options: JSON.stringify(options),
                type: 'image/png',
                filename: `${req.query.name}-${req.query.timeMin}-${req.query.timeMax}-state`,
                resources: JSON.stringify({
                    js: `theme = ${JSON.stringify(highchartsCurrentTheme)};Highcharts.setOptions(theme);`
                }),
                scale: 2
            },
            encoding: null,
            resolveWithFullResponse: true
        }
        let imageResponse = await request.post(highchartsRequestOptions);
        res.set('Content-Type', imageResponse.headers['content-type'])
        res.set('Content-Disposition', imageResponse.headers['content-disposition'])
        res.send(imageResponse.body);
    } catch (err) {
        next(err);
    }
});

module.exports = router;


text:
package io.opensec.six.oval.model.results;

/**
 * An abstract base class for the criteria-related leaf types.
 *
 * @author	Akihito Nakamura, AIST
 * @see OVAL Language
 */
public abstract class CriteriaResultLeafElement
    extends CriteriaResultElement
{

    private int  version;
    //{xsd:nonNegativeInteger, required}

    public static final Integer DEFAULT_VARIABLE_INSTANCE = 1;

    private Integer  variable_instance;
    //{xsd:nonNegativeInteger, optional, default="1"}

    /**
     * Constructor.
     */
    public CriteriaResultLeafElement()
    {
    }

    public CriteriaResultLeafElement(
                    final String id,
                    final int version
                    )
    {
        _setEntityRef( id );
        setVersion( version );
    }

    public CriteriaResultLeafElement(
                    final String id,
                    final int version,
                    final ResultEnumeration result
                    )
    {
        this( id, version );
        setResult( result );
    }

    /**
     */
    protected abstract void _setEntityRef( String entityID );
    protected abstract String _getEntityRef();

//    protected void _setEntityRef(
//                    final String entityID
//                    )
//    {
//        _entityRef = entityID;
//    }
//
//
//    protected String _getEntityRef()
//    {
//        return _entityRef;
//    }

    /**
     */
    public void setVersion(
                    final int version
                    )
    {
        if (version < 0) {
            throw new IllegalArgumentException(
                            "negative version: " + version );
        }

        this.version = version;
    }

    public int getVersion()
    {
        return version;
    }

    /**
     */
    public void setVariableInstance(
                    final Integer variable_instance
                    )
    {
        if (variable_instance != null) {
            if (variable_instance < 0) {
                throw new IllegalArgumentException(
                                "negative variable instance: " + variable_instance );
            }
        }

        this.variable_instance = variable_instance;
    }

    public Integer getVariableInstance()
    {
        return variable_instance;
    }

    public static final Integer variableInstance(
                    final CriteriaResultLeafElement obj
                    )
    {
        Integer  variable_instance = obj.getVariableInstance();
        return (variable_instance == null ? DEFAULT_VARIABLE_INSTANCE : variable_instance);
    }

    //**************************************************************
    //  java.lang.Object
    //**************************************************************

    @Override
    public String toString()
    {
        return "version=" + getVersion()
                        + ", variable_instance=" + getVariableInstance()
                        + ", " + super.toString();
    }

}
// CriterionResultLeafElement


text:
using com.techphernalia.MyPersonalAccounts.Manager.Inventory;
using System;
using System.Windows.Forms;

namespace com.techphernalia.MyPersonalAccounts.Manager
{
    public partial class frmAccountsManager : Form
    {
        private int childFormNumber = 0;

        public frmAccountsManager()
        {
            InitializeComponent();
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            Form childForm = new Form();
            childForm.MdiParent = this;
            childForm.Text = "Window " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void reportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach(Form childForm in MdiChildren)
            {
                if(childForm is frmStockUnitManager)
                {
                    childForm.Show();
                    return;
                }
            }
            var f = new frmStockUnitManager();
            f.MdiParent = this;
            f.Show();
        }
    }
}


text:
<resources>
    <string name="app_name">Example94</string>
    <string name="title_activity_main">MainActivity</string>
</resources>


text:
def get_message():
	return u"hi there"

def get_integer():
	return 42

def sum(a, b):
	return a + b


text:
<?php

namespace Oro\Bundle\DataAuditBundle\Tests\Functional\EventListener;

use Doctrine\ORM\Proxy\Proxy;
use Oro\Bundle\DataAuditBundle\Tests\Functional\Environment\Entity\TestAuditDataChild;
use Oro\Bundle\DataAuditBundle\Tests\Functional\Environment\Entity\TestAuditDataOwner;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

/**
 * @dbIsolationPerTest
 */
class SendInsertedEntitiesToMessageQueueTest extends WebTestCase
{
    use SendChangedEntitiesToMessageQueueExtensionTrait;

    protected function setUp()
    {
        $this->initClient();
    }

    public function testShouldSendWhenNewEntityInsertedWithoutChanges()
    {
        $owner = new TestAuditDataOwner();

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
    }

    public function testShouldSendAllInsertedEntities()
    {
        $em = $this->getEntityManager();

        $owner = new TestAuditDataOwner();
        $em->persist($owner);

        $owner = new TestAuditDataOwner();
        $em->persist($owner);

        $owner = new TestAuditDataOwner();
        $em->persist($owner);

        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(3, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);
    }

    public function testShouldSendWhenStringPropertyChanged()
    {
        $owner = new TestAuditDataOwner();
        $owner->setStringProperty('aString');

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'stringProperty' => [null, 'aString'],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenIntegerPropertyChanged()
    {
        $owner = new TestAuditDataOwner();
        $owner->setIntegerProperty(1234);

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'integerProperty' => [null, 1234],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenObjectPropertyChanged()
    {
        $owner = new TestAuditDataOwner();
        $owner->setObjectProperty(['foo' => 'fooVal']);

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'objectProperty' => [null, ['foo' => 'fooVal']],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenJsonArrayPropertyChanged()
    {
        $owner = new TestAuditDataOwner();
        $owner->setJsonArrayProperty(['foo' => 'fooVal']);

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'jsonArrayProperty' => [null, ['foo' => 'fooVal']],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenDateTimePropertyChanged()
    {
        $owner = new TestAuditDataOwner();
        $owner->setDateProperty(new \DateTime('2010-11-12 00:01:02+0000'));

        $em = $this->getEntityManager();
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'dateProperty' => [null, '2010-11-12T00:01:02+0000'],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenOneToOnePropertyChanged()
    {
        $em = $this->getEntityManager();

        $child = new TestAuditDataChild();
        $em->persist($child);
        $em->flush();

        self::getMessageCollector()->clear();

        $owner = new TestAuditDataOwner();
        $owner->setChild($child);
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals(TestAuditDataOwner::class, $insertedEntity['entity_class']);
        $this->assertEquals($owner->getId(), $insertedEntity['entity_id']);
        $this->assertEquals([
            'child' => [null, [
                'entity_class' => TestAuditDataChild::class,
                'entity_id' => $child->getId(),
            ]],
        ], $insertedEntity['change_set']);
    }

    public function testShouldSendWhenOneToOnePropertyChangedWithProxyChild()
    {
        $em = $this->getEntityManager();

        $child = new TestAuditDataChild();
        $em->persist($child);
        $em->flush();
        $em->clear();

        $childProxy = $em->getReference(TestAuditDataChild::class, $child->getId());
        //guard
        $this->assertInstanceOf(Proxy::class, $childProxy);

        self::getMessageCollector()->clear();

        $owner = new TestAuditDataOwner();
        $owner->setChild($childProxy);
        $em->persist($owner);
        $em->flush();

        $message = $this->getFirstEntitiesChangedMessage();
        $this->assertEntitiesInsertedInMessageCount(1, $message);
        $this->assertEntitiesUpdatedInMessageCount(0, $message);
        $this->assertEntitiesDeletedInMessageCount(0, $message);
        $this->assertCollectionsUpdatedInMessageCount(0, $message);

        $insertedEntity = $message->getBody()['entities_inserted'][spl_object_hash($owner)];

        $this->assertEquals([
            'child' => [null, [
                'entity_class' => TestAuditDataChild::class,
                'entity_id' => $child->getId(),
            ]],
        ], $insertedEntity['change_set']);
    }
}