text:
package org.apache.directory.api.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.apache.directory.api.i18n.I18n;

/**
 *
This class represents the generalized time syntax as defined in
 * RFC 4517 section 3.3.13.

 *
 *
The date, time and time zone information is internally backed
 * by an {@link java.util.Calendar} object

 *
 *
Leap seconds are not supported, as {@link java.util.Calendar}
 * does not support leap seconds.

 *
 *

 * 3.3.13.  Generalized Time
 *
 *  A value of the Generalized Time syntax is a character string
 *  representing a date and time.  The LDAP-specific encoding of a value
 *  of this syntax is a restriction of the format defined in [ISO8601],
 *  and is described by the following ABNF:
 *
 *     GeneralizedTime = century year month day hour
 *                          [ minute [ second / leap-second ] ]
 *                          [ fraction ]
 *                          g-time-zone
 *
 *     century = 2(%x30-39) ; "00" to "99"
 *     year    = 2(%x30-39) ; "00" to "99"
 *     month   =   ( %x30 %x31-39 ) ; "01" (January) to "09"
 *               / ( %x31 %x30-32 ) ; "10" to "12"
 *     day     =   ( %x30 %x31-39 )    ; "01" to "09"
 *               / ( %x31-32 %x30-39 ) ; "10" to "29"
 *               / ( %x33 %x30-31 )    ; "30" to "31"
 *     hour    = ( %x30-31 %x30-39 ) / ( %x32 %x30-33 ) ; "00" to "23"
 *     minute  = %x30-35 %x30-39                        ; "00" to "59"
 *
 *     second      = ( %x30-35 %x30-39 ) ; "00" to "59"
 *     leap-second = ( %x36 %x30 )       ; "60"
 *
 *     fraction        = ( DOT / COMMA ) 1*(%x30-39)
 *     g-time-zone     = %x5A  ; "Z"
 *                       / g-differential
 *     g-differential  = ( MINUS / PLUS ) hour [ minute ]
 *     MINUS           = %x2D  ; minus sign ("-")
 *
 *  The <DOT>, <COMMA>, and <PLUS> rules are defined in [RFC4512].
 *
 *  The above ABNF allows character strings that do not represent valid
 *  dates (in the Gregorian calendar) and/or valid times (e.g., February
 *  31, 1994).  Such character strings SHOULD be considered invalid for
 *  this syntax.
 *
 *  The time value represents coordinated universal time (equivalent to
 *  Greenwich Mean Time) if the "Z" form of <g-time-zone> is used;
 *  otherwise, the value represents a local time in the time zone
 *  indicated by <g-differential>.  In the latter case, coordinated
 *  universal time can be calculated by subtracting the differential from
 *  the local time.  The "Z" form of <g-time-zone> SHOULD be used in
 *  preference to <g-differential>.
 *
 *  If <minute> is omitted, then <fraction> represents a fraction of an
 *  hour; otherwise, if <second> and <leap-second> are omitted, then
 *  <fraction> represents a fraction of a minute; otherwise, <fraction>
 *  represents a fraction of a second.
 *
 *     Examples:
 *        199412161032Z
 *        199412160532-0500
 *
 *  Both example values represent the same coordinated universal time:
 *  10:32 AM, December 16, 1994.
 *
 *  The LDAP definition for the Generalized Time syntax is:
 *
 *     ( 1.3.6.1.4.1.1466.115.121.1.24 DESC 'Generalized Time' )
 *
 *  This syntax corresponds to the GeneralizedTime ASN.1 type from
 *  [ASN.1], with the constraint that local time without a differential
 *  SHALL NOT be used.
 *
 *

 */
public class GeneralizedTime implements Comparable<GeneralizedTime>
{

    /**
     * The format of the generalized time.
     */
    public enum Format
    {
        /** Time format with minutes and seconds, excluding fraction. */
        YEAR_MONTH_DAY_HOUR_MIN_SEC,
        /** Time format with minutes and seconds, including fraction. */
        YEAR_MONTH_DAY_HOUR_MIN_SEC_FRACTION,

        /** Time format with minutes, seconds are omitted, excluding fraction. */
        YEAR_MONTH_DAY_HOUR_MIN,
        /** Time format with minutes seconds are omitted, including fraction. */
        YEAR_MONTH_DAY_HOUR_MIN_FRACTION,

        /** Time format, minutes and seconds are omitted, excluding fraction. */
        YEAR_MONTH_DAY_HOUR,
        /** Time format, minutes and seconds are omitted, including fraction. */
        YEAR_MONTH_DAY_HOUR_FRACTION
    }

    /**
     * The fraction delimiter of the generalized time.
     */
    public enum FractionDelimiter
    {
        /** Use a dot as fraction delimiter. */
        DOT,
        /** Use a comma as fraction delimiter. */
        COMMA
    }

    /**
     * The time zone format of the generalized time.
     */
    public enum TimeZoneFormat
    {
        /** g-time-zone (Zulu) format. */
        Z,
        /** g-differential format, using hour only. */
        DIFF_HOUR,
        /** g-differential format, using hour and minute. */
        DIFF_HOUR_MINUTE
    }

    private static final TimeZone GMT = TimeZone.getTimeZone( "GMT" );

    /** The user provided value */
    private String upGeneralizedTime;

    /** The user provided format */
    private Format upFormat;

    /** The user provided time zone format */
    private TimeZoneFormat upTimeZoneFormat;

    /** The user provided fraction delimiter */
    private FractionDelimiter upFractionDelimiter;

    /** the user provided fraction length */
    private int upFractionLength;

    /** The calendar */
    private Calendar calendar;

    /**
     *
     * Creates a new instance of GeneralizedTime by setting the date to an instance of Calendar.
     * @see #GeneralizedTime(Calendar)
     *
     * @param date the date
     */
    public GeneralizedTime( Date date )
    {
        calendar = Calendar.getInstance();
        calendar.setTime( date );
        setUp( calendar );
    }

    /**
     * Creates a new instance of GeneralizedTime, based on the given Calendar object.
     * Uses
Format.YEAR_MONTH_DAY_HOUR_MIN_SEC
 as default format and
     *
TimeZoneFormat.Z
 as default time zone format.
     *
     * @param calendar the calendar containing the date, time and timezone information
     */
    public GeneralizedTime( Calendar calendar )
    {
        setUp( calendar );
    }

    private void setUp( Calendar calendar )
    {
        if ( calendar == null )
        {
            throw new IllegalArgumentException( I18n.err( I18n.ERR_04358 ) );
        }

        this.calendar = calendar;
        upGeneralizedTime = null;
        upFormat = Format.YEAR_MONTH_DAY_HOUR_MIN_SEC_FRACTION;
        upTimeZoneFormat = TimeZoneFormat.Z;
        upFractionDelimiter = FractionDelimiter.DOT;
        upFractionLength = 3;
    }

