text:
using System;
using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.Creation;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;

namespace Revit.SDK.Samples.CreateAirHandler.CS
{
    /// <summary>
    /// Create one air handler and add connectors.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    public class Command : IExternalCommand
    {
        /// <summary>
        /// The revit application
        /// </summary>
        private static Autodesk.Revit.ApplicationServices.Application m_application;

        /// <summary>
        /// The current document of the application
        /// </summary>
        private static Autodesk.Revit.DB.Document m_document;

        /// <summary>
        /// the factory to creaate extrusions and connectors
        /// </summary>
        private FamilyItemFactory f;

        /// <summary>
        /// the extrusion array
        /// </summary>
        private Extrusion[] extrusions;

        /// <summary>
        /// The list of all the elements to be combined in the air handler system
        /// </summary>
        private CombinableElementArray m_combineElements;

        #region Data used to create extrusions and connectors
        /// <summary>
        /// Data to create extrusions and connectors
        /// </summary>
        private Autodesk.Revit.DB.XYZ [,] profileData = new Autodesk.Revit.DB.XYZ [5, 4]
        {
            // In Array 0 to 2, the data is the points that defines the edges of the profile
            {
                new Autodesk.Revit.DB.XYZ (-17.28, -0.53, 0.9),
                new Autodesk.Revit.DB.XYZ (-17.28, 11, 0.9),
                new Autodesk.Revit.DB.XYZ (-0.57, 11, 0.9),
                new Autodesk.Revit.DB.XYZ (-0.57, -0.53, 0.9)
            },
            {
                new Autodesk.Revit.DB.XYZ (-0.57, 7, 6.58),
                new Autodesk.Revit.DB.XYZ (-0.57, 7, 3),
                new Autodesk.Revit.DB.XYZ (-0.57, 3.6, 3),
                new Autodesk.Revit.DB.XYZ (-0.57, 3.6, 6.58)
            },
            {
                new Autodesk.Revit.DB.XYZ (-17.28, -0.073, 7.17),
                new Autodesk.Revit.DB.XYZ (-17.28, 10.76, 7.17),
                new Autodesk.Revit.DB.XYZ (-17.28, 10.76, 3.58),
                new Autodesk.Revit.DB.XYZ (-17.28, -0.073, 3.58)
            },
            // In Array 3 and 4, the data is the normal and origin of the plane of the arc profile
            {
                new Autodesk.Revit.DB.XYZ (0, -1, 0),
                new Autodesk.Revit.DB.XYZ (-9, 0.53, 7.17),
                null,
                null
            },
            {
                new Autodesk.Revit.DB.XYZ (0, -1, 0),
                new Autodesk.Revit.DB.XYZ (-8.24, 0.53, 0.67),
                null,
                null
            }
        };

        /// <summary>
        /// the normal and origin of the sketch plane
        /// </summary>
        private Autodesk.Revit.DB.XYZ [,] sketchPlaneData = new Autodesk.Revit.DB.XYZ [5, 2]
        {
            {new Autodesk.Revit.DB.XYZ (0, 0, 1), new Autodesk.Revit.DB.XYZ (0, 0, 0.9)},
            {new Autodesk.Revit.DB.XYZ (1, 0, 0), new Autodesk.Revit.DB.XYZ (-0.57, 0, 0)},
            {new Autodesk.Revit.DB.XYZ (-1, 0, 0), new Autodesk.Revit.DB.XYZ (-17.28, 0, 0)},
            {new Autodesk.Revit.DB.XYZ (0, -1, 0), new Autodesk.Revit.DB.XYZ (0, 0.53, 0)},
            {new Autodesk.Revit.DB.XYZ (0, -1, 0), new Autodesk.Revit.DB.XYZ (0, 0.53, 0)}
        };

        /// <summary>
        /// the start and end offsets of the extrusion
        /// </summary>
        private double[,] extrusionOffsets = new double[5, 2]
        {
            {-0.9, 6.77},
            {0, -0.18},
            {0, -0.08},
            {1, 1.15},
            {1, 1.15}
        };

        /// <summary>
        /// whether the extrusion is solid
        /// </summary>
        private bool[] isSolid = new bool[5] { true, false, false, true, true };

        /// <summary>
        /// the radius of the arc profile
        /// </summary>
        private double arcRadius = 0.17;

        /// <summary>
        /// the height and width of the connector
        /// </summary>
        private double[,] connectorDimensions = new double[2, 2]
        {
            {3.58, 3.4},
            {3.59, 10.833}
        };

        /// <summary>
        /// the flow of the connector
        /// </summary>
        private double flow = 547;

        /// <summary>
        /// Transaction of ExternalCommand
        /// </summary>
        private Transaction m_transaction;
        #endregion

        #region IExternalCommand Members
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message,
            ElementSet elements)
        {
            // set out default result to failure.
            Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed;
            m_application = commandData.Application.Application;
            m_document = commandData.Application.ActiveUIDocument.Document;
            f = m_document.FamilyCreate;
            extrusions = new Extrusion[5];
            m_combineElements = new CombinableElementArray();

            m_transaction = new Transaction(m_document, "External Tool");
            m_transaction.Start();

            if (m_document.OwnerFamily.FamilyCategory.Name != "Mechanical Equipment")
            {
                message = "Please make sure you opened a template of Mechanical Equipment.";
                return retRes;
            }

            try
            {
                CreateExtrusions();
                m_document.Regenerate();
                CreateConnectors();
                m_document.Regenerate();
                m_document.CombineElements(m_combineElements);
                m_document.Regenerate();
            }
            catch(Exception x)
            {
                m_transaction.RollBack();
                message = x.Message;
                return retRes;
            }

            m_transaction.Commit();

            retRes = Autodesk.Revit.UI.Result.Succeeded;
            return retRes;
        }
        #endregion

        /// <summary>
        /// get all planar faces of an extrusion
        /// </summary>
        /// <param name="extrusion">the extrusion to read</param>
        /// <returns>a list of all planar faces of the extrusion</returns>
        public List<PlanarFace> GetPlanarFaces(Extrusion extrusion)
        {
            // the option to get geometry elements
            Options m_geoOptions = m_application.Create.NewGeometryOptions();
            m_geoOptions.View = m_document.ActiveView;
            m_geoOptions.ComputeReferences = true;

            // get the planar faces
            List<PlanarFace> m_planarFaces = new List<PlanarFace>();
            Autodesk.Revit.DB.GeometryElement geoElement = extrusion.get_Geometry(m_geoOptions);
            foreach (GeometryObject geoObject in geoElement.Objects)
            {
                Solid geoSolid = geoObject as Solid;
                if (null == geoSolid)
                {
                    continue;
                }
                foreach (Face geoFace in geoSolid.Faces)
                {
                    if (geoFace is PlanarFace)
                    {
                        m_planarFaces.Add(geoFace as PlanarFace);
                    }
                }
            }
            return m_planarFaces;
        }

        /// <summary>
        /// create the extrusions of the air handler system
        /// </summary>
        private void CreateExtrusions()
        {
            Autodesk.Revit.Creation.Application app = m_application.Create;
            CurveArray curves = null;
            CurveArrArray profile = null;
            Plane plane = null;
            SketchPlane sketchPlane = null;

            #region Create the cuboid extrusions

            for (int i = 0; i <= 2; ++i)
            {
                // create the profile
                curves = app.NewCurveArray();
                curves.Append(app.NewLine(profileData[i, 0], profileData[i, 1], true));
                curves.Append(app.NewLine(profileData[i, 1], profileData[i, 2], true));
                curves.Append(app.NewLine(profileData[i, 2], profileData[i, 3], true));
                curves.Append(app.NewLine(profileData[i, 3], profileData[i, 0], true));
                profile = app.NewCurveArrArray();
                profile.Append(curves);

                // create the sketch plane
                plane = app.NewPlane(sketchPlaneData[i, 0], sketchPlaneData[i, 1]);
                sketchPlane = f.NewSketchPlane(plane);

                // create the extrusion
                extrusions[i] = f.NewExtrusion(isSolid[i], profile, sketchPlane,
                    extrusionOffsets[i, 1]);
                extrusions[i].StartOffset = extrusionOffsets[i, 0];
                m_combineElements.Append(extrusions[i]);
            }

            #endregion

            #region Create the round extrusions

            for (int i = 3; i <= 4; ++i)
            {
                // create the profile
                profile = app.NewCurveArrArray();

                curves = app.NewCurveArray();
                plane = new Plane(profileData[i, 0], profileData[i, 1]);
                curves.Append(app.NewArc(plane, arcRadius, 0, Math.PI * 2));
                profile.Append(curves);

                // create the sketch plane
                plane = app.NewPlane(sketchPlaneData[i, 0], sketchPlaneData[i, 1]);
                sketchPlane = f.NewSketchPlane(plane);

                // create the extrusion
                extrusions[i] = f.NewExtrusion(isSolid[i], profile, sketchPlane,
                    extrusionOffsets[i, 1]);
                extrusions[i].StartOffset = extrusionOffsets[i, 0];
                m_combineElements.Append(extrusions[i]);
            }

            #endregion
        }

        /// <summary>
        /// create the connectors on the extrusions
        /// </summary>
        private void CreateConnectors()
        {
            List<PlanarFace> m_planarFaces = null;
            Parameter param = null;

            #region Create the Supply Air duct connector

            // get the planar faces of extrusion1
            m_planarFaces = GetPlanarFaces(extrusions[1]);

            // create the Supply Air duct connector
            DuctConnector connSupplyAir = f.NewDuctConnector(m_planarFaces[0].Reference,
                DuctSystemType.SupplyAir);
            param = connSupplyAir.get_Parameter(BuiltInParameter.CONNECTOR_HEIGHT);
            param.Set(connectorDimensions[0, 0]);
            param = connSupplyAir.get_Parameter(BuiltInParameter.CONNECTOR_WIDTH);
            param.Set(connectorDimensions[0, 1]);
            param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_DIRECTION_PARAM);
            param.Set(2);
            param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_CONFIGURATION_PARAM);
            param.Set(1);
            param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM);
            param.Set(flow);

            #endregion

            #region Create the Return Air duct connector

            // get the planar faces of extrusion2
            m_planarFaces = GetPlanarFaces(extrusions[2]);

            // create the Return Air duct connector
            DuctConnector connReturnAir = f.NewDuctConnector(m_planarFaces[0].Reference,
                DuctSystemType.ReturnAir);
            param = connReturnAir.get_Parameter(BuiltInParameter.CONNECTOR_HEIGHT);
            param.Set(connectorDimensions[1, 0]);
            param = connReturnAir.get_Parameter(BuiltInParameter.CONNECTOR_WIDTH);
            param.Set(connectorDimensions[1, 1]);
            param = connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_DIRECTION_PARAM);
            param.Set(1);
            param =
                connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_CONFIGURATION_PARAM);
            param.Set(1);
            param = connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM);
            param.Set(flow);

            #endregion

            #region Create the Supply Hydronic pipe connector

            // get the planar faces of extrusion3
            m_planarFaces = GetPlanarFaces(extrusions[3]);

            // create the Hydronic Supply pipe connector
            PipeConnector connSupplyHydronic = f.NewPipeConnector(m_planarFaces[0].Reference,
                PipeSystemType.SupplyHydronic);
            param = connSupplyHydronic.get_Parameter(BuiltInParameter.CONNECTOR_RADIUS);
            param.Set(arcRadius);
            param =
                connSupplyHydronic.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_DIRECTION_PARAM);
            param.Set(2);

            #endregion

            #region Create the Return Hydronic pipe connector

            // get the planar faces of extrusion4
            m_planarFaces = GetPlanarFaces(extrusions[4]);

            // create the Hydronic Return pipe connector
            PipeConnector connReturnHydronic = f.NewPipeConnector(m_planarFaces[0].Reference,
                PipeSystemType.ReturnHydronic);
            param = connReturnHydronic.get_Parameter(BuiltInParameter.CONNECTOR_RADIUS);
            param.Set(arcRadius);
            param =
                connReturnHydronic.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_DIRECTION_PARAM);
            param.Set(1);

            #endregion

        }
    }
}


