text:
/**
 * WireHarp.java
 *
 * @author Christopher K. Allen
 * @since  Jan 9, 2013
 *
 */

package xal.smf.impl;

import xal.ca.Channel;
import xal.ca.ChannelFactory;
import xal.ca.ConnectionException;
import xal.ca.GetException;
import xal.ca.PutException;
import xal.tools.data.DataAdaptor;
import xal.smf.NoSuchChannelException;
import xal.smf.impl.profile.ASignal;
import xal.smf.impl.profile.ASignalAttrs;
import xal.smf.impl.profile.ParameterSet;
import xal.smf.impl.profile.ProfileDevice;
import xal.smf.impl.profile.Signal;
import xal.smf.impl.profile.SignalAttrSet;
import xal.smf.impl.profile.SignalSet;
import xal.smf.impl.qualify.ElementTypeManager;
import xal.smf.scada.AScada;
import xal.smf.scada.BadStructException;
import xal.smf.scada.ScadaAnnotationException;
import xal.smf.scada.ScadaFieldMap;
import xal.smf.scada.ScadaRecord;

/**
 *
Wire Harp Hardware

 *

 * Represents a harp diagnostic device, in particular
 * such a device installed at the SNS facility.  The harp has
 * fixed, physical (carbon) wires used to measure the profile of
 * the particle beam.  This class implements the device API.
 *

 *
NOTES:

 *

 * · There is a pretty egregious kluge on the attribute
 * DaqConfig.cntWires.  The value is hard coded with the constant
 * DaqConfig.CNT_WIRES since there is no way to dynamically
 * acquire this value.
 *

 *
 *

 * Ported from XAL on Jul 15, 2014.

 * · Jonathan M. Freed
 *

 *
 * @author Christopher K. Allen
 * @since   Jan 9, 2013
 */
public class WireHarp extends ProfileDevice {

    /*
     * Enumeration Constants for Common Values
     */

    /**
     *
Wire Scanner Commands

     *

     * The commands below represent the possible values for the first argument
     * in the command array.  It provides the
     * command type while additional arguments provide
     * the command parameters.
     *

     *
     * @since  Aug 21, 2009
     * @author Christopher K. Allen
     */
    public enum CMD {

        /**  No operation */
        NOOP(0),

        /** Take a new baseline measurement */
        BASELINE(7),

        /** The secret command */
        SECRET(9);

        /** Command-issuing handle */
        public static final String HANDLE_CMD = "Command"; //$NON-NLS-1$

        /** command result handle */
        public static final String HANDLE_RESULT = "CommandResult"; //$NON-NLS-1$

        /**
         * Returns the integer-value device command associated with the command enumeration
         * constant.
         *
         * @return      device command for constant
         *
         * @since  Aug 21, 2009
         * @author Christopher K. Allen
         */
        public int getCode() {
            return this.intCmd;
        }

        /*
         * Private Stuff
         */

        /** device API command value */
        private final int       intCmd;

        /**
         * Create a new CMD constant
         * with the given device command.
         *
         * @param intCmd        device command for constant
         *
         * @since     Aug 21, 2009
         * @author    Christopher K. Allen
         */
        private CMD(int intCmd) {
            this.intCmd = intCmd;
        }
    }

    /*
     * Configuration and Status Structures
     */

    /**
     * Contains device status parameters.
     *
     * @author Christopher K. Allen
     * @since  Mar 20, 2014
     */
    public static class DevStatus extends ParameterSet {

        /*
         * Global Attributes
         */

        /** Map of field names to field SCADA descriptors for this structure */
        public final static ScadaFieldMap   FLD_MAP = new ScadaFieldMap(DevStatus.class);

        /**
         * Convenience method for retrieving a new initialized data structure
         * populated from the given device state.
         *
         * @param smfHarp    data acquisition device
         *
         * @return current set of device status parameters
         *
         * @throws ConnectionException  unable to connect parameter read back channel
         * @throws GetException         general field initialization exception
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public static DevStatus acquire(WireHarp smfHarp)
                throws ConnectionException, GetException
        {
            return new DevStatus(smfHarp);
        }

        //        /*
        //         * DataAdaptor Interface
        //         */
        //
        //        /**
        //         * Returns the name of this class as the data label
        //         *
        //         * @see xal.tools.data.DataListener#dataLabel()
        //         *
        //         * @author Christopher K. Allen
        //         * @since  Mar 20, 2014
        //         */
        //        @Override
        //        public String dataLabel() {
        //            return this.getClass().getCanonicalName();
        //        }
        //

        /*
         * Status Parameters
         */

        /**
         * Alarm flag for wire signal; it indicates correct operations.
         *

         *

         *  status: 0=OK, 1=Saturated
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatDevStatus"
                )
        public int      statDev;

        /**
         * Machine Protection System status flag
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatMpsStatus"
                )
        public int      statMps;

        /**
         * Manual control status indicator
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatCtrlStatus"
                )
        public int      statCtrl;

        /**
         * Flag indicating harp is inserted
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatHarpInsert"
                )
        public int      hrpIns;

        /**
         * Flag indicating harp is retracted
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatHarpRetract"
                )
        public  int     hrpRetr;

        /**
         * Flag indicating harp is stopped
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatHarpStop"
                )
        public  int     hrpStop;

        /**
         * Result code of the latest harp user command.
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatCmdResult"
                )
        public int      cmdResult;

        /**
         * Create a new DevStatus object.
         *
         * @since     Jan 21, 2010
         * @author    Christopher K. Allen
         */
        public DevStatus() {
            super();
        }

        /**
         * Create a new DevStatus object containing the status
         * information of the given device.
         *
         * @param smfHarp    wire harp device under query
         *
         * @throws ConnectionException  unable to connect parameter read back channel
         * @throws GetException         general field initialization exception
         *
         * @since     Jan 21, 2010
         * @author    Christopher K. Allen
         */
        public DevStatus(WireHarp smfHarp) throws ConnectionException, GetException {
            super(smfHarp);
        }
    }

    /**
     * Class WireHarp.DaqConfig.  A data structure containing fields
     * that indicate the status of the data acquisition capabilities.  In particular,
     * there are status records for the operation of each wire within each
     * measurement plane (eg., horizontal, vertical, diagonal).
     *

     *
NOTE

     *

     * · There is a pretty egregious kluge on the attribute
     * DaqConfig.cntWires.  The value is hard coded with the constant
     * DaqConfig.CNT_WIRES since there is no way to dynamically
     * acquire this value.
     *
     * @author Christopher K. Allen
     * @since  Apr 11, 2014
     */
    public static class DaqConfig extends ParameterSet implements IProfileDomain {

        /*
         * Global Attributes
         */

        /** Map of field names to field SCADA descriptors for this structure */
        public final static ScadaFieldMap   FLD_MAP = new ScadaFieldMap(DaqConfig.class);

        /**
         * Convenience method for retrieving a new initialized data structure
         * populated from the given device state.
         *
         * @param smfHarp    data acquisition device
         *
         * @return current set of device status parameters
         *
         * @throws ConnectionException  unable to connect parameter read back channel
         * @throws GetException         general field initialization exception
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public static DaqConfig acquire(WireHarp smfHarp)
                throws ConnectionException, GetException
                {
            return new DaqConfig(smfHarp);
                }

        /*
         * Status Parameters
         */

        /**
         * The number of wires within the harp.
         *

         *

         * April, 2014: Currently this value must be provided externally as it is not available
         * via the control system.
         */
        //        @AScada.Field(
        //                type = int.class,
        //                ctrl = false,
        //                hndRb = ""
        //                )
        public int      cntWires = CNT_WIRES;

        /**
         * Array of wire positions on the beam axis for the horizontal projection plane.
         */
        @AScada.Field(
                type = double[].class,
                ctrl = false,
                hndRb = "DatHorRawPositions"
                )
        public double[] arrPosHor;

        /**
         * Array of wire positions on the beam axis for the vertical projection plane.
         */
        @AScada.Field(
                type = double[].class,
                ctrl = false,
                hndRb = "DatVerRawPositions"
                )
        public double[] arrPosVer;

        /**
         * Array of wire positions on the beam axis for the diagonal projection plane.
         */
        @AScada.Field(
                type = double[].class,
                ctrl = false,
                hndRb = "DatDiaRawPositions"
                )
        public double[] arrPosDia;

        /**
         * Bit record indicating operation status for each wire of the
         * horizontal wire set.
         *

         *     bolStatus = 2n & statWireHor
         *

         * where n=0,1,... is the index of the wire.
         *

         * Do Not access this field directly!
         */
        @AScada.Field(
                type  = int.class,
                ctrl  = false,
                hndRb = "StatRecHorWires"
                )
        public int     recWiresHor;

        /**
         * Bit record indicating operation status for each wire
         * of the vertical wire set.
         *

         *     bolStatus = 2n & statWireVer
         *

         * where n=0,1,... is the index of the wire.
         *

         * Do Not access this field directly!
         */
        @AScada.Field(
                type  = long.class,
                ctrl  = false,
                hndRb = "StatRecVerWires"
                )
        public int     recWiresVer;

        /**
         * Bit record indicating operation status for each wire
         * of the diagonal wire set.
         *

         *     bolStatus = 2n & statWireDia
         *

         * where n=0,1,... is the index of the wire.
         *

         * Do Not access this field directly!
         */
        @AScada.Field(
                type  = int.class,
                ctrl  = false,
                hndRb = "StatRecDiaWires"
                )
        public int     recWiresDia;