    /**
     * Creates a new instance of GeneralizedTime, based on the
     * given generalized time string.
     *
     * @param generalizedTime the generalized time
     *
     * @throws ParseException if the given generalized time can't be parsed.
     */
    public GeneralizedTime( String generalizedTime ) throws ParseException
    {
        if ( generalizedTime == null )
        {
            throw new ParseException( I18n.err( I18n.ERR_04359 ), 0 );
        }

        this.upGeneralizedTime = generalizedTime;

        calendar = Calendar.getInstance();
        calendar.setTimeInMillis( 0 );
        calendar.setLenient( false );

        parseYear();
        parseMonth();
        parseDay();
        parseHour();

        if ( upGeneralizedTime.length() < 11 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04360 ), 10 );
        }

        // pos 10:
        // if digit => minute field
        // if . or , => fraction of hour field
        // if Z or + or - => timezone field
        // else error
        int pos = 10;
        char c = upGeneralizedTime.charAt( pos );
        if ( '0' <= c && c <= '9' )
        {
            parseMinute();

            if ( upGeneralizedTime.length() < 13 )
            {
                throw new ParseException( I18n.err( I18n.ERR_04361 ), 12 );
            }

            // pos 12:
            // if digit => second field
            // if . or , => fraction of minute field
            // if Z or + or - => timezone field
            // else error
            pos = 12;
            c = upGeneralizedTime.charAt( pos );
            if ( '0' <= c && c <= '9' )
            {
                parseSecond();

                if ( upGeneralizedTime.length() < 15 )
                {
                    throw new ParseException( I18n.err( I18n.ERR_04362 ), 14 );
                }

                // pos 14:
                // if . or , => fraction of second field
                // if Z or + or - => timezone field
                // else error
                pos = 14;
                c = upGeneralizedTime.charAt( pos );
                if ( c == '.' || c == ',' )
                {
                    // read fraction of second
                    parseFractionOfSecond();
                    pos += 1 + upFractionLength;

                    parseTimezone( pos );
                    upFormat = Format.YEAR_MONTH_DAY_HOUR_MIN_SEC_FRACTION;
                }
                else if ( c == 'Z' || c == '+' || c == '-' )
                {
                    // read timezone
                    parseTimezone( pos );
                    upFormat = Format.YEAR_MONTH_DAY_HOUR_MIN_SEC;
                }
                else
                {
                    throw new ParseException( I18n.err( I18n.ERR_04363 ), 14 );
                }
            }
            else if ( c == '.' || c == ',' )
            {
                // read fraction of minute
                parseFractionOfMinute();
                pos += 1 + upFractionLength;

                parseTimezone( pos );
                upFormat = Format.YEAR_MONTH_DAY_HOUR_MIN_FRACTION;
            }
            else if ( c == 'Z' || c == '+' || c == '-' )
            {
                // read timezone
                parseTimezone( pos );
                upFormat = Format.YEAR_MONTH_DAY_HOUR_MIN;
            }
            else
            {
                throw new ParseException( I18n.err( I18n.ERR_04364 ), 12 );
            }
        }
        else if ( c == '.' || c == ',' )
        {
            // read fraction of hour
            parseFractionOfHour();
            pos += 1 + upFractionLength;

            parseTimezone( pos );
            upFormat = Format.YEAR_MONTH_DAY_HOUR_FRACTION;
        }
        else if ( c == 'Z' || c == '+' || c == '-' )
        {
            // read timezone
            parseTimezone( pos );
            upFormat = Format.YEAR_MONTH_DAY_HOUR;
        }
        else
        {
            throw new ParseException( I18n.err( I18n.ERR_04365 ), 10 );
        }

        // this calculates and verifies the calendar
        try
        {
            calendar.getTimeInMillis();
        }
        catch ( IllegalArgumentException iae )
        {
            throw new ParseException( I18n.err( I18n.ERR_04366 ), 0 );
        }

        calendar.setLenient( true );
    }

    private void parseTimezone( int pos ) throws ParseException
    {
        if ( upGeneralizedTime.length() < pos + 1 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04367 ), pos );
        }

        char c = upGeneralizedTime.charAt( pos );
        if ( c == 'Z' )
        {
            calendar.setTimeZone( GMT );
            upTimeZoneFormat = TimeZoneFormat.Z;

            if ( upGeneralizedTime.length() > pos + 1 )
            {
                throw new ParseException( I18n.err( I18n.ERR_04368 ), pos + 1 );
            }
        }
        else if ( c == '+' || c == '-' )
        {
            StringBuilder sb = new StringBuilder( "GMT" );
            sb.append( c );

            String digits = getAllDigits( pos + 1 );
            sb.append( digits );

            if ( digits.length() == 2 && digits.matches( "^([01]\\d|2[0-3])$" ) )
            {
                TimeZone timeZone = TimeZone.getTimeZone( sb.toString() );
                calendar.setTimeZone( timeZone );
                upTimeZoneFormat = TimeZoneFormat.DIFF_HOUR;
            }
            else if ( digits.length() == 4 && digits.matches( "^([01]\\d|2[0-3])([0-5]\\d)$" ) )
            {
                TimeZone timeZone = TimeZone.getTimeZone( sb.toString() );
                calendar.setTimeZone( timeZone );
                upTimeZoneFormat = TimeZoneFormat.DIFF_HOUR_MINUTE;
            }
            else
            {
                throw new ParseException( I18n.err( I18n.ERR_04369 ), pos );
            }

            if ( upGeneralizedTime.length() > pos + 1 + digits.length() )
            {
                throw new ParseException( I18n.err( I18n.ERR_04370 ), pos + 1 + digits.length() );
            }
        }
    }

    private void parseFractionOfSecond() throws ParseException
    {
        parseFractionDelmiter( 14 );
        String fraction = getFraction( 14 + 1 );
        upFractionLength = fraction.length();

        double fract = Double.parseDouble( "0." + fraction );
        int millisecond = ( int ) Math.round( fract * 1000 );

        calendar.set( Calendar.MILLISECOND, millisecond );
    }

    private void parseFractionOfMinute() throws ParseException
    {
        parseFractionDelmiter( 12 );
        String fraction = getFraction( 12 + 1 );
        upFractionLength = fraction.length();

        double fract = Double.parseDouble( "0." + fraction );
        int milliseconds = ( int ) Math.round( fract * 1000 * 60 );
        int second = milliseconds / 1000;
        int millisecond = milliseconds - ( second * 1000 );

        calendar.set( Calendar.SECOND, second );
        calendar.set( Calendar.MILLISECOND, millisecond );
    }

    private void parseFractionOfHour() throws ParseException
    {
        parseFractionDelmiter( 10 );
        String fraction = getFraction( 10 + 1 );
        upFractionLength = fraction.length();

        double fract = Double.parseDouble( "0." + fraction );
        int milliseconds = ( int ) Math.round( fract * 1000 * 60 * 60 );
        int minute = milliseconds / ( 1000 * 60 );
        int second = ( milliseconds - ( minute * 60 * 1000 ) ) / 1000;
        int millisecond = milliseconds - ( minute * 60 * 1000 ) - ( second * 1000 );

        calendar.set( Calendar.MINUTE, minute );
        calendar.set( Calendar.SECOND, second );
        calendar.set( Calendar.MILLISECOND, millisecond );
    }

    private void parseFractionDelmiter( int fractionDelimiterPos )
    {
        char c = upGeneralizedTime.charAt( fractionDelimiterPos );
        upFractionDelimiter = c == '.' ? FractionDelimiter.DOT : FractionDelimiter.COMMA;
    }

    private String getFraction( int startIndex ) throws ParseException
    {
        String fraction = getAllDigits( startIndex );

        // minimum one digit
        if ( fraction.length() == 0 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04371 ), startIndex );
        }

        return fraction;
    }

    private String getAllDigits( int startIndex )
    {
        StringBuilder sb = new StringBuilder();
        while ( upGeneralizedTime.length() > startIndex )
        {
            char c = upGeneralizedTime.charAt( startIndex );
            if ( '0' <= c && c <= '9' )
            {
                sb.append( c );
                startIndex++;
            }
            else
            {
                break;
            }
        }
        return sb.toString();
    }

    private void parseSecond() throws ParseException
    {
        // read minute
        if ( upGeneralizedTime.length() < 14 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04372 ), 12 );
        }
        try
        {
            int second = Integer.parseInt( upGeneralizedTime.substring( 12, 14 ) );
            calendar.set( Calendar.SECOND, second );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04373 ), 12 );
        }
    }

    private void parseMinute() throws ParseException
    {
        // read minute
        if ( upGeneralizedTime.length() < 12 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04374 ), 10 );
        }
        try
        {
            int minute = Integer.parseInt( upGeneralizedTime.substring( 10, 12 ) );
            calendar.set( Calendar.MINUTE, minute );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04375 ), 10 );
        }
    }

    private void parseHour() throws ParseException
    {
        if ( upGeneralizedTime.length() < 10 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04376 ), 8 );
        }
        try
        {
            int hour = Integer.parseInt( upGeneralizedTime.substring( 8, 10 ) );
            calendar.set( Calendar.HOUR_OF_DAY, hour );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04377 ), 8 );
        }
    }

    private void parseDay() throws ParseException
    {
        if ( upGeneralizedTime.length() < 8 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04378 ), 6 );
        }
        try
        {
            int day = Integer.parseInt( upGeneralizedTime.substring( 6, 8 ) );
            calendar.set( Calendar.DAY_OF_MONTH, day );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04379 ), 6 );
        }
    }

    private void parseMonth() throws ParseException
    {
        if ( upGeneralizedTime.length() < 6 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04380 ), 4 );
        }
        try
        {
            int month = Integer.parseInt( upGeneralizedTime.substring( 4, 6 ) );
            calendar.set( Calendar.MONTH, month - 1 );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04381 ), 4 );
        }
    }

    private void parseYear() throws ParseException
    {
        if ( upGeneralizedTime.length() < 4 )
        {
            throw new ParseException( I18n.err( I18n.ERR_04382 ), 0 );
        }
        try
        {
            int year = Integer.parseInt( upGeneralizedTime.substring( 0, 4 ) );
            calendar.set( Calendar.YEAR, year );
        }
        catch ( NumberFormatException e )
        {
            throw new ParseException( I18n.err( I18n.ERR_04383 ), 0 );
        }
    }

    /**
     * Returns the string representation of this generalized time.
     * This method uses the same format as the user provided format.
     *
     * @return the string representation of this generalized time
     */
    public String toGeneralizedTime()
    {
        return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat );
    }

    /**
     * Returns the string representation of this generalized time.
     * This method uses the same format as the user provided format.
     *
     * @return the string representation of this generalized time
     */
    public String toGeneralizedTimeWithoutFraction()
    {
        return toGeneralizedTime( getFormatWithoutFraction( upFormat ), upFractionDelimiter, upFractionLength,
            upTimeZoneFormat );
    }

    /**
     * Gets the corresponding format with fraction.
     *
     * @param f the format
     * @return the corresponding format without fraction
     */
    private Format getFormatWithoutFraction( Format f )
    {
        switch ( f )
        {
            case YEAR_MONTH_DAY_HOUR_FRACTION:
                return Format.YEAR_MONTH_DAY_HOUR;
            case YEAR_MONTH_DAY_HOUR_MIN_FRACTION:
                return Format.YEAR_MONTH_DAY_HOUR_MIN;
            case YEAR_MONTH_DAY_HOUR_MIN_SEC_FRACTION:
                return Format.YEAR_MONTH_DAY_HOUR_MIN_SEC;
            default:
                break;
        }

        return f;
    }

    /**
     * Returns the string representation of this generalized time.
     *
     * @param format the target format
     * @param fractionDelimiter the target fraction delimiter, may be null
     * @param fractionLength the fraction length
     * @param timeZoneFormat the target time zone format
     *
     * @return the string
     */
    public String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
        TimeZoneFormat timeZoneFormat )
    {
        Calendar clonedCalendar = ( Calendar ) this.calendar.clone();
        if ( timeZoneFormat == TimeZoneFormat.Z )
        {
            clonedCalendar.setTimeZone( GMT );
        }

        NumberFormat twoDigits = new DecimalFormat( "00" );
        NumberFormat fourDigits = new DecimalFormat( "00" );
        StringBuffer fractionFormat = new StringBuffer( "" );
        for ( int i = 0; i < fractionLength && i < 3; i++ )
        {
            fractionFormat.append( "0" );
        }

        StringBuilder sb = new StringBuilder();
        sb.append( fourDigits.format( clonedCalendar.get( Calendar.YEAR ) ) );
        sb.append( twoDigits.format( clonedCalendar.get( Calendar.MONTH ) + 1 ) );
        sb.append( twoDigits.format( clonedCalendar.get( Calendar.DAY_OF_MONTH ) ) );
        sb.append( twoDigits.format( clonedCalendar.get( Calendar.HOUR_OF_DAY ) ) );

        switch ( format )
        {
            case YEAR_MONTH_DAY_HOUR_MIN_SEC:
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.MINUTE ) ) );
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.SECOND ) ) );
                break;

            case YEAR_MONTH_DAY_HOUR_MIN_SEC_FRACTION:
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.MINUTE ) ) );
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.SECOND ) ) );

                NumberFormat fractionDigits = new DecimalFormat( fractionFormat.toString() );
                sb.append( fractionDelimiter == FractionDelimiter.COMMA ? ',' : '.' );
                sb.append( fractionDigits.format( clonedCalendar.get( Calendar.MILLISECOND ) ) );
                break;

            case YEAR_MONTH_DAY_HOUR_MIN:
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.MINUTE ) ) );
                break;

            case YEAR_MONTH_DAY_HOUR_MIN_FRACTION:
                sb.append( twoDigits.format( clonedCalendar.get( Calendar.MINUTE ) ) );

                // sec + millis => fraction of minute
                double millisec = 1000 * clonedCalendar.get( Calendar.SECOND )
                    + clonedCalendar.get( Calendar.MILLISECOND );
                double fraction = millisec / ( 1000 * 60 );
                fractionDigits = new DecimalFormat( "0." + fractionFormat );
                sb.append( fractionDelimiter == FractionDelimiter.COMMA ? ',' : '.' );
                sb.append( fractionDigits.format( fraction ).substring( 2 ) );
                break;

            case YEAR_MONTH_DAY_HOUR_FRACTION:
                // min + sec + millis => fraction of minute
                millisec = 1000 * 60 * clonedCalendar.get( Calendar.MINUTE ) + 1000
                    * clonedCalendar.get( Calendar.SECOND )
                    + clonedCalendar.get( Calendar.MILLISECOND );
                fraction = millisec / ( 1000 * 60 * 60 );
                fractionDigits = new DecimalFormat( "0." + fractionFormat );
                sb.append( fractionDelimiter == FractionDelimiter.COMMA ? ',' : '.' );
                sb.append( fractionDigits.format( fraction ).substring( 2 ) );

                break;
        }

        if ( timeZoneFormat == TimeZoneFormat.Z && clonedCalendar.getTimeZone().hasSameRules( GMT ) )
        {
            sb.append( 'Z' );
        }
        else
        {
            TimeZone timeZone = clonedCalendar.getTimeZone();
            int rawOffset = timeZone.getRawOffset();
            sb.append( rawOffset < 0 ? '-' : '+' );

            rawOffset = Math.abs( rawOffset );
            int hour = rawOffset / ( 60 * 60 * 1000 );
            int minute = ( rawOffset - ( hour * 60 * 60 * 1000 ) ) / ( 1000 * 60 );

            if ( hour < 10 )
            {
                sb.append( '0' );
            }
            sb.append( hour );

            if ( timeZoneFormat == TimeZoneFormat.DIFF_HOUR_MINUTE || timeZoneFormat == TimeZoneFormat.Z )
            {
                if ( minute < 10 )
                {
                    sb.append( '0' );
                }
                sb.append( minute );
            }
        }

        return sb.toString();
    }

    /**
     * Gets the calendar. It could be used to manipulate this
     * {@link GeneralizedTime} settings.
     *
     * @return the calendar
     */
    public Calendar getCalendar()
    {
        return calendar;
    }

    @Override
    public String toString()
    {
        return toGeneralizedTime();
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + calendar.hashCode();
        return result;
    }

    @Override
    public boolean equals( Object obj )
    {
        if ( obj instanceof GeneralizedTime )
        {
            GeneralizedTime other = ( GeneralizedTime ) obj;
            return calendar.equals( other.calendar );
        }
        else
        {
            return false;
        }
    }

    /**
     * Compares this GeneralizedTime object with the specified GeneralizedTime object.
     *
     * @param other the other GeneralizedTime object
     *
     * @return a negative integer, zero, or a positive integer as this object
     *      is less than, equal to, or greater than the specified object.
     *
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo( GeneralizedTime other )
    {
        return calendar.compareTo( other.calendar );
    }

    public long getTime()
    {
        return calendar.getTimeInMillis();
    }

    public Date getDate()
    {
        return calendar.getTime();
    }

    public int getYear()
    {
        return calendar.get( Calendar.YEAR );
    }

    public int getMonth()
    {
        return calendar.get( Calendar.MONTH );
    }

    public int getDay()
    {
        return calendar.get( Calendar.DATE );
    }

    public int getHour()
    {
        return calendar.get( Calendar.HOUR_OF_DAY );
    }

    public int getMinutes()
    {
        return calendar.get( Calendar.MINUTE );
    }

    public int getSeconds()
    {
        return calendar.get( Calendar.SECOND );
    }

    public int getFraction()
    {
        return calendar.get( Calendar.MILLISECOND );
    }

    /**
     *
     *
     * @param zuluTime
     * @return
     */
    public static Date getDate( String zuluTime ) throws ParseException
    {
        return new GeneralizedTime( zuluTime ).calendar.getTime();
    }
}