text:
#pragma once

#include "can_types.h"
#include "can_enums.h"
#include "can_regmap.h"

namespace avr_halib
{
namespace canary
{
	/** \brief The base class of the CAN-Driver
	 *
	 *  \tparam Config The configuration of this class
	 *
	 *  This class implements the basic and more chip-specific access-functions.
	 **/
	template<class config>
	class CANBase :
		public can_templates::IdHelper<static_cast<Versions>(config::version)>
	{
		protected:
			/** The special regmap to use for the hardware-access **/

			typedef typename config::template Regmap<static_cast<Versions>(config::version)>
				Regmap;

			/** The special CAN-Base-Message for sending a message **/

			typedef can_templates::CANMsgSendBase<
						static_cast<Versions>(config::version)>
				MsgSendBase;

			/** The special CAN-Base-Message for receiving a message without
			 * timestamp**/

			typedef can_templates::CANMsgRecvBase<
						static_cast<Versions>(config::version)>
				MsgRecvBase;

			/** The special CAN-Base-Message for sending a message with
			 * timestamp**/

			typedef can_templates::CANMsgRecvTimeStamp<
						static_cast<Versions>(config::version)>
				MsgRecvTimeStamp;

			/** The structure, that contains the current state-values**/

			typedef CANState
				State;

			/** The special IdHelper to manage information about the CAN-ID **/

			typedef typename can_templates::IdHelper<
								static_cast<Versions>(config::version)>::IdType
				IdType;

		public:

		/** \brief The general driver start/restart function.

		 *  It resets the hardware and configures the constant parameters, that
		 *  are stated in the template-configuration.

		 *  If the hardware has no CAN-Hardware, an infinite loop is possible.
		 *  **/

		void restart()
		{
			UseRegmap(can, Regmap);
			can.generalControl.swReset=true;
			SyncRegmap(can);

			for(uint8_t i=0;i<NUMMOBS;i++)
			{
				can.curMObNum=i;
				freeMob();
			}

			can.baudRateConfig.brp=config::baudRate::brp;
			can.baudRateConfig.sjw=config::baudRate::sjw;
			can.baudRateConfig.prs=config::baudRate::prs;
			can.baudRateConfig.phs1=config::baudRate::phs1;
			can.baudRateConfig.phs2=config::baudRate::phs2;
			can.baudRateConfig.smp=config::baudRate::smp;

			can.timerPrescaler=config::prescaler;

			can.cangie=0;
			can.canie1=0;
			can.canie2=0;
			can.cansit1=0;
			can.cansit2=0;

			can.generalControl.enable=true;

			while(!can.generalStatus.enabled)
				SyncRegmap(can);
		}

		protected:

		CANBase()
		{
			restart();
		}

		/** \brief Search the Message-Object-Buffers(MOb) for the next free one
		 * and sets it to active

		 * @return the current active MOb or -1 if none was available**/

		int8_t selectMob()
		{
			UseRegmap(can, Regmap);
			for(uint8_t i=0;i<NUMMOBS;i++)
				if(!(can.MObsAvailability&(0x1<<i)))
				{
					can.curMObNum=i;
					SyncRegmap(can);
					return i;
				}
			return -1;
		}

		/** \brief Start the sending of a message

		 *  There will be no check, wether the message was send successful or
		 *  not.

		 * @param msg a reference to the CAN-Message-structure that is to be
		 * send

		 * @param data the data of the CAN-Message that should be send

		 * @return the event that occured during the start of the sending
		 * possible values: INVALIDID, INVALIDMSG, SUCCESS
		 **/

		Events setWrite(MsgSendBase &msg, const uint8_t *data)
		{
			msg.autoReply=false;

			if(!checkId(msg.id))
				return INVALIDID;

			if(!setMsgLen(msg))
				return INVALIDMSG;

			setId(msg);

			if(!msg.getRTR())
				sendData(msg, data);

			startSend();

			return SUCCESS;
		}

		/** \brief Sets a MOb to function as a AutoReply for RTRs.

		 * @param msg a reference to the CAN-Message-structure, that contains
		 * the information for the AutoReply

		 * @param data the data, that is to be send on a automatic reply

		 * @return the event that occured during the start of the sending
		 * possible values: INVALIDID, INVALIDMSG, SUCCESS
		 **/ Events setRTRValid(MsgRecvBase &msg, const uint8_t *data) {
			 if(!checkId(msg.id)) return INVALIDID;

			if(!setMsgLen(msg))
				return INVALIDMSG;

			msg.autoReply=true;
			msg.setRTRMask(true);
			msg.setRTR(true);

			setIdAndIdMask(msg);

			sendData(msg, data);

			startAutoReply();

			return SUCCESS;
		}

		/** \brief Start the receiving of a message.
		 *  There is no check if a message was received successfull.

		 * @param msg a reference to the CAN-Message-structure that is to be
		 * used

		 * @return the event that occured during the start of the sending
		 * possible values: INVALIDID, INVALIDMSG, SUCCESS
		 **/

		Events setRead(MsgRecvBase &msg)
		{
			msg.autoReply=false;

			if(!checkId(msg.id))
				return INVALIDID;

			if(!setMsgLen(msg))
				return INVALIDMSG;

			setIdAndIdMask(msg);

			startRecv();

			return SUCCESS;
		}

		/** \brief Read the received data and the ID

		 *  of the received frame from the hardware into the
		 *  CAN-Message-Structure.

		 * @param msg a reference to the CAN-Message-Structure that is to be
		 * used

		 * @param data the buffer in which the data should be placed, should be
		 * 8 bytes long
		 **/

		void readData(MsgRecvBase &msg, uint8_t *data)
		{
			UseRegmap(can, Regmap);

			can.fifoIndex=0;
			SyncRegmap(can);

			if(!msg.getRTR())
				for(uint8_t i=0; i<can.mobConfig.dataLengthCode; i++)
				{
					data[i]=can.msg;
					SyncRegmap(can);
				}

			if(static_cast<Versions>(config::version)==CAN_20B
			   && !can.mobConfig.idExtension)

				msg.id=reinterpret_cast<can_templates::CANID<CAN_20A>*>(&can.idConfig)->id;

			else

				msg.id=can.idConfig.id;

			msg.length=can.mobConfig.dataLengthCode;
			SyncRegmap(can);
		}

		/** \brief Read the timestamp of the currently received message
		 * into the CAN-Message-Structure if timestamps are enabled.

		 * @param msg a reference to the CAN-Message-Structure that is to be
		 * used
		 **/

		void readTimeStamp(MsgRecvTimeStamp &msg)
		{
			UseRegmap(can, Regmap);

			msg.timeStamp=can.timeStamp;
			SyncRegmap(can);
		}

		/**\brief Do nothing.
		 *  This method just exist to be used when timestamps are deactivated.

		 * @param msg a reference to the CAN-Message-Structure that is to be
		 * used
		 **/

		void readTimeStamp(MsgRecvBase &msg)
		{

		}

		/** \brief Get the last event that occured.
		 *   All satus flags will be reseted by calling this function.
		 *
		 * @return the event that occured
		 **/

		Events getEvent()
		{
			UseRegmap(can, Regmap);

			if(can.mobStatus.ackError)
			{
				can.mobStatus.ackError=false;
				SyncRegmap(can);
				return ACKERROR;
			}
			if(can.mobStatus.formError)
			{
				can.mobStatus.formError=false;
				SyncRegmap(can);
				return FORMERROR;
			}
			if(can.mobStatus.crcError)
			{
				can.mobStatus.crcError=false;
				SyncRegmap(can);
				return CRCERROR;
			}
			if(can.mobStatus.stuffError)
			{
				can.mobStatus.stuffError=false;
				SyncRegmap(can);
				return STUFFERROR;
			}
			if(can.mobStatus.bitError)
			{
				can.mobStatus.bitError=false;
				SyncRegmap(can);
				return BITERROR;
			}
			if(can.mobStatus.receiveOk)
			{
				can.mobStatus.receiveOk=false;
				SyncRegmap(can);
				return RECEIVEOK;
			}
			if(can.mobStatus.transmitOk)
			{
				can.mobStatus.transmitOk=false;
				SyncRegmap(can);
				return TRANSMITOK;
			}
			SyncRegmap(can);
			return NOTHING;
		}

		/** \brief Disables the currently used MOb.
		 * The current action will be completed before deactivation will happen
		 **/

		void freeMob()
		{
			UseRegmap(can, Regmap);

			can.mobConfig.config=DISABLEDMOB;
		}

		public:

			/** \brief Tell the CAN driver, to send an overload frame after the
			 * next received frame
			 **/

			void requestOverloadFrame()
			{
				UseRegmap(can, Regmap);
				can.overloadFrame=true;
			}

			/** \brief Allows the user to track the overload frame
			 *
			 * @return true if overload frame still active, false if not
			 **/

			bool watchOverloadFrame() const
			{
				UseRegmap(can, Regmap);

				return can.frameOverloaded;
			}

			/** \brief Fill the supplied CANState structure with the current
			 * state values of the CAN driver.

			 * @param state The supplied CANState structure
			 **/

			void getState(State &state) const
			{
				UseRegmap(can, Regmap);

				state.receiveErrors=can.canrec;
				state.transmitErrors=can.cantec;

				if(!can.generalStatus.enabled)
					state.state=DISABLED;
				else if(can.generalStatus.errorPassiveMode)
					state.state=ERRORPASSIVE;
				else if(can.generalStatus.busOffMode)
					state.state=BUSOFF;
				else state.state=ENABLED;

				state.busy=NONE;
				if(can.generalStatus.transmitterBusy)
					state.busy=TRANSMITTER;
				if(can.generalStatus.receiverBusy)
					state.busy=RECEIVER;
			}

		protected:

		bool checkForAnything()
		{
			UseRegmap(can, Regmap);
			SyncRegmap(can);
			return can.generalInterrupt.generalInt;
		}

		/** \brief Gets the number of the currently active MOb
		 *
		 * @return number of the current MOb
		 **/
		uint8_t getCurrentMob() const
		{
			UseRegmap(can, Regmap);
			SyncRegmap(can);
			return can.curMObNum;
		}

		/** \brief Activates a MOb
		 *
		 * @param mobNum number of the MOb, that is to be activated
		 **/
		void useMob(uint8_t mobNum)
		{
			UseRegmap(can, Regmap);
			can.curMObNum=mobNum;
			SyncRegmap(can);
		}

		/** \brief Gets the MObs, which currently have an active interrupt

		 * @return a bitfield indicating an interrupt by 1 on pos mobNum for
		 * each MOb
		 **/

		uint16_t getInterruptActivity() const
		{
			UseRegmap(can, Regmap);
			SyncRegmap(can);
			return can.MObsIntActive;
		}

		/** \brief Activates interrupts for a given MOb
		 *
		 * @param mob the mob for which interrupts should be enabled
		 */
		void setInterrupt(uint8_t mob)
		{
			UseRegmap(can, Regmap);

			can.MObsIntUsage|=0x1<<mob;

			SyncRegmap(can);
		}

		/** \brief Deactivates interrupts for a given MOb
		 *
		 * @param mob the mob for which interrupts should be disabled
		 */
		void removeInterrupt(uint8_t mob)
		{
			UseRegmap(can, Regmap);

			can.MObsIntUsage&=~(0x1<<mob);

			SyncRegmap(can);
		}

		/** \brief Gets the compatibility flag of the current MOb
		 *
		 * @return compatibility state of the current MOb
		 **/

		bool isCompat() const
		{
			UseRegmap(can, Regmap);
			return can.mobConfig.idExtension;
		}

		/** \brief Sets the ID, IDExtension-Flag and RTR-Flag
		 *   from the message-structure into the hardware-controller.
		 *
		 * To be used for sending.
		 *
		 * @param msg reference to the message that contains the ID
		 **/
		void setId(const MsgSendBase &msg)
		{
			UseRegmap(can, Regmap);

			can.idConfig.remoteTransmissionRequest=msg.rtr;

			if(static_cast<Versions>(config::version)==CAN_20B)
			{
				if(msg.compat)
				{
					can.mobConfig.idExtension=false;
					reinterpret_cast<can_templates::CANID<CAN_20A>*>(&can.idConfig)->id=msg.id;
				}
				else
				{
					can.mobConfig.idExtension=true;
					can.idConfig.id=msg.id;
				}
			}
			else
			{
				can.mobConfig.idExtension=false;
				can.idConfig.id=msg.id;
			}

			SyncRegmap(can);
		}

		/** \brief Sets the ID, IDMask, IDExtension-Flag and RTR-Flag
		 * from the message-structure into the hardware-controller.
		 *
		 * To be used for receiving.
		 *
		 * @param msg reference to the message that contains the ID
		 **/
		void setIdAndIdMask(const MsgRecvBase &msg)
		{
			UseRegmap(can, Regmap);

			setId(msg);

			if(static_cast<Versions>(config::version)==CAN_20B)
			{
				if(msg.compat)
					reinterpret_cast<can_templates::CANID<CAN_20A>*>(&can.idConfig)->idMask=msg.idMask;
				else
					can.idConfig.idMask=msg.idMask;

				can.idConfig.idExtensionMask=!msg.acceptBoth;
			}
			else
			{
				can.idConfig.idMask=msg.idMask;
				can.idConfig.idExtensionMask=true;
			}

			can.mobConfig.replyValid=false;

			can.idConfig.idExtensionMask=true;
			can.idConfig.remoteTransmissionMask=msg.rtrMask;

			SyncRegmap(can);
		}

		/** \brief Checks if the id fits in the ID-value-space of the current
		 * CAN-Version

		 * CAN_20A: 0<= id <= 0x7FF
		 * CAN_20B: 0<= id <= 0x1FFFFFFF

		 * @param id the ID that is to be checked

		 * @return true if ok, false if out of range
		 **/

		bool checkId(IdType id)
		{
			return id<=can_templates::IdHelper<
						static_cast<Versions>(config::version)>::getMaxId();
		}

		/** \brief Sets the length of the message
		 *  from the message-structure into the hardware-controller
		 * Also checks if the length of the message is between 0 and 8 bytes
		 *
		 * @param msg reference to the CAN-message-structure that is to be send
		 * @return false if message is too long, true otherwise
		 **/

		bool setMsgLen(const MsgSendBase &msg)
		{
			UseRegmap(can, Regmap);

			if(msg.length>MAXMSGLEN)
				return false;

			can.mobConfig.dataLengthCode=msg.length;

			SyncRegmap(can);

			return true;
		}

		/** \brief Copies the data that is to be send

		 * from the message into the hardware-controller.

		 *  @param msg a reference to the message containing the length of the
		 *  data

		 *  @param data the data that is to be send
		 **/

		void sendData(const MsgSendBase &msg, const uint8_t *data)
		{
			UseRegmap(can, Regmap);

			can.fifoIndex=0;
			SyncRegmap(can);

			for(uint8_t i=0;i<msg.length;i++)
			{
				can.msg=data[i];
				SyncRegmap(can);
			}
		}

		/** \brief Starts the send process of the current MOb**/

		void startSend()
		{
			UseRegmap(can, Regmap);

			can.mobConfig.config=TXMOB;
			SyncRegmap(can);
		}

		/** \brief Starts the receive process of the current MOb**/

		void startRecv()
		{
			UseRegmap(can, Regmap);

			can.mobConfig.config=RXMOB;
			SyncRegmap(can);
		}

		/** \brief Sets the current MOb into Auto-Reply-Mode**/

		void startAutoReply()
		{
			UseRegmap(can, Regmap);

			can.idConfig.remoteTransmissionRequest=true;
			can.mobConfig.replyValid=true;
			can.mobConfig.config=RXMOB;
			SyncRegmap(can);
		}
	};
}
}