        /**
         * Type code of the current fitting profile
         *
0 = Super Gaussian
         *
1 = Super Gaussian × Gaussian
         *
2 = Super Gaussian + Gaussian
         *
3 = Super Gaussian × Parabola
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = false,
                hndRb   = "StatFitType"
                )
        public int      fitTypeCode;

        /*
         * Initialization
         */

        /**
         * Create a new, uninitialized DaqConfig object.
         *
         * @since     Jan 21, 2010
         * @author    Christopher K. Allen
         */
        public DaqConfig() {
            super();
        }

        /**
         * Create a new DaqConfig object containing the status
         * information of the given device.
         *
         * @param smfHarp    wire harp device under query
         *
         * @throws ConnectionException  unable to connect parameter read back channel
         * @throws GetException         general field initialization exception
         *
         * @since     Jan 21, 2010
         * @author    Christopher K. Allen
         */
        public DaqConfig(WireHarp smfHarp) throws ConnectionException, GetException {
            super(smfHarp);
        }

        /*
         * Operations
         */

        /**
         * Returns the number of valid harp wires for the given projection
         * plane.
         *
         * @param ang   projection angle for the harp
         *
         * @return      number of wires producing valid data for the given harp
         *
         * @author Christopher K. Allen
         * @since  Jun 5, 2014
         */
        public int  validWireCount(ANGLE ang) {
            boolean[]   arrValWire = this.validWires(ang);

            int     cntValWires = 0;
            for (boolean bolFlag : arrValWire)
                if (bolFlag)
                    cntValWires++;

            return cntValWires;
        }

        /**
         * Check if the indicated wire is valid, that is, producing valid data.  The given wire
         * index must be in the range [0,N] where N is the number of wires
         * in the harp.
         *
         * @param ang       the transverse plane of the profile (i.e., wire set)
         * @param index     the index of the wire within the harp
         *
         * @return          true if the indicated wire is working correctly,
         *                  false otherwise
         *
         * @throws IllegalArgumentException the index provided was not in the correct range
         *
         * @author Christopher K. Allen
         * @since  Apr 14, 2014
         */
        public boolean  validWire(ANGLE ang, int index) throws IllegalArgumentException {

            // Check for proper index values
            if (index < 0)
                throw new IllegalArgumentException("Index must be non-negative");

            if (index >= this.cntWires)
                throw new IllegalArgumentException("Index must be less than number of wires");

            // Create mask for given wire index
            int         intMask = 1 << index;
            boolean     bolValid;   // result of validity check

            switch (ang) {

            case HOR:
                bolValid = (intMask & this.recWiresHor) > 0;
                break;

            case VER:
                bolValid = (intMask & this.recWiresVer) > 0;
                break;

            case DIA:
                bolValid = (intMask & this.recWiresDia) > 0;
                break;

            default:
                bolValid = false;
                break;
            }

            return bolValid;
        }

        /**
         * Creates an array of status flags for each harp wire for the given transverse
         * plane.  The array size equals the number of wires in the harp (cntWires),
         * the index into the array is the index of the harp wire.
         *
         * @param ang   transverse plane of the profile
         *
         * @return      array containing status flags indexed by harp wire
         *
         * @author Christopher K. Allen
         * @since  Apr 14, 2014
         */
        public boolean[] validWires(ANGLE ang) {

            // Get the status record for the desired profile plane
            long    lngStatRec; // status record for the desired transverse plane

            switch (ang) {
            case HOR:
                lngStatRec = this.recWiresHor;
                break;
            case VER:
                lngStatRec = this.recWiresVer;
                break;
            case DIA:
                lngStatRec = this.recWiresDia;
                break;
            default:
                lngStatRec = 0;
                break;
            }

            // Allocate the returned array and initialize loop
            boolean[]   arrValid = new boolean[this.cntWires];
            int         intMask  = 1;

            for (int index=0; index<this.cntWires; index++) {
                arrValid[index] = (intMask & lngStatRec) > 0;
                intMask <<= 1;
            }

            return arrValid;
        }

        /*
         * IProfileDomain Interface
         */

        /**
         *
         * @see xal.smf.impl.profile.ProfileDevice.IProfileDomain#getSampleCount(xal.smf.impl.profile.ProfileDevice.ANGLE)
         *
         * @author Christopher K. Allen
         * @since  Apr 24, 2014
         */
        @Override
        public int getSampleCount(ANGLE angle) {
            return this.cntWires;
        }

        /**
         * Returns the array of sampling positions for the profile data
         *
         * @author Christopher K. Allen
         * @since  Apr 24, 2014
         *
         * @see xal.smf.impl.profile.ProfileDevice.IProfileDomain#getSamplePositions(xal.smf.impl.profile.ProfileDevice.ANGLE)
         */
        @Override
        public double[] getSamplePositions(ANGLE angle) {

            switch (angle) {
            case HOR: return this.arrPosHor;
            case VER: return this.arrPosVer;
            case DIA: return this.arrPosDia;
            default: return null;
            }
        }

        /**
         *
         * @see xal.smf.impl.profile.ProfileDevice.IProfileDomain#getInitialPosition(xal.smf.impl.profile.ProfileDevice.ANGLE)
         *
         * @author Christopher K. Allen
         * @since  Apr 24, 2014
         */
        @Override
        public double getInitialPosition(ANGLE angle) {

            double[]    arrPos = this.getSamplePositions(angle);

            return arrPos[0];
        }

        /**
         *
         * @see xal.smf.impl.profile.ProfileDevice.IProfileDomain#getIntervalLength(xal.smf.impl.profile.ProfileDevice.ANGLE)
         *
         * @author Christopher K. Allen
         * @since  Apr 24, 2014
         */
        @Override
        public double getIntervalLength(ANGLE angle) {
            int         indMax = this.getSampleCount(angle) - 1;
            double[]    arrPos = this.getSamplePositions(angle);
            double      posMax = arrPos[indMax];
            double      dblLen = posMax - this.getInitialPosition(angle);

            return dblLen;
        }
    }

    /**
     * Data structure containing the configuration parameters for
     * a WireHarp device. The data structure is active
     * and can be used to set the configuration parameters as well.
     *
     * @author Christopher K. Allen
     * @since  Mar 20, 2014
     */
    public static class DevConfig extends ParameterSet {

        /**
         * Returns the defined set of configuration parameters currently
         * used for the given device.
         *
         * @param smfHarp   profile device being queried
         *
         * @return          current configuration for the given device
         *
         * @throws ConnectionException  unable to connect to a parameter read back channel
         * @throws GetException         general channel access get exception
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public static DevConfig acquire(WireHarp smfHarp) throws ConnectionException, GetException
        {
            return new DevConfig(smfHarp);
        }

        /*
         * DataListener Interface
         */

        /**
         * Returns the class name as the DataAdaptor
         * data label.
         *
         * @see xal.tools.data.DataListener#dataLabel()
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        @Override
        public String dataLabel() {
            return this.getClass().getCanonicalName();
        }

        /*
         * SCADA Fields
         */

        /**
         * The (discrete) common amplifier gain for all profile channels.
         *

         *     Range = {0, 1, 2}
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = true,
                hndRb   = "CfgGainCmnRb",
                hndSet  = "CfgGainCmnSet"
                )
        public int      gainCmn;

        //        /**
        //         * The (discrete) amplifier gain for for the horizontal profile
        //         * channel.
        //         *

        //         *     Range = {0, 1, 2}
        //         */
        //        @AScada.Field(
        //                type    = int.class,
        //                ctrl    = true,
        //                hndRb   = "CfgGainHorRb",
        //                hndSet  = "CfgGainHorSet"
        //                )
        //        public int      gainHor;
        //
        //        /**
        //         * The (discrete) amplifier gain for for the vertical profile
        //         * channel.
        //         *

        //         *     Range = {0, 1, 2}
        //         */
        //        @AScada.Field(
        //                type    = int.class,
        //                ctrl    = true,
        //                hndRb   = "CfgGainVerRb",
        //                hndSet  = "CfgGainVerSet"
        //                )
        //        public int      gainVer;
        //
        //        /**
        //         * The (discrete) amplifier gain for for the diagonal profile
        //         * channel.
        //         *

        //         *     Range = {0, 1, 2}
        //         */
        //        @AScada.Field(
        //                type    = int.class,
        //                ctrl    = true,
        //                hndRb   = "CfgGainDiaRb",
        //                hndSet  = "CfgGainDiaSet"
        //                )
        //        public int      gainDia;

        /**
         * The triggering delay, I think it is in micro-seconds.
         * This is the delay between the trigger event and the actual
         * data acquisition.
         */
        @AScada.Field(
                type    = double.class,
                ctrl    = true,
                hndRb   = "CfgTrgDelayRb",
                hndSet  = "CfgTrgDelaySet"
                )
        public double   trgDelay;

        /**
         * Triggering event type code.
         *
         * @see TRGEVT
         */
        @AScada.Field(
                type    = int.class,
                ctrl    = true,
                hndRb   = "CfgTrgEventRb",
                hndSet  = "CfgTrgEventSet"
                )
        public int      trgEvent;

        /*
         * Initialization
         */