text:
package nkp.pspValidator.shared;

import nkp.pspValidator.shared.engine.exceptions.InvalidXPathExpressionException;
import nkp.pspValidator.shared.engine.exceptions.PspDataException;
import nkp.pspValidator.shared.engine.exceptions.XmlFileParsingException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.regex.Pattern;

import static nkp.pspValidator.shared.Dmf.Type.*;

/**
 * Created by Martin Řehánek on 2.11.16.
 */
public class DmfDetector {

    public static final String DEFAULT_MONOGRAPH_VERSION = "1.4";
    public static final String DEFAULT_PERIODICAL_VERSION = "1.8";
    public static final String DEFAULT_SOUND_RECORDING_VERSION = "0.3";

    /**
     * Validátor zkontroluje hlavní mets soubor, konkrétně kořenový element <mets:mets> na hodnotu atributu TYPE. Možné hodnoty jsou "Monograph" nebo "Periodical". Platí:
     * Pokud nenalezne atribut TYPE – chyba.
     * Pokud se vyskytne jiná než povolená hodnota atributu – chyba.
     * Pokud se vyskytuje hodnota "Monograph", zachází validátor s balíčkem jako s monografií.
     * Pokud se vyskytuje hodnota "Periodical", zachází validátor s balíčkem jako s periodikem.
     * Pokud se vyskytuje hodnota "sound recording", zachází validátor s balíčkem jako se zvukovým dokumentem.
     */
    public Dmf.Type detectDmfType(File pspRootDir) throws PspDataException, XmlFileParsingException, InvalidXPathExpressionException {

        try {
            File primaryMetsFile = findPrimaryMetsFile(pspRootDir);
            Document metsDoc = loadDocument(primaryMetsFile);
            XPathExpression xPathExpression = buildXpathIgnoringNamespaces("/mets/@TYPE");
            String docType = ((String) xPathExpression.evaluate(metsDoc, XPathConstants.STRING)).trim();
            if ("Monograph".equals(docType)) {
                return MONOGRAPH;
            } else if ("Periodical".equals(docType)) {
                return PERIODICAL;
            } else if ("sound recording".equals(docType)) {
                return SOUND_RECORDING;
            } else {
                throw new PspDataException(pspRootDir, String.format("atribut TYPE elementu mods neobsahuje korektní typ (Monograph/Periodical/sound recording), ale hodnotu '%s'", docType));
            }
        } catch (XPathExpressionException e) {
            throw new InvalidXPathExpressionException("", String.format("chyba v zápisu Xpath: %s", e.getMessage()));
        }
    }

    private File findPrimaryMetsFile(File pspRootDir) throws PspDataException {
        Pattern pattern = Pattern.compile(".*mets.*\\.xml", java.util.regex.Pattern.CASE_INSENSITIVE | java.util.regex.Pattern.UNICODE_CASE);
        File[] metsCandidates = pspRootDir.listFiles((dir, name) -> pattern.matcher(name).matches());
        if (metsCandidates.length >= 2) {
            for(File metsCandidate: metsCandidates){
                System.out.println(metsCandidate.getAbsolutePath());
            }
            throw new PspDataException(pspRootDir,
                    String.format("nalezeno více možných souborů PRIMARY-METS, není jasné, který použít pro zjištění typu dokumentu (monografie/periodikum/zvuk)"));
        } else if (metsCandidates.length == 0) {
            throw new PspDataException(pspRootDir,
                    String.format("nenalezen soubor PRIMARY-METS pro zjištění typu dokumentu (monografie/periodikum/zvuk)"));
        } else {
            return metsCandidates[0];
        }
    }

    private Document loadDocument(File file) throws XmlFileParsingException {
        try {
            return XmlUtils.buildDocumentFromFile(file, false);
        } catch (SAXException e) {
            throw new XmlFileParsingException(file, String.format("chyba parsování xml v souboru %s: %s", file.getAbsolutePath(), e.getMessage()));
        } catch (IOException e) {
            throw new XmlFileParsingException(file, String.format("chyba čtení v souboru %s: %s", file.getAbsolutePath(), e.getMessage()));
        } catch (ParserConfigurationException e) {
            throw new XmlFileParsingException(file, String.format("chyba konfigurace parseru při zpracování souboru %s: %s", file.getAbsolutePath(), e.getMessage()));
        }
    }

    private XPathExpression buildXpathIgnoringNamespaces(String xpathExpression) throws InvalidXPathExpressionException {
        try {
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            return xpath.compile(xpathExpression);
        } catch (XPathExpressionException e) {
            throw new InvalidXPathExpressionException(xpathExpression, String.format("chyba v zápisu Xpath '%s': %s", xpathExpression, e.getMessage()));
        }
    }

    /**
     * @param dmfType
     * @param pspRootDir
     * @return dmf version found in file INFO or null
     */
    public String detectDmfVersionFromInfoFile(Dmf.Type dmfType, File pspRootDir) throws PspDataException, XmlFileParsingException, InvalidXPathExpressionException {
        try {
            File infoFile = findInfoFile(pspRootDir);
            Document infoDoc = loadDocument(infoFile);
            XPathExpression xPathExpression = buildXpathIgnoringNamespaces("/info/metadataversion|/info/metadataVersion");
            String versionFound = ((String) xPathExpression.evaluate(infoDoc, XPathConstants.STRING)).trim();
            return versionFound == null || versionFound.isEmpty() ? null : versionFound;
        } catch (XPathExpressionException e) {
            throw new InvalidXPathExpressionException("", String.format("chyba v zápisu Xpath: %s", e.getMessage()));
        }
    }

