text:
Reader parseSceneXML(const char* filename)
{
	Reader reader;
	TiXmlDocument doc(filename);
	bool loadOkay = doc.LoadFile();

	if (!loadOkay)
	{
		std::cout << "Could not load file: " << filename << "Error = " << doc.ErrorDesc() << std::endl;
		return reader;
	}

	TiXmlNode* pRoot = doc.FirstChild("Scene");
	for (TiXmlNode* pNode = pRoot->FirstChild(); pNode; pNode = pNode->NextSibling())
	{
        if (pNode->Value() == std::string("Material"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // get material index

            //
            // read reflectance coefficients
            //
            float amb[3], dif[3], spe[3], mir[3];
			float phongExp;
			for (TiXmlNode* pChild = pNode->FirstChild(); pChild; pChild = pChild->NextSibling())
			{
				if (pChild->Value() == std::string("Ambient"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &amb[0], &amb[1], &amb[2]);
				}
				else if (pChild->Value() == std::string("Diffuse"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &dif[0], &dif[1], &dif[2]);
				}
				else if (pChild->Value() == std::string("Specular"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f %f", &spe[0], &spe[1], &spe[2], &phongExp);
				}
				else if (pChild->Value() == std::string("Reflectance"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &mir[0], &mir[1], &mir[2]);
				}
			}

            //
            // TODO: Save the scanned values for the current material in your data structures.
            //
			reader.saveMaterials(index, amb, dif, spe, mir, phongExp);

        }
		else if (pNode->Value() == std::string("Vertex"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // get vertex index

			float coords[3];
			TiXmlNode* pChild = pNode->FirstChild();
			sscanf(pChild->FirstChild()->Value(), "%f %f %f", &coords[0], &coords[1], &coords[2]);

            //
            // TODO: Save the scanned values for the current vertex in your data structures.
            //
			reader.saveVertex(index, coords);

		}
		else if (pNode->Value() == std::string("Triangle"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // get triangle index

			int vIndex[3], mIndex;
			for (TiXmlNode* pChild = pNode->FirstChild(); pChild; pChild = pChild->NextSibling())
			{
				if (pChild->Value() == std::string("Vertices"))
				{
					sscanf(pChild->FirstChild()->Value(), "%d %d %d", &vIndex[0], &vIndex[1], &vIndex[2]);
				}
				else if (pChild->Value() == std::string("MaterialId"))
				{
					sscanf(pChild->FirstChild()->Value(), "%d", &mIndex);
				}
			}

            //
            // TODO: Save the scanned values for the current triangle in your data structures.
            //
            reader.saveTriangle(index, vIndex, mIndex);

		}
		else if (pNode->Value() == std::string("Sphere"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // Sphere index

			int vIndex, mIndex;
			float rad;
			for (TiXmlNode* pChild = pNode->FirstChild(); pChild; pChild = pChild->NextSibling())
			{
				if (pChild->Value() == std::string("Center"))
				{
					sscanf(pChild->FirstChild()->Value(), "%d", &vIndex);
				}
				else if (pChild->Value() == std::string("MaterialId"))
				{
					sscanf(pChild->FirstChild()->Value(), "%d", &mIndex);
				}
				else if (pChild->Value() == std::string("Radius"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f", &rad);
				}
			}

            //
            // TODO: Save the scanned values for the current sphere in your data structures.
            //
            reader.saveSphere(index, vIndex, mIndex, rad);

		}
		else if (pNode->Value() == std::string("PointLight"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // Light index

			float pos[3], intensity[3];
			for (TiXmlNode* pChild = pNode->FirstChild(); pChild; pChild = pChild->NextSibling())
			{
				if (pChild->Value() == std::string("Position"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &pos[0], &pos[1], &pos[2]);
				}
				else if (pChild->Value() == std::string("Intensity"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &intensity[0], &intensity[1], &intensity[2]);
				}
			}

            //
            // TODO: Save the scanned values for the current point light in your data structures.
            //
            reader.savePointLight(index, pos, intensity);
		}
		else if (pNode->Value() == std::string("AmbientLight"))
        {
			float intensity[3];
			TiXmlNode* pChild = pNode->FirstChild();
			sscanf(pChild->Value(), "%f %f %f", &intensity[0], &intensity[1], &intensity[2]);

            //
            // TODO: Save the scanned values for the ambient light in your data structures.
            //
            reader.saveAmbientLight(intensity);
		}
		else if (pNode->Value() == std::string("BackgroundColor"))
        {
            float bgColor[3];
			TiXmlNode* pChild = pNode->FirstChild();
			sscanf(pChild->Value(), "%f %f %f", &bgColor[0], &bgColor[1], &bgColor[2]);

            //
            // TODO: Save the scanned values for the background color in your data structures.
            //
            reader.saveBackground(bgColor);
		}
		else if (pNode->Value() == std::string("RayReflectionCount"))
        {
            int rayReflectCount;
			TiXmlNode* pChild = pNode->FirstChild();
			sscanf(pChild->Value(), "%d", &rayReflectCount);

            //
            // TODO: Save the scanned values for the ray reflection count in your data structures.
            //
            reader.saveReflectanceCount(rayReflectCount);
		}
		else if (pNode->Value() == std::string("Camera"))
        {
			TiXmlAttribute* pAtt = pNode->ToElement()->FirstAttribute();
			int index = pAtt->IntValue(); // Camera index

			float gaze[3], up[3], pos[3];
			float left, right, bottom, top, distance;
			int nx, ny;
			std::string imageName;
			for (TiXmlNode* pChild = pNode->FirstChild(); pChild; pChild = pChild->NextSibling())
			{
				if (pChild->Value() == std::string("Position"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &pos[0], &pos[1], &pos[2]);
				}
				else if (pChild->Value() == std::string("Gaze"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &gaze[0], &gaze[1], &gaze[2]);
				}
				else if (pChild->Value() == std::string("Up"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f", &up[0], &up[1], &up[2]);
				}
				else if (pChild->Value() == std::string("ImagePlane"))
				{
					sscanf(pChild->FirstChild()->Value(), "%f %f %f %f %f %d %d", &left, &right, &bottom, &top, &distance, &nx, &ny);
				}
				else if (pChild->Value() == std::string("OutputName"))
				{
					imageName = pChild->FirstChild()->Value();
				}
			}

            //
            // TODO: Save the scanned values for the current camera in your data structures.
            //
            reader.saveCamera(index, gaze, up, pos, left, right, bottom, top, distance, nx, ny, imageName);
		}
	}

    return reader;
}


text:
namespace Azure.ResourceManager.Network.Models
{
    /// <summary> Qos Traffic Profiler IP Range properties. </summary>
    public partial class QosIpRange
    {
        /// <summary> Initializes a new instance of QosIpRange. </summary>
        public QosIpRange()
        {
        }

        /// <summary> Initializes a new instance of QosIpRange. </summary>
        /// <param name="startIP"> Start IP Address. </param>
        /// <param name="endIP"> End IP Address. </param>
        internal QosIpRange(string startIP, string endIP)
        {
            StartIP = startIP;
            EndIP = endIP;
        }

        /// <summary> Start IP Address. </summary>
        public string StartIP { get; set; }
        /// <summary> End IP Address. </summary>
        public string EndIP { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Ambitia\Http\Routing\Exceptions;

class MethodNotFound extends \Exception
{
    public function __construct($className, $methodName, \Exception $previous = null)
    {
        $message = sprintf('Class of name %s doesn\'t have method %s', $className, $methodName);

        parent::__construct($message, 500, $previous);
    }
}


text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using FluentAssertions.Execution;

namespace FluentAssertions.Primitives;

///
/// Contains a number of methods to assert that a nullable <see cref="TimeSpan"/> is in the expected state.
///
[DebuggerNonUserCode]
public class SimpleTimeSpanAssertions : SimpleTimeSpanAssertions<SimpleTimeSpanAssertions>
{
    public SimpleTimeSpanAssertions(TimeSpan? value)
        : base(value)
    {
    }
}

#pragma warning disable CS0659 // Ignore not overriding Object.GetHashCode()
#pragma warning disable CA1065 // Ignore throwing NotSupportedException from Equals
///
/// Contains a number of methods to assert that a nullable <see cref="TimeSpan"/> is in the expected state.
///
[DebuggerNonUserCode]
public class SimpleTimeSpanAssertions<TAssertions>
    where TAssertions : SimpleTimeSpanAssertions<TAssertions>
{
    public SimpleTimeSpanAssertions(TimeSpan? value)
    {
        Subject = value;
    }

    ///
    /// Gets the object which value is being asserted.
    ///
    public TimeSpan? Subject { get; }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is greater than zero.
    ///
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BePositive(string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject > TimeSpan.Zero)
            .FailWith("Expected {context:time} to be positive{reason}, but found {0}.", Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is less than zero.
    ///
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeNegative(string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject < TimeSpan.Zero)
            .FailWith("Expected {context:time} to be negative{reason}, but found {0}.", Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is equal to the
    /// specified <paramref name="expected"/> time.
    ///
    /// <param name="expected">The expected time difference</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> Be(TimeSpan expected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(expected == Subject)
            .FailWith("Expected {0}{reason}, but found {1}.", expected, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is not equal to the
    /// specified <paramref name="unexpected"/> time.
    ///
    /// <param name="unexpected">The unexpected time difference</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> NotBe(TimeSpan unexpected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .ForCondition(unexpected != Subject)
            .BecauseOf(because, becauseArgs)
            .FailWith("Did not expect {0}{reason}.", unexpected);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is less than the
    /// specified <paramref name="expected"/> time.
    ///
    /// <param name="expected">The time difference to which the current value will be compared</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeLessThan(TimeSpan expected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject < expected)
            .FailWith("Expected {context:time} to be less than {0}{reason}, but found {1}.", expected, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is less than or equal to the
    /// specified <paramref name="expected"/> time.
    ///
    /// <param name="expected">The time difference to which the current value will be compared</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeLessThanOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject <= expected)
            .FailWith("Expected {context:time} to be less than or equal to {0}{reason}, but found {1}.", expected, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public AndConstraint<TAssertions> BeLessOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs) => BeLessThanOrEqualTo(expected, because, becauseArgs);

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is greater than the
    /// specified <paramref name="expected"/> time.
    ///
    /// <param name="expected">The time difference to which the current value will be compared</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeGreaterThan(TimeSpan expected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject > expected)
            .FailWith("Expected {context:time} to be greater than {0}{reason}, but found {1}.", expected, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the time difference of the current <see cref="TimeSpan"/> is greater than or equal to the
    /// specified <paramref name="expected"/> time.
    ///
    /// <param name="expected">The time difference to which the current value will be compared</param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeGreaterThanOrEqualTo(TimeSpan expected, string because = "",
        params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject >= expected)
            .FailWith("Expected {context:time} to be greater than or equal to {0}{reason}, but found {1}.", expected, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public AndConstraint<TAssertions> BeGreaterOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs) => BeGreaterThanOrEqualTo(expected, because, becauseArgs);

    ///
    /// Asserts that the current <see cref="TimeSpan"/> is within the specified time
    /// from the specified <paramref name="nearbyTime"/> value.
    ///
    /// <remarks>
    /// Use this assertion when, for example the database truncates datetimes to nearest 20ms. If you want to assert to the exact datetime,
    /// use <see cref="Be"/>.
    /// </remarks>
    /// <param name="nearbyTime">
    /// The expected time to compare the actual value with.
    /// </param>
    /// <param name="precision">
    /// The maximum amount of time which the two values may differ.
    /// </param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> BeCloseTo(TimeSpan nearbyTime, TimeSpan precision, string because = "",
        params object[] becauseArgs)
    {
        if (precision < TimeSpan.Zero)
        {
            throw new ArgumentOutOfRangeException(nameof(precision), $"The value of {nameof(precision)} must be non-negative.");
        }

        TimeSpan minimumValue = nearbyTime - precision;
        TimeSpan maximumValue = nearbyTime + precision;

        Execute.Assertion
            .ForCondition((Subject >= minimumValue) && (Subject.Value <= maximumValue))
            .BecauseOf(because, becauseArgs)
            .FailWith("Expected {context:time} to be within {0} from {1}{reason}, but found {2}.",
                precision,
                nearbyTime, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    ///
    /// Asserts that the current <see cref="TimeSpan"/> is not within the specified time
    /// from the specified <paramref name="distantTime"/> value.
    ///
    /// <remarks>
    /// Use this assertion when, for example the database truncates datetimes to nearest 20ms. If you want to assert to the exact datetime,
    /// use <see cref="NotBe"/>.
    /// </remarks>
    /// <param name="distantTime">
    /// The time to compare the actual value with.
    /// </param>
    /// <param name="precision">
    /// The maximum amount of time which the two values may differ.
    /// </param>
    /// <param name="because">
    /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
    /// is needed. If the phrase does not start with the word because, it is prepended automatically.
    /// </param>
    /// <param name="becauseArgs">
    /// Zero or more objects to format using the placeholders in <paramref name="because" />.
    /// </param>
    public AndConstraint<TAssertions> NotBeCloseTo(TimeSpan distantTime, TimeSpan precision, string because = "",
        params object[] becauseArgs)
    {
        if (precision < TimeSpan.Zero)
        {
            throw new ArgumentOutOfRangeException(nameof(precision), $"The value of {nameof(precision)} must be non-negative.");
        }

        TimeSpan minimumValue = distantTime - precision;
        TimeSpan maximumValue = distantTime + precision;

        Execute.Assertion
            .ForCondition(Subject < minimumValue || Subject > maximumValue)
            .BecauseOf(because, becauseArgs)
            .FailWith("Expected {context:time} to not be within {0} from {1}{reason}, but found {2}.",
                precision,
                distantTime, Subject);

        return new AndConstraint<TAssertions>((TAssertions)this);
    }

    /// <inheritdoc/>
    public override bool Equals(object obj) =>
        throw new NotSupportedException("Equals is not part of Fluent Assertions. Did you mean Be() instead?");
}


text:
var express = require('express');
var router = express.Router();
var md = require('marked');
var p = require('../model/problems');

var nav = [
	{ name: '首页', ref: '/', active: false },
	{ name: '问题', ref: '/problem', active: true },
	{ name: '状态', ref: '/status', active: false },
	{ name: '比赛', ref: '/contest', active: false },
	{ name: '排名', ref: '/ranklist', active: false }
            ];

var problemId, user;

router.get('/:problemId', function(req, res) {
    problemId = Number(req.params.problemId);
    if (req.session.user)
        user = req.session.user;
    else user = null;
    p.fetchProblem(problemId, function(err, doc) {
        if ((doc && doc.avail) || (doc && doc.avail == false && user && user.admin)) res.render('problems', { problemId: problemId, title: problemId + ' - 问题 - CodeBursts!', nav: nav, md: md, doc: doc, login: user});
        else {
            if (doc && doc.avail == false) {
                var error = {status: '权限狗专用入口', stack: '玛雅这是权限题!少侠请回吧……要权限请联系jcpwfloi@163.com'};
                res.render('error', {error: error});
                error = null;
            } else {
                var error = {status: 404, stack: '404 not found'};
                res.render('error', {error: error});
                error = null;
            }
        }
    });
});

module.exports = router;


text:
#pragma once
#include "Network_Event_Prototype.h"
#include "Link_Prototype.h"
#include "Zone_Prototype.h"

define_static_typelist_loop(Initialize_Type,Initialize_List);
//define_feature_dispatcher(Initialize,Initialize_Object);

namespace Network_Event_Components
{
	using std::shared_ptr;
	using std::weak_ptr;

	namespace Types
	{
		enum WEATHER_TYPE
		{
			CLEAR_DRY_PAVEMENT = 0,
			CLEAR_WET_PAVEMENT,
			RAIN,
			SNOW,
			TEMP,
			WIND,
			VISIBILITY
		};

		enum ACCIDENT_SEVERITY
		{
			SHOULDER_DISABLEMENT = 0,
			SHOULDER_ACCIDENT,
			ONE_LANE_BLOCKED,
			TWO_LANES_BLOCKED,
			THREE_LANES_BLOCKED
		};
	}

	namespace Concepts
	{
	}

	namespace Implementations
	{
		implementation struct Base_Network_Event : public Polaris_Component<MasterType,INHERIT(Base_Network_Event),Execution_Object>
		{
			typedef typename  Polaris_Component<MasterType,INHERIT(Base_Network_Event),Execution_Object>::Component_Type ComponentType;
			typedef Link_Components::Prototypes::Link<typename MasterType::link_type> Link_Interface;
			typedef Zone_Components::Prototypes::Zone<typename MasterType::zone_type> Zone_Interface;
			typedef  Activity_Location_Components::Prototypes::Activity_Location<typename remove_pointer<typename Link_Interface::get_type_of(activity_locations)::value_type>::type> Location_Interface;
			typedef Random_Access_Sequence<typename Link_Interface::get_type_of(activity_locations),Location_Interface*> Location_Container_Interface;

			typedef Network_Components::Prototypes::Network<typename MasterType::network_type> _Network_Interface;
			typedef  Link_Components::Prototypes::Link<typename remove_pointer< typename _Network_Interface::get_type_of(links_container)::value_type>::type>  _Link_Interface2;
			typedef  Random_Access_Sequence< typename _Network_Interface::get_type_of(links_container), _Link_Interface2*> _Links_Container_Interface;

			template<typename TargetType> static void Initialize_Type(const std::vector<shared_ptr<polaris::io::Event_Key>>& keys)
			{
				for(typename std::vector<shared_ptr<polaris::io::Event_Key>>::const_iterator itr=keys.begin();itr!=keys.end();itr++)
				{
					_event_keys.push_back( (*itr)->getKey() );
				}
			}

			template<typename TargetType> static void Accept_Subscriber(TargetType callback,int subscriber)
			{
				_callbacks_by_component_id[subscriber]=callback;
			}

			template<typename TargetType> void Start()
			{
				int start = _start_time;

				if(start == iteration()) ++start;

				if(start < _end_time)
				{
					Load_Event<ComponentType>(&ComponentType::Incident_Conditional,start, 0);
				}
				else
				{
					THROW_WARNING("Invalid Network Event");
				}
			}

			template<typename TargetType> void Initialize(int start_time, int end_time, boost::container::vector<typename MasterType::link_type*>& affected_links)
			{
				_start_time = start_time;
				_end_time = end_time;

				for(typename std::vector<typename MasterType::link_type*>::iterator vitr=affected_links.begin();vitr!=affected_links.end();vitr++)
				{
					Link_Interface* link = (Link_Interface*)(*vitr);
					_affected_links.push_back( (Link_Interface*)(*vitr) );
					//Location_Container_Interface* locations = link->template activity_locations<Location_Container_Interface*>();

					//// push locations from link to affected locations container
					//for (typename Location_Container_Interface::iterator litr = locations->begin(); litr != locations->end(); ++litr)
					//{
					//	Location_Interface* loc = (*litr);
					//	this->_affected_locations.push_back(loc);
					//	zone_set.insert(loc->template zone<Zone_Interface*>());
					//}
				}
			}

			template<typename TargetType> void Initialize(weak_ptr<polaris::io::Event_Instance>& instance)
			{
				using namespace polaris::io;

				_active = false;

				_start_time = instance.lock()->getStart_Time();
				_end_time = instance.lock()->getEnd_Time();

				_notes = instance.lock()->getNote();

				const std::vector<int>& links=instance.lock()->getLinks();
				// temporary containers used to fill affected zone boost::container::vector
				boost::unordered::unordered_set<Zone_Interface*> zone_set;
				if (links[0] == -1)
				{
					// affect all links
					_Links_Container_Interface& links_container = ((_Network_Interface*)_global_network)->template links_container<_Links_Container_Interface&>();
					typename _Links_Container_Interface::iterator link_itr;
					for (link_itr = links_container.begin(); link_itr != links_container.end(); link_itr++)
					{
						Link_Interface* link = (Link_Interface*)(*link_itr);
						_affected_links.push_back(link);
//cout << "link " << link->template internal_id<int>() << " affected" << endl;
						Location_Container_Interface* locations = link->template activity_locations<Location_Container_Interface*>();

						// push locations from link to affected locations container
						for (typename Location_Container_Interface::iterator litr = locations->begin(); litr != locations->end(); ++litr)
						{
							Location_Interface* loc = (Location_Interface*)(*litr);
								this->_affected_locations.push_back(loc);
								zone_set.insert(loc->template zone<Zone_Interface*>());
						}
					}
				}
				else
				{

					boost::unordered::unordered_map<int,boost::container::vector<typename MasterType::link_type*>>& db_map=((Network<typename MasterType::network_type>*)_global_network)->template db_id_to_links_map<boost::unordered::unordered_map<int,boost::container::vector<typename MasterType::link_type*>>&>();

					cout << endl << "INITIALIZE NETWORK EVENT:";
					for(typename std::vector<int>::const_iterator itr=links.begin();itr!=links.end();itr++)
					{
						int link = *itr;

						if(db_map.count(link))
						{
							boost::container::vector<typename MasterType::link_type*>& links=db_map[link];

							typename boost::container::vector<typename MasterType::link_type*>::iterator vitr;

							for(vitr=links.begin();vitr!=links.end();vitr++)
							{
								Link_Interface* link = (Link_Interface*)(*vitr);
								_affected_links.push_back( (Link_Interface*)(*vitr) );
								Location_Container_Interface* locations = link->template activity_locations<Location_Container_Interface*>();

								// push locations from link to affected locations container
								for (typename Location_Container_Interface::iterator litr = locations->begin(); litr != locations->end(); ++litr)
								{
									Location_Interface* loc = (Location_Interface*)(*litr);
									 this->_affected_locations.push_back(loc);
									 zone_set.insert(loc->template zone<Zone_Interface*>());
								}

							}
						}
					}
				}

				// create the affected zones boost::container::list
				for (typename boost::unordered::unordered_set<Zone_Interface*>::iterator zitr = zone_set.begin(); zitr != zone_set.end(); ++zitr)
				{
					Zone_Interface* zone = (Zone_Interface*)(*zitr);
					this->_affected_zones.push_back(zone);
					cout <<endl << "Affected zone: "<< zone->template uuid<int>();
				}

				// create the unaffected locations boost::container::list
				Location_Container_Interface* all_locations = ((Network<typename MasterType::network_type>*)_global_network)->template activity_locations_container<Location_Container_Interface*>();
				for (typename Location_Container_Interface::iterator litr = all_locations->begin(); litr != all_locations->end(); ++litr)
				{
					bool add = true;
					for (typename boost::container::vector<Location_Interface*>::iterator itr = this->_affected_locations.begin(); itr != this->_affected_locations.end(); ++itr)
					{
						if ((void*)*litr == (void*)*itr){add=false; break;}
					}
					if (add) this->_unaffected_locations.push_back((Location_Interface*)*litr);
				}
				cout << endl << "Total Locations: " << all_locations->size() << ", Affected Locations: " << this->_affected_locations.size() << ", Unaffected Locations: " << this->_unaffected_locations.size();
			}

			static void Incident_Conditional(ComponentType* _this,Event_Response& response)
			{
				ComponentType* pthis = (ComponentType*)_this;

				if( iteration() >= pthis->_end_time )
				{
					response.next._iteration = END;
					response.next._sub_iteration = 0;
				}
				else if(iteration() < pthis->_start_time)
				{
					response.next._iteration = pthis->_start_time;
					response.next._sub_iteration = 0;
				}
				else
				{
					response.next._iteration = iteration() + 1;
					response.next._sub_iteration = 0;
				}

				_this->Incident_Event();
			}

			template<typename TargetType> void Notify_Subscribers()
			{
				size_t subscriber = Link_Interface::Component_Type::component_id;

				if(_callbacks_by_component_id.count(subscriber))
				{
					typename Network_Event_Callback<ComponentType>::type callback=_callbacks_by_component_id[subscriber];

					for(typename boost::container::vector<Link_Interface*>::iterator itr=_affected_links.begin();itr!=_affected_links.end();itr++)
					{
						(*callback)( (void*)(*itr), (Network_Event<ComponentType>*)this );
					}
				}
			}

			void Incident_Event()
			{
				if(iteration() == _start_time)
				{
					_active = true;
					Notify_Subscribers<NT>();
				}
				else if(iteration() == _end_time)
				{
					_active = false;
					Notify_Subscribers<NT>();
				}
			}

			m_data(boost::container::vector<Link_Interface*>,affected_links, NONE, NONE);
			m_data(boost::container::vector<Location_Interface*>,affected_locations, NONE, NONE);
			m_data(boost::container::vector<Location_Interface*>,unaffected_locations, NONE, NONE);
			m_data(boost::container::vector<Zone_Interface*>,affected_zones, NONE, NONE);

			m_data(int,start_time, NONE, NONE);
			m_data(int,end_time, NONE, NONE);
			m_data(bool,active, NONE, NONE);
			m_data(string,notes, NONE, NONE);

			static m_data(boost::container::vector<string>,event_keys, NONE, NONE);
			static m_prototype(Null_Prototype,typename MasterType::network_event_manager_type,network_event_manager, NONE, NONE);

			static m_data(concat(boost::unordered::unordered_map<size_t,typename Network_Event_Callback<ComponentType>::type>),callbacks_by_component_id, NONE, NONE);
		};

		template<typename MasterType,typename InheritanceList>
		boost::container::vector<string> Base_Network_Event<MasterType,InheritanceList>::_event_keys;

		template<typename MasterType,typename InheritanceList>
		boost::unordered::unordered_map<size_t,typename Network_Event_Callback<typename Base_Network_Event<MasterType,InheritanceList>::ComponentType>::type> Base_Network_Event<MasterType,InheritanceList>::_callbacks_by_component_id;

		template<typename MasterType,typename InheritanceList>
		Network_Event_Manager<typename MasterType::network_event_manager_type>* Base_Network_Event<MasterType,InheritanceList>::_network_event_manager;

		implementation struct Weather_Network_Event : public Base_Network_Event<MasterType,INHERIT(Weather_Network_Event)>
		{
			//template<typename TargetType> static void Initialize_Type(void* obj){Base_Network_Event::template Initialize_Type<NT>(obj);}

			//template<typename TargetType> void Start(){Base_Network_Event::template Start<NT>();}
			template<typename TargetType> void Start(){((Base_Network_Event<MasterType,INHERIT(Weather_Network_Event)>*)this)->template Start<NT>();}

			template<typename TargetType> void Initialize(weak_ptr<polaris::io::Event_Instance>& instance)
			{
				using namespace polaris::io;
				//Base_Network_Event::template Initialize< ComponentType,ComponentType,weak_ptr<Event_Instance>& >(instance);

				((Base_Network_Event<MasterType,INHERIT(Weather_Network_Event)>*)this)-> Initialize<weak_ptr<Event_Instance>& >(instance);

				//_start_time = 14400;
				//_end_time = 43200;

				const std::vector<shared_ptr<Event_Instance_Value>>& values=instance.lock()->getValues();

				for(typename std::vector<shared_ptr<Event_Instance_Value>>::const_iterator itr=values.begin();itr!=values.end();itr++)
				{
					//_weather_type = Types::WEATHER_TYPE::SNOW;
					//_precipitation_depth = .6;

					if( (*itr)->getKey()->getKey() == "type" )
					{
						if((*itr)->getValue() == "clear_dry_pavement")
						{
							_weather_type = Types::WEATHER_TYPE::CLEAR_DRY_PAVEMENT;
						}
						else if((*itr)->getValue() == "clear_wet_pavement")
						{
							_weather_type = Types::WEATHER_TYPE::CLEAR_WET_PAVEMENT;
						}
						else if((*itr)->getValue() == "rain")
						{
							_weather_type = Types::WEATHER_TYPE::RAIN;
						}
						else if((*itr)->getValue() == "snow")
						{
							_weather_type = Types::WEATHER_TYPE::SNOW;
						}
						else if((*itr)->getValue() == "temperature")
						{
							_weather_type = Types::WEATHER_TYPE::TEMP;
						}
						else if((*itr)->getValue() == "wind")
						{
							_weather_type = Types::WEATHER_TYPE::WIND;
						}
						else if ((*itr)->getValue() == "visibility")
						{
							_weather_type = Types::WEATHER_TYPE::VISIBILITY;
						}
					}
					else if( (*itr)->getKey()->getKey() == "snowdepthm" )
					{
						_snow_depth = stof((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "precipm" )
					{
						_precipitation_depth = stof((*itr)->getValue());

					}
					else if( (*itr)->getKey()->getKey() == "vism" )
					{
						_visibility = stof((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "wind" )
					{
						_wind_speed = stof((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "temperature" )
					{
						_wind_speed = stof((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "county" )
					{
						_county = (*itr)->getValue();
					}
				}
			}

			m_data(Types::WEATHER_TYPE,weather_type, NONE, NONE);
			m_data(float,precipitation_depth, NONE, NONE);
			m_data(float,snow_depth, NONE, NONE);
			m_data(float,visibility, NONE, NONE);
			m_data(string,county, NONE, NONE);
			m_data(float,temperature, NONE, NONE);
			m_data(float,wind_speed, NONE, NONE);
		};

		implementation struct Accident_Network_Event : public Base_Network_Event<MasterType,INHERIT(Accident_Network_Event)>
		{
			typedef Scenario_Components::Prototypes::Scenario<typename MasterType::scenario_type> _Scenario_Interface;
			//template<typename TargetType> static void Initialize_Type(void* obj){Base_Network_Event::template Initialize_Type<NT>(obj);}

			//template<typename TargetType> void Start(){Base_Network_Event::template Start<NT>();}
			template<typename TargetType> void Start(){((Base_Network_Event<MasterType,INHERIT(Accident_Network_Event)>*)this)->template Start<NT>();}

			template<typename TargetType> void Initialize(weak_ptr<polaris::io::Event_Instance>& instance)
			{
				using namespace polaris::io;

				//Base_Network_Event::template Initialize< ComponentType,ComponentType,weak_ptr<Event_Instance>& >(instance);
				((Base_Network_Event<MasterType,INHERIT(Accident_Network_Event)>*)this)->template Initialize<weak_ptr<Event_Instance>& >(instance);

				//_start_time = 28800 + rand()%(20*60);
				//_start_time = 500;
				Base_Network_Event::_end_time = Base_Network_Event::_end_time * ((_Scenario_Interface*)_global_scenario)->template accident_event_duration_reduction<float>();

				const std::vector<shared_ptr<Event_Instance_Value>>& values=instance.lock()->getValues();

				for(typename std::vector<shared_ptr<Event_Instance_Value>>::const_iterator itr=values.begin();itr!=values.end();itr++)
				{
					if( (*itr)->getKey()->getKey() == "lanes" )
					{
						_lanes = stoi((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "severity" )
					{
						_severity = stoi((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "vehicles" )
					{
						_vehicles_involved = stoi((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "accident_type" )
					{
						_accident_type = (*itr)->getValue();
					}
					else if( (*itr)->getKey()->getKey() == "vehicle_type" )
					{
						_vehicle_type = (*itr)->getValue();
					}
					else if( (*itr)->getKey()->getKey() == "injury" )
					{
						_injury_type = (*itr)->getValue();
					}
					else if( (*itr)->getKey()->getKey() == "lanes_closed" )
					{
						_lanes_closed = stoi((*itr)->getValue());
					}
				}
			}

			m_data(int,lanes, NONE, NONE);
			m_data(int,lanes_closed, NONE, NONE);
			m_data(int,severity, NONE, NONE);
			m_data(string,accident_type, NONE, NONE);
			m_data(int,vehicles_involved, NONE, NONE);
			m_data(string,vehicle_type, NONE, NONE);
			m_data(string,injury_type, NONE, NONE);
		};

		implementation struct Congestion_Network_Event : public Base_Network_Event<MasterType,INHERIT(Congestion_Network_Event)>
		{
			//template<typename TargetType> static void Initialize_Type(void* obj){Base_Network_Event::template Initialize_Type<NT>(obj);}

			//template<typename TargetType> void Start(){Base_Network_Event::template Start<NT>();}
			template<typename TargetType> void Start(){((Base_Network_Event<MasterType,INHERIT(Congestion_Network_Event)>*)this)->template Start<NT>();}

			template<typename TargetType> void Initialize(int start_time, int end_time, boost::container::vector<typename MasterType::link_type*>& affected_links)
			{
				((Base_Network_Event<MasterType,INHERIT(Congestion_Network_Event)>*)this)->template Initialize<MasterType>(start_time,end_time,affected_links);
			}

			template<typename TargetType> void Initialize(weak_ptr<polaris::io::Event_Instance>& instance)
			{
				using namespace polaris::io;

				//Base_Network_Event::template Initialize< ComponentType,ComponentType,weak_ptr<Event_Instance>& >(instance);
				((Base_Network_Event<MasterType,INHERIT(Congestion_Network_Event)>*)this)->template Initialize<weak_ptr<Event_Instance>& >(instance);

				const std::vector<shared_ptr<Event_Instance_Value>>& values=instance.lock()->getValues();

				for(typename std::vector<shared_ptr<Event_Instance_Value>>::const_iterator itr=values.begin();itr!=values.end();itr++)
				{
					if( (*itr)->getKey()->getKey() == "travel_time" )
					{
						_travel_time = stoi((*itr)->getValue());
					}
					else if( (*itr)->getKey()->getKey() == "slowdown_index" )
					{
						_slowdown_index = stof((*itr)->getValue());
					}
				}
			}

			m_data(int,travel_time, NONE, NONE);
			m_data(float,slowdown_index, NONE, NONE);
		};

		implementation struct Lane_Closure_Network_Event : public Base_Network_Event<MasterType,INHERIT(Lane_Closure_Network_Event)>
		{
			//template<typename TargetType> static void Initialize_Type(void* obj){Base_Network_Event::template Initialize_Type<NT>(obj);}

			//template<typename TargetType> void Start(){Base_Network_Event::template Start<NT>();}
			template<typename TargetType> void Start(){((Base_Network_Event<MasterType,INHERIT(Lane_Closure_Network_Event)>*)this)->template Start<NT>();}

			template<typename TargetType> void Initialize(weak_ptr<polaris::io::Event_Instance>& instance)
			{
				using namespace polaris::io;

				//Base_Network_Event::template Initialize< ComponentType,ComponentType,weak_ptr<Event_Instance>& >(instance);
				((Base_Network_Event<MasterType,INHERIT(Lane_Closure_Network_Event)>*)this)->template Initialize<weak_ptr<Event_Instance>& >(instance);

				const std::vector<shared_ptr<Event_Instance_Value>>& values=instance.lock()->getValues();

				for(typename std::vector<shared_ptr<Event_Instance_Value>>::const_iterator itr=values.begin();itr!=values.end();itr++)
				{
					if( (*itr)->getKey()->getKey() == "lanes_closed" )
					{
						_lanes = stoi((*itr)->getValue());
					}
				}
			}

			m_data(int,lanes, NONE, NONE);
		};

		implementation struct Network_Event_Manager_Implementation : public Polaris_Component<MasterType,INHERIT(Network_Event_Manager_Implementation),Data_Object>
		{
			typedef typename Polaris_Component<MasterType,INHERIT(Network_Event_Manager_Implementation),Data_Object>::Component_Type ComponentType;
			typedef Network_Event<typename MasterType::base_network_event_type> Base_Network_Event_Interface;
			typedef Network_Event<typename MasterType::weather_network_event_type> Weather_Network_Event_Interface;
			typedef Network_Event<typename MasterType::accident_network_event_type> Accident_Network_Event_Interface;
			typedef Network_Event<typename MasterType::congestion_network_event_type> Congestion_Network_Event_Interface;
			typedef Network_Event<typename MasterType::lane_closure_network_event_type> Lane_Closure_Network_Event_Interface;

			typedef Link<typename MasterType::link_type> Link_Interface;

			template<typename TargetType> void Push_Subscriber(typename Network_Event_Callback<TargetType>::type callback,int component_id)
			{
				//TODO
				Network_Event<TargetType>::template Push_Subscriber<typename Network_Event_Callback<TargetType>::type>(callback,component_id);
			}

			template<typename TargetType> void Initialize()
			{
				Read_DB<NT>();
				//execute_static_typelist_loop(Initialize_List,MasterType::network_event_types,this);
			}

			template<typename TargetType> void Read_DB()
			{
				using namespace odb;
				using namespace polaris;

				typedef Scenario_Components::Prototypes::Scenario<typename MasterType::scenario_type> _Scenario_Interface;
				string name( ((_Scenario_Interface*)_global_scenario)->template database_name<string&>());

				unique_ptr<database> db (open_sqlite_database (name));

				session s;

				transaction t (db->begin());
				result<io::Network_Event> r = db->template query<io::Network_Event> (query<io::Network_Event>::true_expr);

				for (result<io::Network_Event>::iterator itr=r.begin(); itr!=r.end(); ++itr)
				{
					const string& name = itr->getName();

					if(name == "Weather")
					{
						Weather_Network_Event_Interface::template Initialize_Type<const std::vector<shared_ptr<io::Event_Key>>&>(itr->getKeys());
					}
					else if(name == "Accident")
					{
						Accident_Network_Event_Interface::template Initialize_Type<const std::vector<shared_ptr<io::Event_Key>>&>(itr->getKeys());
					}
					else if(name == "Congestion")
					{
						Congestion_Network_Event_Interface::template Initialize_Type<const std::vector<shared_ptr<io::Event_Key>>&>(itr->getKeys());
					}
					else if(name == "Lane Closure")
					{
						Lane_Closure_Network_Event_Interface::template Initialize_Type<const std::vector<shared_ptr<io::Event_Key>>&>(itr->getKeys());
					}

					const std::vector<weak_ptr<io::Event_Instance> >& instances = itr->getInstances();

					for(typename std::vector<weak_ptr<io::Event_Instance>>::const_iterator vitr=instances.begin();vitr!=instances.end();vitr++)
					{
						weak_ptr<io::Event_Instance> _ptr=*vitr;

						if(name == "Weather")
						{
							Weather_Network_Event_Interface* net_event = (Weather_Network_Event_Interface*)Allocate<typename MasterType::weather_network_event_type>();
							net_event->Initialize< weak_ptr<io::Event_Instance>& >(_ptr);
							net_event->template Start<NT>();
							Add_Network_Event<typename Weather_Network_Event_Interface::ComponentType>(net_event);
						}
						else if(name == "Accident")
						{
							Accident_Network_Event_Interface* net_event = (Accident_Network_Event_Interface*)Allocate<typename MasterType::accident_network_event_type>();
							net_event->Initialize< weak_ptr<io::Event_Instance>& >(_ptr);
							net_event->template Start<NT>();
							Add_Network_Event<typename Accident_Network_Event_Interface::ComponentType>(net_event);
						}
						else if(name == "Congestion")
						{
							Congestion_Network_Event_Interface* net_event = (Congestion_Network_Event_Interface*)Allocate<typename MasterType::congestion_network_event_type>();
							net_event->Initialize< weak_ptr<io::Event_Instance>& >(_ptr);
							net_event->template Start<NT>();
							Add_Network_Event<typename Congestion_Network_Event_Interface::ComponentType>(net_event);
						}
						else if(name == "Lane Closure")
						{
							Lane_Closure_Network_Event_Interface* net_event = (Lane_Closure_Network_Event_Interface*)Allocate<typename MasterType::lane_closure_network_event_type>();
							net_event->Initialize< weak_ptr<io::Event_Instance>& >(_ptr);
							net_event->template Start<NT>();
							Add_Network_Event<typename Lane_Closure_Network_Event_Interface::ComponentType>(net_event);
						}
					}
				}
			}

			template<typename TargetType> void Get_Network_Events(int link_id,boost::container::vector< Network_Event<TargetType>* >& container/*,requires(TargetType,check_2(TargetType,typename type_of(MasterType::weather_network_event),is_same) || check_2(typename type_of(MasterType::traffic_management_center),is_same))*/)
			{
				boost::container::list<Network_Event<TargetType,NT>*>* events_of_type = (boost::container::list<Network_Event<TargetType,NT>*>*) & (_network_event_container[TargetType::component_id]);

				for(typename boost::container::list< Network_Event<TargetType,NT>* >::iterator itr=events_of_type->begin();itr!=events_of_type->end();itr++)
				{
					Network_Event<TargetType,NT>* network_event=*itr;

					if(network_event->template active<bool>())
					{
						boost::container::vector<Link_Interface*>* affected_links = network_event->template affected_links<vector<Link_Interface*>*>();

						for(typename boost::container::vector<Link_Interface*>::iterator vitr = affected_links->begin();vitr != affected_links->end();vitr++)
						{
							if((*vitr)->template internal_id<int>() == link_id)
							{
								container.push_back( *itr );
								break;
							}
						}
					}
				}
			}

			template<typename TargetType> void Get_Network_Events( boost::container::vector< Network_Event<TargetType>* >& container, requires(TargetType,!check_2(TargetType,typename MasterType::base_network_event_type,is_same)))
			{
				boost::container::list<Network_Event<TargetType>*>* events_of_type = (boost::container::list<Network_Event<TargetType>*>*) & (_network_event_container[TargetType::component_id]);

				for(typename boost::container::list< Network_Event<TargetType>* >::iterator itr=events_of_type->begin();itr!=events_of_type->end();itr++)
				{
					Network_Event<TargetType>* network_event=*itr;

					if(network_event->template active<bool>())
					{
						container.push_back( *itr );
					}
				}
			}

			template<typename TargetType> void Get_Network_Events( boost::container::vector< Network_Event<TargetType>* >& container, requires(TargetType,check_2(TargetType,typename MasterType::base_network_event_type,is_same)))
			{
				for(typename boost::unordered::unordered_map< size_t, boost::container::list<Base_Network_Event_Interface*> >::iterator h_itr=_network_event_container.begin();h_itr!=_network_event_container.end();h_itr++)
				{
					boost::container::list< Base_Network_Event_Interface* >* events_of_type=&h_itr->second;

					for(typename boost::container::list< Base_Network_Event_Interface* >::iterator itr=events_of_type->begin();itr!=events_of_type->end();itr++)
					{
						Base_Network_Event_Interface* network_event=*itr;

						if(network_event->template active<bool>())
						{
							container.push_back( (Network_Event<typename MasterType::base_network_event_type>*) *itr );
						}
					}
				}
			}

			//template<typename TargetType> void Get_Network_Events(int link_id,boost::container::vector< Network_Event<TargetType,NT>* >& container,requires(TargetType,!(check_2(TargetType,typename type_of(MasterType::weather_network_event),is_same) || check_2(typename type_of(MasterType::traffic_management_center),is_same))))
			//{
			//	static_assert(false,"Non-TMC are only allowed to withdraw weather events!");
			//}

			template<typename TargetType> void Add_Network_Event(Network_Event<TargetType>* network_event)
			{
				_network_event_container[TargetType::component_id].push_back( (Base_Network_Event_Interface*) network_event );
			}

			template<typename TargetType> void Remove_Network_Event(Network_Event<TargetType>* network_event)
			{
				boost::container::list<Network_Event<typename TargetType::ControlType,NT>*>* events_of_type = (list<Network_Event<typename TargetType::ControlType,NT>*>*) & (_network_event_container[TargetType::ControlType::component_id]);

				for(typename boost::container::list< Network_Event<typename TargetType::ControlType,NT>* >::iterator itr=events_of_type->begin();itr!=events_of_type->end();itr++)
				{
					if( (*itr) == network_event )
					{
						events_of_type->erase(itr);
					}
				}
			}

			m_data( concat(boost::unordered::unordered_map< size_t, boost::container::list<Base_Network_Event_Interface*> >), network_event_container, NONE , NONE);
		};
	}

}


text:
package org.apache.flink.runtime.rpc.akka;

import org.apache.flink.runtime.rpc.MainThreadValidatorUtil;
import org.apache.flink.runtime.rpc.RpcEndpoint;
import org.apache.flink.runtime.rpc.RpcGateway;
import org.apache.flink.runtime.rpc.akka.exceptions.AkkaHandshakeException;
import org.apache.flink.runtime.rpc.akka.exceptions.AkkaRpcException;
import org.apache.flink.runtime.rpc.akka.exceptions.AkkaRpcInvalidStateException;
import org.apache.flink.runtime.rpc.akka.exceptions.AkkaUnknownMessageException;
import org.apache.flink.runtime.rpc.exceptions.RpcConnectionException;
import org.apache.flink.runtime.rpc.messages.CallAsync;
import org.apache.flink.runtime.rpc.messages.HandshakeSuccessMessage;
import org.apache.flink.runtime.rpc.messages.LocalRpcInvocation;
import org.apache.flink.runtime.rpc.messages.RemoteHandshakeMessage;
import org.apache.flink.runtime.rpc.messages.RpcInvocation;
import org.apache.flink.runtime.rpc.messages.RunAsync;
import org.apache.flink.types.Either;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.concurrent.FutureUtils;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Status;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import scala.concurrent.duration.FiniteDuration;
import scala.concurrent.impl.Promise;

import static org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.runWithContextClassLoader;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Akka rpc actor which receives {@link LocalRpcInvocation}, {@link RunAsync} and {@link CallAsync}
 * {@link ControlMessages} messages.
 *
 *
The {@link LocalRpcInvocation} designates a rpc and is dispatched to the given {@link
 * RpcEndpoint} instance.
 *
 *
The {@link RunAsync} and {@link CallAsync} messages contain executable code which is executed
 * in the context of the actor thread.
 *
 *
The {@link ControlMessages} message controls the processing behaviour of the akka rpc actor. A
 * {@link ControlMessages#START} starts processing incoming messages. A {@link ControlMessages#STOP}
 * message stops processing messages. All messages which arrive when the processing is stopped, will
 * be discarded.
 *
 * @param <T> Type of the {@link RpcEndpoint}
 */
class AkkaRpcActor<T extends RpcEndpoint & RpcGateway> extends AbstractActor {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    /** the endpoint to invoke the methods on. */
    protected final T rpcEndpoint;

    private final ClassLoader flinkClassLoader;

    /** the helper that tracks whether calls come from the main thread. */
    private final MainThreadValidatorUtil mainThreadValidator;

    private final CompletableFuture<Boolean> terminationFuture;

    private final int version;

    private final long maximumFramesize;

    private final AtomicBoolean rpcEndpointStopped;

    private volatile RpcEndpointTerminationResult rpcEndpointTerminationResult;

    @Nonnull private State state;

    AkkaRpcActor(
            final T rpcEndpoint,
            final CompletableFuture<Boolean> terminationFuture,
            final int version,
            final long maximumFramesize,
            final ClassLoader flinkClassLoader) {

        checkArgument(maximumFramesize > 0, "Maximum framesize must be positive.");
        this.rpcEndpoint = checkNotNull(rpcEndpoint, "rpc endpoint");
        this.flinkClassLoader = checkNotNull(flinkClassLoader);
        this.mainThreadValidator = new MainThreadValidatorUtil(rpcEndpoint);
        this.terminationFuture = checkNotNull(terminationFuture);
        this.version = version;
        this.maximumFramesize = maximumFramesize;
        this.rpcEndpointStopped = new AtomicBoolean(false);
        this.rpcEndpointTerminationResult =
                RpcEndpointTerminationResult.failure(
                        new AkkaRpcException(
                                String.format(
                                        "RpcEndpoint %s has not been properly stopped.",
                                        rpcEndpoint.getEndpointId())));
        this.state = StoppedState.STOPPED;
    }

    @Override
    public void postStop() throws Exception {
        super.postStop();

        if (rpcEndpointTerminationResult.isSuccess()) {
            log.debug("The RpcEndpoint {} terminated successfully.", rpcEndpoint.getEndpointId());
            terminationFuture.complete(null);
        } else {
            log.info(
                    "The RpcEndpoint {} failed.",
                    rpcEndpoint.getEndpointId(),
                    rpcEndpointTerminationResult.getFailureCause());
            terminationFuture.completeExceptionally(rpcEndpointTerminationResult.getFailureCause());
        }

        state = state.finishTermination();
    }

    @Override
    public Receive createReceive() {
        return ReceiveBuilder.create()
                .match(RemoteHandshakeMessage.class, this::handleHandshakeMessage)
                .match(ControlMessages.class, this::handleControlMessage)
                .matchAny(this::handleMessage)
                .build();
    }

    private void handleMessage(final Object message) {
        if (state.isRunning()) {
            mainThreadValidator.enterMainThread();

            try {
                handleRpcMessage(message);
            } finally {
                mainThreadValidator.exitMainThread();
            }
        } else {
            log.info(
                    "The rpc endpoint {} has not been started yet. Discarding message {} until processing is started.",
                    rpcEndpoint.getClass().getName(),
                    message.getClass().getName());

            sendErrorIfSender(
                    new AkkaRpcException(
                            String.format(
                                    "Discard message, because the rpc endpoint %s has not been started yet.",
                                    rpcEndpoint.getAddress())));
        }
    }

    private void handleControlMessage(ControlMessages controlMessage) {
        try {
            switch (controlMessage) {
                case START:
                    state = state.start(this, flinkClassLoader);
                    break;
                case STOP:
                    state = state.stop();
                    break;
                case TERMINATE:
                    state = state.terminate(this, flinkClassLoader);
                    break;
                default:
                    handleUnknownControlMessage(controlMessage);
            }
        } catch (Exception e) {
            this.rpcEndpointTerminationResult = RpcEndpointTerminationResult.failure(e);
            throw e;
        }
    }

    private void handleUnknownControlMessage(ControlMessages controlMessage) {
        final String message =
                String.format(
                        "Received unknown control message %s. Dropping this message!",
                        controlMessage);
        log.warn(message);
        sendErrorIfSender(new AkkaUnknownMessageException(message));
    }

    protected void handleRpcMessage(Object message) {
        if (message instanceof RunAsync) {
            handleRunAsync((RunAsync) message);
        } else if (message instanceof CallAsync) {
            handleCallAsync((CallAsync) message);
        } else if (message instanceof RpcInvocation) {
            handleRpcInvocation((RpcInvocation) message);
        } else {
            log.warn(
                    "Received message of unknown type {} with value {}. Dropping this message!",
                    message.getClass().getName(),
                    message);

            sendErrorIfSender(
                    new AkkaUnknownMessageException(
                            "Received unknown message "
                                    + message
                                    + " of type "
                                    + message.getClass().getSimpleName()
                                    + '.'));
        }
    }

    private void handleHandshakeMessage(RemoteHandshakeMessage handshakeMessage) {
        if (!isCompatibleVersion(handshakeMessage.getVersion())) {
            sendErrorIfSender(
                    new AkkaHandshakeException(
                            String.format(
                                    "Version mismatch between source (%s) and target (%s) rpc component. Please verify that all components have the same version.",
                                    handshakeMessage.getVersion(), getVersion())));
        } else if (!isGatewaySupported(handshakeMessage.getRpcGateway())) {
            sendErrorIfSender(
                    new AkkaHandshakeException(
                            String.format(
                                    "The rpc endpoint does not support the gateway %s.",
                                    handshakeMessage.getRpcGateway().getSimpleName())));
        } else {
            getSender().tell(new Status.Success(HandshakeSuccessMessage.INSTANCE), getSelf());
        }
    }

    private boolean isGatewaySupported(Class<?> rpcGateway) {
        return rpcGateway.isAssignableFrom(rpcEndpoint.getClass());
    }

    private boolean isCompatibleVersion(int sourceVersion) {
        return sourceVersion == getVersion();
    }

    private int getVersion() {
        return version;
    }

    /**
     * Handle rpc invocations by looking up the rpc method on the rpc endpoint and calling this
     * method with the provided method arguments. If the method has a return value, it is returned
     * to the sender of the call.
     *
     * @param rpcInvocation Rpc invocation message
     */
    private void handleRpcInvocation(RpcInvocation rpcInvocation) {
        Method rpcMethod = null;

        try {
            String methodName = rpcInvocation.getMethodName();
            Class<?>[] parameterTypes = rpcInvocation.getParameterTypes();

            rpcMethod = lookupRpcMethod(methodName, parameterTypes);
        } catch (ClassNotFoundException e) {
            log.error("Could not load method arguments.", e);

            RpcConnectionException rpcException =
                    new RpcConnectionException("Could not load method arguments.", e);
            getSender().tell(new Status.Failure(rpcException), getSelf());
        } catch (IOException e) {
            log.error("Could not deserialize rpc invocation message.", e);

            RpcConnectionException rpcException =
                    new RpcConnectionException("Could not deserialize rpc invocation message.", e);
            getSender().tell(new Status.Failure(rpcException), getSelf());
        } catch (final NoSuchMethodException e) {
            log.error("Could not find rpc method for rpc invocation.", e);

            RpcConnectionException rpcException =
                    new RpcConnectionException("Could not find rpc method for rpc invocation.", e);
            getSender().tell(new Status.Failure(rpcException), getSelf());
        }

        if (rpcMethod != null) {
            try {
                // this supports declaration of anonymous classes
                rpcMethod.setAccessible(true);

                final Method capturedRpcMethod = rpcMethod;
                if (rpcMethod.getReturnType().equals(Void.TYPE)) {
                    // No return value to send back
                    runWithContextClassLoader(
                            () -> capturedRpcMethod.invoke(rpcEndpoint, rpcInvocation.getArgs()),
                            flinkClassLoader);
                } else {
                    final Object result;
                    try {
                        result =
                                runWithContextClassLoader(
                                        () ->
                                                capturedRpcMethod.invoke(
                                                        rpcEndpoint, rpcInvocation.getArgs()),
                                        flinkClassLoader);
                    } catch (InvocationTargetException e) {
                        log.debug(
                                "Reporting back error thrown in remote procedure {}", rpcMethod, e);

                        // tell the sender about the failure
                        getSender().tell(new Status.Failure(e.getTargetException()), getSelf());
                        return;
                    }

                    final String methodName = rpcMethod.getName();

                    if (result instanceof CompletableFuture) {
                        final CompletableFuture<?> responseFuture = (CompletableFuture<?>) result;
                        sendAsyncResponse(responseFuture, methodName);
                    } else {
                        sendSyncResponse(result, methodName);
                    }
                }
            } catch (Throwable e) {
                log.error("Error while executing remote procedure call {}.", rpcMethod, e);
                // tell the sender about the failure
                getSender().tell(new Status.Failure(e), getSelf());
            }
        }
    }

    private void sendSyncResponse(Object response, String methodName) {
        if (isRemoteSender(getSender())) {
            Either<AkkaRpcSerializedValue, AkkaRpcException> serializedResult =
                    serializeRemoteResultAndVerifySize(response, methodName);

            if (serializedResult.isLeft()) {
                getSender().tell(new Status.Success(serializedResult.left()), getSelf());
            } else {
                getSender().tell(new Status.Failure(serializedResult.right()), getSelf());
            }
        } else {
            getSender().tell(new Status.Success(response), getSelf());
        }
    }

    private void sendAsyncResponse(CompletableFuture<?> asyncResponse, String methodName) {
        final ActorRef sender = getSender();
        Promise.DefaultPromise<Object> promise = new Promise.DefaultPromise<>();

        FutureUtils.assertNoException(
                asyncResponse.handle(
                        (value, throwable) -> {
                            if (throwable != null) {
                                promise.failure(throwable);
                            } else {
                                if (isRemoteSender(sender)) {
                                    Either<AkkaRpcSerializedValue, AkkaRpcException>
                                            serializedResult =
                                                    serializeRemoteResultAndVerifySize(
                                                            value, methodName);

                                    if (serializedResult.isLeft()) {
                                        promise.success(serializedResult.left());
                                    } else {
                                        promise.failure(serializedResult.right());
                                    }
                                } else {
                                    promise.success(new Status.Success(value));
                                }
                            }

                            // consume the provided throwable
                            return null;
                        }));

        Patterns.pipe(promise.future(), getContext().dispatcher()).to(sender);
    }

    private boolean isRemoteSender(ActorRef sender) {
        return !sender.path().address().hasLocalScope();
    }

    private Either<AkkaRpcSerializedValue, AkkaRpcException> serializeRemoteResultAndVerifySize(
            Object result, String methodName) {
        try {
            AkkaRpcSerializedValue serializedResult = AkkaRpcSerializedValue.valueOf(result);

            long resultSize = serializedResult.getSerializedDataLength();
            if (resultSize > maximumFramesize) {
                return Either.Right(
                        new AkkaRpcException(
                                "The method "
                                        + methodName
                                        + "'s result size "
                                        + resultSize
                                        + " exceeds the maximum size "
                                        + maximumFramesize
                                        + " ."));
            } else {
                return Either.Left(serializedResult);
            }
        } catch (IOException e) {
            return Either.Right(
                    new AkkaRpcException(
                            "Failed to serialize the result for RPC call : " + methodName + '.',
                            e));
        }
    }

    /**
     * Handle asynchronous {@link Callable}. This method simply executes the given {@link Callable}
     * in the context of the actor thread.
     *
     * @param callAsync Call async message
     */
    private void handleCallAsync(CallAsync callAsync) {
        try {
            Object result =
                    runWithContextClassLoader(
                            () -> callAsync.getCallable().call(), flinkClassLoader);

            getSender().tell(new Status.Success(result), getSelf());
        } catch (Throwable e) {
            getSender().tell(new Status.Failure(e), getSelf());
        }
    }

    /**
     * Handle asynchronous {@link Runnable}. This method simply executes the given {@link Runnable}
     * in the context of the actor thread.
     *
     * @param runAsync Run async message
     */
    private void handleRunAsync(RunAsync runAsync) {
        final long timeToRun = runAsync.getTimeNanos();
        final long delayNanos;

        if (timeToRun == 0 || (delayNanos = timeToRun - System.nanoTime()) <= 0) {
            // run immediately
            try {
                runWithContextClassLoader(() -> runAsync.getRunnable().run(), flinkClassLoader);
            } catch (Throwable t) {
                log.error("Caught exception while executing runnable in main thread.", t);
                ExceptionUtils.rethrowIfFatalErrorOrOOM(t);
            }
        } else {
            // schedule for later. send a new message after the delay, which will then be
            // immediately executed
            FiniteDuration delay = new FiniteDuration(delayNanos, TimeUnit.NANOSECONDS);
            RunAsync message = new RunAsync(runAsync.getRunnable(), timeToRun);

            final Object envelopedSelfMessage = envelopeSelfMessage(message);

            getContext()
                    .system()
                    .scheduler()
                    .scheduleOnce(
                            delay,
                            getSelf(),
                            envelopedSelfMessage,
                            getContext().dispatcher(),
                            ActorRef.noSender());
        }
    }

    /**
     * Look up the rpc method on the given {@link RpcEndpoint} instance.
     *
     * @param methodName Name of the method
     * @param parameterTypes Parameter types of the method
     * @return Method of the rpc endpoint
     * @throws NoSuchMethodException Thrown if the method with the given name and parameter types
     *     cannot be found at the rpc endpoint
     */
    private Method lookupRpcMethod(final String methodName, final Class<?>[] parameterTypes)
            throws NoSuchMethodException {
        return rpcEndpoint.getClass().getMethod(methodName, parameterTypes);
    }

    /**
     * Send throwable to sender if the sender is specified.
     *
     * @param throwable to send to the sender
     */
    protected void sendErrorIfSender(Throwable throwable) {
        if (!getSender().equals(ActorRef.noSender())) {
            getSender().tell(new Status.Failure(throwable), getSelf());
        }
    }

    /**
     * Hook to envelope self messages.
     *
     * @param message to envelope
     * @return enveloped message
     */
    protected Object envelopeSelfMessage(Object message) {
        return message;
    }

    /** Stop the actor immediately. */
    private void stop(RpcEndpointTerminationResult rpcEndpointTerminationResult) {
        if (rpcEndpointStopped.compareAndSet(false, true)) {
            this.rpcEndpointTerminationResult = rpcEndpointTerminationResult;
            getContext().stop(getSelf());
        }
    }

    // ---------------------------------------------------------------------------
    // Internal state machine
    // ---------------------------------------------------------------------------

    interface State {
        default State start(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            throw new AkkaRpcInvalidStateException(
                    invalidStateTransitionMessage(StartedState.STARTED));
        }

        default State stop() {
            throw new AkkaRpcInvalidStateException(
                    invalidStateTransitionMessage(StoppedState.STOPPED));
        }

        default State terminate(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            throw new AkkaRpcInvalidStateException(
                    invalidStateTransitionMessage(TerminatingState.TERMINATING));
        }

        default State finishTermination() {
            return TerminatedState.TERMINATED;
        }

        default boolean isRunning() {
            return false;
        }

        default String invalidStateTransitionMessage(State targetState) {
            return String.format(
                    "AkkaRpcActor is currently in state %s and cannot go into state %s.",
                    this, targetState);
        }
    }

    @SuppressWarnings("Singleton")
    enum StartedState implements State {
        STARTED;

        @Override
        public State start(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            return STARTED;
        }

        @Override
        public State stop() {
            return StoppedState.STOPPED;
        }

        @Override
        public State terminate(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            akkaRpcActor.mainThreadValidator.enterMainThread();

            CompletableFuture<Void> terminationFuture;
            try {
                terminationFuture =
                        runWithContextClassLoader(
                                () -> akkaRpcActor.rpcEndpoint.internalCallOnStop(),
                                flinkClassLoader);
            } catch (Throwable t) {
                terminationFuture =
                        FutureUtils.completedExceptionally(
                                new AkkaRpcException(
                                        String.format(
                                                "Failure while stopping RpcEndpoint %s.",
                                                akkaRpcActor.rpcEndpoint.getEndpointId()),
                                        t));
            } finally {
                akkaRpcActor.mainThreadValidator.exitMainThread();
            }

            // IMPORTANT: This only works if we don't use a restarting supervisor strategy.
            // Otherwise
            // we would complete the future and let the actor system restart the actor with a
            // completed
            // future.
            // Complete the termination future so that others know that we've stopped.

            terminationFuture.whenComplete(
                    (ignored, throwable) ->
                            akkaRpcActor.stop(RpcEndpointTerminationResult.of(throwable)));

            return TerminatingState.TERMINATING;
        }

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

    @SuppressWarnings("Singleton")
    enum StoppedState implements State {
        STOPPED;

        @Override
        public State start(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            akkaRpcActor.mainThreadValidator.enterMainThread();

            try {
                runWithContextClassLoader(
                        () -> akkaRpcActor.rpcEndpoint.internalCallOnStart(), flinkClassLoader);
            } catch (Throwable throwable) {
                akkaRpcActor.stop(
                        RpcEndpointTerminationResult.failure(
                                new AkkaRpcException(
                                        String.format(
                                                "Could not start RpcEndpoint %s.",
                                                akkaRpcActor.rpcEndpoint.getEndpointId()),
                                        throwable)));
            } finally {
                akkaRpcActor.mainThreadValidator.exitMainThread();
            }

            return StartedState.STARTED;
        }

        @Override
        public State stop() {
            return STOPPED;
        }

        @Override
        public State terminate(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            akkaRpcActor.stop(RpcEndpointTerminationResult.success());

            return TerminatingState.TERMINATING;
        }
    }

    @SuppressWarnings("Singleton")
    enum TerminatingState implements State {
        TERMINATING;

        @Override
        public State terminate(AkkaRpcActor<?> akkaRpcActor, ClassLoader flinkClassLoader) {
            return TERMINATING;
        }

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

    enum TerminatedState implements State {
        TERMINATED
    }

    private static final class RpcEndpointTerminationResult {

        private static final RpcEndpointTerminationResult SUCCESS =
                new RpcEndpointTerminationResult(null);

        @Nullable private final Throwable failureCause;

        private RpcEndpointTerminationResult(@Nullable Throwable failureCause) {
            this.failureCause = failureCause;
        }

        public boolean isSuccess() {
            return failureCause == null;
        }

        public Throwable getFailureCause() {
            Preconditions.checkState(failureCause != null);
            return failureCause;
        }

        private static RpcEndpointTerminationResult success() {
            return SUCCESS;
        }

        private static RpcEndpointTerminationResult failure(Throwable failureCause) {
            return new RpcEndpointTerminationResult(failureCause);
        }

        private static RpcEndpointTerminationResult of(@Nullable Throwable failureCause) {
            if (failureCause == null) {
                return success();
            } else {
                return failure(failureCause);
            }
        }
    }
}


text:
This page was generated with Wiki Builder. Do not change the format!

## Info
Approve all pending members for a group that the current user is an admin for.
* **URI:** [[/Group/{groupId}/Members/ApproveAll/|https://www.bungie.net/Platform/Group/{groupId}/Members/ApproveAll/]]
* **Method:** POST
* **Accessibility:** Private
* **Service:** [[GroupService|Endpoints#GroupService]]

## Parameters
### Path Parameters
Name | Description
---- | -----------
groupId | A valid groupId.

### Query String Parameters
None

### JSON POST Parameters
Name | Description
---- | -----------
message | A message to include with the approval.

## Example
POST https://www.bungie.net/Platform/Group/177526/Members/ApproveAll/
```javascript
{
    "message": "Congrats! You are now part of a super exclusive Destiny clan of awesomeness!!"
}
```
 ```javascript
{
    "Response": 0,
    "ErrorCode": 1,
    "ThrottleSeconds": 0,
    "ErrorStatus": "Success",
    "Message": "Ok",
    "MessageData": {}
}
```

## References
1. https://www.bungie.net/Scripts/bungienet/clans/clans.min.js


text:
describe "every accessible many_to_one composite association", :shared => true do

  it "should allow to update an existing person via Membership#person_attributes" do
    Person.all.size.should     == 0
    Project.all.size.should    == 0
    Membership.all.size.should == 0

    person = Person.create(:audit_id => 1, :name => 'Martin')
    project = Project.create(:audit_id => 2, :name => 'trippings')
    membership = Membership.new(:role => 'maintainer')
    membership.person = person
    membership.project = project
    membership.save.should be_true

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1
    Person.first.name.should   == 'Martin'

    membership.person_attributes = { :id => person.id, :audit_id => person.audit_id, :name => 'Martin Gamsjaeger' }
    membership.save.should be_true

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1
    Person.first.name.should   == 'Martin Gamsjaeger'
  end

  it "should return the attributes written to Membership#person_attributes from the Membership#person_attributes reader" do
    membership = Membership.new(:role => 'maintainer')
    membership.person_attributes.should be_nil
    membership.person_attributes = { :name => 'Martin' }
    membership.person_attributes.should == { :name => 'Martin' }
  end

end

describe "every accessible many_to_one composite association with a valid reject_if proc", :shared => true do

  it "should not allow to create a new person via Membership#person_attributes" do
    project = Project.create(:audit_id => 2, :name => 'trippings')

    Person.all.size.should     == 0
    Project.all.size.should    == 1
    Membership.all.size.should == 0

    membership = Membership.new(:project_id => project.id, :project_audit_id => project.audit_id, :role => 'maintainer')
    membership.person_attributes = { :name => 'Martin' }

    Person.all.size.should     == 0
    Project.all.size.should    == 1
    Membership.all.size.should == 0

    begin
      membership.save.should be(false)
    rescue
      # swallow native FK errors which is basically like expecting save to be false
    end
  end

end

describe "every accessible many_to_one composite association with no reject_if proc", :shared => true do

  it "should allow to create a new person via Membership#person_attributes" do
    project = Project.create(:audit_id => 2, :name => 'trippings')

    Person.all.size.should     == 0
    Project.all.size.should    == 1
    Membership.all.size.should == 0

    membership = Membership.new(:project_id => project.id, :project_audit_id => project.audit_id, :role => 'maintainer')
    membership.person_attributes = { :audit_id => 1, :name => 'Martin' }

    Person.all.size.should     == 0
    Project.all.size.should    == 1
    Membership.all.size.should == 0

    membership.save.should be_true

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1
    Person.first.name.should   == 'Martin'
  end

end

describe "every accessible many_to_one composite association with :allow_destroy => false", :shared => true do

  it "should not allow to delete an existing person via Membership#person_attributes" do
    person = Person.create(:audit_id => 1, :name => 'Martin')
    project = Project.create(:audit_id => 2, :name => 'trippings')
    membership = Membership.new(:role => 'maintainer')
    membership.person = person
    membership.project = project
    membership.save

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1

    membership.person_attributes = {
      :id => person.id,
      :audit_id => person.audit_id,
      :_delete => true
    }

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1

    membership.save

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1
  end

end

describe "every accessible many_to_one composite association with :allow_destroy => true", :shared => true do

  it "should allow to delete an existing person via Membership#person_attributes" do
    Person.all.size.should     == 0
    Project.all.size.should    == 0
    Membership.all.size.should == 0

    person = Person.create(:audit_id => 1, :name => 'Martin')
    project = Project.create(:audit_id => 2, :name => 'trippings')

    membership = Membership.new(:role => 'maintainer')
    membership.person = person
    membership.project = project
    membership.save.should be_true

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1

    membership.person_attributes = {
      :id => person.id,
      :audit_id => person.audit_id,
      :_delete => true
    }

    Person.all.size.should     == 1
    Project.all.size.should    == 1
    Membership.all.size.should == 1

    membership.save

    Person.all.size.should     == 0
    Project.all.size.should    == 1

    # TODO also test this behavior in situations where setting the FK to nil is allowed

  end

end


text:
<?php

namespace Eva\Form;

class Datetimepicker extends Input implements ElementInterface
{
    public function setValue($value)
    {
        $dateTime = new \DateTime($value);
        $this->value = $dateTime->format('d.m.Y H:i');
        $this->setAttribute('class', 'datetimepicker');
        $this->setAttribute('type', 'text');

        return $this;
    }

}


text:
/* globals localStorage */
const _ = require('lodash')
const cuid = require('cuid')
const update = require('immutability-helper')
const p2pClient = require('./p2p-client')

module.exports = ({ hubUrl }) => {
  const client = p2pClient({
    hubUrl,
    cid: cuid()
  })

  return {
    namespace: 'client',

    state: getStateFromLocalStorage(),

    reducers: {
      setUsername: (state, { username }) => {
        state.username = username
        localStorage.setItem('roboSession', JSON.stringify(state))
        return state
      },

      _setGroupId: (state, { groupId }) => {
        state.groupId = groupId
        localStorage.setItem('roboSession', JSON.stringify(state))
        return state
      },

      _setConnectionStatus: (state, { connected, connecting }) =>
        update(state, {
          connected: { $set: connected },
          connecting: { $set: connecting }
        }),

      denyRecovery: (state) => {
        localStorage.setItem('roboSession', '')
        state.username = null
        state.groupId = null
        state.clientId = null
        state.connecting = false
        state.recoveryPossible = false
        return state
      },

      _setClientId: (state, { clientId }) => {
        console.log(clientId)
        state.clientId = clientId
        localStorage.setItem('roboSession', JSON.stringify(state))
        return state
      }
    },

    effects: {
      disconnect: (state, data, send) => {
        client.stop()
        send('client:_setGroupId', { groupId: null }, _.noop)
        send('client:setUsername', { username: null }, _.noop)
      },

      joinGroup: (state, { groupId }, send) => {
        client.joinStar(groupId, state.clientId)
        send('client:_setGroupId', { groupId }, _.noop)
      },

      sendCode: (state, { code }) => {
        client.send({
          type: 'COMMIT_CODE',
          data: { code }
        })
      },

      sendUsername: ({ username }) => {
        client.send({
          type: 'SET_USERNAME',
          data: { username }
        })
      }
    },

    subscriptions: {
      p2pConnection: (send) => {
        client.onConnect((groupId, clientId) => {
          send('client:_setConnectionStatus', { connected: true, connecting: false }, _.noop)
          send('client:_setClientId', { clientId: clientId }, _.noop)
          send('client:sendUsername', { }, _.noop)
        })

        client.onDisconnect(() => {
          send('client:_setConnectionStatus', { connected: false, connecting: true }, _.noop)
        })

        client.onConnecting(() => {
          send('client:_setConnectionStatus', { connected: false, connecting: true }, _.noop)
        })
      }
    }
  }
}

function getStateFromLocalStorage () {
  let localState = {
    username: null,
    groupId: null,
    clientId: null,
    connecting: false,
    recoveryPossible: false
  }
  try {
    let session = JSON.parse(localStorage.getItem('roboSession'))
    if (!session || !session.username || !session.groupId || !session.clientId) {
      return localState
    }
    localState.username = session.username
    localState.groupId = session.groupId
    localState.clientId = session.clientId
    localState.recoveryPossible = true
  } catch (e) {
    console.log('Error loading local Storage')
  }
  return localState
}


text:
import * as events from 'htmlrapier/src/eventdispatcher';
import * as pageWidget from './PageNumberWidget';

export type ItemUpdatedCallback = (data: any) => Promise<any>;
export type ItemEditorClosedCallback = () => void;

export class ShowItemEditorEventArgs {
    /**
     * A promise to get the data.
     */
    dataPromise: Promise<any>;

    /**
     * The function to call to update the data. Can be null, which means update
     * cannot be performed.
     */
    update: ItemUpdatedCallback | null;

    /**
     * The function called when the item editor is closed. This might happen even if the data
     * is not updated. It also might never happen if "close" is not an appropriate action for
     * the editor. But if it appears in another window or location, this should fire.
     */
    closed: ItemEditorClosedCallback;

    /**
     * If the data came from another result this will have a value.
     * What value this is depends on the crud service that fired the event.
     */
    dataResult: any;

    constructor(dataPromise: Promise<any>, update: ItemUpdatedCallback | null, dataResult?: any, closed?: ItemEditorClosedCallback) {
        this.dataPromise = dataPromise;
        this.update = update;
        this.dataResult = dataResult;
        this.closed = closed;
    }
}

export class DataLoadingEventArgs {
    constructor(private _dataPromise: Promise<any>, private _query?: any) {
        if (this._query === undefined) {
            this._query = null;
        }
    }

    /**
     * Get the promise that will resolve when the data is loaded.
     */
    public get data(): Promise<any> {
        return this._dataPromise;
    }

    /**
     * Get the query used to load the data. This can be null if no
     * query was provided when the loading event was triggered. Also
     * note that this query could have its properties in different formats
     * depending on how it was created. For example properties could be
     * in different cases or other mutations.
     */
    public get query(): any | null {
        return this._query;
    }
}

export class CrudDataModifiedEventArgs {

}

export class MainUiShownEventArgs {

}

export abstract class ICrudService {
    private showItemEditorDispatcher = new events.ActionEventDispatcher<ShowItemEditorEventArgs>();
    private showAddItemDispatcher = new events.ActionEventDispatcher<ShowItemEditorEventArgs>();
    private closeItemEditorDispatcher = new events.ActionEventDispatcher<void>();
    private dataLoadingDispatcher = new events.ActionEventDispatcher<DataLoadingEventArgs>();
    private crudDataModifiedDispatcher = new events.ActionEventDispatcher<CrudDataModifiedEventArgs>();
    private mainUiShownDispatcher = new events.ActionEventDispatcher<MainUiShownEventArgs>();

    /**
     * This function will return the schema for adding an item. The default implementation will just return
     * getItemSchema, but if you can return a unique schema for adding, overwrite this function.
     */
    public async getAddItemSchema(): Promise<any>{
        return this.getItemSchema();
    }

    /**
     * This function will return the schema for editing an item. This function should try to return update
     * schema first, and failing that return the add schema.
     */
    public abstract getItemSchema(): Promise<any>;

    /**
     * This function will return a schema for viewing items.
     */
    public abstract getViewSchema() : Promise<any>;

    /**
     * Get the schema for listing objects in the table. This helps format items on the table according to how
     * the service dictates they should be formatted.
     */
    public abstract getListingSchema(): Promise<any>;

    /**
     * Get the schema to use when searching for items in this service.
     */
    public abstract getSearchSchema(): Promise<any>;

    /**
     * Start trying to add a new item to the service.
     * @param item The default settings for the item
     */
    public abstract add(item?: any);

    /**
     * Determine if the crud service can add items.
     */
    public abstract canAdd(): Promise<boolean>;

    /**
     * Start trying to edit an item in the service
     * @param item The item to edit
     */
    public abstract edit(item: any);

    /**
     * Determine if an item can be edited.
     * @param item The item to check for editing capability
     */
    public abstract canEdit(item: any): boolean;

    /**
     * Get the prompt to show the user when trying to delete an item.
     * @param item The item to get the prompt for
     */
    public abstract getDeletePrompt(item: any): string;

    /**
     * Delete item
     * @param item The item to delete
     */
    public abstract del(item: any): Promise<any>;

    /**
     * Determine if an item can be deleted.
     * @param item The item to check
     */
    public abstract canDel(item: any): boolean;

    /**
     * Get a particular page in the item collection based on the query.
     * @param query The query to use
     */
    public abstract getPage(query: any): Promise<any>;

    /**
     * Get the first page of the last query.
     */
    public abstract firstPage(): void;

    /**
     * Get the last page of the last query.
     */
    public abstract lastPage(): void;

    /**
     * Get the next page of the last query.
     */
    public abstract nextPage(): void;

    /**
     * Get the previous page of the last query.
     */
    public abstract previousPage(): void;

    /**
     * Refresh the page of the last query.
     */
    public abstract refreshPage(): void;

    /**
     * Get the items from a list result. This allows you to have the items be a separate object
     * from the result. This depends on your server implementation.
     * @param list The listing result.
     */
    public abstract getItems(list: any): any[];

    /**
     * Get the listing display object version of the given item.
     * @param item The item
     */
    public abstract getListingDisplayObject(item: any);

    /**
     * Get the object to pass to the page numbers to set their state.
     * @param list The listing result.
     */
    public abstract getPageNumberState(list: any): pageWidget.PageNumberState;

    /**
     * Get the view of item that is its search query.
     * @param item The item
     */
    public getSearchObject(item: any) {
        return item;
    }

    /**
     * This event is fired when the service is requesting to show the item editor.
     */
    public get showItemEditorEvent() {
        return this.showItemEditorDispatcher.modifier;
    }

    /**
     * Call this function to show the item editor. What editor is shown depends on how your crud page is setup.
     * @param args The args for showing the editor
     */
    protected fireShowItemEditorEvent(args: ShowItemEditorEventArgs) {
        this.showItemEditorDispatcher.fire(args);
    }

    /**
     * This event is fired when the service is requesting to show the add item editor.
     */
    public get showAddItemEvent() {
        return this.showAddItemDispatcher.modifier;
    }

    /**
     * Call this function to show the add item editor. What editor is really shown depends on how your crud page is setup.
     * @param args The args for showing the editor.
     */
    protected fireAddItemEvent(args: ShowItemEditorEventArgs) {
        this.showAddItemDispatcher.fire(args);
    }

    /**
     * This event is fired when item editors should close. Any open item editors should fire this event.
     */
    public get closeItemEditorEvent() {
        return this.closeItemEditorDispatcher.modifier;
    }

    /**
     * Fire this function to close any open item editors. This should apply to both add and update.
     */
    protected fireCloseItemEditorEvent() {
        this.closeItemEditorDispatcher.fire(undefined);
    }

    /**
     * This event is fired when the service is loading data for the main display.
     */
    public get dataLoadingEvent() {
        return this.dataLoadingDispatcher.modifier;
    }

    /**
     * Call this function to alert the crud page that main display data is loading.
     * @param args The args
     */
    protected fireDataLoadingEvent(args: DataLoadingEventArgs) {
        this.dataLoadingDispatcher.fire(args);
    }

    /**
     * This event is fired when the service has changed some of its data.
     */
    public get crudDataModifiedEvent() {
        return this.crudDataModifiedDispatcher.modifier;
    }

    /**
     * Call this function to alert the crud page that crud data has changed.
     * @param args The args
     */
    protected fireCrudDataModifiedEvent(args: CrudDataModifiedEventArgs) {
        this.crudDataModifiedDispatcher.fire(args);
    }

    /**
     * This event is fired when the service is loading data for the main display.
     */
    public get mainUiShownEvent() {
        return this.mainUiShownDispatcher.modifier;
    }

    /**
     * Call this function to alert the crud page that main display data is loading.
     * Since it is hard to know inside the service if the main ui is visible or not
     * this function is public so you can call it from the ui controller itself. Do
     * not call this unless you are the class responsible for showing/hiding the main ui.
     * @param args The args
     */
    public fireMainUiShownEvent(args: MainUiShownEventArgs) {
        this.mainUiShownDispatcher.fire(args);
    }
}