        /**
         * Create a new, uninitialized DevConfig object.
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public DevConfig() {
            super();
        }

        /**
         * Create a new DevConfig object initialized
         * from the given data source.
         *
         * @param daptSrc       data source containing data structure fields
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public DevConfig(DataAdaptor daptSrc) {
            super(daptSrc);
        }

        /**
         * Create a new ActrConfig object initialize
         * with values fetched from the given device.
         *
         * @param smHarp    data acquisition device
         *
         * @throws ConnectionException  unable to connect to a parameter channel
         * @throws GetException         unable to retrieve values from channel access
         *
         * @author Christopher K. Allen
         * @since  Mar 20, 2014
         */
        public DevConfig(WireHarp smHarp) throws ConnectionException, GetException {
            super(smHarp);
        }

        /*
         * Operations
         */

        /**
         * Set the gain as a GAIN
         * enumeration.
         *
         * @param gain  new gain value
         *
         * @since  Dec 23, 2009
         * @author Christopher K. Allen
         */
        public void setGain(GAIN gain) {
            this.gainCmn = gain.getGainValue();
        }

        /**
         * Return the gain as a GAIN
         * enumeration.
         *
         * @return      current gain value
         *
         * @since  Dec 23, 2009
         * @author Christopher K. Allen
         */
        public GAIN getGain() {
            return GAIN.getGainFromValue(this.gainCmn);
        }

        /**
         * Sets the trigger event code by converting the given
         * TRGEVT enumeration constant to the correct
         * code and assigning the value to the trigger event
         * field in this data structure.
         *
         * @param evt       enumeration for the desired trigger event code
         *
         * @author Christopher K. Allen
         * @since  Mar 21, 2014
         *
         * @see DevConfig#trgEvent
         */
        public void setTriggerEvent(TRGEVT evt) {
            this.trgEvent = evt.getEventValue();
        }

        /**
         * Converts the trigger event code to the corresponding
         * TRGEVT enumeration constant and returns it.
         *
         * @return  the TRGEVT constant for the current
         *          trigger event code
         *
         * @author Christopher K. Allen
         * @since  Mar 21, 2014
         *
         * @see DevConfig#trgEvent
         */
        public TRGEVT getTriggerEvent() {
            return TRGEVT.getEventFromValue(trgEvent);
        }
    }

    /*
     * Processed Signal Attributes
     */

    /**
     * Data structure containing the profile signal characteristics.
     * I believe the signal is processed by assuming a Gaussian profile.
     *
     * @author Christopher K. Allen
     * @since  Mar 19, 2014
     */
    @ASignalAttrs.ASet(
            attrHor = @ASignalAttrs( hndAmpRb = "FitAttrHorAmp", hndAreaRb = "FitAttrHorArea", hndMeanRb = "FitAttrHorMean", hndOffsetRb = "FitAttrHorOffset", hndStdevRb = FitAttrSet.X_RMS_HANDLE),
            attrVer = @ASignalAttrs( hndAmpRb = "FitAttrVerAmp", hndAreaRb = "FitAttrVerArea", hndMeanRb = "FitAttrVerMean", hndOffsetRb = "FitAttrVerOffset", hndStdevRb = FitAttrSet.Y_RMS_HANDLE),
            attrDia = @ASignalAttrs( hndAmpRb = "FitAttrDiaAmp", hndAreaRb = "FitAttrDiaArea", hndMeanRb = "FitAttrDiaMean", hndOffsetRb = "FitAttrDiaOffset", hndStdevRb = "FitAttrDiaStd")
            )
    public static class FitAttrSet extends SignalAttrSet {
		/** handle to the X RMS PV */
		public static final String X_RMS_HANDLE = "FitAttrHorStd";

		/** handle to the Y RMS PV */
		public static final String Y_RMS_HANDLE = "FitAttrVerStd";

        /**
         * Convenience method for retrieving a new, initialized data
         * structure populated from the current given device state.
         *
         * @param smfHarp   data acquisition device
         *
         * @return          data structure containing the current
         *                  state of the given hardware device
         *
         * @throws NoSuchChannelException unable to find channel for given handle
         * @throws ConnectionException  unable to connect to a field's channel
         * @throws GetException         general CA GET exception while fetch field value
         *
         * @author Christopher K. Allen
         * @since  Mar 19, 2014
         */
        public static FitAttrSet    aquire(WireHarp smfHarp)
                throws NoSuchChannelException, ConnectionException, GetException
        {
            return new FitAttrSet(smfHarp);
        }

        /*
         * Initialization
         */

        /**
         * Constructor for FitAttrSet, creates a new, uninitialized
         * FitAttrSet abject.
         *
         *
         * @author Christopher K. Allen
         * @since  Mar 19, 2014
         */
        public FitAttrSet() {
            super();
        }

        /**
         * Constructor for FitAttrSet. Create a new FitAttrSet
         * object initialized from the given data source.
         *
         * @param daptSrc   persistent data store containing initializing
         *                  data field values
         *
         * @author Christopher K. Allen
         * @since  Mar 19, 2014
         */
        public FitAttrSet(DataAdaptor daptSrc) {
            this();
            this.update(daptSrc);
        }

        /**
         * Constructor for FitAttrSet.
         *
         * @param wharp
         * @throws ConnectionException
         * @throws GetException
         *
         * @author Christopher K. Allen
         * @since  Mar 19, 2014
         */
        private FitAttrSet(WireHarp wharp) throws ConnectionException, GetException {
            super(wharp);
        }
    }

    /**
     *

     * Structure for maintaining a WireHarp profile data
     * measurement.  Each instance of
     * this data structure contains a snapshot of the beam profile provided by the
     * wire harp and acquired through the SCADA mechanism of {@link ScadaRecord}.
     *

     *

     * The data structure is derived from the SignalSet
     * base class which does all the work.
     * The data from each plane is available through the attributes of type
     * {@link WireHarp.Signal} in the WireHarp.SignalSet base class.
     * The data acquisition channels are identified with
     * the annotation {@link ASignalSet} which tells the base class how to
     * connect the {@link WireHarp.Signal} attributes.
     *

     *
     * @author Christopher K. Allen
     * @since  Feb 5, 2013
     *
     * @see SignalSet
     * @see ScadaRecord
     */
    @ASignal.ASet(
            sigHor = @ASignal(hndPosRb = "DatHorRawPositions", hndValRb = "DatHorRawSignal" ),
            sigVer = @ASignal(hndPosRb = "DatVerRawPositions", hndValRb = "DatVerRawSignal" ),
            sigDia = @ASignal(hndPosRb = "DatDiaRawPositions", hndValRb = "DatDiaRawSignal" )
            )
    static public class DataRaw extends SignalSet {

        /*
         * Global Operations
         */

        /**
         * Convenience method for retrieving a new, initialized measurement set
         * acquired from the given device.
         *
         * @param smfHarp   measurement device
         *
         * @return          newly acquired data set from the given device
         *
         * @throws ConnectionException          unable to connect data read back channel
         * @throws GetException                 general CA GET exception while fetch field value
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws BadStructException          the DAQ data structure and DAQ channels are incompatible, bad definition
         *
         *
         * @since  Nov 14, 2009
         * @author Christopher K. Allen
         */
        public static DataRaw  aquire(WireHarp smfHarp)
                throws ConnectionException, GetException, ScadaAnnotationException, BadStructException
        {
            return new DataRaw(smfHarp);
        }

        /*
         * Initialization
         */

        /**
         * Creates a new, empty instance of Measurement.
         *
         * @throws ScadaAnnotationException this class is not annotated with ASignal.ASet,
         *                                  or the annotation is corrupt
         *
         * @author Christopher K. Allen
         * @since  Feb 5, 2013
         */
        public DataRaw() throws ScadaAnnotationException {
            super();

            WireHarp.klugeTheSampleCount(this);
        }

        /**
         * Creates a new instance of DataRaw initialized with the data provided by the
         * given data source.
         *
         * @param daSrc     measurement data source presenting DataAdaptor interface
         *
         * @throws IllegalAccessException       if an underlying Signal field is inaccessible.
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws IllegalArgumentException     general field incompatibility exception
         *
         * @author Christopher K. Allen
         * @since  Feb 12, 2013
         */
        public DataRaw(DataAdaptor daSrc) throws IllegalArgumentException, IllegalAccessException {
            super(daSrc);

            WireHarp.klugeTheSampleCount(this);
        }

        /**
         * Creates a new instance of DataRaw and initializes the signal values
         * by acquiring data from the given device.
         *
         * @param smfHarp        data acquisition device
         *
         * @throws BadStructException          the DAQ data structure and DAQ channels are incompatible, bad definition
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws ConnectionException          unable to connect to a parameter read back channel
         * @throws GetException                 general CA GET exception while fetch field value
         *
         * @author Christopher K. Allen
         * @since  Feb 12, 2013
         */
        public DataRaw(WireHarp smfHarp) throws ConnectionException, GetException, ScadaAnnotationException, BadStructException  {
            super(smfHarp);

//            DaqConfig   cfgDaq = DaqConfig.acquire(smfHarp);
            WireHarp.klugeTheSampleCount(this);
//            WireHarp.cleanTheDataSet(this, cfgDaq);
        }
    }