    private File findInfoFile(File pspRootDir) throws PspDataException {
        Pattern pattern = Pattern.compile("info.*\\.xml", java.util.regex.Pattern.CASE_INSENSITIVE | java.util.regex.Pattern.UNICODE_CASE);

        File[] infoCandidates = pspRootDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return pattern.matcher(name).matches();
            }
        });
        if (infoCandidates.length >= 2) {
            throw new PspDataException(pspRootDir,
                    String.format("nalezeno více možných souborů INFO, není jasné, který použít pro zjištění verze standardu DMF"));
        } else if (infoCandidates.length == 0) {
            throw new PspDataException(pspRootDir,
                    String.format("nenalezen soubor INFO pro zjištění verze standardu DMF"));
        } else {
            return infoCandidates[0];
        }
    }

    public Dmf resolveDmf(File pspRoot, Params params) throws PspDataException, InvalidXPathExpressionException, XmlFileParsingException {
        Dmf.Type type = detectDmfType(pspRoot);
        switch (type) {
            case MONOGRAPH: {
                return chooseVersion(MONOGRAPH, pspRoot, params.forcedDmfMonVersion, params.preferredDmfMonVersion, DEFAULT_MONOGRAPH_VERSION);
            }
            case PERIODICAL: {
                return chooseVersion(PERIODICAL, pspRoot, params.forcedDmfPerVersion, params.preferredDmfPerVersion, DEFAULT_PERIODICAL_VERSION);
            }
            case SOUND_RECORDING: {
                return chooseVersion(SOUND_RECORDING, pspRoot, params.forcedDmfSRVersion, params.preferredDmfSRVersion, DEFAULT_SOUND_RECORDING_VERSION);
            }
            default:
                throw new IllegalStateException();
        }
    }

    private Dmf chooseVersion(Dmf.Type type, File pspRoot, String forcedVersion, String preferredVersion, String defaultVersion) throws PspDataException, InvalidXPathExpressionException, XmlFileParsingException {
        if (forcedVersion != null) {
            return new Dmf(type, forcedVersion);
        } else {
            String versionFromInfo = detectDmfVersionFromInfoFile(type, pspRoot);
            if (versionFromInfo != null) {
                return new Dmf(type, versionFromInfo);
            } else if (preferredVersion != null) {
                return new Dmf(type, preferredVersion);
            } else {
                return new Dmf(type, defaultVersion);
            }
        }
    }

    public static class Params {
        public String preferredDmfMonVersion;
        public String preferredDmfPerVersion;
        public String preferredDmfSRVersion;
        public String forcedDmfMonVersion;
        public String forcedDmfPerVersion;
        public String forcedDmfSRVersion;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __SETIF_H__
#define __SETIF_H__

int add_address(const char *ifname, int family, const void *address, int cidr, const void *broadcast);
int if_up(const char *ifname, int mtu);

int add_anycast_address(int sock, const struct in6_addr *addr, const char *interface);
int del_anycast_address(int sock, const struct in6_addr *addr);

#endif


text:
set -e

this_dir="$(cd $(dirname $0) && pwd)"

pushd "$this_dir"

rm -rf out
certstrap init --common-name "CA" --passphrase ""
certstrap request-cert --common-name "client" --domain "client" --passphrase ""
certstrap sign client --CA "CA"

certstrap request-cert --common-name "metron" --domain "metron" --passphrase ""
certstrap sign metron --CA "CA"

rm -rf ./metron
mkdir -p ./metron
mv -f out/* ./metron/
rm -rf out

certstrap init --common-name "ca" --passphrase ""
certstrap request-cert --common-name "cert" --passphrase "" --domain "localhost" --ip "127.0.0.1"
certstrap sign cert --CA "ca"

mv -f out/* ./
rm -rf out

popd


text:
#import "ANAdAdapterInterstitialAdColony.h"
#import "ANAdAdapterBaseAdColony+PrivateMethods.h"
#import "ANLogging.h"
#import <AdColony/AdColony.h>

@interface ANAdAdapterInterstitialAdColony () <AdColonyAdDelegate>

@property (nonatomic, readwrite, strong) NSString *zoneID;

@end

@implementation ANAdAdapterInterstitialAdColony

#pragma mark - ANCustomAdapterInterstitial

@synthesize delegate = _delegate;

- (void)requestInterstitialAdWithParameter:(NSString *)parameterString
                                  adUnitId:(NSString *)idString
                       targetingParameters:(ANTargetingParameters *)targetingParameters {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    [ANAdAdapterBaseAdColony setAdColonyTargetingWithTargetingParameters:targetingParameters];
    self.zoneID = idString;
    ADCOLONY_ZONE_STATUS zoneStatus = [AdColony zoneStatusForZone:idString];
    ANAdResponseCode errorCode = ANAdResponseInternalError;
    switch (zoneStatus) {
        case ADCOLONY_ZONE_STATUS_ACTIVE:
            ANLogDebug(@"%@ %@ | AdColony interstitial ad available", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
            [self.delegate didLoadInterstitialAd:self];
            return;
        case ADCOLONY_ZONE_STATUS_NO_ZONE:
            errorCode = ANAdResponseInvalidRequest;
            break;
        case ADCOLONY_ZONE_STATUS_OFF:
            errorCode = ANAdResponseInvalidRequest;
            break;
        case ADCOLONY_ZONE_STATUS_LOADING:
            errorCode = ANAdResponseUnableToFill;
            break;
        case ADCOLONY_ZONE_STATUS_UNKNOWN:
            errorCode = ANAdResponseInternalError;
            break;
        default:
            ANLogDebug(@"%@ %@ | Unhandled AdColony Zone Status: %ld", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (long)zoneStatus);
            errorCode = ANAdResponseInternalError;
            break;
    }
    ANLogDebug(@"%@ %@ | AdColony interstitial unavailable, zone status %ld", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (long)zoneStatus);
    [self.delegate didFailToLoadAd:errorCode];
}

- (void)presentFromViewController:(UIViewController *)viewController {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    if ([self isReady]) {
        [AdColony playVideoAdForZone:self.zoneID
                        withDelegate:self];
    } else {
        ANLogDebug(@"%@ %@ | failedToDisplayAd", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        [self.delegate failedToDisplayAd];
    }
}

- (BOOL)isReady {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    ADCOLONY_ZONE_STATUS zoneStatus = [AdColony zoneStatusForZone:self.zoneID];
    return (zoneStatus == ADCOLONY_ZONE_STATUS_ACTIVE);
}

#pragma mark - AdColonyAdDelegate

- (void)onAdColonyAdStartedInZone:(NSString *)zoneID {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    // Do nothing.
}

- (void)onAdColonyAdFinishedWithInfo:(AdColonyAdInfo *)info {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    if (info.shown) {
        [self.delegate willCloseAd];
        [self.delegate didCloseAd];
    } else {
        ANLogDebug(@"%@ %@ | failedToDisplayAd", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        [self.delegate failedToDisplayAd];
    }
}

- (void)onAdColonyAdAttemptFinished:(BOOL)shown
                             inZone:(NSString *)zoneID {
    ANLogTrace(@"%@ %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    if (shown) {
        [self.delegate willCloseAd];
        [self.delegate didCloseAd];
    } else {
        ANLogDebug(@"%@ %@ | failedToDisplayAd", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        [self.delegate failedToDisplayAd];
    }
}

@end


text:
"""Select individuals into a new population trying to maintain diversity.

This selection mechanism seeks to try and get both high fitness levels
and high diversity levels in the population.
"""
# standard modules
import random
import math

# biopython
from Bio.Seq import MutableSeq

# local modules
from .Abstract import AbstractSelection
from .Tournament import TournamentSelection

class DiversitySelection(AbstractSelection):
    """Implement diversity selection.

    Diversity selection is performed by trying to select individuals
    from the population that aren't already in the new_population. A group
    of selected individuals is then subjected to selection using
    a passed selection routine.

    If new individuals can not be selected, new individuals will be
    randomly generated and inserted into the population.
    """
    def __init__(self, internal_selector, genome_generator):
        """Initialize a diversity selector.

        Arguments:

        o internal_selector - A selection object that will be used to select
        individuals based on fitness, perform crossover, mutation and repair.

        o genome_generator - A function that, when called, will return a
        genome to be used for a new organism. The genome returned must
        be a MutableSeq() object.
        """
        self._internal_selector = internal_selector
        self._genome_generator = genome_generator

        self.sub_pop_percent = .1
        self.random_tries = 10

    def _get_new_organism(self, new_pop, old_pop):
        """Get a new organism from old_pop that isn't in new_pop.

        This attempts to select an organism from old_pop that isn't in
        new_pop. If we can't do this in the number of tries specified
        by the class attribute random_tries, we generate a new random
        organism and return that.
        """
        # try to pick an organism that isn't in the population
        new_org = None
        num_tries = 0
        while new_org is None and num_tries < self.random_tries:
            chance_org = random.choice(old_pop)

            if chance_org not in new_pop:
                new_org = chance_org

            num_tries += 1

        # if we don't get an organism, generate a random one
        if new_org is None:
            new_org = old_pop[0].copy()
            random_genome = self._genome_generator()
            new_org.genome = random_genome
            new_org.recalculate_fitness()

        return new_org

    def select(self, population):
        """Perform selection on the current population, encouraging diversity.
        """
        new_population = []

        while len(new_population) < len(population):
            # generate a sub population
            sub_pop_size = int(math.ceil(len(population) *
                                         self.sub_pop_percent))
            sub_pop = []
            for individual in range(sub_pop_size):
                new_org = self._get_new_organism(new_population, population)
                sub_pop.append(new_org)

            # put the new sub population through selection, mutation
            # and all of that good stuff
            new_sub_pop = self._internal_selector.select(sub_pop)

            new_population.extend(new_sub_pop)

        # return the new population, which should have the same number
        # of individuals we started with.
        return new_population[:len(population)]


text:
<?php

class FrmEntryValidate {
    public static function validate( $values, $exclude = false ) {
        FrmEntry::sanitize_entry_post( $values );
        $errors = array();

        if ( ! isset($values['form_id']) || ! isset($values['item_meta']) ) {
            $errors['form'] = __( 'There was a problem with your submission. Please try again.', 'formidable' );
            return $errors;
        }

		if ( FrmAppHelper::is_admin() && is_user_logged_in() && ( ! isset( $values[ 'frm_submit_entry_' . $values['form_id'] ] ) || ! wp_verify_nonce( $values[ 'frm_submit_entry_' . $values['form_id'] ], 'frm_submit_entry_nonce' ) ) ) {
            $errors['form'] = __( 'You do not have permission to do that', 'formidable' );
        }

		self::set_item_key( $values );

		$posted_fields = self::get_fields_to_validate( $values, $exclude );

		// Pass exclude value to validate_field function so it can be used for repeating sections
		$args = array( 'exclude' => $exclude );

		foreach ( $posted_fields as $posted_field ) {
			self::validate_field( $posted_field, $errors, $values, $args );
			unset( $posted_field );
		}

		if ( ! empty( $errors ) ) {
			return $errors;
		}

		self::spam_check( $exclude, $values, $errors );

		if ( ! empty( $errors ) ) {
			return $errors;
		}

		$errors = apply_filters( 'frm_validate_entry', $errors, $values, compact( 'exclude' ) );

		return $errors;
	}

	private static function set_item_key( &$values ) {
		if ( ! isset( $values['item_key'] ) || $values['item_key'] == '' ) {
			global $wpdb;
			$values['item_key'] = FrmAppHelper::get_unique_key( '', $wpdb->prefix . 'frm_items', 'item_key' );
			$_POST['item_key'] = $values['item_key'];
		}
	}

	private static function get_fields_to_validate( $values, $exclude ) {
		$where = apply_filters( 'frm_posted_field_ids', array( 'fi.form_id' => $values['form_id'] ) );

		// Don't get subfields
		$where['fr.parent_form_id'] = array( null, 0 );

		// Don't get excluded fields (like file upload fields in the ajax validation)
		if ( ! empty( $exclude ) ) {
			$where['fi.type not'] = $exclude;
		}

		return FrmField::getAll( $where, 'field_order' );
	}

    public static function validate_field( $posted_field, &$errors, $values, $args = array() ) {
        $defaults = array(
            'id'              => $posted_field->id,
            'parent_field_id' => '', // the id of the repeat or embed form
            'key_pointer'     => '', // the pointer in the posted array
            'exclude'         => array(), // exclude these field types from validation
        );
        $args = wp_parse_args( $args, $defaults );

        if ( empty($args['parent_field_id']) ) {
			$value = isset( $values['item_meta'][ $args['id'] ] ) ? $values['item_meta'][ $args['id'] ] : '';
        } else {
            // value is from a nested form
            $value = $values;
        }

        // Check for values in "Other" fields
        FrmEntriesHelper::maybe_set_other_validation( $posted_field, $value, $args );

		self::maybe_clear_value_for_default_blank_setting( $posted_field, $value );

		// Reset arrays with only one value if it's not a field where array keys need to be preserved
		if ( is_array($value) && count( $value ) == 1 && isset( $value[0] ) ) {
			$value = reset($value);
		}

        if ( $posted_field->required == '1' && ! is_array( $value ) && trim( $value ) == '' ) {
			$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $posted_field, 'blank' );
        } else if ( $posted_field->type == 'text' && ! isset( $_POST['item_name'] ) ) {
            $_POST['item_name'] = $value;
        }

		if ( $value != '' ) {
			self::validate_url_field( $errors, $posted_field, $value, $args );
			self::validate_email_field( $errors, $posted_field, $value, $args );
			self::validate_number_field( $errors, $posted_field, $value, $args );
			self::validate_phone_field( $errors, $posted_field, $value, $args );
		}

        FrmEntriesHelper::set_posted_value($posted_field, $value, $args);

        self::validate_recaptcha($errors, $posted_field, $args);

		$errors = apply_filters( 'frm_validate_' . $posted_field->type . '_field_entry', $errors, $posted_field, $value, $args );
		$errors = apply_filters( 'frm_validate_field_entry', $errors, $posted_field, $value, $args );
    }

	private static function maybe_clear_value_for_default_blank_setting( $field, &$value ) {
		if ( FrmField::is_option_true_in_object( $field, 'default_blank' ) && $value == $field->default_value ) {
			$value = '';
		}
	}

	public static function validate_url_field( &$errors, $field, &$value, $args ) {
		if ( $value == '' || ! in_array( $field->type, array( 'website', 'url', 'image' ) ) ) {
            return;
        }

        if ( trim($value) == 'http://' ) {
            $value = '';
        } else {
            $value = esc_url_raw( $value );
			$value = preg_match( '/^(https?|ftps?|mailto|news|feed|telnet):/is', $value ) ? $value : 'http://' . $value;
        }

        // validate the url format
		if ( ! preg_match('/^http(s)?:\/\/(?:localhost|(?:[\da-z\.-]+\.[\da-z\.-]+))/i', $value) ) {
			$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $field, 'invalid' );
		}
    }

	public static function validate_email_field( &$errors, $field, $value, $args ) {
        if ( $value == '' || $field->type != 'email' ) {
            return;
        }

        //validate the email format
        if ( ! is_email($value) ) {
			$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $field, 'invalid' );
        }
    }

	public static function validate_number_field( &$errors, $field, $value, $args ) {
		//validate the number format
		if ( $field->type != 'number' ) {
			return;
		}

		if ( ! is_numeric( $value) ) {
			$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $field, 'invalid' );
		}

		// validate number settings
		if ( $value != '' ) {
			$frm_settings = FrmAppHelper::get_settings();
			// only check if options are available in settings
			if ( $frm_settings->use_html && isset( $field->field_options['minnum'] ) && isset( $field->field_options['maxnum'] ) ) {
				//minnum maxnum
				if ( (float) $value < $field->field_options['minnum'] ) {
					$errors[ 'field' . $args['id'] ] = __( 'Please select a higher number', 'formidable' );
				} else if ( (float) $value > $field->field_options['maxnum'] ) {
					$errors[ 'field' . $args['id'] ] = __( 'Please select a lower number', 'formidable' );
				}
			}
		}
	}

	public static function validate_phone_field( &$errors, $field, $value, $args ) {
		if ( $field->type == 'phone' || ( $field->type == 'text' && FrmField::is_option_true_in_object( $field, 'format' ) ) ) {

			$pattern = self::phone_format( $field );

			if ( ! preg_match( $pattern, $value ) ) {
				$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $field, 'invalid' );
			}
		}
	}

	public static function phone_format( $field ) {
		$default_format = '^((\+\d{1,3}(-|.| )?\(?\d\)?(-| |.)?\d{1,5})|(\(?\d{2,6}\)?))(-|.| )?(\d{3,4})(-|.| )?(\d{4})(( x| ext)\d{1,5}){0,1}$';
		if ( FrmField::is_option_empty( $field, 'format' ) ) {
			$pattern = $default_format;
		} else {
			$pattern = FrmField::get_option( $field, 'format' );
		}

		$pattern = apply_filters( 'frm_phone_pattern', $pattern, $field );

		// Create a regexp if format is not already a regexp
		if ( strpos( $pattern, '^' ) !== 0 ) {
			$pattern = self::create_regular_expression_from_format( $pattern );
		}

		$pattern = '/' . $pattern . '/';
		return $pattern;
	}

	/**
	 * Create a regular expression from a phone number format
	 *
	 * @since 2.02.02
	 * @param string $pattern
	 * @return string
	 */
	private static function create_regular_expression_from_format( $pattern ) {
		$pattern = preg_quote( $pattern );

		// Firefox doesn't like escaped dashes or colons
		$pattern = str_replace( array( '\-', '\:' ), array( '-', ':' ), $pattern );

		// Switch generic values out for their regular expression
		$pattern = preg_replace( '/\d/', '\d', $pattern );
		$pattern = str_replace( 'a', '[a-z]', $pattern );
		$pattern = str_replace( 'A', '[A-Z]', $pattern );
		$pattern = str_replace( '*', 'w', $pattern );
		$pattern = str_replace( '/', '\/', $pattern );

		if ( strpos( $pattern, '\?' ) !== false ) {
			$parts = explode( '\?', $pattern );
			$pattern = '';
			foreach ( $parts as $part ) {
				if ( empty( $pattern ) ) {
					$pattern .= $part;
				} else {
					$pattern .= '(' . $part . ')?';
				}
			}
		}
		$pattern = '^' . $pattern . '$';

		return $pattern;
	}

	public static function validate_recaptcha( &$errors, $field, $args ) {
        if ( $field->type != 'captcha' || FrmAppHelper::is_admin() || apply_filters( 'frm_is_field_hidden', false, $field, stripslashes_deep( $_POST ) ) ) {
            return;
        }

		$frm_settings = FrmAppHelper::get_settings();
		if ( empty( $frm_settings->pubkey ) ) {
			// don't require the captcha if it shouldn't be shown
			return;
		}

        if ( ! isset($_POST['g-recaptcha-response']) ) {
            // If captcha is missing, check if it was already verified
			if ( ! isset( $_POST['recaptcha_checked'] ) || ! wp_verify_nonce( $_POST['recaptcha_checked'], 'frm_ajax' ) ) {
                // There was no captcha submitted
				$errors[ 'field' . $args['id'] ] = __( 'The captcha is missing from this form', 'formidable' );
            }
            return;
        }

        $arg_array = array(
            'body'      => array(
				'secret'   => $frm_settings->privkey,
				'response' => $_POST['g-recaptcha-response'],
				'remoteip' => FrmAppHelper::get_ip_address(),
			),
		);
        $resp = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', $arg_array );
        $response = json_decode(wp_remote_retrieve_body( $resp ), true);

        if ( isset( $response['success'] ) && ! $response['success'] ) {
            // What happens when the CAPTCHA was entered incorrectly
			$errors[ 'field' . $args['id'] ] = ( ! isset( $field->field_options['invalid'] ) || $field->field_options['invalid'] == '' ) ? $frm_settings->re_msg : $field->field_options['invalid'];
        } else if ( is_wp_error( $resp ) ) {
			$error_string = $resp->get_error_message();
			$errors[ 'field' . $args['id'] ] = __( 'There was a problem verifying your recaptcha', 'formidable' );
			$errors[ 'field' . $args['id'] ] .= ' ' . $error_string;
        }
    }

    /**
     * check for spam
     * @param boolean $exclude
     * @param array $values
     * @param array $errors by reference
     */
    public static function spam_check( $exclude, $values, &$errors ) {
        if ( ! empty( $exclude ) || ! isset( $values['item_meta'] ) || empty( $values['item_meta'] ) || ! empty( $errors ) ) {
            // only check spam if there are no other errors
            return;
        }

		if ( self::is_honeypot_spam() || self::is_spam_bot() ) {
			$errors['spam'] = __( 'Your entry appears to be spam!', 'formidable' );
		}

    	if ( self::blacklist_check( $values ) ) {
            $errors['spam'] = __( 'Your entry appears to be blacklist spam!', 'formidable' );
    	}

        if ( self::is_akismet_spam( $values ) ) {
			if ( self::is_akismet_enabled_for_user( $values['form_id'] ) ) {
				$errors['spam'] = __( 'Your entry appears to be spam!', 'formidable' );
			}
	    }
    }

	private static function is_honeypot_spam() {
		$honeypot_value = FrmAppHelper::get_param( 'frm_verify', '', 'get', 'sanitize_text_field' );
		return ( $honeypot_value !== '' );
	}

	private static function is_spam_bot() {
		$ip = FrmAppHelper::get_ip_address();
		return empty( $ip );
	}

	private static function is_akismet_spam( $values ) {
		global $wpcom_api_key;
		return ( is_callable('Akismet::http_post') && ( get_option('wordpress_api_key') || $wpcom_api_key ) && self::akismet( $values ) );
	}

	private static function is_akismet_enabled_for_user( $form_id ) {
		$form = FrmForm::getOne( $form_id );
		return ( isset( $form->options['akismet'] ) && ! empty( $form->options['akismet'] ) && ( $form->options['akismet'] != 'logged' || ! is_user_logged_in() ) );
	}

    public static function blacklist_check( $values ) {
        if ( ! apply_filters('frm_check_blacklist', true, $values) ) {
            return false;
        }

    	$mod_keys = trim( get_option( 'blacklist_keys' ) );
    	if ( empty( $mod_keys ) ) {
    		return false;
    	}

		$content = FrmEntriesHelper::entry_array_to_string( $values );
		if ( empty( $content ) ) {
			return false;
		}

		$ip = FrmAppHelper::get_ip_address();
		$user_agent = FrmAppHelper::get_server_value( 'HTTP_USER_AGENT' );
		$user_info = self::get_spam_check_user_info( $values );

		return wp_blacklist_check( $user_info['comment_author'], $user_info['comment_author_email'], $user_info['comment_author_url'], $content, $ip, $user_agent );
    }

	/**
	 * Check entries for Akismet spam
	 *
	 * @return boolean true if is spam
	 */
	public static function akismet( $values ) {
		$content = FrmEntriesHelper::entry_array_to_string( $values );
		if ( empty( $content ) ) {
			return false;
		}

		$datas = array( 'comment_type' => 'formidable', 'comment_content' => $content );
		self::parse_akismet_array( $datas, $values );

		$query_string = _http_build_query( $datas, '', '&' );
		$response = Akismet::http_post( $query_string, 'comment-check' );

		return ( is_array( $response ) && $response[1] == 'true' );
	}

	/**
	 * @since 2.0
	 */
	private  static function parse_akismet_array( &$datas, $values ) {
		self::add_site_info_to_akismet( $datas );
		self::add_user_info_to_akismet( $datas, $values );
		self::add_server_values_to_akismet( $datas );
	}

	private static function add_site_info_to_akismet( &$datas ) {
		$datas['blog'] = FrmAppHelper::site_url();
		$datas['user_ip'] = preg_replace( '/[^0-9., ]/', '', FrmAppHelper::get_ip_address() );
		$datas['user_agent'] = FrmAppHelper::get_server_value( 'HTTP_USER_AGENT' );
		$datas['referrer'] = isset( $_SERVER['HTTP_REFERER'] ) ? FrmAppHelper::get_server_value( 'HTTP_REFERER' ) : false;
		$datas['blog_lang'] = get_locale();
		$datas['blog_charset'] = get_option('blog_charset');

		if ( akismet_test_mode() ) {
			$datas['is_test'] = 'true';
		}
	}

	private static function add_user_info_to_akismet( &$datas, $values ) {
		$user_info = self::get_spam_check_user_info( $values );
		$datas = $datas + $user_info;

		if ( isset( $user_info['user_ID'] ) ) {
			$datas['user_role'] = Akismet::get_user_roles( $user_info['user_ID'] );
		}
	}

	private static function get_spam_check_user_info( $values ) {
		$datas = array();

		if ( is_user_logged_in() ) {
			$user = wp_get_current_user();
			$datas['user_ID'] = $user->ID;
			$datas['user_id'] = $user->ID;
			$datas['comment_author'] = $user->display_name;
			$datas['comment_author_email'] = $user->user_email;
			$datas['comment_author_url'] = $user->user_url;
		} else {
			$datas['comment_author'] = '';
			$datas['comment_author_email'] = '';
			$datas['comment_author_url'] = '';

			$values = array_filter( $values );
			foreach ( $values as $value ) {
				if ( ! is_array( $value ) ) {
					if ( $datas['comment_author_email'] == '' && strpos( $value, '@' ) && is_email( $value ) ) {
						$datas['comment_author_email'] = $value;
					} elseif ( $datas['comment_author_url'] == '' && strpos( $value, 'http' ) === 0 ) {
						$datas['comment_author_url'] = $value;
					} elseif ( $datas['comment_author'] == '' && ! is_numeric( $value ) && strlen( $value ) < 200 ) {
						$datas['comment_author'] = $value;
					}
				}
			}
		}

		return $datas;
	}

	private static function add_server_values_to_akismet( &$datas ) {
		foreach ( $_SERVER as $key => $value ) {
			$include_value = is_string( $value ) && ! preg_match( '/^HTTP_COOKIE/', $key ) && preg_match( '/^(HTTP_|REMOTE_ADDR|REQUEST_URI|DOCUMENT_URI)/', $key );

			// Send any potentially useful $_SERVER vars, but avoid sending junk we don't need.
			if ( $include_value ) {
				$datas[ $key ] = $value;
			}
			unset( $key, $value );
		}
	}
}