redpajama_set_name: RedPajamaGithub


text:
#include <linux/module.h>

#include <linux/init.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
#include <linux/of_platform.h>
#include <linux/of_gpio.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/wakelock.h>
#include <linux/hall.h>

struct device *sec_device_create(void *drvdata, const char *fmt);

struct certify_hall_drvdata {
	struct input_dev *input;
	int gpio_certify_cover;
	int irq_certify_cover;
	struct work_struct work;
	struct delayed_work certify_cover_dwork;
	struct wake_lock certify_wake_lock;
};

static bool certify_cover = 0;

static ssize_t certify_hall_detect_show(struct device *dev,
					struct device_attribute *attr, char *buf)
{
	if (certify_cover) {
		sprintf(buf, "CLOSE\n");
	} else {
		sprintf(buf, "OPEN\n");
	}

	return strlen(buf);
}
static DEVICE_ATTR(certify_hall_detect, 0664, certify_hall_detect_show, NULL);

static struct attribute *certify_hall_attrs[] = {
	&dev_attr_certify_hall_detect.attr,
	NULL,
};

static struct attribute_group certify_hall_attr_group = {
	.attrs = certify_hall_attrs,
};

#ifdef CONFIG_SEC_FACTORY
static void certify_cover_work(struct work_struct *work)
{
	bool first,second;
	struct certify_hall_drvdata *ddata =
		container_of(work, struct certify_hall_drvdata,
				certify_cover_dwork.work);

	first = !gpio_get_value(ddata->gpio_certify_cover);

	printk("[keys] %s certify_status #1 : %d (%s)\n", __func__, first, first?"attach":"detach");

	msleep(50);

	second = !gpio_get_value(ddata->gpio_certify_cover);

	printk("[keys] %s certify_status #2 : %d (%s)\n", __func__, second, second?"attach":"detach");

	if(first == second) {
		certify_cover = first;
#ifdef CONFIG_CERTIFY_HALL_NFC_WA
		if(certify_cover)
			felica_ant_tuning(1);
		else
			felica_ant_tuning(0);
#endif
		input_report_switch(ddata->input, SW_CERTIFYHALL, certify_cover);
		input_sync(ddata->input);
	}
}
#else
static void certify_cover_work(struct work_struct *work)
{
	bool first;
	struct certify_hall_drvdata *ddata =
		container_of(work, struct certify_hall_drvdata,
				certify_cover_dwork.work);

	first = !gpio_get_value(ddata->gpio_certify_cover);

	printk("[keys] %s certify_status : %d (%s)\n", __func__, first, first?"attach":"detach");

	certify_cover = first;
#ifdef CONFIG_CERTIFY_HALL_NFC_WA
	if(certify_cover)
		felica_ant_tuning(1);
	else
		felica_ant_tuning(0);
#endif
	input_report_switch(ddata->input,
			SW_CERTIFYHALL, certify_cover);
	input_sync(ddata->input);

/* WorkAround for Hall IRQ Noise problem in connect to GSM band */
#ifdef CONFIG_SENSORS_HALL_IRQ_CTRL
	if(certify_cover)
		hall_irq_set(enable, true);
	else
		hall_irq_set(disable, true);
#endif
}
#endif

static void __certify_cover_detect(struct certify_hall_drvdata *ddata, bool flip_certify_status)
{
	cancel_delayed_work_sync(&ddata->certify_cover_dwork);
#ifdef CONFIG_SEC_FACTORY
	schedule_delayed_work(&ddata->certify_cover_dwork, HZ / 20);
#else
	if(flip_certify_status)	{
		wake_lock_timeout(&ddata->certify_wake_lock, HZ * 5 / 100); /* 50ms */
		schedule_delayed_work(&ddata->certify_cover_dwork, HZ * 1 / 100); /* 10ms */
	} else {
		wake_unlock(&ddata->certify_wake_lock);
		schedule_delayed_work(&ddata->certify_cover_dwork, 0);
	}
#endif
}

static irqreturn_t certify_cover_detect(int irq, void *dev_id)
{
	bool flip_certify_status;
	struct certify_hall_drvdata *ddata = dev_id;

	flip_certify_status = !gpio_get_value(ddata->gpio_certify_cover);

	printk(KERN_DEBUG "keys:%s certify_status : %d\n",
		 __func__, flip_certify_status);

	__certify_cover_detect(ddata, flip_certify_status);

	return IRQ_HANDLED;
}

static int certify_hall_open(struct input_dev *input)
{
	struct certify_hall_drvdata *ddata = input_get_drvdata(input);
	/* update the current status */
	schedule_delayed_work(&ddata->certify_cover_dwork, HZ / 2);
	/* Report current state of buttons that are connected to GPIOs */
	input_sync(input);

	return 0;
}

static void certify_hall_close(struct input_dev *input)
{
}

static void init_certify_hall_ic_irq(struct input_dev *input)
{
	struct certify_hall_drvdata *ddata = input_get_drvdata(input);

	int ret = 0;
	int irq = ddata->irq_certify_cover;

	certify_cover = gpio_get_value(ddata->gpio_certify_cover);

	INIT_DELAYED_WORK(&ddata->certify_cover_dwork, certify_cover_work);

	ret =
		request_threaded_irq(
		irq, NULL,
		certify_cover_detect,
		IRQF_DISABLED | IRQF_TRIGGER_RISING |
		IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
		"certify_cover", ddata);
	if (ret < 0) {
		printk(KERN_ERR
		"keys: failed to certify about request flip cover irq %d gpio %d\n",
		irq, ddata->gpio_certify_cover);
	} else {
		pr_info("%s : success\n", __func__);
	}
}

#ifdef CONFIG_OF
static int of_certify_hall_data_parsing_dt(struct certify_hall_drvdata *ddata)
{
	struct device_node *np_haptic;
	int gpio;
	enum of_gpio_flags flags;

	np_haptic = of_find_node_by_path("/certify_hall");
	if (np_haptic == NULL) {
		printk("%s : error to get dt node\n", __func__);
		return -EINVAL;
	}

	gpio = of_get_named_gpio_flags(np_haptic, "certify_hall,gpio_certify_cover", 0, &flags);
	if (gpio < 0) {
		pr_info("%s: fail to get certify_cover \n", __func__ );
		return -EINVAL;
	}
	ddata->gpio_certify_cover = gpio;

	gpio = gpio_to_irq(gpio);
	if (gpio < 0) {
		pr_info("%s: fail to return irq corresponding gpio \n", __func__ );
		return -EINVAL;
	}
	ddata->irq_certify_cover = gpio;

	return 0;
}
#endif