    /**
     *

     * Structure for maintaining a WireHarp profile data
     * fits.  The instances of this data structure contains the fits to the
     * current profile data as computed by the harp device controller.  The fit
     * data is acquired in the same manner as the actual measurement data, specifically
     * through the SCADA mechanism of {@link ScadaRecord}.
     *

     *

     * The data structure is derived from the SignalSet
     * base class which does all the work.
     * The fit data for each plane is available through the attributes of type
     * {@link Signal} in the WireHarp.SignalSet base class.
     * The PV channels for the fit data are identified with
     * the annotation {@link ASignalSet} which tells the base class how to
     * connect the {@link Signal} attributes.
     *

     *
     * @author Christopher K. Allen
     * @since  Feb 13, 2013
     *
     */
    @ASignal.ASet(
            sigHor = @ASignal(hndPosRb = "DatHorFitPositions", hndValRb = "DatHorFitSignal" ),
            sigVer = @ASignal(hndPosRb = "DatVerFitPositions", hndValRb = "DatVerFitSignal" ),
            sigDia = @ASignal(hndPosRb = "DatDiaFitPositions", hndValRb = "DatDiaFitSignal" )
            )
    public static class DataFit extends SignalSet {

        /*
         * Global Operations
         */

        /**
         * Convenience method for retrieving a new, initialized measurement set
         * acquired from the given device.
         *
         * @param smfHarp   measurement device
         *
         * @return          newly acquired data set from the given device
         *
         * @throws ConnectionException          unable to connect data read back channel
         * @throws GetException                 general CA GET exception while fetch field value
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws BadStructException          the DAQ data structure and DAQ channels are incompatible, bad definition
         *
         *
         * @since  Nov 14, 2009
         * @author Christopher K. Allen
         */
        public static DataFit   aquire(WireHarp smfHarp)
                throws ConnectionException, GetException, ScadaAnnotationException, BadStructException
        {
            return new DataFit(smfHarp);
        }

        /**
         * Creates a new, empty instance of DataFit.
         *
         * @throws ScadaAnnotationException this class is not annotated with ASignal.ASet,
         *                                  or the annotation is corrupt
         *
         * @author Christopher K. Allen
         * @since  Feb 12, 2013
         */
        public DataFit() throws ScadaAnnotationException {
            super();

            WireHarp.klugeTheSampleCount(this);
        }

        /**
         * Creates a new instance of DataFit initialized with the data provided by the
         * given data source.
         *
         * @param daSrc     measurement data source presenting DataAdaptor interface
         *
         * @throws IllegalAccessException       if an underlying Signal field is inaccessible.
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws IllegalArgumentException     general field incompatibility exception
         *
         * @author Christopher K. Allen
         * @since  Feb 12, 2013
         */
        public DataFit(DataAdaptor daSrc) throws IllegalArgumentException,
        IllegalAccessException {
            super(daSrc);

            WireHarp.klugeTheSampleCount(this);
        }

        /**
         * Creates a new instance of DataFit and initializes the signal values
         * by acquiring data from the given device.
         *
         * @param smfHarp        data acquisition device
         *
         * @throws BadStructException          the DAQ data structure and DAQ channels are incompatible, bad definition
         * @throws ScadaAnnotationException     the ADaqProfile annotations are incomplete
         * @throws ConnectionException          unable to connect to a parameter read back channel
         * @throws GetException                 general CA GET exception while fetch field value
         *
         * @author Christopher K. Allen
         * @since  Feb 12, 2013
         */
        public DataFit(WireHarp smfHarp) throws ScadaAnnotationException,
        ConnectionException, GetException, BadStructException
        {
            super(smfHarp);

//            DaqConfig cfgDaq = DaqConfig.acquire(smfHarp);

            WireHarp.klugeTheSampleCount(this);
//            WireHarp.cleanTheDataSet(this, cfgDaq);
        }
    }

    /**************************
     *
     * WireHarp Class
     *
     */

    /*
     * Global Constants
     */

    /** The type code for this hardware device */
    public static final String      STR_TYPE_ID = "Harp";

    /** software type for the WireHarp class */
    static final public String      SOFTWARE_TYPE = "Version 2.0.0";

    /** Hardware type for the WireHarp class */
    static final public String      HARDWARE_TYPE = "wireharp";

    /** Kluge - Number of wires on current SNS harps */
    public final static int             CNT_WIRES = 30;

    /*
     * Global Operations
     */

    /**
     * Sets sample size attribute for each signal in the
     * set to the static value {@link #CNT_WIRES}.  The
     * obvious kluge for the fact that there is no dynamic way to get
     * this number.
     *
     * @param setSigs   the set of Signal objects to be modified
     *
     * @author Christopher K. Allen
     * @since  Jun 5, 2014
     */
    private static void klugeTheSampleCount(SignalSet setSigs) {

        setSigs.hor.cnt = CNT_WIRES;
        setSigs.ver.cnt = CNT_WIRES;
        setSigs.dia.cnt = CNT_WIRES;
    }

    /**
     * This methods processes the given data set removing samples from
     * invalid wires.  These wires are identified in the DAQ structure
     * provided in the arguments. The given signal set is modified so that
     * the Signal objects within have new Signal#pos
     * and Signal#val objects.
     *
     * @param setSigs       the set of signals to be processed and modified
     * @param cfgDaq        data structure containing the valid wire info
     *
     * @author Christopher K. Allen
     * @since  Jun 5, 2014
     *
     * @deprecated  I don't want to throw this away but I don't want anyone
     *              using it yet either.
     */
    @Deprecated
    private static void cleanTheDataSet(SignalSet setSigs, DaqConfig cfgDaq) {

        for (ANGLE angle : ANGLE.values()) {
            int                 cntWires = cfgDaq.getSampleCount(angle);
            int                 cntValid = cfgDaq.validWireCount(angle);

            double[]            arrPos = new double[cntValid];
            double[]            arrVal = new double[cntValid];
            Signal              sigAng = setSigs.getSignal(angle);
            int                 indVld = 0;
            for (int indSmp=0; indSmp<cntWires; indSmp++) {
                if ( !cfgDaq.validWire(angle, indSmp) )
                    continue;

                arrPos[indVld] = sigAng.pos[indSmp];
                arrVal[indVld] = sigAng.val[indSmp];
                indVld++;
            }

            sigAng.cnt = cntValid;
            sigAng.pos = arrPos;
            sigAng.val = arrVal;
        }
    }

    /*
     * SMF Requirements
     */

    /**
     * Register the hardware device types that this class
     * recognizes.
     */
    static {
		ElementTypeManager.defaultManager().registerTypes( WireHarp.class, STR_TYPE_ID, HARDWARE_TYPE );
    }

    /*
     * Initialization
     */

	/**
	 * Primary Constructor
	 * @param strId unique identifier of this node
	 * @param channelFactory factory for generating channels for this node
	 */
	public WireHarp( final String strId, final ChannelFactory channelFactory ) {
		super( strId, channelFactory );
	}

    /**
     * Creates a new instance of WireHarp.
     *
     * @param strId
     *
     * @author Christopher K. Allen
     * @since  Feb 13, 2013
     */
    public WireHarp( final String strId ) {
        this( strId, null );
    }

    /*
     * Node Properties
     */

    /**
     * Get the device type
     *
     * @return  The type identifier of this class
     */
    @Override
    public String getType()  {
        return STR_TYPE_ID;
    }

    /**
     * Derived class may furnish a unique software type
     *
     * @return     the "software type" or the driver version
     *              for the hardware.
     */
    @Override
    public String getSoftType() {
        return SOFTWARE_TYPE;
    }

    /*
     * Operations
     */

    /**
     * Issue a wire scanner command with no arguments.
     *
     * @param cmd       wire scanner command
     *
     * @throws ConnectionException      unable to find channel
     * @throws PutException             unable to set channel value
     * @throws InterruptedException     command buffer reset thread interrupted
     */
    public synchronized void runCommand(final CMD cmd) throws  ConnectionException, PutException, InterruptedException
    {
        // Issue command
        Channel channel = getAndConnectChannel( CMD.HANDLE_CMD );
        channel.putVal( cmd.getCode() );

        //        // Reset the on-board command buffer to avoid the IOC echo (a kluge)
        //        Thread.sleep(INT_CMD_LATCY);
        //        channel.putVal( CMD.NOOP.getCode() );
    }

    /**
     * Returns the command result code(s).  These are integer valued
     * codes for the result of a previous issued device command.  See
     * the wire scanner documentation to interpret the particular
     * resultant code.
     *
     * @return command result   array of integer codes for a command result.
     *
     * @throws ConnectionException Unable to connect to result readback channel
     * @throws GetException        Unable to read result from readback channel
     */
    public int[] getCommandResult() throws ConnectionException, GetException {
        final Channel channel = getAndConnectChannel( CMD.HANDLE_RESULT );

        return channel.getArrInt();
    }

}


text:
package org.jenkinsmvn.jenkins.api.http;

import org.apache.commons.lang.Validate;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

/**
 * Abstract response processing
 */
public abstract class AbstractResponseHttpInvoker<T> extends AbstractHttpInvoker{

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

    protected HttpEntity responseEntity;

    public AbstractResponseHttpInvoker(HttpClient client, HttpContext context, HttpHost targetHost, ObjectMapper mapper) {
        super(client, context, targetHost, mapper, true);
    }

    public AbstractResponseHttpInvoker(HttpClient client, HttpContext context, HttpHost targetHost, ObjectMapper mapper, boolean getMethod) {
        super(client, context, targetHost, mapper, getMethod);
    }

    protected abstract T doOnResponse() throws IOException;