text:
package com.wisobi.leanbean.dto;

import java.io.Serializable;

/**
 * Created by bjork on 05/11/14.
 */
public class VoteViewTO implements Serializable {

  private long id;
  private DeviceTO device;

  public VoteViewTO() {

  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public DeviceTO getDevice() { return device; }

  public void setDevice(DeviceTO device) { this.device = device; }
}


text:
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;

void InitializeApp() {
    // Only init once.
    // No lock needed as this is only called from the UI thread.
    static bool initialized = false;
    if (initialized) {
        return;
    }
    initialized = true;

    // Set our writable and temp folders
    char writableFolder[2048];
    size_t outLen;
    auto pathData = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
    wcstombs_s(&outLen, writableFolder, pathData->Data(), sizeof(writableFolder) - 1);
    EbrSetWritableFolder(writableFolder);

    auto tempPathData = Windows::Storage::ApplicationData::Current->TemporaryFolder->Path;
    wcstombs_s(&outLen, writableFolder, tempPathData->Data(), sizeof(writableFolder) - 1);
    SetTemporaryFolder(writableFolder);

    // Set the waiter routine for the main runloop to yield
    SetupMainRunLoopTimedMultipleWaiter();
}

extern "C" void RunApplicationMain(Platform::String^ principalClassName,
                                   Platform::String^ delegateClassName,
                                   float windowWidth,
                                   float windowHeight,
                                   ActivationType activationType,
                                   Platform::Object^ activationArg) {

    // Perform initialization
    InitializeApp();

    // Kick off iOS application main startup
    // Convert Object^ to IInspectable* so it can be passed into Objective C and there converted to its projection
    ApplicationMainStart(
            Strings::WideToNarrow(principalClassName->Data()).c_str(),
            Strings::WideToNarrow(delegateClassName->Data()).c_str(),
            windowWidth,
            windowHeight,
            activationType,
            reinterpret_cast<IInspectable*>(activationArg));
}

// clang-format off


text:
package io.soabase.halva.examples;

import io.soabase.halva.alias.TypeAlias;
import io.soabase.halva.any.Any;
import io.soabase.halva.any.AnyType;
import io.soabase.halva.caseclass.CaseClass;
import io.soabase.halva.caseclass.CaseClassIgnore;
import io.soabase.halva.caseclass.CaseObject;
import io.soabase.halva.any.AnyVal;
import io.soabase.halva.sugar.ConsList;
import io.soabase.halva.tuple.Pair;
import java.util.function.Function;

import static io.soabase.halva.comprehension.For.forComp;
import static io.soabase.halva.examples.Add.Add;
import static io.soabase.halva.examples.Add.AddAny;
import static io.soabase.halva.examples.App.App;
import static io.soabase.halva.examples.App.AppAny;
import static io.soabase.halva.examples.Con.Con;
import static io.soabase.halva.examples.Con.ConAny;
import static io.soabase.halva.examples.Environment.Environment;
import static io.soabase.halva.examples.Fun.Fun;
import static io.soabase.halva.examples.Fun.FunAny;
import static io.soabase.halva.examples.Lam.Lam;
import static io.soabase.halva.examples.Lam.LamAny;
import static io.soabase.halva.examples.M.M;
import static io.soabase.halva.examples.Num.Num;
import static io.soabase.halva.examples.Num.NumAny;
import static io.soabase.halva.examples.Var.Var;
import static io.soabase.halva.examples.Var.VarAny;
import static io.soabase.halva.examples.Wrong.Wrong;
import static io.soabase.halva.matcher.Matcher.match;
import static io.soabase.halva.sugar.Sugar.Iterable;
import static io.soabase.halva.sugar.Sugar.List;
import static io.soabase.halva.sugar.Sugar.cons;
import static io.soabase.halva.tuple.Tuple.Pair;

class SimpleInterpreter
{
    @CaseClass interface M_<A>{ A value();
        default <B> M_<B> bind(Function<A, M_<B>> k){ return k.apply(value()); }
        default <B> M_<B> map(Function<A, B> f){ return bind(x -> unitM(f.apply(x))); }
        default <B> M_<B> flatMap(Function<A, M_<B>> f){ return bind(f); }
    }