static int certify_hall_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct certify_hall_drvdata *ddata;
	struct input_dev *input;
	int error;
	int wakeup = 0;

	ddata = kzalloc(sizeof(struct certify_hall_drvdata), GFP_KERNEL);
	if (!ddata) {
		dev_err(dev, "failed to allocate state\n");
		return -ENOMEM;
	}

#ifdef CONFIG_OF
	if(dev->of_node) {
		error = of_certify_hall_data_parsing_dt(ddata);
		if (error < 0) {
			pr_info("%s : fail to get the dt (HALL)\n", __func__);
			goto fail1;
		}
	}
#endif

	input = input_allocate_device();
	if (!input) {
		dev_err(dev, "failed to allocate state\n");
		error = -ENOMEM;
		goto fail1;
	}

	ddata->input = input;

	wake_lock_init(&ddata->certify_wake_lock, WAKE_LOCK_SUSPEND,
		"flip wake lock");

	platform_set_drvdata(pdev, ddata);
	input_set_drvdata(input, ddata);

	input->name = "certify_hall";
	input->phys = "certify_hall";
	input->dev.parent = &pdev->dev;

	input->evbit[0] |= BIT_MASK(EV_SW);
	input_set_capability(input, EV_SW, SW_CERTIFYHALL);

	input->open = certify_hall_open;
	input->close = certify_hall_close;

	/* Enable auto repeat feature of Linux input subsystem */
	__set_bit(EV_REP, input->evbit);

	init_certify_hall_ic_irq(input);

	error = sysfs_create_group(&sec_key->kobj, &certify_hall_attr_group);
	if (error) {
		dev_err(dev, "Unable to export keys/switches, error: %d\n",
			error);
		goto fail2;
	}

	error = input_register_device(input);
	if (error) {
		dev_err(dev, "Unable to register input device, error: %d\n",
			error);
		goto fail3;
	}

	device_init_wakeup(&pdev->dev, wakeup);

	return 0;

 fail3:
	sysfs_remove_group(&pdev->dev.kobj, &certify_hall_attr_group);
 fail2:
	platform_set_drvdata(pdev, NULL);
	wake_lock_destroy(&ddata->certify_wake_lock);
	input_free_device(input);
 fail1:
	kfree(ddata);

	return error;
}

static int certify_hall_remove(struct platform_device *pdev)
{
	struct certify_hall_drvdata *ddata = platform_get_drvdata(pdev);
	struct input_dev *input = ddata->input;

	printk("%s start\n", __func__);
	sysfs_remove_group(&pdev->dev.kobj, &certify_hall_attr_group);

	device_init_wakeup(&pdev->dev, 0);

	input_unregister_device(input);

	wake_lock_destroy(&ddata->certify_wake_lock);

	kfree(ddata);

	return 0;
}

#if defined(CONFIG_OF)
static struct of_device_id hall_dt_ids[] = {
	{ .compatible = "certify_hall" },
	{ },
};
MODULE_DEVICE_TABLE(of, hall_dt_ids);
#endif /* CONFIG_OF */

#ifdef CONFIG_PM_SLEEP
static int certify_hall_suspend(struct device *dev)
{
	struct certify_hall_drvdata *ddata = dev_get_drvdata(dev);
	struct input_dev *input = ddata->input;
	bool status;

	printk("%s start\n", __func__);
	status = !gpio_get_value(ddata->gpio_certify_cover);
	printk("[keys] %s certify_status : %d (%s)\n", __func__, status, status?"attach":"detach");

/* need to be change */
/* Without below one line, it is not able to get the irq during freezing */
	enable_irq_wake(ddata->irq_certify_cover);

	if (device_may_wakeup(dev)) {
		enable_irq_wake(ddata->irq_certify_cover);
	} else {
		mutex_lock(&input->mutex);
		if (input->users)
			certify_hall_close(input);
		mutex_unlock(&input->mutex);
	}

	return 0;
}

static int certify_hall_resume(struct device *dev)
{
	struct certify_hall_drvdata *ddata = dev_get_drvdata(dev);
	struct input_dev *input = ddata->input;
	bool status;

	printk("%s start\n", __func__);
	status = !gpio_get_value(ddata->gpio_certify_cover);
	printk("[keys] %s certify_status : %d (%s)\n", __func__, status, status?"attach":"detach");
	input_sync(input);

	return 0;
}
#endif

static SIMPLE_DEV_PM_OPS(hall_pm_ops, certify_hall_suspend, certify_hall_resume);

static struct platform_driver certify_hall_device_driver = {
	.probe		= certify_hall_probe,
	.remove		= certify_hall_remove,
	.driver		= {
		.name	= "certify_hall",
		.owner	= THIS_MODULE,
		.pm	= &hall_pm_ops,
#if defined(CONFIG_OF)
		.of_match_table	= hall_dt_ids,
#endif /* CONFIG_OF */
	}
};

static int __init certify_hall_init(void)
{
	printk("%s start\n", __func__);
	return platform_driver_register(&certify_hall_device_driver);
}

static void __exit certify_hall_exit(void)
{
	printk("%s start\n", __func__);
	platform_driver_unregister(&certify_hall_device_driver);
}