    public T execute(String path) throws IOException {
        Validate.notNull(path, "path argument should not be null.");

        LOG.info(String.format("Retrieving for uri '%s'.", path));

        HttpRequest request = createHttpRequest(path);

        try {
            HttpResponse response = client.execute(targetHost, request, context);
            StatusLine status = response.getStatusLine();

            if(status.getStatusCode() != HttpStatus.SC_OK) {
                throw new IllegalStateException("Error retrieving object. Status: " + status.toString());
            }

            responseEntity = response.getEntity();

            String contentType = responseEntity.getContentType().getValue().toLowerCase();

            LOG.info(String.format("Received Content-Type: %s", contentType));

            return doOnResponse();
        } finally {
            EntityUtils.consume(responseEntity);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as fs from 'fs';
import * as path from 'path';

import "mocha";
import * as chai from "chai";

import { TestHost } from "../common/testHost";
import * as util from "../common/testUtils";

// uses the same test cases as the blocks decompiler tests
const decompilerCases = path.join(process.cwd(), "tests", "decompile-test", "cases");
const decompilerBaselines = path.join(process.cwd(), "tests", "pydecompile-test", "decompiler-baselines");
const pydecompilerCases = path.join(process.cwd(), "tests", "pydecompile-test", "cases");
const pydecompilerBaselines = path.join(process.cwd(), "tests", "pydecompile-test", "baselines");

const testBlocksDir = path.relative(process.cwd(), path.join("tests", "decompile-test", "cases", "testBlocks"));

function initGlobals() {
    let g = global as any
    g.pxt = pxt;
    g.ts = ts;
    g.pxtc = pxtc;
    g.btoa = (str: string) => Buffer.from(str, "binary").toString("base64");
    g.atob = (str: string) => Buffer.from(str, "base64").toString("binary");
}

initGlobals();

// Just needs to exist
pxt.setAppTarget(util.testAppTarget);

// TODO: deduplicate this code with decompilerrunner.ts
describe("pydecompiler", () => {
    let decompilerBaselineFiles = util.getFilesByExt(decompilerBaselines, ".py")
    decompilerBaselineFiles = decompilerBaselineFiles.filter(f => f.indexOf(".local.py") === -1);

    decompilerBaselineFiles.forEach(filename => {
        it("should decompile " + path.basename(filename), () => {
            return testDecompilerBaselineAsync(filename);
        });
    });

    let filenames = util.getFilesByExt(pydecompilerCases, ".ts")

    filenames.forEach(filename => {
        it("should decompile " + path.basename(filename), () => {
            return pydecompileTestAsync(filename);
        });
    });
});

function fail(msg: string) {
    chai.assert(false, msg);
}

function testDecompilerBaselineAsync(baselineFile: string) {
    const basename = path.basename(baselineFile);
    const filename = path.join(decompilerCases, util.replaceFileExtension(basename, ".ts"))

    return pydecompileTestCoreAsync(filename, baselineFile);
}

function pydecompileTestAsync(caseFile: string) {
    const basename = path.basename(caseFile);
    const baselineFile = path.join(pydecompilerBaselines, util.replaceFileExtension(basename, ".py"))

    return pydecompileTestCoreAsync(caseFile, baselineFile);
}

function pydecompileTestCoreAsync(tsFilename: string, baselineFile: string) {
    return new Promise<void>((resolve, reject) => {
        const basename = path.basename(baselineFile);

        let baselineExists: boolean;
        try {
            const stats = fs.statSync(baselineFile)
            baselineExists = stats.isFile()
        }
        catch (e) {
            baselineExists = false
        }

        const tsMainRaw = fs.readFileSync(tsFilename, "utf8").replace(/\r\n/g, "\n");
        const [tsMain, compareOpts] = util.getAndStripComparisonOptions(tsMainRaw, false)

        return util.ts2pyAsync(tsMain, testBlocksDir, false, tsFilename)
            .then(decompiled => {
                const outFile = path.join(util.replaceFileExtension(baselineFile, ".local.py"));

                if (!baselineExists) {
                    fs.writeFileSync(outFile, decompiled)
                    fail(`no baseline found for ${basename}, output written to ${outFile}`);
                    return;
                }

                const baseline = fs.readFileSync(baselineFile, "utf8")

                if (!util.compareBaselines(decompiled, baseline, compareOpts)) {
                    fs.writeFileSync(outFile, decompiled)
                    fail(`${basename} did not match baseline, output written to ${outFile}`);
                }
            }, error => {
                const outFile = path.join(util.replaceFileExtension(baselineFile, ".local.py"));
                fs.writeFileSync(outFile, error.stack)
                fail("Could not decompile: " + error.stack)
            })
            .then(() => resolve(), reject);
    });
}


text:
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"os"
	"runtime"
	"syscall"

	"github.com/appc/cni/pkg/ip"
	"github.com/appc/cni/pkg/ipam"
	"github.com/appc/cni/pkg/ns"
	"github.com/appc/cni/pkg/skel"
	"github.com/appc/cni/pkg/types"
	"github.com/vishvananda/netlink"
)

const defaultBrName = "cni0"

type NetConf struct {
	types.NetConf
	BrName string `json:"bridge"`
	IsGW   bool   `json:"isGateway"`
	IPMasq bool   `json:"ipMasq"`
	MTU    int    `json:"mtu"`
}

func init() {
	// this ensures that main runs only on main thread (thread group leader).
	// since namespace ops (unshare, setns) are done for a single thread, we
	// must ensure that the goroutine does not jump from OS thread to thread
	runtime.LockOSThread()
}

func loadNetConf(bytes []byte) (*NetConf, error) {
	n := &NetConf{
		BrName: defaultBrName,
	}
	if err := json.Unmarshal(bytes, n); err != nil {
		return nil, fmt.Errorf("failed to load netconf: %v", err)
	}
	return n, nil
}

func ensureBridgeAddr(br *netlink.Bridge, ipn *net.IPNet) error {
	addrs, err := netlink.AddrList(br, syscall.AF_INET)
	if err != nil && err != syscall.ENOENT {
		return fmt.Errorf("could not get list of IP addresses: %v", err)
	}

	// if there're no addresses on the bridge, it's ok -- we'll add one
	if len(addrs) > 0 {
		ipnStr := ipn.String()
		for _, a := range addrs {
			// string comp is actually easiest for doing IPNet comps
			if a.IPNet.String() == ipnStr {
				return nil
			}
		}
		return fmt.Errorf("%q already has an IP address different from %v", br.Name, ipn.String())
	}

	addr := &netlink.Addr{IPNet: ipn, Label: ""}
	if err := netlink.AddrAdd(br, addr); err != nil {
		return fmt.Errorf("could not add IP address to %q: %v", br.Name, err)
	}
	return nil
}

func bridgeByName(name string) (*netlink.Bridge, error) {
	l, err := netlink.LinkByName(name)
	if err != nil {
		return nil, fmt.Errorf("could not lookup %q: %v", name, err)
	}
	br, ok := l.(*netlink.Bridge)
	if !ok {
		return nil, fmt.Errorf("%q already exists but is not a bridge", name)
	}
	return br, nil
}

func ensureBridge(brName string, mtu int) (*netlink.Bridge, error) {
	br := &netlink.Bridge{
		LinkAttrs: netlink.LinkAttrs{
			Name: brName,
			MTU:  mtu,
		},
	}

	if err := netlink.LinkAdd(br); err != nil {
		if err != syscall.EEXIST {
			return nil, fmt.Errorf("could not add %q: %v", brName, err)
		}

		// it's ok if the device already exists as long as config is similar
		br, err = bridgeByName(brName)
		if err != nil {
			return nil, err
		}
	}

	if err := netlink.LinkSetUp(br); err != nil {
		return nil, err
	}

	return br, nil
}

func setupVeth(netns string, br *netlink.Bridge, ifName string, mtu int) error {
	var hostVethName string

	err := ns.WithNetNSPath(netns, false, func(hostNS *os.File) error {
		// create the veth pair in the container and move host end into host netns
		hostVeth, _, err := ip.SetupVeth(ifName, mtu, hostNS)
		if err != nil {
			return err
		}

		hostVethName = hostVeth.Attrs().Name
		return nil
	})
	if err != nil {
		return err
	}

	// need to lookup hostVeth again as its index has changed during ns move
	hostVeth, err := netlink.LinkByName(hostVethName)
	if err != nil {
		return fmt.Errorf("failed to lookup %q: %v", hostVethName, err)
	}

	// connect host veth end to the bridge
	if err = netlink.LinkSetMaster(hostVeth, br); err != nil {
		return fmt.Errorf("failed to connect %q to bridge %v: %v", hostVethName, br.Attrs().Name, err)
	}

	return nil
}

func calcGatewayIP(ipn *net.IPNet) net.IP {
	nid := ipn.IP.Mask(ipn.Mask)
	return ip.NextIP(nid)
}

func setupBridge(n *NetConf) (*netlink.Bridge, error) {
	// create bridge if necessary
	br, err := ensureBridge(n.BrName, n.MTU)
	if err != nil {
		return nil, fmt.Errorf("failed to create bridge %q: %v", n.BrName, err)
	}

	return br, nil
}

func cmdAdd(args *skel.CmdArgs) error {
	n, err := loadNetConf(args.StdinData)
	if err != nil {
		return err
	}

	br, err := setupBridge(n)
	if err != nil {
		return err
	}

	if err = setupVeth(args.Netns, br, args.IfName, n.MTU); err != nil {
		return err
	}

	// run the IPAM plugin and get back the config to apply
	result, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
	if err != nil {
		return err
	}

	if result.IP4 == nil {
		return errors.New("IPAM plugin returned missing IPv4 config")
	}

	if result.IP4.Gateway == nil && n.IsGW {
		result.IP4.Gateway = calcGatewayIP(&result.IP4.IP)
	}

	err = ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
		return ipam.ConfigureIface(args.IfName, result)
	})
	if err != nil {
		return err
	}