    static <A> M<A> unitM(A a){ return M(a); }

    static String showM(M<Value> m){ return m.value().value(); }

    interface Term{}

    @CaseClass interface Var_ extends Term{String name();}
    @CaseClass interface Con_ extends Term{int n();}
    @CaseClass interface Add_ extends Term{Term l(); Term r();}
    @CaseClass interface Lam_ extends Term{String name(); Term body();}
    @CaseClass interface App_ extends Term{Term fun(); Term arg();}

    interface Value{String value();}
    @CaseObject interface Wrong_ extends Value {
        default String value() { return "wrong"; }
    }
    @CaseClass interface Num_ extends Value{int n();
        @CaseClassIgnore default String value() { return String.valueOf(n()); }
    }
    @CaseClass interface Fun_ extends Value{Function<Value, M_<Value>> f();
        @CaseClassIgnore default String value() { return "<function>"; }
    }

    @TypeAlias interface Environment_ extends ConsList<Pair<String, Value>>{}

    static M<Value> lookup(String x, Environment e) {
        AnyVal<String> y = new AnyVal<String>(){};
        AnyVal<Value> b = new AnyVal<Value>(){};
        AnyVal<Environment> e1 = Any.typeAlias(Environment.TypeAliasType);

        return match(e).as(new AnyType<M<Value>>(){}).
            caseOf( List(), () -> unitM(Wrong) ).
            caseOf( Any.headAnyTail(Pair(y, b), e1), () -> x.equals(y.val()) ? unitM(b.val()) : lookup(x, e1.val()) ).
        get();
    }

    static M<Value> add(Value a, Value b)
    {
        AnyVal<Integer> m = new AnyVal<Integer>(){};
        AnyVal<Integer> n = new AnyVal<Integer>(){};

        return match(Pair(a, b)).as(new AnyType<M<Value>>(){}).
            caseOf( Pair(NumAny(m), NumAny(n)), () -> unitM(Num(m.val() + n.val())) ).
            caseOf( () -> unitM(Wrong) ).
        get();
    }

    static M<Value> apply(Value a, Value b)
    {
        AnyVal<Function<Value, M<Value>>> k = new AnyVal<Function<Value, M<Value>>>(){};

        return match(a).
            caseOf( FunAny(k), () -> k.val().apply(b) ).
            caseOf( () -> unitM(Wrong) ).
        get();
    }

    static M<Value> interp(Term term, Environment e)
    {
        AnyVal<String> x = new AnyVal<String>(){};
        AnyVal<Integer> n = new AnyVal<Integer>(){};
        AnyVal<Term> l = new AnyVal<Term>(){};
        AnyVal<Term> r = new AnyVal<Term>(){};
        AnyVal<Term> t = new AnyVal<Term>(){};
        AnyVal<Term> f = new AnyVal<Term>(){};

        AnyVal<M<Value>> a = Any.any();
        AnyVal<M<Value>> b = Any.any();
        AnyVal<M<Value>> c = Any.any();

        return match(term).
            caseOf( VarAny(x), () -> lookup( x.val(), e) ).
            caseOf( ConAny(n), () -> unitM( Num(n.val())) ).
            caseOf( AddAny(l, r), () -> forComp (a, Iterable(interp(l.val(), e)) ).
                                      forComp( b, () -> Iterable(interp(r.val(), e)) ).
                                      forComp( c, () -> Iterable(add(a.val().value(), b.val().value())) ).
                                      yield1( c::val )
                   ).
            caseOf( LamAny(x, t), () -> unitM( Fun(arg -> interp(t.val(), Environment(cons(Pair(x.val(), arg), e))))) ).
            caseOf( AppAny(f, t), () -> forComp( a, Iterable(interp(f.val(), e)) ).
                                      forComp( b, () -> Iterable(interp(t.val(), e)) ).
                                      forComp( c, () -> Iterable(apply(a.val().value(), b.val().value())) ).
                                      yield1( c::val )
                   ).
            get();
    }

    static String test(Term t)
    {
        return showM(interp(t, Environment(List())));
    }

    static final App term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
    static final App term1 = App(Con(1), Con(2));