late_initcall(certify_hall_init);
module_exit(certify_hall_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Insun Choi <insun77.choi@samsung.com>");
MODULE_DESCRIPTION("Hall IC driver for GPIOs");
MODULE_ALIAS("platform:gpio-keys");


text:
<?php

namespace JMGQ\AStar\Tests;

use JMGQ\AStar\AStar;
use JMGQ\AStar\DomainLogicInterface;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;

class AStarTest extends TestCase
{
    /** @var AStar<string> */
    private AStar $sut;
    /** @var Stub & DomainLogicInterface<string> */
    private Stub | DomainLogicInterface $domainLogic;

    protected function setUp(): void
    {
        $this->domainLogic = $this->createStub(DomainLogicInterface::class);

        /** @psalm-suppress MixedPropertyTypeCoercion */
        $this->sut = new AStar($this->domainLogic);
    }

    public function testShouldFindSolutionIfTheStartAndGoalNodesAreTheSame(): void
    {
        $startNode = 'foo';
        $goalNode = 'foo';

        $path = (array) $this->sut->run($startNode, $goalNode);

        $this->assertCount(1, $path);

        $firstAndOnlySolutionNode = reset($path);

        $this->assertSame($startNode, $firstAndOnlySolutionNode);
        /** @psalm-suppress RedundantConditionGivenDocblockType */
        $this->assertSame($goalNode, $firstAndOnlySolutionNode);
    }

    public function testShouldReturnEmptyPathIfSolutionNotFound(): void
    {
        $startNode = 'startNode';
        $unreachableGoalNode = 'unreachableGoalNode';

        $this->domainLogic->method('getAdjacentNodes')
            ->willReturn([]);

        $path = $this->sut->run($startNode, $unreachableGoalNode);

        $this->assertCount(0, $path);
    }

    public function testSimplePath(): void
    {
        $startNode = 'startNode';
        $goalNode = 'goalNode';
        $otherNode = 'otherNode';

        $allNodes = [$startNode, $goalNode, $otherNode];

        $this->domainLogic->method('getAdjacentNodes')
            ->willReturnCallback(function (string $argumentNode) use ($allNodes) {
                // The adjacent nodes are all other nodes (not including itself)
                return array_filter($allNodes, static fn ($node) => $argumentNode !== $node);
            });

        $this->domainLogic->method('calculateRealCost')
            ->willReturn(5);

        $this->domainLogic->method('calculateEstimatedCost')
            ->willReturn(2);

        $path = (array) $this->sut->run($startNode, $goalNode);

        $this->assertCount(2, $path);

        $firstSolutionNode = reset($path);
        $lastSolutionNode = end($path);

        $this->assertSame($startNode, $firstSolutionNode);
        $this->assertSame($goalNode, $lastSolutionNode);
    }
}


text:
module RTanque
  class Explosion
    include Movable
    attr_reader :position, :width
    LIFE_SPAN = Configuration.explosion.life_span # ticks
    def initialize(position)
      @position = position
      @ticks = 0
      @width = 0
    end

    def percent_dead
      @ticks / LIFE_SPAN.to_f
    end

    def tick
      @ticks += 1
    end

    def dead?
      @ticks > LIFE_SPAN
    end
  end
end


text:
This repo implements a [Deep Convolutional GAN](https://arxiv.org/abs/1511.06434)(DCGAN) and a [Wasserstein GAN](https://arxiv.org/abs/1701.07875)(WGAN) to generate novel images of food.

## Data
I [scraped](https://github.com/rtlee9/recipe-box) ~125,000 recipes from various websites for use in this model. Each recipe consists of:

* A recipe title
* A list of ingredients
* Preparation instructions
* An image of the prepared recipe (missing for ~40% of recipes collected)

These GANs were fitted on the recipe images; they did not utilize the recipe's title, ingredients list, or instructions.

## Sampled outputs
Below are a few randomly selected outputs from both the DCGAN and the WGAN:

### DCGAN
![DCGAN](fake_DCGAN.png)

### WGAN
![WGAN](fake_WGAN.png)

## Training
Each model was trained for ~4 hours on an nVidia Tesla K80. The loss curve for the WGAN is depicted below:

### WGAN loss curve
![WGAN-loss-curve](WGAN_loss_history.png)

## Usage (Python 3.6)

* Clone repo: `git clone https://github.com/rtlee9/food-GAN.git; cd food-GAN`
* Download images from my Google Cloud Bucket: `wget -P imgs https://storage.googleapis.com/recipe-box/imgs.zip; unzip imgs/imgs.zip -d imgs` (alternatively, see the recipe-box submodule to scrape fresh recipe data)
* Remove blacklisted images: `./src/rm_blacklist.sh`
* Train and sample GAN: `python src/pytorch_DCGAN.py --dataset folder --dataroot imgs --outf outputs` or `python src/pytorch_WGAN.py --dataset folder --dataroot imgs --outf outputs`

## Next steps

* Incorporate recipe text (title, ingredients, and instructions) to generate images conditioned on recipe context.
* Filter out placeholder images prior to training


text:
define(function( require, exports, module ){

var backbone = require('backbone');

var Service = backbone.Model.extend({

    defaults: {
        id: null,
        key: null,
        label: null,
    },
});

exports.Service = Service;

});


text:
import sys, getopt, traceback

from py4j.java_gateway import java_import, JavaGateway, GatewayClient
from py4j.protocol import Py4JJavaError
from pyspark.conf import SparkConf
from pyspark.context import SparkContext
from pyspark.rdd import RDD
from pyspark.files import SparkFiles
from pyspark.storagelevel import StorageLevel
from pyspark.accumulators import Accumulator, AccumulatorParam
from pyspark.broadcast import Broadcast
from pyspark.serializers import MarshalSerializer, PickleSerializer

# for back compatibility
from pyspark.sql import SQLContext, HiveContext, SchemaRDD, Row

client = GatewayClient(port=int(sys.argv[1]))
gateway = JavaGateway(client)

java_import(gateway.jvm, "org.apache.spark.SparkEnv")
java_import(gateway.jvm, "org.apache.spark.SparkConf")
java_import(gateway.jvm, "org.apache.spark.api.java.*")
java_import(gateway.jvm, "org.apache.spark.api.python.*")
java_import(gateway.jvm, "org.apache.spark.mllib.api.python.*")

intp = gateway.entry_point
intp.onPythonScriptInitialized()

jsc = intp.getJavaSparkContext()

if jsc.version().startswith("1.2"):
  java_import(gateway.jvm, "org.apache.spark.sql.SQLContext")
  java_import(gateway.jvm, "org.apache.spark.sql.hive.HiveContext")
  java_import(gateway.jvm, "org.apache.spark.sql.hive.LocalHiveContext")
  java_import(gateway.jvm, "org.apache.spark.sql.hive.TestHiveContext")
elif jsc.version().startswith("1.3"):
  java_import(gateway.jvm, "org.apache.spark.sql.*")
  java_import(gateway.jvm, "org.apache.spark.sql.hive.*")

java_import(gateway.jvm, "scala.Tuple2")

jconf = intp.getSparkConf()
conf = SparkConf(_jvm = gateway.jvm, _jconf = jconf)
sc = SparkContext(jsc=jsc, gateway=gateway, conf=conf)
sqlc = SQLContext(sc, intp.getSQLContext())

z = intp.getZeppelinContext()

class Logger(object):
  def __init__(self):
    self.out = ""

  def write(self, message):
    self.out = self.out + message

  def get(self):
    return self.out

  def reset(self):
    self.out = ""

output = Logger()
sys.stdout = output
sys.stderr = output

while True :
  req = intp.getStatements()
  try:
    stmts = req.statements().split("\n")
    jobGroup = req.jobGroup()
    final_code = None

    for s in stmts:
      if s == None or len(s.strip()) == 0:
        continue

      # skip comment
      if s.strip().startswith("#"):
        continue

      if final_code:
        final_code += "\n" + s
      else:
        final_code = s

    if final_code:
      compiledCode = compile(final_code, "<string>", "exec")
      sc.setJobGroup(jobGroup, "Zeppelin")
      eval(compiledCode)

    intp.setStatementsFinished(output.get(), False)
  except Py4JJavaError:
    excInnerError = traceback.format_exc() # format_tb() does not return the inner exception
    innerErrorStart = excInnerError.find("Py4JJavaError:")
    if innerErrorStart > -1:
       excInnerError = excInnerError[innerErrorStart:]
    intp.setStatementsFinished(excInnerError + str(sys.exc_info()), True)
  except:
    intp.setStatementsFinished(str(sys.exc_info()), True)

  output.reset()


text:
// (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.cloudera.director.aws.ec2;

import static com.cloudera.director.aws.ec2.VirtualizationMappings.VirtualizationMappingsConfigProperties.VirtualizationMappingsConfigurationPropertyToken.CUSTOM_MAPPINGS_PATH;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.cloudera.director.aws.common.PropertyResolvers;
import com.cloudera.director.spi.v2.model.ConfigurationProperty;
import com.cloudera.director.spi.v2.model.Configured;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.ChildLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertyResolver;

/**
 * Maps a virtualization type to the instance types that support it. EC2 does
 * not provide a means through the API to discover mappings. This class looks up
 * mappings using a built-in list and an override list that the user can easily
 * modify.
 */
public class VirtualizationMappings implements Function<String, List<String>> {

  private static final Logger LOG = LoggerFactory.getLogger(VirtualizationMappings.class);

  private static final Splitter SPLITTER = Splitter.on(',').trimResults();
  private static final Joiner JOINER = Joiner.on(',');

  public static class VirtualizationMappingsConfigProperties {

    /**
     * Virtualization mappings configuration properties.
     */
    // Fully qualifying class name due to compiler bug
    public enum VirtualizationMappingsConfigurationPropertyToken
        implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {

      /**
       * Path for the custom virtualization mappings file. Relative paths are
       * based on the plugin configuration directory.
       */
      CUSTOM_MAPPINGS_PATH(new SimpleConfigurationPropertyBuilder()
          .configKey("customMappingsPath")
          .name("Custom mappings path")
          .defaultDescription("The path for the custom virtualization mappings file. Relative " +
              "paths are based on the plugin configuration directory.")
          .build());

      /**
       * The configuration property.
       */
      private final ConfigurationProperty configurationProperty;

      /**
       * Creates a configuration property token with the specified parameters.
       *
       * @param configurationProperty the configuration property
       */
      VirtualizationMappingsConfigurationPropertyToken(
          ConfigurationProperty configurationProperty) {
        this.configurationProperty = configurationProperty;
      }

      @Override
      public ConfigurationProperty unwrap() {
        return configurationProperty;
      }
    }

    public static final String DEFAULT_CUSTOM_MAPPINGS_PATH =
        "ec2.virtualizationmappings.properties";

    private final File configurationDirectory;

    private String customMappingsPath = DEFAULT_CUSTOM_MAPPINGS_PATH;

    /**
     * Creates virtualization mappings config properties with the specified parameters.
     *
     * @param configuration            the configuration
     * @param configurationDirectory   the plugin configuration directory
     * @param cloudLocalizationContext the parent cloud localization context
     */
    public VirtualizationMappingsConfigProperties(Configured configuration,
        File configurationDirectory,
        LocalizationContext cloudLocalizationContext) {
      this.configurationDirectory = configurationDirectory;
      LocalizationContext localizationContext = new ChildLocalizationContext(
          cloudLocalizationContext, "virtualizationMappings");
      setCustomMappingsPath(
          configuration.getConfigurationValue(CUSTOM_MAPPINGS_PATH, localizationContext));
    }

    public String getCustomMappingsPath() {
      return customMappingsPath;
    }

    File getCustomMappingsFile() {
      return getCustomMappingsFile(customMappingsPath);
    }

    File getCustomMappingsFile(String customMappingsPath) {
      File customMappingsPathFile = new File(customMappingsPath);
      return customMappingsPathFile.isAbsolute() ?
          customMappingsPathFile :
          new File(configurationDirectory, customMappingsPath);
    }

    public void setCustomMappingsPath(String customMappingsPath) {
      if (customMappingsPath != null) {
        LOG.info("Overriding customMappingsPath=%s (default {})",
            customMappingsPath, DEFAULT_CUSTOM_MAPPINGS_PATH);
        checkArgument(getCustomMappingsFile(customMappingsPath).exists(),
            "Custom virtualization mappings path " +
                customMappingsPath + " does not exist");
        this.customMappingsPath = customMappingsPath;
      }
    }
  }

  public static class VirtualizationMappingsConfig {

    public static final String BUILT_IN_LOCATION =
        "classpath:/com/cloudera/director/aws/ec2/virtualizationmappings.properties";

    protected VirtualizationMappingsConfigProperties
        virtualizationMappingsConfigProperties;

    public PropertyResolver virtualizationMappingsResolver() {
      try {
        return PropertyResolvers.newMultiResourcePropertyResolver(
            BUILT_IN_LOCATION,
            "file:" + virtualizationMappingsConfigProperties.getCustomMappingsFile().getAbsolutePath()
        );
      } catch (IOException e) {
        throw new IllegalArgumentException("Could not load custom virtualization mappings", e);
      }
    }

    /**
     * Creates an virtualization mappings config with the specified parameters.
     *
     * @param virtualizationMappingsConfigProperties the config properties
     */
    public VirtualizationMappingsConfig(
        VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties) {
      this.virtualizationMappingsConfigProperties = virtualizationMappingsConfigProperties;
    }
  }

  VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties;

  PropertyResolver virtualizationMappingsResolver;

  /**
   * Creates virtualization mappings with the specified parameters.
   *
   * @param configuration          the configuration
   * @param configurationDirectory the plugin configuration directory
   * @param localizationContext    the localization context
   */
  public VirtualizationMappings(Configured configuration, File configurationDirectory,
      LocalizationContext localizationContext) {
    this(new VirtualizationMappingsConfigProperties(configuration, configurationDirectory,
        localizationContext));
  }

  /**
   * Creates virtualization mappings with the specified parameters.
   *
   * @param virtualizationMappingsConfigProperties the config properties
   */
  public VirtualizationMappings(VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties) {
    this(virtualizationMappingsConfigProperties, new VirtualizationMappingsConfig(virtualizationMappingsConfigProperties).virtualizationMappingsResolver());
  }

  /**
   * Creates virtualization mappings with the specified parameters.
   *
   * @param virtualizationMappingsConfigProperties the config properties
   * @param virtualizationMappingsResolver         the virtualization mappings resolver
   */
  private VirtualizationMappings(VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties,
      PropertyResolver virtualizationMappingsResolver) {
    this.virtualizationMappingsConfigProperties = virtualizationMappingsConfigProperties;
    this.virtualizationMappingsResolver = virtualizationMappingsResolver;
  }

  /**
   * Gets the instance types that support the given virtualization type.
   *
   * @param virtualizationType virtualization type
   * @return list of instance types
   * @throws IllegalArgumentException if the virtualization type is unknown
   */
  @Nonnull
  public List<String> apply(String virtualizationType) {
    checkNotNull(virtualizationType, "virtualizationType is null");
    String instanceTypeList =
        virtualizationMappingsResolver.getProperty(virtualizationType);
    if (instanceTypeList == null) {
      throw new IllegalArgumentException("Unknown virtualization type " +
          virtualizationType);
    }
    return SPLITTER.splitToList(instanceTypeList);
  }

  /**
   * Gets a test instance of this class that uses only the given mapping.
   *
   * @param instanceTypes       map of virtualization types to instance types
   * @param localizationContext the localization context
   * @return new mapping object
   */
  public static VirtualizationMappings getTestInstance(
      final Map<String, List<String>> instanceTypes, LocalizationContext localizationContext) {
    Map<String, String> propertyMap =
        Maps.transformValues(instanceTypes, JOINER::join);
    PropertyResolver virtualizationMappingsResolver =
        PropertyResolvers.newMapPropertyResolver(propertyMap);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties =
        new VirtualizationMappingsConfigProperties(new SimpleConfiguration(),
            tempDir, localizationContext);
    return new VirtualizationMappings(virtualizationMappingsConfigProperties,
        virtualizationMappingsResolver);
  }
}


text:
drop database if exists site;
create database site;
use site;

/*
 * entities
 */

create table account (
  id bigint not null primary key auto_increment,
  email varchar(250) not null unique,
  display_name varchar(63) not null unique,
  password_hash varchar(128) not null,
  password_salt varchar(31) not null,
  active tinyint(1) not null,
  member bigint null
)ENGINE=InnoDB;

create table comment (
  id bigint not null primary key auto_increment,
  body text not null,
  created datetime not null,
  updated datetime null,
  account bigint not null,
  ticket bigint not null
)ENGINE=InnoDB;

create table member (
  id bigint not null primary key auto_increment,
  email varchar(250) not null unique,
  complete_name varchar(63) not null unique,
  account bigint null
)ENGINE=InnoDB;

create table sector (
  id bigint not null primary key auto_increment,
  email varchar(250) not null unique,
  name varchar(255) not null,
  initial varchar(255) not null unique
)ENGINE=InnoDB;

/*
create table sector (
  id bigint not null primary key auto_increment,
  email varchar(250) not null unique,
  name varchar(255) not null,
  initial varchar(255) not null unique,
  place varchar(255) not null,
  telephone varchar(255) not null
)ENGINE=InnoDB;
*/
create table session (
  id bigint not null primary key auto_increment,
  code varchar(31) not null,
  created datetime not null,
  account bigint not null
)ENGINE=InnoDB;

create table setting (
  id bigint not null primary key auto_increment,
  site_name varchar(63) not null
)ENGINE=InnoDB;

create table ticket (
  id bigint not null primary key auto_increment,
  body text not null,
  created datetime not null,
  updated datetime null,
  account bigint not null
)ENGINE=InnoDB;

/*
 * relations
 */

create table sector_closure (
  ancestor bigint not null,
  descendant bigint not null,
  primary key (ancestor, descendant)
);

create table sector_member (
  member bigint not null,
  sector bigint not null,
  primary key (member, sector)
);

create table ticket_member (
  id bigint not null primary key auto_increment,
  member bigint not null,
  created datetime not null,
  updated datetime null,
  account bigint not null,
  ticket bigint not null
)ENGINE=InnoDB;

create table ticket_sector (
  id bigint not null primary key auto_increment,
  sector bigint not null,
  created datetime not null,
  updated datetime null,
  account bigint not null,
  ticket bigint not null
)ENGINE=InnoDB;

/*
 * foreign keys
 */

alter table account add foreign key (member) references member(id);

alter table comment add foreign key (account) references account(id);
alter table comment add foreign key (ticket) references ticket(id);

alter table member add foreign key (account) references account(id);

alter table session add foreign key (account) references account(id);

alter table ticket add foreign key (account) references account(id);

alter table sector_closure add foreign key (ancestor) references sector(id);
alter table sector_closure add foreign key (descendant) references sector(id);

alter table sector_member add foreign key (member) references member(id);
alter table sector_member add foreign key (sector) references sector(id);

alter table ticket_member add foreign key (member) references member(id);
alter table ticket_member add foreign key (account) references account(id);
alter table ticket_member add foreign key (ticket) references ticket(id);
alter table ticket_member add unique unique_index (member, ticket);

alter table ticket_sector add foreign key (sector) references sector(id);
alter table ticket_sector add foreign key (account) references account(id);
alter table ticket_sector add foreign key (ticket) references ticket(id);
alter table ticket_sector add unique unique_index (sector, ticket);


text:
from __future__ import absolute_import, print_function

import colorsys
import inspect
import itertools
import logging
import math
import platform
import re
from collections import OrderedDict
from datetime import datetime
from functools import partial
from itertools import islice
from time import time
from uuid import uuid1

import numpy
import pandas
import pkg_resources
from cobra.util.context import HistoryManager
from numpy.random import RandomState

logger = logging.getLogger(__name__)

_BIOMASS_RE_ = re.compile("biomass", re.IGNORECASE)

class frozendict(dict):
    def __init__(self, iterable, **kwargs):
        super(frozendict, self).__init__(iterable, **kwargs)

    def popitem(self):
        raise AttributeError("'frozendict' object has no attribute 'popitem")

    def pop(self, k, d=None):
        raise AttributeError("'frozendict' object has no attribute 'pop")

    def __setitem__(self, key, value):
        raise AttributeError("'frozendict' object has no attribute '__setitem__")

    def setdefault(self, k, d=None):
        raise AttributeError("'frozendict' object has no attribute 'setdefault")

    def __delitem__(self, key):
        raise AttributeError("'frozendict' object has no attribute '__delitem__")

    def __hash__(self):
        return hash(tuple(sorted(self.items())))

    def update(self, E=None, **F):
        raise AttributeError("'frozendict' object has no attribute 'update")

def float_ceil(val, decimals=0):
    """
    Like ceil but the number of decimals can be set.

    Equivalent of $$round(val + 1e^{-decimals}/2, decimals)$$

    val: float, numpy.array
        The initial value.
    decimals: int
        The number of decimal places.

    Returns
    -------
    float, numpy.array

    """
    aux = math.pow(10, -decimals) / 2

    return numpy.round(val + aux, decimals)

def float_floor(val, decimals=0):
    """
    Like floor but the number of decimals can be set.

    Equivalent of $$round(val - 1e^{-decimals}/2, decimals)$$

    val: float, numpy.array
        The initial value.
    decimals: int
        The number of decimal places.

    Returns
    -------
    float, numpy.array

    """
    aux = math.pow(10, -decimals) / 2

    return numpy.round(val - aux, decimals)

class ProblemCache(object):
    """
    Variable and constraint cache for models.

    To be used in complex methods that require many extra variables and constraints when one must run
    simulations with the same method many times.

    It allows rollback to the previous state in case one iteration fails to build the problem or
    generates an invalid state.
    """

    def __init__(self, model):
        self.history_manager = None
        self._model = model
        self.variables = {}
        self.constraints = {}
        self.objective = None
        self.original_objective = model.solver.objective
        self._contexts = [HistoryManager()]
        self.transaction_id = None

    def begin_transaction(self):
        """
        Creates a time point. If rollback is called, the variables and constrains will be reverted to this point.
        """
        self._contexts.append(HistoryManager())

    @property
    def model(self):
        return self._model

    def _append_constraint(self, constraint_id, create, *args, **kwargs):
        constraint = self.constraints[constraint_id] = create(self._model, constraint_id, *args, **kwargs)
        assert constraint_id in self.constraints
        self._model.solver.add(constraint)

    def _remove_constraint(self, constraint_id):
        constraint = self.constraints.pop(constraint_id)
        self._model.solver.remove(constraint)

    def _append_variable(self, variable_id, create, *args, **kwargs):
        variable = self.variables[variable_id] = create(self._model, variable_id, *args, **kwargs)
        assert variable_id in self.variables
        self._model.solver.add(variable)

    def _remove_variable(self, variable_id):
        variable = self.variables.pop(variable_id)
        self._model.solver.remove(variable)

    def _rebuild_variable(self, variable):
        (type, lb, ub, name) = variable.type, variable.lb, variable.ub, variable.name

        def rebuild():
            self._model.solver.remove(variable)
            new_variable = self.model.solver.interface.Variable(name, lb=lb, ub=ub, type=type)
            self.variables[name] = variable
            self._model.solver.add(new_variable, sloppy=True)

        return rebuild

    def add_constraint(self, constraint_id, create, update, *args, **kwargs):
        """
        Adds a new cached constraint.

        The create and update functions must have the following signatures:
        >>> create(model, constraint_id, *args)
        >>> update(model, constraint, *args)

        "args" in the first example must match args on the second example.

        Parameters
        ----------
        constraint_id : str
            The identifier of the constraint
        create : function
            A function that creates an optlang.interface.Constraint
        update : function
            a function that updates an optlang.interface.Constraint

        """
        context = self._contexts[-1]

        if constraint_id not in self.constraints:
            self._append_constraint(constraint_id, create, *args, **kwargs)
            context(partial(self._remove_constraint, constraint_id))
        elif update is not None:
            update(self._model, self.constraints[constraint_id], *args, **kwargs)

        assert constraint_id in self.constraints

    def add_variable(self, variable_id, create, update, *args, **kwargs):
        """
        Adds a new cached variable.

        The create and update functions must have the following signatures:
        >>> create(model, variable_id, *args)
        >>> update(model, variable, *args)

        "args" in the first example must match args on the second example.

        Parameters
        ----------
        variable_id : str
            The identifier of the constraint
        create : function
            A function that creates an optlang.interface.Variable
        update : function
            a function that updates an optlang.interface.Variable

        """
        context = self._contexts[-1]
        if variable_id not in self.variables:
            self._append_variable(variable_id, create, *args, **kwargs)
            context(partial(self._remove_variable, variable_id))
        elif update is not None:
            # rebuild_function = self._rebuild_variable(self.variables[variable_id])
            update(self._model, self.variables[variable_id], *args, **kwargs)
            # context(rebuild_function)

        assert variable_id in self.variables

    def add_objective(self, create, update, *args):
        context = self._contexts[-1]
        if self.objective is None:
            previous_objective = self._model.solver.objective
            self.model.solver.objective = self.objective = create(self._model, *args)
            context(partial(setattr, self._model.solver, 'objective', previous_objective))

        elif update:
            previous_objective = self._model.solver.objective
            self.model.solver.objective = self.objective = update(self._model, *args)
            context(partial(setattr, self._model.solver, 'objective', previous_objective))

    def reset(self):
        """
        Removes all constraints and variables from the cache.
        """
        variables = list(self.variables.keys())
        constraints = list(self.constraints.keys())
        while len(self._contexts) > 0:
            manager = self._contexts.pop()
            manager.reset()
        self._contexts.append(HistoryManager())
        assert all(var_id not in self._model.solver.variables for var_id in variables)
        assert all(const_id not in self._model.solver.constraints for const_id in constraints)
        self.variables = {}
        self.constraints = {}
        self._model.objective = self.original_objective
        self.objective = None

    def rollback(self):
        """
        Returns to the previous transaction start point.
        """
        if len(self._contexts) < 2:
            raise RuntimeError("Start transaction must be called before rollback")
        self._contexts.pop().reset()

    def __enter__(self):
        """
        Allows problem cache to be used with a _with_ statement.

        Examples
        --------
        You want to run room/lmoma for every single knockout.
        >>> with ProblemCache(model) as cache:
        >>>     for reaction in reactions:
        >>>         reaction.knock_out()
        >>>         result = lmoma(model, reference=reference, cache=cache)

        Returns
        -------
        ProblemCache
            returns itself
        """
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.reset()

class RandomGenerator(object):
    def __init__(self, seed=None):
        self._random = RandomState(seed=seed)

    def seed(self, seed):
        self._random = RandomState(seed=seed)

    def random(self):
        return self._random.rand()

    def randint(self, a, b=None):
        if b is None:
            b = a
            a = 0
        r = self._random.randint(a, high=b, size=1)
        return r[0]

    def sample(self, population, k):
        if k == 0:
            return []
        return list(self._random.choice(population, size=k, replace=False))

    def __getattr__(self, attr):
        return getattr(self._random, attr)

    def __getstate__(self):
        return {'_random': self._random}

    def __setstate__(self, d):
        self._random = d['_random']

    def uniform(self, low=0.0, high=1.0, size=None):
        return self._random.uniform(low, high, size)

class Singleton(object):
    """
    Singleton class to be extended
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

class AutoVivification(dict):
    """Implementation of perl's autovivification feature. Checkout http://stackoverflow.com/a/652284/280182"""

    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

class TimeMachine(object):
    """Travel back and forth in time."""

    def __init__(self):
        super(TimeMachine, self).__init__()
        self.history = OrderedDict()

    def __call__(self, do=None, undo=None, bookmark=None):
        output = do()
        current_time = time()
        if bookmark is None:
            entry_id = uuid1()
        else:
            entry_id = bookmark
        # make sure that entry is added to the end of history
        self.history.pop(entry_id, None)
        self.history[entry_id] = {'unix_epoch': current_time, 'undo': undo, 'redo': do}
        return entry_id, output

    def __str__(self):
        info = '\n'
        for item in self.history.items():
            info += self._history_item_to_str(item)
        return info

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.reset()

    @staticmethod
    def _history_item_to_str(item):
        info = ''
        uuid, entry = item
        info += datetime.fromtimestamp(entry['unix_epoch']).strftime('%Y-%m-%d %H:%M:%S') + '\n'
        undo_entry = entry['undo']
        try:
            # partial  (if .keywords is None print {} instead)
            elements = undo_entry.func, undo_entry.args, undo_entry.keywords or {}
            info += 'undo: ' + ' '.join([str(elem) for elem in elements]) + '\n'
        except AttributeError:  # normal python function
            info += 'undo: ' + undo_entry.__name__ + '\n'

        redo_entry = entry['redo']
        try:
            elements = redo_entry.func, redo_entry.args, redo_entry.keywords or {}  # partial
            info += 'redo: ' + ' '.join([str(elem) for elem in elements]) + '\n'
        except AttributeError:
            info += 'redo: ' + redo_entry.__name__ + '\n'
        return info

    def undo(self, bookmark=None):
        if bookmark is None:
            try:
                (uuid, entry) = self.history.popitem()
                entry['undo']()
            except KeyError:  # history is empty
                pass
        elif bookmark in list(self.history.keys()):
            uuid = False
            while uuid is not bookmark:
                (uuid, entry) = self.history.popitem()
                entry['undo']()
        else:
            raise Exception(
                'Provided bookmark %s cannot be found in the time machine.')

    def redo(self):
        raise NotImplementedError

    def reset(self):
        if self.history:  # history is not empty
            self.undo(bookmark=list(self.history.keys())[0])

class Timer(object):
    """Taken from http://stackoverflow.com/a/5849861/280182"""

    def __init__(self, name=None):
        self.name = name

    def __enter__(self):
        self.tstart = time()

    def __exit__(self, type, value, traceback):
        if self.name:
            print('[%s]' % self.name, end=' ')
        print('Elapsed: %s' % (time() - self.tstart))

class IntelliContainer(object):
    def __init__(self, **kwargs):
        self._dict = dict(**kwargs)

    def __getattr__(self, value):
        return self._dict.get(value)

    def __setitem__(self, key, value):
        self._dict[key] = value

    def __iter__(self):
        return iter(self._dict.values())

    def __dir__(self):
        return list(self._dict.keys())

def inheritdocstring(name, bases, attrs):
    """Use as metaclass to inherit class and method docstrings from parent.
    Adapted from http://stackoverflow.com/questions/13937500/inherit-a-parent-class-docstring-as-doc-attribute"""
    temp = type('temporaryclass', bases, {})
    if '__doc__' not in attrs or not attrs["__doc__"]:
        # create a temporary 'parent' to (greatly) simplify the MRO search
        for cls in inspect.getmro(temp):
            if cls.__doc__ is not None:
                attrs['__doc__'] = cls.__doc__
                break

    for attr_name, attr in attrs.items():
        if not attr.__doc__:
            for cls in inspect.getmro(temp):
                try:
                    if getattr(cls, attr_name).__doc__ is not None:
                        attr.__doc__ = getattr(cls, attr_name).__doc__
                        break
                except (AttributeError, TypeError):
                    continue

    return type(name, bases, attrs)

def partition_(lst, n):
    """Partition a list into n bite size chunks."""
    division = len(lst) / float(n)
    return [lst[int(round(division * i)): int(round(division * (i + 1)))] for i in range(n)]

def partition(ite, n):
    """Partition an iterable into n bite size chunks."""
    try:
        length = len(ite)
    except TypeError:
        ite = list(ite)
        length = len(ite)
    division = length / float(n)
    iterator = iter(ite)
    return [list(islice(iterator, 0, round(division * (i + 1)) - round(division * i))) for i in range(n)]

def flatten(input_list):
    return [item for sublist in input_list for item in sublist]

def generate_colors(n):
    hsv_tuples = [(v * 1.0 / n, 0.5, 0.5) for v in range(n)]
    color_map = {}
    for i in range(n):
        rgb = colorsys.hsv_to_rgb(*hsv_tuples[i])
        color = tuple(int(channel * 256) for channel in rgb)
        color_map[i] = '#%02x%02x%02x' % color
    return color_map

def memoize(function, memo={}):
    def wrapper(*args):
        if args in memo:
            return memo[args]
        else:
            rv = function(*args)
            memo[args] = rv
            return rv

    return wrapper

def get_system_info():
    package_info = list()
    for dist in pkg_resources.working_set:
        req = str(dist.as_requirement())
        package_info.append(req)
    return dict(package_info=package_info,
                platform=platform.platform(),
                machine=platform.machine(),
                system=platform.system())

def in_ipnb():
    """
    Check if it is running inside an IPython Notebook (updated for new notebooks)
    """
    return pandas.io.formats.console.in_ipython_frontend()

def str_to_valid_variable_name(s):
    """Adapted from http://stackoverflow.com/a/3303361/280182"""

    # Remove invalid characters
    s = re.sub('[^0-9a-zA-Z_]', '_', s)

    # Remove leading characters until we find a letter or underscore
    s = re.sub('^[^a-zA-Z_]+', '', s)

    return s

def zip_repeat(long_iter, short_iter):
    """
    Zips two iterable objects but repeats the second one if it is shorter than the first one.

    Parameters
    ----------
    long_iter: iterable

    short_iter: iterable

    Returns
    -------
    generator
    """
    for i, j in zip(long_iter, itertools.cycle(short_iter)):
        yield i, j

def pick_one(iterable):
    """
    Helper function that returns an element of an iterable (it the iterable is ordered this will be the first
    element).
    """
    it = iter(iterable)
    return next(it)

def reduce_reaction_set(reaction_set, groups):
    """
    Reduces a set of reactions according to a number of groups of reactions.
    The reduction will be performed so that the resulting set will contain no more than 1 reaction from each group.
    Reactions that are not in any of the groups will remain in the set.

    Parameters
    ----------
    reaction_set: Set
    groups: Iterable of sets

    Returns
    -------
    Set
    """
    reaction_set = set(reaction_set)  # Make a shallow copy
    result = []
    for group in groups:
        intersection = group & reaction_set
        if intersection:  # If any elements of group are in reaction_set, add one of these to result
            result.append(pick_one(intersection))
            reaction_set = reaction_set - intersection
    result = set(result) | reaction_set  # Add the remaining reactions to result
    return result

def decompose_reaction_groups(reaction_groups, reactions):
    """

    reaction_groups : list
        A list with dictionaries (element: relative_coefficient)
    reactions : list, set, tuple
        A collection of reactions.

    Returns
    -------
    list
        A list of all possible group substitutions.

    """
    to_keep = []
    to_replace = {}
    for element in reactions:
        for g in reaction_groups:
            if element in g:
                to_replace[element] = g.keys()
                break
        if element not in to_replace:
            to_keep.append(element)

    return (list(combo) + to_keep for combo in itertools.product(*to_replace.values()))

def current_solver_name(model):
    """Give a string representation for an optlang interface.

    Parameters
    ----------
    model : cobra.Model
        A model

    Returns
    -------
    string
       The name of the interface as a string
    """
    interface = model.solver.interface.__name__
    return re.sub(r"optlang.|.interface", "", interface)


text:
/* UMD.define */ (typeof define=="function"&&define||function(d,f,m){m={module:module,require:require};module.exports=f.apply(null,d.map(function(n){return m[n]||require(n)}))})
([], function(){
	"use strict";

	function Parser(grammar, name, index){
		this.reset(grammar, name, index);
	}

	Parser.prototype = {
		reset: function(grammar, name, index){
			this.expected = null;
			this.triedTokens = [];
			this.arrayStack = [grammar[name || "main"]];
			this.indexStack = [index || 0];
		},
		getExpectedState: function(){
			while(this.arrayStack.length){
				var a = this.arrayStack.pop(),
					i = this.indexStack.pop();
				if(i < a.length){
					var value = a[i++];
					this.arrayStack.push(a);
					this.indexStack.push(i);
					return this.expected = value;
				}
				if(a.repeatable){
					this.arrayStack.push(a);
					this.indexStack.push(0);
				}
			}
			return null;
		},
		putToken: function(token, scanner){
			if(token){
				this.arrayStack.push.apply(this.arrayStack, token.nextArray);
				this.indexStack.push.apply(this.indexStack, token.nextIndex);
				if(this.triedTokens.length){
					this.triedTokens = [];
				}
				this.onToken(token);
			}else{
				// no match: save failed tokens
				this.triedTokens.push.apply(this.triedTokens, this.expected.tokens);
				// check optional items
				if(this.expected.optional){
					return;
				}
				var a = this.arrayStack.pop(),
					i = this.indexStack.pop();
				if(a.optional && i === 1){
					return;
				}
				var buffer = scanner.buffer;
				throw Error("Can't find a legal token" +
						(scanner ? " at (" + scanner.line + ", " + scanner.pos + ") in: " +
							(buffer.length > 16 ?
								(Buffer.isBuffer(buffer) ? buffer.toString("utf8", 0, 16) :
									buffer.substring(0, 16)) + "..." :
								buffer.toString()) + "\n" : ".\n") +
						"Tried: " +
						this.triedTokens.map(function(token){
							return "'" + token.id + "'";
						}).join(", ") + ".");
			}
		},
		onToken: function(token){
			//console.log(token.id + " (" + token.line + ", " + token.pos + "): " + token.value);
		}
	};

	return Parser;
});


text:
package org.apache.nifi.web.api.entity;

import com.wordnik.swagger.annotations.ApiModelProperty;
import org.apache.nifi.web.api.dto.ConnectionDTO;
import org.apache.nifi.web.api.dto.PositionDTO;
import org.apache.nifi.web.api.dto.status.ConnectionStatusDTO;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

/**
 * A serialized representation of this class can be placed in the entity body of a response to the API. This particular entity holds a reference to a ConnectionDTO.
 */
@XmlRootElement(name = "connectionEntity")
public class ConnectionEntity extends ComponentEntity implements Permissible<ConnectionDTO> {

    private ConnectionDTO component;
    private ConnectionStatusDTO status;
    private List<PositionDTO> bends;
    private Integer labelIndex;
    private Long zIndex;
    private String sourceId;
    private String sourceGroupId;
    private String sourceType;
    private String destinationId;
    private String destinationGroupId;
    private String destinationType;

    /**
     * @return RelationshipDTO that is being serialized
     */
    public ConnectionDTO getComponent() {
        return component;
    }

    public void setComponent(ConnectionDTO component) {
        this.component = component;
    }

    /**
     * @return the connection status
     */
    @ApiModelProperty(
        value = "The status of the connection."
    )
    public ConnectionStatusDTO getStatus() {
        return status;
    }

    public void setStatus(ConnectionStatusDTO status) {
        this.status = status;
    }

    /**
     * @return position of the bend points on this connection
     */
    @ApiModelProperty(
        value = "The bend points on the connection."
    )
    public List<PositionDTO> getBends() {
        return bends;
    }

    public void setBends(List<PositionDTO> bends) {
        this.bends = bends;
    }

    /**
     * @return The index of control point that the connection label should be placed over
     */
    @ApiModelProperty(
        value = "The index of the bend point where to place the connection label."
    )
    public Integer getLabelIndex() {
        return labelIndex;
    }

    public void setLabelIndex(Integer labelIndex) {
        this.labelIndex = labelIndex;
    }

    /**
     * @return z index for this connection
     */
    @ApiModelProperty(
            value = "The z index of the connection."
    )
    public Long getzIndex() {
        return zIndex;
    }

    public void setzIndex(Long zIndex) {
        this.zIndex = zIndex;
    }

    /**
     * @return The identifier of the source of this connection
     */
    @ApiModelProperty(
        value = "The identifier of the source of this connection."
    )
    public String getSourceId() {
        return sourceId;
    }

    public void setSourceId(String sourceId) {
        this.sourceId = sourceId;
    }

    /**
     * @return The identifier of the destination of this connection
     */
    @ApiModelProperty(
        value = "The identifier of the destination of this connection."
    )
    public String getDestinationId() {
        return destinationId;
    }

    public void setDestinationId(String destinationId) {
        this.destinationId = destinationId;
    }

    /**
     * @return The identifier of the group of the source of this connection
     */
    @ApiModelProperty(
        value = "The identifier of the group of the source of this connection."
    )
    public String getSourceGroupId() {
        return sourceGroupId;
    }

    public void setSourceGroupId(String sourceGroupId) {
        this.sourceGroupId = sourceGroupId;
    }

    /**
     * @return type of this source connectable component
     */
    @ApiModelProperty(
            value = "The type of component the source connectable is.",
            required = true,
            allowableValues = "PROCESSOR, REMOTE_INPUT_PORT, REMOTE_OUTPUT_PORT, INPUT_PORT, OUTPUT_PORT, FUNNEL"
    )
    public String getSourceType() {
        return sourceType;
    }

    public void setSourceType(String sourceType) {
        this.sourceType = sourceType;
    }

    /**
     * @return The identifier of the group of the destination of this connection
     */
    @ApiModelProperty(
        value = "The identifier of the group of the destination of this connection."
    )
    public String getDestinationGroupId() {
        return destinationGroupId;
    }

    public void setDestinationGroupId(String destinationGroupId) {
        this.destinationGroupId = destinationGroupId;
    }

    /**
     * @return type of this destination connectable component
     */
    @ApiModelProperty(
            value = "The type of component the destination connectable is.",
            required = true,
            allowableValues = "PROCESSOR, REMOTE_INPUT_PORT, REMOTE_OUTPUT_PORT, INPUT_PORT, OUTPUT_PORT, FUNNEL"
    )
    public String getDestinationType() {
        return destinationType;
    }

    public void setDestinationType(String destinationType) {
        this.destinationType = destinationType;
    }
}


text:
import random
import logging

from helga.plugins import Plugin

logger = logging.getLogger('plugins.misc')

class MiscPlugin(Plugin):
    """Everything that doesnt fit somewhere else."""

    def register(self):
        self.bot.register_command('yn', self.yn)
        self.bot.register_command('random', self.random)
        self.bot.register_command('test', self.test)
        self.bot.register_command('dice', self.dice)

    def yn(self, msg, *args):
        """Prints 'yes' or 'no'"""
        self.bot.send_reply(msg, random.choice(('Ja', 'Nein')))

    def random(self, msg, *args):
        """Random number generator :smirk:"""
        self.bot.send_reply(msg, "9")

    def test(self, msg, *args):
        self.bot.send_photo(msg.chat.id, photo=open('test.jpg', 'rb'))

    def dice(self, msg, *args):
        """Rolls a dice, format <rolls>d<sides>"""
        if len(args) == 0:
            args = ['1d6']
        try:
            rolls, maxint = map(int, args[0].split('d'))
            if rolls > 30 or maxint > 1000:
                self.bot.send_reply(msg, 'Please use more reasonable values!')
                return
            maxint = int(maxint)

            if rolls > 100 or maxint > 100:
                self.bot.send_reply(msg, "Very funny.")
                return

            results = []
            for roll in range(rolls):
                results.append(str(random.randint(1, maxint)))
            self.bot.send_reply(msg, ' '.join(results))
        except Exception as e:
            self.bot.send_reply(msg, 'An error occurred!')


text:
function Rectangle (width, height) {
  this.width = width
  this.height = height
}

Rectangle.prototype.area = function () {
  return this.width * this.height
}

module.exports = Rectangle


text:
namespace RailDataEngine.ScheduleJob
{
    class Program
    {
        static void Main()
        {
            Schedule.Fetch();
        }
    }
}


text:
package org.todorovdi.oo.osprov.vmware;

import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;

import com.google.gson.*;

import java.net.URL;

import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;

public class VIConnectionManager {
    public static ServiceInstance getServiceInstance(String host, String user, String password, String protocol, String port, String sessionTicket) throws RemoteException, MalformedURLException
    {
        String viURL=protocol+"://"+host+":"+port+"/sdk";
        //Session ID Is provided. Attempt to re-use session.
        if(!((sessionTicket==null)||(sessionTicket.equals("")))){
            try{
                ServiceInstance si = new ServiceInstance(new URL(viURL),sessionTicket,true);
                String currentTime=si.currentTime().toString();
                return si;
            //If not authenticated or session is expired try to re-authenticate.
            }catch(NotAuthenticated e){
                try{
                    ServiceInstance si = new ServiceInstance(new URL(viURL),user,password,true);
                    String currentTime2=si.currentTime().toString();
                    return si;
                }catch(Exception ee){
                    throw new RemoteException("Error during VI Connection "+e);
                }
            }
        //No Session ID Found. Authenticate a new session.
        }else{
            try{
                ServiceInstance si = new ServiceInstance(new URL(viURL),user,password,true);
                String currentTime2=si.currentTime().toString();
                return si;
            }catch(Exception ee){
                throw new RemoteException("Error during VI Connection "+ee);
            }
        }

    }

    //Not fully implemented yet.
    public static String endVIServiceSession(ServiceInstance si, String closeSession)
    {
        String viSessionToken="";
        try{
            if(closeSession.equals("true")){
                si.getSessionManager().logout();
                viSessionToken="";
            }else{
                String sessionToken = si.getServerConnection().getSessionStr();
                viSessionToken=sessionToken;
            }
        }catch(Exception e){
            viSessionToken="";
            return viSessionToken;
        }
        return viSessionToken;
    }
}


text:
import fields from './fields';

function resultArrayToObject(fieldResults) {
  return fieldResults.reduce((accumulator, value) => Object.assign({}, accumulator, value), {});
}

function inferredOptions(oldOptions, fieldResults) {
  const newOptions = resultArrayToObject(fieldResults);
  return Object.assign({}, oldOptions, newOptions);
}

// Takes the options object and infers new values
// which may need async work
export default function (options) {
  const tasks = fields(options);
  return Promise.all(tasks)
    .then(fieldResults => inferredOptions(options, fieldResults));
}


text:
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Features.Consensus;
using Stratis.Bitcoin.Features.RPC.Controllers;

namespace Stratis.Bitcoin.Features.RPC
{
    public class RPCFeature : FullNodeFeature
    {
        private readonly FullNode fullNode;

        private readonly NodeSettings nodeSettings;

        private readonly ILogger logger;

        private readonly IFullNodeBuilder fullNodeBuilder;

        private readonly RpcSettings rpcSettings;

        public RPCFeature(IFullNodeBuilder fullNodeBuilder, FullNode fullNode, NodeSettings nodeSettings, ILoggerFactory loggerFactory, RpcSettings rpcSettings)
        {
            this.fullNodeBuilder = fullNodeBuilder;
            this.fullNode = fullNode;
            this.nodeSettings = nodeSettings;
            this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
            this.rpcSettings = rpcSettings;
        }

        /// <summary>
        /// Prints command-line help.
        /// </summary>
        /// <param name="network">The network to extract values from.</param>
        public static void PrintHelp(Network network)
        {
            RpcSettings.PrintHelp(network);
        }

        /// <summary>
        /// Get the default configuration.
        /// </summary>
        /// <param name="builder">The string builder to add the settings to.</param>
        /// <param name="network">The network to base the defaults off.</param>
        public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
        {
            builder.AppendLine("####RPC Settings####");
            builder.AppendLine("#Activate RPC Server (default: 0)");
            builder.AppendLine("#server=0");
            builder.AppendLine("#Where the RPC Server binds (default: 127.0.0.1 and ::1)");
            builder.AppendLine("#rpcbind=127.0.0.1");
            builder.AppendLine("#Ip address allowed to connect to RPC (default all: 0.0.0.0 and ::)");
            builder.AppendLine("#rpcallowip=127.0.0.1");
            builder.AppendLine("#Adjust RPC Content Type (default: application/json; charset=utf-8)");
            builder.AppendLine("#rpccontenttype=application/json; charset=utf-8");
        }

        public override Task InitializeAsync()
        {
            if (this.rpcSettings.Server)
            {
                // TODO: The web host wants to create IServiceProvider, so build (but not start)
                // earlier, if you want to use dependency injection elsewhere
                this.fullNode.RPCHost = new WebHostBuilder()
                .UseKestrel()
                .ForFullNode(this.fullNode)
                .UseUrls(this.rpcSettings.GetUrls())
                .UseIISIntegration()
                .ConfigureServices(collection =>
                {
                    if (this.fullNodeBuilder != null && this.fullNodeBuilder.Services != null && this.fullNode != null)
                    {
                        // copies all the services defined for the full node to the Api.
                        // also copies over singleton instances already defined
                        foreach (ServiceDescriptor service in this.fullNodeBuilder.Services)
                        {
                            // open types can't be singletons
                            if (service.ServiceType.IsGenericType || service.Lifetime == ServiceLifetime.Scoped)
                            {
                                collection.Add(service);
                                continue;
                            }

                            object obj = this.fullNode.Services.ServiceProvider.GetService(service.ServiceType);

                            if (obj != null && service.Lifetime == ServiceLifetime.Singleton && service.ImplementationInstance == null)
                            {
                                collection.AddSingleton(service.ServiceType, obj);
                            }
                            else
                            {
                                collection.Add(service);
                            }
                        }
                    }
                })
                .UseStartup<Startup>()
                .Build();

                this.fullNode.RPCHost.Start();
                this.logger.LogInformation("RPC Server listening on: " + Environment.NewLine + string.Join(Environment.NewLine, this.rpcSettings.GetUrls()));
            }
            else
            {
                this.logger.LogInformation("RPC Server is off based on configuration.");
            }

            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// A class providing extension methods for <see cref="IFullNodeBuilder"/>.
    /// </summary>
    public static class FullNodeBuilderRPCExtension
    {
        public static IFullNodeBuilder AddRPC(this IFullNodeBuilder fullNodeBuilder)
        {
            LoggingConfiguration.RegisterFeatureNamespace<RPCFeature>("rpc");

            fullNodeBuilder.ConfigureFeature(features =>
            {
                features
                .AddFeature<RPCFeature>()
                .DependOn<ConsensusFeature>()
                .FeatureServices(services => services.AddSingleton(fullNodeBuilder));
            });

            fullNodeBuilder.ConfigureServices(service =>
            {
                service.AddSingleton<RpcSettings>();
                service.AddSingleton<IRPCClientFactory, RPCClientFactory>();
            });

            return fullNodeBuilder;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
V-Index
</TITLE>

<META NAME="date" CONTENT="2011-04-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C E F G H I J N P Q R S T V

V

valueOf(String) -
Static method in enum com.meltingice.caman.PluginType

Returns the enum constant of this type with the specified name.

values() -
Static method in enum com.meltingice.caman.PluginType

Returns an array containing the constants of this enum type, in
the order they are declared.

Vibrance - Class in com.meltingice.caman.filters
Adjusts the vibrance of the colors in the image.
Vibrance() -
Constructor for class com.meltingice.caman.filters.Vibrance

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C E F G H I J N P Q R S T V