	if n.IsGW {
		gwn := &net.IPNet{
			IP:   result.IP4.Gateway,
			Mask: result.IP4.IP.Mask,
		}

		if err = ensureBridgeAddr(br, gwn); err != nil {
			return err
		}

		if err := ip.EnableIP4Forward(); err != nil {
			return fmt.Errorf("failed to enable forwarding: %v", err)
		}
	}

	if n.IPMasq {
		chain := "CNI-" + n.Name
		if err = ip.SetupIPMasq(ip.Network(&result.IP4.IP), chain); err != nil {
			return err
		}
	}

	return result.Print()
}

func cmdDel(args *skel.CmdArgs) error {
	n, err := loadNetConf(args.StdinData)
	if err != nil {
		return err
	}

	err = ipam.ExecDel(n.IPAM.Type, args.StdinData)
	if err != nil {
		return err
	}

	return ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
		return ip.DelLinkByName(args.IfName)
	})
}

func main() {
	skel.PluginMain(cmdAdd, cmdDel)
}


text:
Integradores de Aplicaciones CLOUD AWS

              Hemos integrado con Éxito aplicaciones AWS en varias empresas, brindandoles todos los beneficios
              que provee AWS CLOUD, tanto para PYMES o empresas de escala mayor, implementando aplicaciones en la nube
              utilizando servidores y utilitarios propios de AWS.


text:
#pragma once

#include <folly/Conv.h>
#include <folly/CppAttributes.h>
#include <folly/Range.h>
#include <folly/Synchronized.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include <folly/experimental/logging/LogName.h>

namespace folly {

class LogCategory;
enum class LogLevel : uint32_t;

/**
 * LoggerDB stores the set of LogCategory objects.
 */
class LoggerDB {
 public:
  /**
   * Get the main LoggerDB singleton.
   */
  static LoggerDB* get();

  /**
   * Get the LogCategory for the specified name.
   *
   * This creates the LogCategory for the specified name if it does not exist
   * already.
   */
  LogCategory* getCategory(folly::StringPiece name);

  /**
   * Get the LogCategory for the specified name, if it already exists.
   *
   * This returns nullptr if no LogCategory has been created yet for the
   * specified name.
   */
  LogCategory* FOLLY_NULLABLE getCategoryOrNull(folly::StringPiece name);

  /**
   * Set the log level for the specified category.
   *
   * Messages logged to a specific log category will be ignored unless the
   * message log level is greater than the LogCategory's effective log level.
   *
   * If inherit is true, LogCategory's effective log level is the minimum of
   * its level and it's parent category's effective log level.  If inherit is
   * false, the LogCategory's effective log level is simply its log level.
   * (Setting inherit to false is necessary if you want a child LogCategory to
   * use a less verbose level than its parent categories.)
   */
  void setLevel(folly::StringPiece name, LogLevel level, bool inherit = true);
  void setLevel(LogCategory* category, LogLevel level, bool inherit = true);

  /**
   * Apply a configuration string specifying a series a log levels.
   *
   * The string format is a comma separated list of <name>=<level> sections.
   * e.g.: "foo=DBG3,log.bar=WARN"
   *
   * Returns a list of error messages for each error encountered trying to
   * parse the config string.  The return value will be an empty vector if no
   * errors were encountered.
   */
  std::vector<std::string> processConfigString(folly::StringPiece config);

  /**
   * Remove all registered LogHandlers on all LogCategory objects.
   *
   * This is called on the main LoggerDB object during shutdown.
   */
  void cleanupHandlers();

  /**
   * Call flush() on all LogHandler objects registered on any LogCategory in
   * this LoggerDB.
   *
   * Returns the number of registered LogHandlers.
   */
  size_t flushAllHandlers();

  /**
   * Initialize the LogCategory* and std::atomic<LogLevel> used by an XLOG()
   * statement.
   *
   * Returns the current effective LogLevel of the category.
   */
  LogLevel xlogInit(
      folly::StringPiece categoryName,
      std::atomic<LogLevel>* xlogCategoryLevel,
      LogCategory** xlogCategory);
  LogCategory* xlogInitCategory(
      folly::StringPiece categoryName,
      LogCategory** xlogCategory,
      std::atomic<bool>* isInitialized);

  enum TestConstructorArg { TESTING };

  /**
   * Construct a LoggerDB for testing purposes.
   *
   * Most callers should not need this function, and should use
   * LoggerDB::get() to obtain the main LoggerDB singleton.  This function
   * exists mainly to allow testing LoggerDB objects in unit tests.
   * It requires an explicit argument just to prevent callers from calling it
   * unintentionally.
   */
  explicit LoggerDB(TestConstructorArg);

  /**
   * internalWarning() is used to report a problem when something goes wrong
   * internally in the logging library.
   *
   * We can't log these messages through the normal logging flow since logging
   * itself has failed.
   *
   * Example scenarios where this is used:
   * - We fail to write to a log file (for instance, when the disk is full)
   * - A LogHandler throws an unexpected exception
   */
  template <typename... Args>
  static void internalWarning(
      folly::StringPiece file,
      int lineNumber,
      Args&&... args) noexcept {
    internalWarningImpl(
        file, lineNumber, folly::to<std::string>(std::forward<Args>(args)...));
  }

  using InternalWarningHandler =
      void (*)(folly::StringPiece file, int lineNumber, std::string&&);

  /**
   * Set a function to be called when the logging library generates an internal
   * warning.
   *
   * The supplied handler should never throw exceptions.
   *
   * If a null handler is supplied, the default built-in handler will be used.
   *
   * The default handler reports the message with _CrtDbgReport(_CRT_WARN) on
   * Windows, and prints the message to stderr on other platforms.  It also
   * rate limits messages if they are arriving too quickly.
   */
  static void setInternalWarningHandler(InternalWarningHandler handler);

 private:
  using LoggerNameMap = std::unordered_map<
      folly::StringPiece,
      std::unique_ptr<LogCategory>,
      LogName::Hash,
      LogName::Equals>;

  // Forbidden copy constructor and assignment operator
  LoggerDB(LoggerDB const&) = delete;
  LoggerDB& operator=(LoggerDB const&) = delete;

  LoggerDB();
  LogCategory* getOrCreateCategoryLocked(
      LoggerNameMap& loggersByName,
      folly::StringPiece name);
  LogCategory* createCategoryLocked(
      LoggerNameMap& loggersByName,
      folly::StringPiece name,
      LogCategory* parent);

  static void internalWarningImpl(
      folly::StringPiece filename,
      int lineNumber,
      std::string&& msg) noexcept;
  static void defaultInternalWarningImpl(
      folly::StringPiece filename,
      int lineNumber,
      std::string&& msg) noexcept;

  /**
   * A map of LogCategory objects by name.
   *
   * Lookups can be performed using arbitrary StringPiece values that do not
   * have to be in canonical form.
   */
  folly::Synchronized<LoggerNameMap> loggersByName_;

  static std::atomic<InternalWarningHandler> warningHandler_;
};
} // namespace folly


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Tavern</title>

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="images/android-desktop.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Material Design Lite">
    <link rel="apple-touch-icon-precomposed" href="images/ios-desktop.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="images/favicon.png">

  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
  <link rel="stylesheet" href="styles/main.css">

<button id="signin" class="mdl-button mdl-js-button mdl-button--raised">
  Sign In
</button>
	<button id="signout" class="mdl-button mdl-js-button mdl-button--raised">
  Sign Out
</button>

    <button class="mdl-button mdl-js-button mdl-button--raised" data-filter=".fun">
        Filter fun
    </button>
     <button class="mdl-button mdl-js-button mdl-button--raised" data-filter=".edu">
        Filter edu
    </button>

    <button class="mdl-button mdl-js-button mdl-button--raised" data-sort="name">
       Sort Name
    </button>
     <button class="mdl-button mdl-js-button mdl-button--raised" data-sort="number">
        Sort Num
    </button>

              play_circle_filled

                Read our features

            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="btn1">
              more_vert
            </button>

Lorem

Ipsum

Dolor

Details

Lorem ipsum dolor sit amet

                  Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis proident minim.

Lorem ipsum dolor sit amet

                  Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis proident minim.

Lorem ipsum dolor sit amet

                  Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis proident minim.

                Read our features

            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="btn2">
              more_vert
            </button>

Lorem

Ipsum

Dolor

Technology

                Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Nostrud in laboris labore nisi amet do dolor eu fugiat consectetur elit cillum esse. Pariatur occaecat nisi laboris tempor laboris eiusmod qui id Lorem esse commodo in. Exercitation aute dolore deserunt culpa consequat elit labore incididunt elit anim.

                Read our features

            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="btn3">
              more_vert
            </button>

Lorem

Ipsum

Dolor

Lorem ipsum dolor sit amet

              Qui sint ut et qui nisi cupidatat. Reprehenderit nostrud proident officia exercitation anim et pariatur ex.