    public static void main(String[] args)
    {
        System.out.println(test(term0));
        System.out.println(test(term1));
    }
}


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.

import {PodListActionBarController} from 'podlist/podlistactionbar_controller';
import podListModule from 'podlist/podlist_module';
import {stateName as deploy} from 'deploy/deploy_state';

describe('Replica Set List Action Bar controller', () => {
  /**
   * Replica Set List controller.
   * @type {!PodListController}
   */
  let ctrl;
  /** @type {ui.router.$state} */
  let state;

  beforeEach(() => {
    angular.mock.module(podListModule.name);

    angular.mock.inject(($controller, $state) => {
      state = $state;
      ctrl = $controller(PodListActionBarController, {
        $state: state,
      });
    });
  });

  it('should redirect to deploy page', () => {
    // given
    spyOn(state, 'go');

    // when
    ctrl.redirectToDeployPage();

    // then
    expect(state.go).toHaveBeenCalledWith(deploy);
  });
});


text:
ANSIBLE_METADATA = {
    'status': ['preview'],
    'supported_by': 'community',
    'metadata_version': '1.0'
}

DOCUMENTATION = '''
---
module: bigip_ucs_fetch
short_description: Fetches a UCS file from remote nodes
description:
   - This module is used for fetching UCS files from remote machines and
     storing them locally in a file tree, organized by hostname. Note that
     this module is written to transfer UCS files that might not be present,
     so a missing remote UCS won't be an error unless fail_on_missing is
     set to 'yes'.
version_added: "2.2"
options:
  backup:
    description:
      - Create a backup file including the timestamp information so you can
        get the original file back if you somehow clobbered it incorrectly.
    default: no
    required: False
    choices:
      - yes
      - no
  create_on_missing:
    description:
      - Creates the UCS based on the value of C(src) if the file does not already
        exist on the remote system.
    default: True
    required: False
  dest:
    description:
      - A directory to save the UCS file into.
    required: yes
  encryption_password:
    description:
      - Password to use to encrypt the UCS file if desired
    required: False
  fail_on_missing:
    description:
      - Make the module fail if the UCS file on the remote system is missing.
    default: False
    required: False
  force:
    description:
      - If C(no), the file will only be transferred if the destination does not
        exist.
    default: yes
    required: False
  password:
    description:
      - BIG-IP password
    required: true
  src:
    description:
      - The name of the UCS file to create on the remote server for downloading
    required: false
    default: temporary file name
  server:
    description:
      - BIG-IP host
    required: true
  user:
    description:
      - BIG-IP username
    required: true
  validate_certs:
    description:
      - If C(no), SSL certificates will not be validated. This should only be
        used on personally controlled sites using self-signed certificates.
    required: false
    default: true
notes:
  - Requires the bigsuds Python package on the host if using the iControl
    interface. This is as easy as pip install bigsuds
  - BIG-IP provides no way to get a checksum of the UCS files on the system
    via any interface except, perhaps, logging in directly to the box (which
    would not support appliance mode). Therefore, the best this module can
    do is check for the existence of the file on disk; no checksumming.
requirements:
  - bigsuds
  - requests
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = '''
- name: Download a new UCS
  bigip_ucs_fetch:
      server: "bigip.localhost.localdomain"
      user: "admin"
      password: "admin"
      src: "cs_backup.ucs"
      dest: "/tmp/cs_backup.ucs"
  delegate_to: localhost
'''

RETURN = '''
checksum:
  description: The SHA1 checksum of the downloaded file
  returned: success or changed
  type: string
  sample: 7b46bbe4f8ebfee64761b5313855618f64c64109
dest:
  description: Location on the ansible host that the UCS was saved to
  returned: success
  type: string
  sample: "/path/to/file.txt"
src:
  description:
    - Name of the UCS file on the remote BIG-IP to download. If not
      specified, then this will be a randomly generated filename
  returned: changed
  type: string
  sample: "cs_backup.ucs"
backup_file:
  description: Name of backup file created
  returned: changed and if backup=yes
  type: string
  sample: "/path/to/file.txt.2015-02-12@22:09~"
gid:
  description: Group id of the UCS file, after execution
  returned: success
  type: int
  sample: 100
group:
  description: Group of the UCS file, after execution
  returned: success
  type: string
  sample: "httpd"
owner:
  description: Owner of the UCS file, after execution
  returned: success
  type: string
  sample: "httpd"
uid:
  description: Owner id of the UCS file, after execution
  returned: success
  type: int
  sample: 100
md5sum:
  description: The MD5 checksum of the downloaded file
  returned: changed or success
  type: string
  sample: 96cacab4c259c4598727d7cf2ceb3b45
mode:
  description: Permissions of the target UCS, after execution
  returned: success
  type: string
  sample: "0644"
size:
  description: Size of the target UCS, after execution
  returned: success
  type: int
  sample: 1220
'''

import base64
import os
import socket
import tempfile

# Size of chunks of data to read and send via the iControl API
CHUNK_SIZE = 512 * 1024
SAVE_FULL = "SAVE_FULL"

def bigip_version():
    """Check the BIG-IP version

    Different versions of BIG-IP support different arguments to the load
    command. This method will return the version of the system for
    comparison.
    """
    version = self.api.System.SystemInfo.get_version()
    return version

class BigIpCommon(object):
    def __init__(self, username, password, hostname, validate_certs=True,
                 check_mode=False):

        self._username = username
        self._password = password
        self._hostname = hostname
        self._validate_certs = validate_certs

class BigIpIControl(BigIpCommon):
    def __init__(self, username, password, hostname,
                 validate_certs=True, check_mode=False):

        super(BigIpIControl, self).__init__(username, password, hostname,
                                            validate_certs, check_mode)

        self.api = bigip_api(hostname, username, password, validate_certs)

    def create(self, filename, encryption_password=None):
        if encryption_password:
            self.api.System.ConfigSync.save_encrypted_configuration(
                filename=filename,
                passphrase=encryption_password
            )
        else:
            self.api.System.ConfigSync.save_configuration(
                filename=filename,
                save_flag=SAVE_FULL
            )

    def read(self):
        result = []

        try:
            resp = self.api.System.ConfigSync.get_configuration_list()
            for ucs in resp:
                result.append(ucs['file_name'])
        except bigsuds.ServerError:
            pass

        return result

    def is_ucs_available(self, ucs):
        if ucs in self.read():
            return True
        else:
            return False

    def download(self, src, dest):
        fileobj = open(dest, 'wb')
        offset = 0
        done = False

        while not done:
            data = self.api.System.ConfigSync.download_configuration(
                config_name=src,
                chunk_size=CHUNK_SIZE,
                file_offset=offset
            )
            fileobj.write(base64.b64decode(data['return']['file_data']))
            offset = data['file_offset']
            if data['return']['chain_type'] in ['FILE_LAST', 'FILE_FIRST_AND_LAST']:
                break
        fileobj.close()

class BigIpRest(BigIpCommon):
    def __init__(self, username, password, hostname,
                 validate_certs=True, check_mode=False):

        super(BigIpRest, self).__init__(username, password, hostname,
                                        validate_certs, check_mode)

    def download(self, filename):
        headers = {
            'Content-Type': 'application/octet-stream'
        }
        filename = os.path.basename(fp)
        uri = 'https://%s/mgmt/cm/autodeploy/software-image-downloads/%s' % (host, filename)
        requests.packages.urllib3.disable_warnings()

        with open(fp, 'wb') as f:
            start = 0
            end = CHUNK_SIZE - 1
            size = 0
            current_bytes = 0

            while True:
                content_range = "%s-%s/%s" % (start, end, size)
                headers['Content-Range'] = content_range

                resp = requests.get(uri,
                                    auth=creds,
                                    headers=headers,
                                    verify=False,
                                    stream=True)

                if resp.status_code == 200:
                    # If the size is zero, then this is the first time through the
                    # loop and we don't want to write data because we haven't yet
                    # figured out the total size of the file.
                    if size > 0:
                        current_bytes += CHUNK_SIZE
                        for chunk in resp.iter_content(CHUNK_SIZE):
                            f.write(chunk)

                    # Once we've downloaded the entire file, we can break out of
                    # the loop
                    if end == size:
                        break

                crange = resp.headers['Content-Range']

                # Determine the total number of bytes to read
                if size == 0:
                    size = int(crange.split('/')[-1]) - 1

                    # If the file is smaller than the chunk size, BIG-IP will
                    # return an HTTP 400. So adjust the CHUNK_SIZE down to the
                    # total file size...
                    if CHUNK_SIZE > size:
                        end = size

                    # ...and pass on the rest of the code
                    continue

                start += CHUNK_SIZE

                if (current_bytes + CHUNK_SIZE) > size:
                    end = size
                else:
                    end = start + CHUNK_SIZE - 1

def main():
    backup_file = None

    argument_spec = f5_argument_spec()

    meta_args = dict(
        backup=dict(required=False, default=False, type='bool', choices=BOOLEANS),
        create_on_missing=dict(required=False, default=True, type='bool', choices=BOOLEANS),
        encryption_password=dict(required=False, default=None),
        dest=dict(required=True),
        force=dict(required=False, default=True, type='bool', choices=BOOLEANS),
        fail_on_missing=dict(required=False, default=False, type='bool', choices=BOOLEANS),
        src=dict(required=False, default=None)
    )
    argument_spec.update(meta_args)

    module = AnsibleModule(
        argument_spec=argument_spec,
        add_file_common_args=True,
        supports_check_mode=True
    )

    (server, user, password, state, partition, validate_certs) = f5_parse_arguments(module)

    try:
        backup = module.params['backup']
        connection = module.params['connection']
        create_on_missing = module.params['create_on_missing']
        dest = os.path.expanduser(module.params['dest'])
        encryption_password = module.params.get('encryption_password')
        force = module.params.get('force')
        fail_on_missing = module.params['fail_on_missing']
        src = module.params.get('src')

        # Generates a random filename if no 'src' argument was provided
        #
        # This random name will be supplied in the output of this module as the
        # value of the 'src' field so that you can use it in later modules
        if not src:
            tf = tempfile.NamedTemporaryFile(suffix='.ucs')
            src = os.path.basename(tf.name)
            tf.close()

        if connection == 'soap':
            if not BIGSUDS_AVAILABLE:
                raise Exception("The python bigsuds module is required")

            test_icontrol(user, password, server, validate_certs)
            obj = BigIpIControl(user, password, server, validate_certs)
        elif connection == 'rest':
            module.fail_json(msg='The REST connection is currently not supported')

        if fail_on_missing and not obj.is_ucs_available(src):
            module.exit_json(msg="UCS was not found", src=src, dest=dest, changed=False)

        if not create_on_missing and not obj.is_ucs_available(src):
            module.exit_json(msg="UCS was not found", src=src, dest=dest, changed=False)

        if create_on_missing and not obj.is_ucs_available(src):
            obj.create(src, encryption_password)

        if os.path.exists(dest):
            if not force:
                module.exit_json(msg="File already exists", src=src, dest=dest, changed=False)

        if os.path.isdir(dest):
            dest = os.path.join(dest, src)
        else:
            if not os.path.exists(os.path.dirname(dest)):
                try:
                    # os.path.exists() can return false in some
                    # circumstances where the directory does not have
                    # the execute bit for the current user set, in
                    # which case the stat() call will raise an OSError
                    os.stat(os.path.dirname(dest))
                except OSError as e:
                    if "permission denied" in str(e).lower():
                        module.fail_json(msg="Destination directory %s is not accessible" % (os.path.dirname(dest)))
                module.fail_json(msg="Destination directory %s does not exist" % (os.path.dirname(dest)))

        if not os.access(os.path.dirname(dest), os.W_OK):
            module.fail_json(msg="Destination %s not writable" % (os.path.dirname(dest)))

        try:
            if backup:
                if os.path.exists(dest):
                    backup_file = module.backup_local(dest)
            obj.download(src, dest)
        except IOError:
            module.fail_json(msg="Failed to copy: %s to %s" % (src, dest))

        changed = True
        checksum_dest = module.sha1(dest)
        try:
            md5sum_dest = module.md5(dest)
        except ValueError:
            md5sum_dest = None

        res_args = dict(
            dest=dest,
            src=src,
            changed=changed,
            md5sum=md5sum_dest,
            checksum=checksum_dest
        )
        if backup_file:
            res_args['backup_file'] = backup_file
    except (bigsuds.ConnectionError, bigsuds.ParseError) as e:
        module.fail_json(msg="Could not connect to BIG-IP host %s" % server)
    except socket.timeout as e:
        module.fail_json(msg="Timed out connecting to the BIG-IP")
    except socket.timeout as e:
        module.fail_json(msg=str(e))

    file_args = module.load_file_common_arguments(module.params)
    res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed'])

    module.exit_json(**res_args)

from ansible.module_utils.basic import *
from ansible.module_utils.f5_utils import *

if __name__ == '__main__':
    main()


text:
typedef struct PK11SlotInfoStr PK11SlotInfo;

#include "net/cert/scoped_nss_types.h"
#endif

namespace base {
class FilePath;
}

namespace net {

class EVRootCAMetadata;

#if BUILDFLAG(USE_NSS_CERTS)
// Imports a private key from file |key_filename| in |dir| into |slot|. The file
// must contain a PKCS#8 PrivateKeyInfo in DER encoding. Returns true on success
// and false on failure.
bool ImportSensitiveKeyFromFile(const base::FilePath& dir,
                                base::StringPiece key_filename,
                                PK11SlotInfo* slot);

bool ImportClientCertToSlot(CERTCertificate* cert, PK11SlotInfo* slot);

ScopedCERTCertificate ImportClientCertToSlot(
    const scoped_refptr<X509Certificate>& cert,
    PK11SlotInfo* slot);

scoped_refptr<X509Certificate> ImportClientCertAndKeyFromFile(
    const base::FilePath& dir,
    base::StringPiece cert_filename,
    base::StringPiece key_filename,
    PK11SlotInfo* slot,
    ScopedCERTCertificate* nss_cert);
scoped_refptr<X509Certificate> ImportClientCertAndKeyFromFile(
    const base::FilePath& dir,
    base::StringPiece cert_filename,
    base::StringPiece key_filename,
    PK11SlotInfo* slot);

ScopedCERTCertificate ImportCERTCertificateFromFile(
    const base::FilePath& certs_dir,
    base::StringPiece cert_file);

ScopedCERTCertificateList CreateCERTCertificateListFromFile(
    const base::FilePath& certs_dir,
    base::StringPiece cert_file,
    int format);
#endif

// Imports all of the certificates in |cert_file|, a file in |certs_dir|, into a
// CertificateList.
CertificateList CreateCertificateListFromFile(const base::FilePath& certs_dir,
                                              base::StringPiece cert_file,
                                              int format);

// Imports all the certificates given a list of filenames, and assigns the
// result to |*certs|. The filenames are relative to the test certificates
// directory.
::testing::AssertionResult LoadCertificateFiles(
    const std::vector<std::string>& cert_filenames,
    CertificateList* certs);

// Imports all of the certificates in |cert_file|, a file in |certs_dir|, into
// a new X509Certificate. The first certificate in the chain will be used for
// the returned cert, with any additional certificates configured as
// intermediate certificates.
scoped_refptr<X509Certificate> CreateCertificateChainFromFile(
    const base::FilePath& certs_dir,
    base::StringPiece cert_file,
    int format);

// Imports a single certificate from |cert_path|.
// If the file contains multiple certificates, the first certificate found
// will be returned.
scoped_refptr<X509Certificate> ImportCertFromFile(
    const base::FilePath& cert_path);

// Imports a single certificate from |cert_file|.
// |certs_dir| represents the test certificates directory. |cert_file| is the
// name of the certificate file. If cert_file contains multiple certificates,
// the first certificate found will be returned.
scoped_refptr<X509Certificate> ImportCertFromFile(
    const base::FilePath& certs_dir,
    base::StringPiece cert_file);

// Imports a private key from |key_path|, which should be a PEM file containing
// a PRIVATE KEY block. Only the first private key found will be returned, if
// the file contains multiple private keys or other PEM blocks, they will be
// ignored.
bssl::UniquePtr<EVP_PKEY> LoadPrivateKeyFromFile(
    const base::FilePath& key_path);

// ScopedTestEVPolicy causes certificates marked with |policy|, issued from a
// root with the given fingerprint, to be treated as EV. |policy| is expressed
// as a string of dotted numbers: i.e. "1.2.3.4".
// This should only be used in unittests as adding a CA twice causes a CHECK
// failure.
class ScopedTestEVPolicy {
 public:
  ScopedTestEVPolicy(EVRootCAMetadata* ev_root_ca_metadata,
                     const SHA256HashValue& fingerprint,
                     const char* policy);
  ~ScopedTestEVPolicy();

 private:
  SHA256HashValue fingerprint_;
  const raw_ptr<EVRootCAMetadata> ev_root_ca_metadata_;
};

}  // namespace net

#endif  // NET_TEST_CERT_TEST_UTIL_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Nat. Hist. Soc. Formosa 32: 225, 247 (1942)

#### Original name
Peronospora capparis Sawada

### Remarks
null


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>

<?php
$pk = PermissionKey::getByID($_REQUEST['pkID']);
$pk->setPermissionObject($board);

?>

<?php Loader::element("permission/detail", array('permissionKey' => $pk)); ?>

<script type="text/javascript">
    var ccm_permissionDialogURL = '<?=URL::to("/ccm/system/dialogs/boards/permissions", "board")?>';
</script>


text:
package admin_test

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	_ "github.com/mattn/go-sqlite3"

	"testing"
)

func TestCreateRecord(t *testing.T) {
	form := url.Values{
		"QorResource.Name": {"create_record"},
		"QorResource.Role": {"admin"},
	}

	if req, err := http.PostForm(server.URL+"/admin/users", form); err == nil {
		if req.StatusCode != 200 {
			t.Errorf("Create request should be processed successfully")
		}

		if db.First(&User{}, "name = ?", "create_record").RecordNotFound() {
			t.Errorf("User should be created successfully")
		}
	} else {
		t.Errorf(err.Error())
	}
}

// func TestCreateRecordWithXML(t *testing.T) {
// 	xml := []byte(`<?xml version="1.0" encoding="utf-8"?>
// <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
//   <soap:Body>
//     <ClientGetByGuid xmlns="http://tempuri.org/">
//       <guid>fc40a874-2902-4539-b8e7-6aa7084644ec</guid>
//     </ClientGetByGuid>
//   </soap:Body>
// </soap:Envelope>`)
// 	buf := bytes.NewBuffer(xml)

// 	if req, err := http.Post(server.URL+"/admin/user", "application/xml", buf); err == nil {
// 		fmt.Println(req)
// 		fmt.Println(err)
// 		t.Errorf("sss")
// 	}
// }

func TestCreateHasOneRecord(t *testing.T) {
	name := "create_record_and_has_one"
	form := url.Values{
		"QorResource.Name":              {name},
		"QorResource.Role":              {"admin"},
		"QorResource.CreditCard.Number": {"1234567890"},
		"QorResource.CreditCard.Issuer": {"Visa"},
	}

	if req, err := http.PostForm(server.URL+"/admin/users", form); err == nil {
		if req.StatusCode != 200 {
			t.Errorf("Create request should be processed successfully")
		}

		var user User
		if db.First(&user, "name = ?", name).RecordNotFound() {
			t.Errorf("User should be created successfully")
		}

		if db.Model(&user).Related(&user.CreditCard).RecordNotFound() || user.CreditCard.Number != "1234567890" {
			t.Errorf("Embedded struct should be created successfully")
		}
	} else {
		t.Errorf(err.Error())
	}
}

func TestCreateHasManyRecord(t *testing.T) {
	name := "create_record_and_has_many"
	form := url.Values{
		"QorResource.Name":                  {name},
		"QorResource.Role":                  {"admin"},
		"QorResource.Addresses[0].Address1": {"address_1"},
		"QorResource.Addresses[1].Address1": {"address_2"},
		"QorResource.Addresses[2].ID":       {"0"},
		"QorResource.Addresses[2].Address1": {""},
	}

	if req, err := http.PostForm(server.URL+"/admin/users", form); err == nil {
		if req.StatusCode != 200 {
			t.Errorf("Create request should be processed successfully")
		}

		var user User
		if db.First(&user, "name = ?", name).RecordNotFound() {
			t.Errorf("User should be created successfully")
		}

		if db.First(&Address{}, "user_id = ? and address1 = ?", user.ID, "address_1").RecordNotFound() {
			t.Errorf("Address 1 should be created successfully")
		}

		if db.First(&Address{}, "user_id = ? and address1 = ?", user.ID, "address_2").RecordNotFound() {
			t.Errorf("Address 2 should be created successfully")
		}

		var addresses []Address
		if db.Find(&addresses, "user_id = ?", user.ID); len(addresses) != 2 {
			t.Errorf("Blank address should not be created")
		}
	} else {
		t.Errorf(err.Error())
	}
}

func TestCreateManyToManyRecord(t *testing.T) {
	name := "create_record_many_to_many"
	var languageCN Language
	var languageEN Language
	db.FirstOrCreate(&languageCN, Language{Name: "CN"})
	db.FirstOrCreate(&languageEN, Language{Name: "EN"})

	form := url.Values{
		"QorResource.Name":      {name},
		"QorResource.Role":      {"admin"},
		"QorResource.Languages": {fmt.Sprintf("%d", languageCN.ID), fmt.Sprintf("%d", languageEN.ID)},
	}

	if req, err := http.PostForm(server.URL+"/admin/users", form); err == nil {
		if req.StatusCode != 200 {
			t.Errorf("Create request should be processed successfully")
		}

		var user User
		if db.First(&user, "name = ?", name).RecordNotFound() {
			t.Errorf("User should be created successfully")
		}

		var languages []Language
		db.Model(&user).Related(&languages, "Languages")

		if len(languages) != 2 {
			t.Errorf("User should have two languages after create")
		}
	} else {
		t.Errorf(err.Error())
	}
}

func TestUploadAttachment(t *testing.T) {
	name := "create_record_upload_attachment"

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	if attachment, err := filepath.Abs("tests/qor.png"); err == nil {
		if part, err := writer.CreateFormFile("QorResource.Avatar", filepath.Base(attachment)); err == nil {
			if file, err := os.Open(attachment); err == nil {
				io.Copy(part, file)
			}
		}
		form := url.Values{
			"QorResource.Name": {name},
			"QorResource.Role": {"admin"},
		}
		for key, val := range form {
			_ = writer.WriteField(key, val[0])
		}
		writer.Close()

		if req, err := http.Post(server.URL+"/admin/users", writer.FormDataContentType(), body); err == nil {
			if req.StatusCode != 200 {
				t.Errorf("Create request should be processed successfully")
			}

			var user User
			if db.First(&user, "name = ?", name).RecordNotFound() {
				t.Errorf("User should be created successfully")
			}

			// fmt.Println(user.Avatar.Path)
			// if user.Avatar.Path == "" {
			// 	t.Errorf("Avatar should be saved")
			// }
		}
	}
}

func TestCreateRecordWithJSON(t *testing.T) {
	name := "api_create_record"

	var languageCN Language
	var languageEN Language
	db.FirstOrCreate(&languageCN, Language{Name: "CN"})
	db.FirstOrCreate(&languageEN, Language{Name: "EN"})

	json := fmt.Sprintf(`{"Name":"api_create_record",
                        "Role":"admin",
                          "CreditCard": {"Number": "987654321", "Issuer": "Visa"},
                          "Addresses": [{"Address1": "address_1"}, {"Address1": "address_2"}, {"_id": "0"}],
                          "Languages": [%v, %v]
                       }`, languageCN.ID, languageEN.ID)

	buf := strings.NewReader(json)

	if req, err := http.Post(server.URL+"/admin/users", "application/json", buf); err == nil {
		if req.StatusCode != 200 {
			t.Errorf("Create request should be processed successfully")
		}

		var user User
		if db.First(&user, "name = ?", name).RecordNotFound() {
			t.Errorf("User should be created successfully")
		}

		if db.Model(&user).Related(&user.CreditCard).RecordNotFound() || user.CreditCard.Number != "987654321" {
			t.Errorf("Embedded struct should be created successfully")
		}

		if db.First(&Address{}, "user_id = ? and address1 = ?", user.ID, "address_1").RecordNotFound() {
			t.Errorf("Address 1 should be created successfully")
		}

		if db.First(&Address{}, "user_id = ? and address1 = ?", user.ID, "address_2").RecordNotFound() {
			t.Errorf("Address 2 should be created successfully")
		}

		var addresses []Address
		if db.Find(&addresses, "user_id = ?", user.ID); len(addresses) != 2 {
			t.Errorf("Blank address should not be created")
		}

		var languages []Language
		db.Model(&user).Related(&languages, "Languages")

		if len(languages) != 2 {
			t.Errorf("User should have two languages after create")
		}
	}
}