Lorem ipsum dolor sit amet

              Qui sint ut et qui nisi cupidatat. Reprehenderit nostrud proident officia exercitation anim et pariatur ex.


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

				<select id="files">

				<option value="file0">sort/search (100.0%)</option>

				<option value="file1">sort/sort.go (98.3%)</option>

				</select>

				not tracked

				not covered
				covered

// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements binary search.

package sort

// Search uses binary search to find and return the smallest index i
// in [0, n) at which f(i) is true, assuming that on the range [0, n),
// f(i) == true implies f(i+1) == true.  That is, Search requires that
// f is false for some (possibly empty) prefix of the input range [0, n)
// and then true for the (possibly empty) remainder; Search returns
// the first true index.  If there is no such index, Search returns n.
// (Note that the "not found" return value is not -1 as in, for instance,
// strings.Index).
// Search calls f(i) only for i in the range [0, n).
//
// A common use of Search is to find the index i for a value x in
// a sorted, indexable data structure such as an array or slice.
// In this case, the argument f, typically a closure, captures the value
// to be searched for, and how the data structure is indexed and
// ordered.
//
// For instance, given a slice data sorted in ascending order,
// the call Search(len(data), func(i int) bool { return data[i] >= 23 })
// returns the smallest index i such that data[i] >= 23.  If the caller
// wants to find whether 23 is in the slice, it must test data[i] == 23
// separately.
//
// Searching data sorted in descending order would use the <=
// operator instead of the >= operator.
//
// To complete the example above, the following code tries to find the value
// x in an integer slice data sorted in ascending order:
//
//        x := 23
//        i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
//        if i < len(data) && data[i] == x {
//                // x is present at data[i]
//        } else {
//                // x is not present in data,
//                // but i is the index where it would be inserted.
//        }
//
// As a more whimsical example, this program guesses your number:
//
//        func GuessingGame() {
//                var s string
//                fmt.Printf("Pick an integer from 0 to 100.\n")
//                answer := sort.Search(100, func(i int) bool {
//                        fmt.Printf("Is your number <= %d? ", i)
//                        fmt.Scanf("%s", &s)
//                        return s != "" && s[0] == 'y'
//                })
//                fmt.Printf("Your number is %d.\n", answer)
//        }
//
func Search(n int, f func(int) bool) int {
        // Define f(-1) == false and f(n) == true.
        // Invariant: f(i-1) == false, f(j) == true.
        i, j := 0, n
        for i < j {
                h := i + (j-i)/2 // avoid overflow when computing h
                // i ≤ h < j
                if !f(h) {
                        i = h + 1 // preserves f(i-1) == false
                } else {
                        j = h // preserves f(j) == true
                }
        }
        // i == j, f(i-1) == false, and f(j) (= f(i)) == true  =>  answer is i.
        return i
}

// Convenience wrappers for common cases.

// SearchInts searches for x in a sorted slice of ints and returns the index
// as specified by Search. The return value is the index to insert x if x is
// not present (it could be len(a)).
// The slice must be sorted in ascending order.
//
func SearchInts(a []int, x int) int {
        return Search(len(a), func(i int) bool { return a[i] >= x })
}

// SearchFloat64s searches for x in a sorted slice of float64s and returns the index
// as specified by Search.  The return value is the index to insert x if x is not
// present (it could be len(a)).
// The slice must be sorted in ascending order.
//
func SearchFloat64s(a []float64, x float64) int {
        return Search(len(a), func(i int) bool { return a[i] >= x })
}

// SearchStrings searches for x in a sorted slice of strings and returns the index
// as specified by Search.  The return value is the index to insert x if x is not
// present (it could be len(a)).
// The slice must be sorted in ascending order.
//
func SearchStrings(a []string, x string) int {
        return Search(len(a), func(i int) bool { return a[i] >= x })
}

// Search returns the result of applying SearchInts to the receiver and x.
func (p IntSlice) Search(x int) int { return SearchInts(p, x) }

// Search returns the result of applying SearchFloat64s to the receiver and x.
func (p Float64Slice) Search(x float64) int { return SearchFloat64s(p, x) }

// Search returns the result of applying SearchStrings to the receiver and x.
func (p StringSlice) Search(x string) int { return SearchStrings(p, x) }

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package sort provides primitives for sorting slices and user-defined
// collections.
package sort

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package.  The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
        // Len is the number of elements in the collection.
        Len() int
        // Less reports whether the element with
        // index i should sort before the element with index j.
        Less(i, j int) bool
        // Swap swaps the elements with indexes i and j.
        Swap(i, j int)
}

func min(a, b int) int {
        if a < b {
                return a
        }
        return b
}

// Insertion sort
func insertionSort(data Interface, a, b int) {
        for i := a + 1; i < b; i++ {
                for j := i; j > a && data.Less(j, j-1); j-- {
                        data.Swap(j, j-1)
                }
        }
}

// siftDown implements the heap property on data[lo, hi).
// first is an offset into the array where the root of the heap lies.
func siftDown(data Interface, lo, hi, first int) {
        root := lo
        for {
                child := 2*root + 1
                if child >= hi {
                        break
                }
                if child+1 < hi && data.Less(first+child, first+child+1) {
                        child++
                }
                if !data.Less(first+root, first+child) {
                        return
                }
                data.Swap(first+root, first+child)
                root = child
        }
}

func heapSort(data Interface, a, b int) {
        first := a
        lo := 0
        hi := b - a

        // Build heap with greatest element at top.
        for i := (hi - 1) / 2; i >= 0; i-- {
                siftDown(data, i, hi, first)
        }

        // Pop elements, largest first, into end of data.
        for i := hi - 1; i >= 0; i-- {
                data.Swap(first, first+i)
                siftDown(data, lo, i, first)
        }
}

// Quicksort, following Bentley and McIlroy,
// ``Engineering a Sort Function,'' SP&E November 1993.

// medianOfThree moves the median of the three values data[a], data[b], data[c] into data[a].
func medianOfThree(data Interface, a, b, c int) {
        m0 := b
        m1 := a
        m2 := c
        // bubble sort on 3 elements
        if data.Less(m1, m0) {
                data.Swap(m1, m0)
        }
        if data.Less(m2, m1) {
                data.Swap(m2, m1)
        }
        if data.Less(m1, m0) {
                data.Swap(m1, m0)
        }
        // now data[m0] <= data[m1] <= data[m2]
}

func swapRange(data Interface, a, b, n int) {
        for i := 0; i < n; i++ {
                data.Swap(a+i, b+i)
        }
}

func doPivot(data Interface, lo, hi int) (midlo, midhi int) {
        m := lo + (hi-lo)/2 // Written like this to avoid integer overflow.
        if hi-lo > 40 {
                // Tukey's ``Ninther,'' median of three medians of three.
                s := (hi - lo) / 8
                medianOfThree(data, lo, lo+s, lo+2*s)
                medianOfThree(data, m, m-s, m+s)
                medianOfThree(data, hi-1, hi-1-s, hi-1-2*s)
        }
        medianOfThree(data, lo, m, hi-1)

        // Invariants are:
        //        data[lo] = pivot (set up by ChoosePivot)
        //        data[lo <= i < a] = pivot
        //        data[a <= i < b] < pivot
        //        data[b <= i < c] is unexamined
        //        data[c <= i < d] > pivot
        //        data[d <= i < hi] = pivot
        //
        // Once b meets c, can swap the "= pivot" sections
        // into the middle of the slice.
        pivot := lo
        a, b, c, d := lo+1, lo+1, hi, hi
        for {
                for b < c {
                        if data.Less(b, pivot) { // data[b] < pivot
                                b++
                        } else if !data.Less(pivot, b) { // data[b] = pivot
                                data.Swap(a, b)
                                a++
                                b++
                        } else {
                                break
                        }
                }
                for b < c {
                        if data.Less(pivot, c-1) { // data[c-1] > pivot
                                c--
                        } else if !data.Less(c-1, pivot) { // data[c-1] = pivot
                                data.Swap(c-1, d-1)
                                c--
                                d--
                        } else {
                                break
                        }
                }
                if b >= c {
                        break
                }
                // data[b] > pivot; data[c-1] < pivot
                data.Swap(b, c-1)
                b++
                c--
        }

        n := min(b-a, a-lo)
        swapRange(data, lo, b-n, n)

        n = min(hi-d, d-c)
        swapRange(data, c, hi-n, n)

        return lo + b - a, hi - (d - c)
}

func quickSort(data Interface, a, b, maxDepth int) {
        for b-a > 7 {
                if maxDepth == 0 {
                        heapSort(data, a, b)
                        return
                }
                maxDepth--
                mlo, mhi := doPivot(data, a, b)
                // Avoiding recursion on the larger subproblem guarantees
                // a stack depth of at most lg(b-a).
                if mlo-a < b-mhi {
                        quickSort(data, a, mlo, maxDepth)
                        a = mhi // i.e., quickSort(data, mhi, b)
                } else {
                        quickSort(data, mhi, b, maxDepth)
                        b = mlo // i.e., quickSort(data, a, mlo)
                }
        }
        if b-a > 1 {
                insertionSort(data, a, b)
        }
}

// Sort sorts data.
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface) {
        // Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
        n := data.Len()
        maxDepth := 0
        for i := n; i > 0; i >>= 1 {
                maxDepth++
        }
        maxDepth *= 2
        quickSort(data, 0, n, maxDepth)
}

type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
}

// Less returns the opposite of the embedded implementation's Less method.
func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
}

// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
        return &reverse{data}
}

// IsSorted reports whether data is sorted.
func IsSorted(data Interface) bool {
        n := data.Len()
        for i := n - 1; i > 0; i-- {
                if data.Less(i, i-1) {
                        return false
                }
        }
        return true
}

// Convenience types for common cases

// IntSlice attaches the methods of Interface to []int, sorting in increasing order.
type IntSlice []int

func (p IntSlice) Len() int           { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// Sort is a convenience method.
func (p IntSlice) Sort() { Sort(p) }

// Float64Slice attaches the methods of Interface to []float64, sorting in increasing order.
type Float64Slice []float64

func (p Float64Slice) Len() int           { return len(p) }
func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j]) }
func (p Float64Slice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// isNaN is a copy of math.IsNaN to avoid a dependency on the math package.
func isNaN(f float64) bool {
        return f != f
}

// Sort is a convenience method.
func (p Float64Slice) Sort() { Sort(p) }

// StringSlice attaches the methods of Interface to []string, sorting in increasing order.
type StringSlice []string

func (p StringSlice) Len() int           { return len(p) }
func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p StringSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// Sort is a convenience method.
func (p StringSlice) Sort() { Sort(p) }

// Convenience wrappers for common cases

// Ints sorts a slice of ints in increasing order.
func Ints(a []int) { Sort(IntSlice(a)) }

// Float64s sorts a slice of float64s in increasing order.
func Float64s(a []float64) { Sort(Float64Slice(a)) }

// Strings sorts a slice of strings in increasing order.
func Strings(a []string) { Sort(StringSlice(a)) }

// IntsAreSorted tests whether a slice of ints is sorted in increasing order.
func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) }

// Float64sAreSorted tests whether a slice of float64s is sorted in increasing order.
func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) }

// StringsAreSorted tests whether a slice of strings is sorted in increasing order.
func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) }

// Notes on stable sorting:
// The used algorithms are simple and provable correct on all input and use
// only logarithmic additional stack space.  They perform well if compared
// experimentally to other stable in-place sorting algorithms.
//
// Remarks on other algorithms evaluated:
//  - GCC's 4.6.3 stable_sort with merge_without_buffer from libstdc++:
//    Not faster.
//  - GCC's __rotate for block rotations: Not faster.
//  - "Practical in-place mergesort" from  Jyrki Katajainen, Tomi A. Pasanen
//    and Jukka Teuhola; Nordic Journal of Computing 3,1 (1996), 27-40:
//    The given algorithms are in-place, number of Swap and Assignments
//    grow as n log n but the algorithm is not stable.
//  - "Fast Stable In-Plcae Sorting with O(n) Data Moves" J.I. Munro and
//    V. Raman in Algorithmica (1996) 16, 115-160:
//    This algorithm either needs additional 2n bits or works only if there
//    are enough different elements available to encode some permutations
//    which have to be undone later (so not stable an any input).
//  - All the optimal in-place sorting/merging algorithms I found are either
//    unstable or rely on enough different elements in each step to encode the
//    performed block rearrangements. See also "In-Place Merging Algorithms",
//    Denham Coates-Evely, Department of Computer Science, Kings College,
//    January 2004 and the reverences in there.
//  - Often "optimal" algorithms are optimal in the number of assignments
//    but Interface has only Swap as operation.

// Stable sorts data while keeping the original order of equal elements.
//
// It makes one call to data.Len to determine n, O(n*log(n)) calls to
// data.Less and O(n*log(n)*log(n)) calls to data.Swap.
func Stable(data Interface) {
        n := data.Len()
        blockSize := 20
        a, b := 0, blockSize
        for b <= n {
                insertionSort(data, a, b)
                a = b
                b += blockSize
        }
        insertionSort(data, a, n)

        for blockSize < n {
                a, b = 0, 2*blockSize
                for b <= n {
                        symMerge(data, a, a+blockSize, b)
                        a = b
                        b += 2 * blockSize
                }
                symMerge(data, a, a+blockSize, n)
                blockSize *= 2
        }
}

// SymMerge merges the two sorted subsequences data[a:m] and data[m:b] using
// the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
// Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
// Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
// Computer Science, pages 714-723. Springer, 2004.
//
// Let M = m-a and N = b-n. Wolog M < N.
// The recursion depth is bound by ceil(log(N+M)).
// The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
// The algorithm needs O((M+N)*log(M)) calls to data.Swap.
//
// The paper gives O((M+N)*log(M)) as the number of assignments assuming a
// rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
// in the paper carries through for Swap operations, especially as the block
// swapping rotate uses only O(M+N) Swaps.
func symMerge(data Interface, a, m, b int) {
        if a >= m || m >= b {
                return
        }

        mid := a + (b-a)/2
        n := mid + m
        start := 0
        if m > mid {
                start = n - b
                r, p := mid, n-1
                for start < r {
                        c := start + (r-start)/2
                        if !data.Less(p-c, c) {
                                start = c + 1
                        } else {
                                r = c
                        }
                }
        } else {
                start = a
                r, p := m, n-1
                for start < r {
                        c := start + (r-start)/2
                        if !data.Less(p-c, c) {
                                start = c + 1
                        } else {
                                r = c
                        }
                }
        }
        end := n - start
        rotate(data, start, m, end)
        symMerge(data, a, start, mid)
        symMerge(data, mid, end, b)
}

// Rotate two consecutives blocks u = data[a:m] and v = data[m:b] in data:
// Data of the form 'x u v y' is changed to 'x v u y'.
// Rotate performs at most b-a many calls to data.Swap.
func rotate(data Interface, a, m, b int) {
        i := m - a
        if i == 0 {
                return
        }
        j := b - m
        if j == 0 {
                return
        }

        if i == j {
                swapRange(data, a, m, i)
                return
        }

        p := a + i
        for i != j {
                if i > j {
                        swapRange(data, p-i, p, j)
                        i -= j
                } else {
                        swapRange(data, p-i, p+j-i, i)
                        j -= i
                }
        }
        swapRange(data, p-i, p, i)
}

/*
Complexity of Stable Sorting

Complexity of block swapping rotation

Each Swap puts one new element into its correct, final position.
Elements which reach their final position are no longer moved.
Thus block swapping rotation needs |u|+|v| calls to Swaps.
This is best possible as each element might need a move.

Pay attention when comparing to other optimal algorithms which
typically count the number of assignments instead of swaps:
E.g. the optimal algorithm of Dudzinski and Dydek for in-place
rotations uses O(u + v + gcd(u,v)) assignments which is
better than our O(3 * (u+v)) as gcd(u,v) <= u.

Stable sorting by SymMerge and BlockSwap rotations

SymMerg complexity for same size input M = N:
Calls to Less:  O(M*log(N/M+1)) = O(N*log(2)) = O(N)
Calls to Swap:  O((M+N)*log(M)) = O(2*N*log(N)) = O(N*log(N))

(The following argument does not fuzz over a missing -1 or
other stuff which does not impact the final result).

Let n = data.Len(). Assume n = 2^k.

Plain merge sort performs log(n) = k iterations.
On iteration i the algorithm merges 2^(k-i) blocks, each of size 2^i.

Thus iteration i of merge sort performs:
Calls to Less  O(2^(k-i) * 2^i) = O(2^k) = O(2^log(n)) = O(n)
Calls to Swap  O(2^(k-i) * 2^i * log(2^i)) = O(2^k * i) = O(n*i)

In total k = log(n) iterations are performed; so in total:
Calls to Less O(log(n) * n)
Calls to Swap O(n + 2*n + 3*n + ... + (k-1)*n + k*n)
   = O((k/2) * k * n) = O(n * k^2) = O(n * log^2(n))

Above results should generalize to arbitrary n = 2^k + p
and should not be influenced by the initial insertion sort phase:
Insertion sort is O(n^2) on Swap and Less, thus O(bs^2) per block of
size bs at n/bs blocks:  O(bs*n) Swaps and Less during insertion sort.
Merge sort iterations start at i = log(bs). With t = log(bs) constant:
Calls to Less O((log(n)-t) * n + bs*n) = O(log(n)*n + (bs-t)*n)
   = O(n * log(n))
Calls to Swap O(n * log^2(n) - (t^2+t)/2*n) = O(n * log^2(n))

*/


text:
Edit recipe

                <form name="loginForm" ng-submit="submitForm(loginForm.$valid)" ng-init="setFormScope()" role="form">
                    <fieldset>

                            Title
                            <input class="form-control" type="text" id="title" name="title" ng-model="article.title" required ng-required="true">
                            {{ errors.title }}

                            Image
                            <input class="form-control" type="text" id="image" name="image" ng-model="article.image" required ng-required="true">
                            {{ errors.image }}

                            Recette
                              <tabset justified="true">
                                <tab heading="Editor">
                                    <textarea class="form-control" type="text" id="body" name="body" ng-model="article.body" required ng-required="true" rows="10"></textarea>
                                </tab>
                                <tab heading="Preview">

                                </tab>
                              </tabset>
                            {{ errors.body }}

                            Category
                            <select class="form-control" ng-model="article.category_id" ng-options="category.id as category.name for category in categories"></select>
                            {{ errors.category_id }}

                                Cancel

                                <input class="btn btn-lg btn-danger btn-block" type="submit" value="Save">

                    </fieldset>
                </form>