text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using UnityEngine;
using KSP;
using KSPPluginFramework;

namespace KerbalAlarmClock
{
    /// <summary>
    /// A class to store the UT of events and get back useful data
    /// </summary>
//    public class KACTime
//    {

//        //really there are 31,446,925.9936 seconds in a year, use 365*24 so the reciprocal math
//        //  to go to years and get back to full days isnt confusing - have to sort this out some day though.
//        //NOTE: KSP Dates appear to all be 365 * 24 as well - no fractions - woohoo
//        const double HoursPerDayEarth = 24;
//        const double HoursPerYearEarth = 365 * HoursPerDayEarth;

//        const double HoursPerDayKerbin = 6;
//        const double HoursPerYearKerbin = 426 * HoursPerDayKerbin;

//        #region "Constructors"
//        public KACTime()
//        { }
//        public KACTime(double NewUT)
//        {
//            UT = NewUT;
//        }
//        public KACTime(double Years, double Days, double Hours, double Minutes, double Seconds)
//        {
//            UT = KACTime.BuildUTFromRaw(Years, Days, Hours, Minutes, Seconds);
//        }
//        #endregion

//        /// <summary>
//        /// Build the UT from raw values
//        /// </summary>
//        /// <param name="Years"></param>
//        /// <param name="Days"></param>
//        /// <param name="Hours"></param>
//        /// <param name="Minutes"></param>
//        /// <param name="Seconds"></param>
//        public void BuildUT(double Years, double Days, double Hours, double Minutes, double Seconds)
//        {
//            UT = KACTime.BuildUTFromRaw(Years, Days, Hours, Minutes, Seconds);
//        }

//        public void BuildUT(String Years, String Days, String Hours, String Minutes, String Seconds)
//        {
//            BuildUT(Convert.ToDouble(Years), Convert.ToDouble(Days), Convert.ToDouble(Hours), Convert.ToDouble(Minutes), Convert.ToDouble(Seconds));
//        }

//        #region "Properties"

//        //Stores the Universal Time in game seconds
//        public double UT;

//        //readonly props that resolve from UT
//        public long Second
//        {
//            get { return Convert.ToInt64(Math.Truncate(UT % 60)); }
//        }
//        public long Minute
//        {
//            get { return Convert.ToInt64(Math.Truncate((UT / 60) % 60)); }
//        }

//        private double HourRaw { get { return UT / 60 / 60; } }

//        public long Hour
//        {
//            get {
//                if (GameSettings.KERBIN_TIME) {
//                    return Convert.ToInt64(Math.Truncate(HourRaw % HoursPerDayKerbin));
//                } else {
//                    return Convert.ToInt64(Math.Truncate(HourRaw % HoursPerDayEarth));
//                }
//            }
//        }

//        public long Day
//        {
//            get {
//                if (GameSettings.KERBIN_TIME) {
//                    return Convert.ToInt64(Math.Truncate(((HourRaw % HoursPerYearKerbin) / HoursPerDayKerbin)));
//                } else {
//                    return Convert.ToInt64(Math.Truncate(((HourRaw % HoursPerYearEarth) / HoursPerDayEarth)));
//                }
//            }
//        }

//        public long Year
//        {
//            get {
//                if (GameSettings.KERBIN_TIME) {
//                    return Convert.ToInt64(Math.Truncate((HourRaw / HoursPerYearKerbin)));
//                } else {
//                    return Convert.ToInt64(Math.Truncate((HourRaw / HoursPerYearEarth)));
//                }
//            }
//        }
//        //public long HourKerbin
//        //{
//        //    get { return Convert.ToInt64(Math.Truncate(HourRaw % HoursPerDayKerbin)); }
//        //}

//        //public long DayKerbin
//        //{
//        //    get { return Convert.ToInt64(Math.Truncate(((HourRaw % HoursPerYearKerbin) / HoursPerDayKerbin))); }
//        //}

//        //public long YearKerbin
//        //{
//        //    get { return Convert.ToInt64(Math.Truncate((HourRaw / HoursPerYearKerbin))); }
//        //}
//        #endregion

//        #region "String Formatting"
//        public String IntervalString()
//        {
//            return IntervalString(6);
//        }
//        public String IntervalString(int segments)
//        {
//            String strReturn = "";

//            if (UT < 0) strReturn += "+ ";

//            int intUsed = 0;

//            if (intUsed < segments && Year != 0)
//            {
//                strReturn += String.Format("{0}y", Math.Abs(Year));
//                intUsed++;
//            }

//            if (intUsed < segments && (Day != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0}d", Math.Abs(Day));
//                intUsed++;
//            }

//            if (intUsed < segments && (Hour != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0}h", Math.Abs(Hour));
//                intUsed++;
//            }
//            if (intUsed < segments && (Minute != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0}m", Math.Abs(Minute));
//                intUsed++;
//            }
//            if (intUsed < segments)// && (Second != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0}s", Math.Abs(Second));
//                intUsed++;
//            }

//            return strReturn;
//        }

//        public String IntervalDateTimeString()
//        {
//            return IntervalDateTimeString(6);
//        }
//        public String IntervalDateTimeString(int segments)
//        {
//            String strReturn = "";

//            if (UT < 0) strReturn += "+ ";

//            int intUsed = 0;

//            if (intUsed < segments && Year != 0)
//            {
//                strReturn += String.Format("{0}y", Math.Abs(Year));
//                intUsed++;
//            }

//            if (intUsed < segments && (Day != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0}d", Math.Abs(Day));
//                intUsed++;
//            }

//            if (intUsed < segments && (Hour != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ", ";
//                strReturn += String.Format("{0:00}", Math.Abs(Hour));
//                intUsed++;
//            }
//            if (intUsed < segments && (Minute != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ":";
//                strReturn += String.Format("{0:00}", Math.Abs(Minute));
//                intUsed++;
//            }
//            if (intUsed < segments)// && (Second != 0 || intUsed > 0))
//            {
//                if (intUsed > 0) strReturn += ":";
//                strReturn += String.Format("{0:00}", Math.Abs(Second));
//                intUsed++;
//            }

//            return strReturn;
//        }

//        public String DateString()
//        {
//            return String.Format("Year {0},Day {1}, {2}h, {3}m, {4}s", Year + 1, Day + 1, Hour, Minute, Second);
//        }

//        public String DateTimeString()
//        {
//            return String.Format("Year {0},Day {1}, {2:00}:{3:00}:{4:00}", Year + 1, Day + 1, Hour, Minute, Second);
//        }

//        public String IntervalStringLong()
//        {
//            String strReturn = "";
//            if (UT < 0) strReturn += "+ ";
//            strReturn += String.Format("{0} Years, {1} Days, {2:00}:{3:00}:{4:00}", Math.Abs(Year), Math.Abs(Day), Math.Abs(Hour), Math.Abs(Minute), Math.Abs(Second));
//            return strReturn;
//        }

//        public String UTString()
//        {
//            String strReturn = "";
//            if (UT < 0) strReturn += "+ ";
//            strReturn += String.Format("{0:N0}s", Math.Abs(UT));
//            return strReturn;
//        }
//        #endregion

//        public override String ToString()
//        {
//            return IntervalStringLong();
//        }

//        #region Static Properties
//        public static Double HoursPerDay { get { return GameSettings.KERBIN_TIME ? HoursPerDayKerbin : HoursPerDayEarth; } }
//        public static Double SecondsPerDay { get { return HoursPerDay * 60 * 60; } }
//        public static Double HoursPerYear { get { return GameSettings.KERBIN_TIME ? HoursPerYearKerbin : HoursPerYearEarth; } }
//        public static Double DaysPerYear { get { return HoursPerYear / HoursPerDay; } }
//        public static Double SecondsPerYear { get { return HoursPerYear * 60 * 60; } }
//        #endregion

//        #region "Static Functions"
//        //fudging for dates
//        public static KACTime timeDateOffest = new KACTime(1, 1, 0, 0, 0);

//        public static Double BuildUTFromRaw(String Years, String Days, String Hours, String Minutes, String Seconds)
//        {
//            return BuildUTFromRaw(Convert.ToDouble(Years), Convert.ToDouble(Days), Convert.ToDouble(Hours), Convert.ToDouble(Minutes), Convert.ToDouble(Seconds));
//        }
//        public static Double BuildUTFromRaw(double Years, double Days, double Hours, double Minutes, double Seconds)
//        {
//            if (GameSettings.KERBIN_TIME)
//            {
//                return Seconds +
//                   Minutes * 60 +
//                   Hours * 60 * 60 +
//                   Days * HoursPerDayKerbin * 60 * 60 +
//                   Years * HoursPerYearKerbin * 60 * 60;
//            }
//            else
//            {
//                return Seconds +
//                   Minutes * 60 +
//                   Hours * 60 * 60 +
//                   Days * HoursPerDayEarth * 60 * 60 +
//                   Years * HoursPerYearEarth * 60 * 60;
//            }
//        }

//        public static String PrintInterval(KACTime timeTemp, OldPrintTimeFormat TimeFormat)
//        {
//            return PrintInterval(timeTemp, 3, TimeFormat);
//        }

//        public static String PrintInterval(KACTime timeTemp, int Segments, OldPrintTimeFormat TimeFormat)
//        {
//            switch (TimeFormat )
//            {
//                case OldPrintTimeFormat.TimeAsUT:
//                    return timeTemp.UTString();
//                case OldPrintTimeFormat.KSPString:
//                    return timeTemp.IntervalString(Segments);
//                case OldPrintTimeFormat.DateTimeString:
//                    return timeTemp.IntervalDateTimeString(Segments);
//                default:
//                    return timeTemp.IntervalString(Segments);
//            }
//        }

//        public static String PrintDate(KACTime timeTemp, OldPrintTimeFormat TimeFormat)
//        {
//            switch (TimeFormat)
//            {
//                case OldPrintTimeFormat.TimeAsUT:
//                    return timeTemp.UTString();
//                case OldPrintTimeFormat.KSPString:
//                    return timeTemp.DateString();
//                case OldPrintTimeFormat.DateTimeString:
//                    return timeTemp.DateTimeString();
//                default:
//                    return timeTemp.DateTimeString();
//            }
//        }

//        //public enum PrintTimeFormat
//        //{
//        //    TimeAsUT,
//        //    KSPString,
//        //    DateTimeString
//        //}
//#endregion
//    }

    public enum OldPrintTimeFormat
    {
        TimeAsUT,
        KSPString,
        DateTimeString
    }

    public class KACTimeStringArray
    {
        public enum TimeEntryPrecisionEnum
        {
            Seconds = 0,
            Minutes = 1,
            Hours = 2,
            Days = 3,
            Years = 4
        }

        public TimeEntryPrecisionEnum TimeEntryPrecision { get; private set; }

        private String _Years="",_Days="",_Hours="",_Minutes="",_Seconds="";

        public String Years { get { return _Years; } set { _Years = value; SetValid(); } }
        public String Days { get { return _Days; } set { _Days = value; SetValid(); } }
        public String Hours { get { return _Hours; } set { _Hours = value; SetValid(); } }
        public String Minutes { get { return _Minutes; } set { _Minutes = value; SetValid(); } }
        public String Seconds { get { return _Seconds; } set { _Seconds = value; SetValid(); } }

        public Boolean Valid { get { return _Valid; } }
        Boolean _Valid=true;

        public KACTimeStringArray(TimeEntryPrecisionEnum LevelOfPrecision)
        {
            TimeEntryPrecision = LevelOfPrecision;
        }
        public KACTimeStringArray(Double NewUT, TimeEntryPrecisionEnum LevelOfPrecision)
            : this(LevelOfPrecision)
        {
            BuildFromUT(NewUT);
        }

        private void SetValid()
        {
            Double dblTest;
            if (Double.TryParse(_Years, out dblTest) &&
                Double.TryParse(_Days, out dblTest) &&
                Double.TryParse(_Hours, out dblTest) &&
                Double.TryParse(_Minutes, out dblTest) &&
                Double.TryParse(_Seconds, out dblTest)
                )
            {
                _Valid = true;
            }
            else
            {
                _Valid = false;
            }
        }

        public void BuildFromUT(Double UT)
        {
            KSPTimeSpan timeTemp = new KSPTimeSpan(UT);
            if (TimeEntryPrecision >= TimeEntryPrecisionEnum.Years)
                Years = timeTemp.Years.ToString();
            else
                Years = "0";

            if (TimeEntryPrecision > TimeEntryPrecisionEnum.Days)
                Days = timeTemp.Days.ToString();
            else if (TimeEntryPrecision == TimeEntryPrecisionEnum.Days)
                Days = ((timeTemp.Years * KSPDateStructure.DaysPerYear) + timeTemp.Days).ToString();
            else
                Days = "0";

            if (TimeEntryPrecision > TimeEntryPrecisionEnum.Hours)
                Hours = timeTemp.Hours.ToString();
            else if (TimeEntryPrecision == TimeEntryPrecisionEnum.Hours)
                Hours = ((timeTemp.Years * KSPDateStructure.HoursPerYear) + (timeTemp.Days * KSPDateStructure.HoursPerDay) + timeTemp.Hours).ToString();
            else
                Hours = "0";

            Minutes = timeTemp.Minutes.ToString();
            Seconds = timeTemp.Seconds.ToString();
        }

        public double UT
        {
            get
            {
                if (KSPDateStructure.CalendarType == CalendarTypeEnum.Earth)
                {

                    //ZeroString(Years),
                    Double result = new KSPTimeSpan(
                        ZeroString(Days),
                        ZeroString(Hours),
                        ZeroString(Minutes),
                        ZeroString(Seconds)
                        ).UT;

                    if (Convert.ToInt32(ZeroString(Years)) != 0)
                    {
                        result += Convert.ToInt32(ZeroString(Years)) * KSPDateStructure.SecondsPerYear;
                    }
                    return result;
                }
                else
                {
                    IDateTimeFormatter tf = KSPUtil.dateTimeFormatter;
                    Double result = tf.Year * Convert.ToInt32(ZeroString(Years))
                        + tf.Day * Convert.ToInt32(ZeroString(Days))
                        + tf.Hour * Convert.ToInt32(ZeroString(Hours))
                        + tf.Minute * Convert.ToInt32(ZeroString(Minutes))
                        + Convert.ToDouble(ZeroString(Seconds));
                    return result;
                }

            }
        }
        private String ZeroString(String strInput)
        {
            Double dblTemp;
            if (!Double.TryParse(strInput,out dblTemp))
                return "0";
            else
                return strInput;
        }
    }

    ///// <summary>
    ///// Class to hold an Alarm event
    ///// </summary>
    //public class KACAlarm
    //{
    //    //Some Structures
    //    //"R","M","A","P","A","D","S","X"
    //    public enum AlarmType
    //    {
    //        Raw,
    //        Maneuver,
    //        ManeuverAuto,
    //        Apoapsis,
    //        Periapsis,
    //        AscendingNode,
    //        DescendingNode,
    //        LaunchRendevous,
    //        Closest,
    //        SOIChange,
    //        SOIChangeAuto,
    //        Transfer,
    //        TransferModelled,
    //        Distance,
    //        Crew,
    //        EarthTime
    //    }

    //    public static Dictionary<AlarmType, int> AlarmTypeToButton = new Dictionary<AlarmType, int>() {
    //        {AlarmType.Raw, 0},
    //        {AlarmType.Maneuver , 1},
    //        {AlarmType.ManeuverAuto , 1},
    //        {AlarmType.Apoapsis , 2},
    //        {AlarmType.Periapsis , 2},
    //        {AlarmType.AscendingNode , 3},
    //        {AlarmType.DescendingNode , 3},
    //        {AlarmType.LaunchRendevous , 3},
    //        {AlarmType.Closest , 4},
    //        {AlarmType.Distance , 4},
    //        {AlarmType.SOIChange , 5},
    //        {AlarmType.SOIChangeAuto , 5},
    //        {AlarmType.Transfer , 6},
    //        {AlarmType.TransferModelled , 6},
    //        {AlarmType.Crew , 7}
    //    };
    //    public static Dictionary<int,AlarmType> AlarmTypeFromButton = new Dictionary<int,AlarmType>() {
    //        {0,AlarmType.Raw},
    //        {1,AlarmType.Maneuver },
    //        {2,AlarmType.Apoapsis },
    //        {3,AlarmType.AscendingNode },
    //        {4,AlarmType.Closest },
    //        {5,AlarmType.SOIChange },
    //        {6,AlarmType.Transfer },
    //        {7,AlarmType.Crew }
    //    };

    //    public enum AlarmAction
    //    {
    //        MessageOnly,
    //        KillWarp,
    //        PauseGame
    //    }

    //    public String SaveName = "";                                    //Which Save File
    //    public String VesselID = "";                                    //uniqueID of Vessel
    //    public String Name = "";                                        //Name of Alarm
    //    //public String Message = "";                                     //Some descriptive text
    //    public String Notes = "";                                       //Entered extra details
    //    public AlarmType TypeOfAlarm=AlarmType.Raw;                     //What Type of Alarm

    //    public KACTime AlarmTime = new KACTime();                       //UT of the alarm
    //    public Double AlarmMarginSecs = 0;                              //What the margin from the event was
    //    public Boolean Enabled = true;                                  //Whether it is enabled - not in use currently
    //    public Boolean HaltWarp = true;                                 //Whether the time warp will be halted at this event
    //    public Boolean PauseGame = false;                               //Whether the Game will be paused at this event

    //    public Double ActionedAt = 0;                                   //At What UT an alarm was actioned at (for use in not refiring fired events on ship change)

    //    public Boolean DeleteOnClose;                                   //Whether the checkbox is on or off for this

    //    //public ManeuverNode ManNode;                                  //Stored ManeuverNode attached to alarm
    //    public List<ManeuverNode> ManNodes=null;                        //Stored ManeuverNode's attached to alarm

    //    public String XferOriginBodyName = "";                          //Stored orbital transfer details
    //    public String XferTargetBodyName = "";

    //    //Have to generate these details when the target object is set
    //    private ITargetable _TargetObject = null;                       //Stored Target Details

    //    //Vessel Target - needs the fancy get routine as the alarms load before the vessels are loaded.
    //    //This means that each time the object is accessed if its not yet loaded it trys again
    //    public ITargetable TargetObject
    //    {
    //        get {
    //            if (_TargetObject != null)
    //                return _TargetObject;
    //            else
    //            {
    //                //is there something to load here from the string
    //                if (TargetLoader != "")
    //                {
    //                    String[] TargetParts = TargetLoader.Split(",".ToCharArray());
    //                    switch (TargetParts[0])
    //                    {
    //                        case "Vessel":
    //                            if (KerbalAlarmClock.StoredVesselExists(TargetParts[1]))
    //                                _TargetObject = KerbalAlarmClock.StoredVessel(TargetParts[1]);
    //                            break;
    //                        case "CelestialBody":
    //                            if (KerbalAlarmClock.CelestialBodyExists(TargetParts[1]))
    //                                TargetObject = KerbalAlarmClock.CelestialBody(TargetParts[1]);
    //                            break;
    //                        default:
    //                            MonoBehaviourExtended.LogFormatted("No Target Found:{0}", TargetLoader);
    //                            break;
    //                    }
    //                }
    //                return _TargetObject;
    //            }
    //        }
    //        set { _TargetObject = value; }
    //    }
    //    //Need this one as some vessels arent loaded when the config comes in
    //    public String TargetLoader = "";

    //    //Dynamic props down here
    //    public KACTime Remaining = new KACTime();                        //UT value of how long till the alarm fires
    //    public Boolean WarpInfluence = false;                           //Whether the Warp setting is being influenced by this alarm

    //    public Boolean Triggered = false;                               //Has this alarm been triggered
    //    public Boolean Actioned = false;                                //Has the code actioned th alarm - ie. displayed its message

    //    //Details of the alarm message
    //    public Rect AlarmWindow;
    //    public int AlarmWindowID=0;
    //    public int AlarmWindowHeight = 148;
    //    public Boolean AlarmWindowClosed = false;

    //    //Details of the alarm message
    //    public Boolean EditWindowOpen=false;

    //    #region "Constructors"
    //    public KACAlarm()
    //    {
    //        //if (KACWorkerGameState.IsFlightMode)
    //        try { SaveName = HighLogic.CurrentGame.Title; }
    //        catch (Exception) { }
    //    }
    //    public KACAlarm(double UT)
    //    {
    //        //if (KACWorkerGameState.IsFlightMode)
    //        try { SaveName = HighLogic.CurrentGame.Title; }
    //        catch (Exception) { }
    //        AlarmTime.UT = UT;
    //    }

    //    public KACAlarm(String vID, String NewName, String NewNotes, double UT, Double Margin, AlarmType atype, Boolean NewHaltWarp, Boolean NewPause)
    //    {
    //        //if (KACWorkerGameState.IsFlightMode)
    //        try { SaveName = HighLogic.CurrentGame.Title; }
    //        catch (Exception) { }
    //        VesselID = vID;
    //        Name = NewName;
    //        Notes = NewNotes;
    //        AlarmTime.UT = UT;
    //        AlarmMarginSecs = Margin;
    //        TypeOfAlarm = atype;
    //        Remaining.UT = AlarmTime.UT - Planetarium.GetUniversalTime();
    //        HaltWarp = NewHaltWarp;
    //        PauseGame = NewPause;
    //    }

    //    public KACAlarm(String vID, String NewName, String NewNotes,  double UT, Double Margin, AlarmType atype, Boolean NewHaltWarp, Boolean NewPause, List<ManeuverNode> NewManeuvers)
    //        : this(vID, NewName, NewNotes, UT, Margin, atype, NewHaltWarp, NewPause)
    //    {
    //        //set maneuver node
    //        ManNodes = NewManeuvers;
    //    }

    //    public KACAlarm(String vID, String NewName, String NewNotes, double UT, Double Margin, AlarmType atype, Boolean NewHaltWarp, Boolean NewPause, KACXFerTarget NewTarget)
    //        : this(vID, NewName, NewNotes, UT, Margin, atype, NewHaltWarp, NewPause)
    //    {
    //        //Set target details
    //        XferOriginBodyName = NewTarget.Origin.bodyName;
    //        XferTargetBodyName = NewTarget.Target.bodyName;
    //    }

    //    public KACAlarm(String vID, String NewName, String NewNotes, double UT, Double Margin, AlarmType atype, Boolean NewHaltWarp, Boolean NewPause, ITargetable NewTarget)
    //        : this(vID,NewName,NewNotes,UT,Margin,atype,NewHaltWarp,NewPause)
    //    {
    //        //Set the ITargetable proerty
    //        TargetObject = NewTarget;
    //    }
    //    #endregion

    //    /// <summary>
    //    /// Convert properties for the save file to a single String for storage
    //    /// </summary>
    //    /// <returns>CSV String of persistant properties</returns>
    //    public String SerializeString()
    //    {
    //        return KACUtils.PipeSepVariables(SaveName, Name, Enabled, AlarmTime.UT, HaltWarp, PauseGame, Notes);
    //    }

    //    public String SerializeString2()
    //    {
    //        //"VesselID, Name, Notes, AlarmTime.UT, AlarmMarginSecs, Type, Enabled,  HaltWarp, PauseGame, Maneuver/Xfer"
    //        String strReturn = "";
    //        strReturn += VesselID + "|";
    //        strReturn += KACUtils.PipeSepVariables(Name, Notes, AlarmTime.UT, AlarmMarginSecs, TypeOfAlarm, Enabled, HaltWarp, PauseGame);
    //        strReturn += "|";

    //        if (ManNodes != null)
    //        {
    //            strReturn += ManNodeSerializeList(ManNodes);
    //        }
    //        else if (XferTargetBodyName!=null && XferTargetBodyName!="")
    //        {
    //            strReturn += "" + XferOriginBodyName;
    //            strReturn += "," + XferTargetBodyName;
    //        }
    //        else if (TargetObject != null)
    //        {
    //            strReturn += KACAlarm.TargetSerialize(TargetObject);
    //        }
    //        return strReturn;
    //    }

    //    //String is "VesselID|Name|Notes|AlarmTime.UT|AlarmMarginSecs|Type|Enabled|HaltWarp|PauseGame|ActionedAt|Maneuver|Xfer|Target|Options|<ENDLINE>");
    //    public String SerializeString3()
    //    {
    //        //"VesselID, Name, Notes, AlarmTime.UT, AlarmMarginSecs, Type, Enabled,  HaltWarp, PauseGame, Maneuver/Xfer"
    //        String strReturn = "";
    //        strReturn += VesselID + "|";
    //        strReturn += KACUtils.PipeSepVariables(Name, Notes, AlarmTime.UT, AlarmMarginSecs, TypeOfAlarm, Enabled, HaltWarp, PauseGame,ActionedAt);
    //        strReturn += "|";

    //        if (ManNodes != null)
    //        {
    //            strReturn += ManNodeSerializeList(ManNodes);
    //        }
    //        strReturn += "|";

    //        if (XferTargetBodyName != null && XferTargetBodyName != "")
    //        {
    //            strReturn += "" + XferOriginBodyName;
    //            strReturn += "," + XferTargetBodyName;
    //        }
    //        strReturn += "|";

    //        if (TargetObject != null)
    //        {
    //            strReturn += KACAlarm.TargetSerialize(TargetObject);
    //        }
    //        strReturn += "|";

    //        //Extra Options go here if we need it later
    //        strReturn += "|";
    //        return strReturn;
    //    }

    //     /// <summary>
    //    /// Basically deserializing the alarm
    //    /// </summary>
    //    /// <param name="AlarmDetails"></param>
    //    public void LoadFromString(String AlarmDetails)
    //    {
    //        String[] vars = AlarmDetails.Split("|".ToCharArray());
    //        VesselID = "";
    //        SaveName = vars[0];
    //        Name = vars[1];
    //        Enabled = Convert.ToBoolean(vars[2]);
    //        AlarmTime.UT = Convert.ToDouble(vars[3]);
    //        HaltWarp = Convert.ToBoolean(vars[4]);
    //        if (vars.Length == 6)
    //            Notes = vars[5];
    //        else
    //        {
    //            PauseGame = Convert.ToBoolean(vars[5]);
    //            Notes = vars[6];
    //        }
    //    }

    //    public void LoadFromString2(String AlarmDetails)
    //    {
    //        String[] vars = AlarmDetails.Split("|".ToCharArray(), StringSplitOptions.None);
    //        SaveName = HighLogic.CurrentGame.Title;
    //        VesselID = vars[0];
    //        Name = vars[1];
    //        Notes = vars[2];
    //        AlarmTime.UT = Convert.ToDouble(vars[3]);
    //        AlarmMarginSecs = Convert.ToDouble(vars[4]);
    //        TypeOfAlarm = (KACAlarm.AlarmType)Enum.Parse(typeof(KACAlarm.AlarmType), vars[5]);
    //        Enabled = Convert.ToBoolean(vars[6]);
    //        HaltWarp = Convert.ToBoolean(vars[7]);
    //        PauseGame = Convert.ToBoolean(vars[8]);

    //        String strOptions = vars[9];
    //        switch (TypeOfAlarm)
    //        {
    //            case AlarmType.Maneuver:
    //                //Generate the Nodes List from the string
    //                ManNodes = ManNodeDeserializeList(strOptions);
    //                break;
    //            case AlarmType.Transfer:
    //                try
    //                {
    //                    String[] XferParts = strOptions.Split(",".ToCharArray());
    //                    XferOriginBodyName = XferParts[0];
    //                    XferTargetBodyName = XferParts[1];
    //                }
    //                catch (Exception ex)
    //                {
    //                    MonoBehaviourExtended.LogFormatted("Unable to load transfer details for {0}", Name);
    //                    MonoBehaviourExtended.LogFormatted(ex.Message);
    //                }
    //                break;
    //            case AlarmType.AscendingNode:
    //            case AlarmType.DescendingNode:
    //            case AlarmType.LaunchRendevous:
    //                if (strOptions != "")
    //                {
    //                    //find the targetable object and set it
    //                    TargetObject = TargetDeserialize(strOptions);
    //                    if (TargetObject==null && strOptions.StartsWith("Vessel,"))
    //                        TargetLoader = strOptions;
    //                }
    //                break;
    //            default:
    //                break;
    //        }
    //    }

    //    public void LoadFromString3(String AlarmDetails,Double CurrentUT)
    //    {
    //        //String is "VesselID|Name|Notes|AlarmTime.UT|AlarmMarginSecs|Type|Enabled|HaltWarp|PauseGame|ActionedAt|Maneuver|Xfer|Target|Options|<ENDLINE>");

    //        String[] vars = AlarmDetails.Split("|".ToCharArray(), StringSplitOptions.None);
    //        this.SaveName = HighLogic.CurrentGame.Title;
    //        this.VesselID = vars[0];
    //        this.Name = KACUtils.DecodeVarStrings(vars[1]);
    //        this.Notes = KACUtils.DecodeVarStrings(vars[2]);
    //        this.AlarmTime.UT = Convert.ToDouble(vars[3]);
    //        this.AlarmMarginSecs = Convert.ToDouble(vars[4]);
    //        this.TypeOfAlarm = (KACAlarm.AlarmType)Enum.Parse(typeof(KACAlarm.AlarmType), vars[5]);
    //        this.Enabled = Convert.ToBoolean(vars[6]);
    //        this.HaltWarp = Convert.ToBoolean(vars[7]);
    //        this.PauseGame = Convert.ToBoolean(vars[8]);
    //        this.ActionedAt = Convert.ToDouble(vars[9]);

    //        if (vars[10] != "")
    //            this.ManNodes = ManNodeDeserializeList(vars[10]);

    //        if (vars[11] != "")
    //        {
    //            try
    //            {
    //                String[] XferParts = vars[11].Split(",".ToCharArray());
    //                this.XferOriginBodyName = XferParts[0];
    //                this.XferTargetBodyName = XferParts[1];
    //            }
    //            catch (Exception ex)
    //            {
    //                MonoBehaviourExtended.LogFormatted("Unable to load transfer details for {0}", Name);
    //                MonoBehaviourExtended.LogFormatted(ex.Message);
    //            }
    //        }
    //        if (vars[12] != "")
    //        {
    //            //find the targetable object and set it
    //            this.TargetObject = TargetDeserialize(vars[12]);
    //            if (this.TargetObject == null && vars[12].StartsWith("Vessel,"))
    //                this.TargetLoader = vars[12];
    //        }

    //        //Now do the work to set Actioned/triggered/etc if needed
    //        //LogFormatted("A:{0},T:{1:0},Act:{2:0}", this.Name, CurrentUT, this.ActionedAt);
    //        if (ActionedAt > 0 && CurrentUT > ActionedAt)
    //        {
    //            MonoBehaviourExtended.LogFormatted("Suppressing Alarm on Load:{0}", this.Name);
    //            this.Triggered = true;
    //            this.Actioned = true;
    //            this.AlarmWindowClosed = true;
    //        }
    //        else if (ActionedAt > CurrentUT)
    //        {
    //            MonoBehaviourExtended.LogFormatted("Reenabling Alarm on Load:{0}", this.Name);
    //            this.Triggered = false;
    //            this.Actioned = false;
    //            this.ActionedAt = 0;
    //            this.AlarmWindowClosed = false;
    //        }

    //    }

    //    public static ITargetable TargetDeserialize(String strInput)
    //    {
    //        ITargetable tReturn = null;
    //        String[] TargetParts = strInput.Split(",".ToCharArray());
    //        switch (TargetParts[0])
    //        {
    //            case "Vessel":
    //                if (KerbalAlarmClock.StoredVesselExists(TargetParts[1]))
    //                    tReturn = KerbalAlarmClock.StoredVessel(TargetParts[1]);
    //                break;
    //            case "CelestialBody":
    //                if (KerbalAlarmClock.CelestialBodyExists(TargetParts[1]))
    //                    tReturn = KerbalAlarmClock.CelestialBody(TargetParts[1]);
    //                break;
    //            default:
    //                break;
    //        }
    //        return tReturn;
    //    }

    //    public static String TargetSerialize(ITargetable tInput)
    //    {
    //        string strReturn = "";

    //        strReturn += tInput.GetType();
    //        strReturn += ",";

    //        if (tInput is Vessel)
    //        {
    //            Vessel tmpVessel = tInput as Vessel;
    //            strReturn += tmpVessel.id.ToString();
    //        }
    //        else if (tInput is CelestialBody)
    //        {
    //            CelestialBody tmpBody = tInput as CelestialBody;
    //            strReturn += tmpBody.bodyName;
    //        }

    //        return strReturn;

    //    }

    //    public static List<ManeuverNode> ManNodeDeserializeList(String strInput)
    //    {
    //        List<ManeuverNode> lstReturn = new List<ManeuverNode>();

    //        String[] strInputParts = strInput.Split(",".ToCharArray());
    //        MonoBehaviourExtended.LogFormatted("Found {0} Maneuver Nodes to deserialize", strInputParts.Length / 8);

    //        //There are 8 parts per mannode
    //        for (int iNode = 0; iNode < strInputParts.Length / 8; iNode++)
    //        {
    //            String strTempNode = String.Join(",", strInputParts.Skip(iNode * 8).Take(8).ToArray());
    //            lstReturn.Add(ManNodeDeserialize(strTempNode));
    //        }

    //        return lstReturn;
    //    }

    //    public static ManeuverNode ManNodeDeserialize(String strInput)
    //    {
    //        ManeuverNode mReturn =  new ManeuverNode();
    //        String[] manparts = strInput.Split(",".ToCharArray());
    //        mReturn.UT = Convert.ToDouble(manparts[0]);
    //        mReturn.DeltaV = new Vector3d(Convert.ToDouble(manparts[1]),
    //                                    Convert.ToDouble(manparts[2]),
    //                                    Convert.ToDouble(manparts[3])
    //                );
    //        mReturn.nodeRotation = new Quaternion(Convert.ToSingle(manparts[4]),
    //                                            Convert.ToSingle(manparts[5]),
    //                                            Convert.ToSingle(manparts[6]),
    //                                            Convert.ToSingle(manparts[7])
    //                );
    //        return mReturn;
    //    }

    //    public static string ManNodeSerializeList(List<ManeuverNode> mInput)
    //    {
    //        String strReturn = "";
    //        foreach (ManeuverNode tmpMNode in mInput)
    //        {
    //            strReturn += ManNodeSerialize(tmpMNode);
    //            strReturn += ",";
    //        }
    //        strReturn = strReturn.TrimEnd(",".ToCharArray());
    //        return strReturn;
    //    }

    //    public static string ManNodeSerialize(ManeuverNode mInput)
    //    {
    //        String strReturn = mInput.UT.ToString();
    //        strReturn += "," + KACUtils.CommaSepVariables(mInput.DeltaV.x, mInput.DeltaV.y, mInput.DeltaV.z);
    //        strReturn += "," + KACUtils.CommaSepVariables(mInput.nodeRotation.x, mInput.nodeRotation.y, mInput.nodeRotation.z, mInput.nodeRotation.w);
    //        return strReturn;
    //    }

    //    public static Boolean CompareManNodeListSimple(List<ManeuverNode> l1, List<ManeuverNode> l2)
    //    {
    //        Boolean blnReturn = true;

    //        if (l1.Count != l2.Count)
    //            blnReturn=false;
    //        else
    //        {
    //            for (int i = 0; i < l1.Count; i++)
    //            {
    //                if (l1[i].UT != l2[i].UT)
    //                    blnReturn = false;
    //                else if (l1[i].DeltaV != l2[i].DeltaV)
    //                    blnReturn = false;
    //            }
    //        }

    //        return blnReturn;
    //    }

    //    public static int SortByUT(KACAlarm c1, KACAlarm c2)
    //    {
    //        return c1.Remaining.UT.CompareTo(c2.Remaining.UT);
    //    }
    //}

    ///// <summary>
    ///// Extended List class to deal with multiple save files"/>
    ///// </summary>
    //public class KACAlarmList : List<KACAlarm>
    //{
    //    /// <summary>
    //    /// How many alarms in the supplied save file
    //    /// </summary>
    //    /// <param name="SaveName"></param>
    //    /// <returns></returns>
    //    public Int64 CountInSave(String SaveName)
    //    {
    //        long lngReturn=0;

    //        foreach (KACAlarm tmpAlarm in this)
    //        {
    //            if (tmpAlarm.SaveName.ToLower() == SaveName.ToLower())
    //                lngReturn++;
    //        }

    //        return lngReturn;
    //    }

    //    /// <summary>
    //    /// Are there any alarms for this save file that are in the future and not already actioned
    //    /// </summary>
    //    /// <param name="SaveName"></param>
    //    /// <returns></returns>
    //    public Boolean ActiveEnabledFutureAlarms(String SaveName)
    //    {
    //        Boolean blnReturn = false;
    //        foreach (KACAlarm tmpAlarm in this)
    //        {
    //            if (tmpAlarm.AlarmTime.UT > Planetarium.GetUniversalTime() && tmpAlarm.Enabled && !tmpAlarm.Actioned && (tmpAlarm.SaveName.ToLower() == SaveName.ToLower()))
    //            {
    //                blnReturn = true;
    //            }
    //        }
    //        return blnReturn;
    //    }

    //    /// <summary>
    //    /// Get a filtered list of alarms for a specirfic save file
    //    /// </summary>
    //    /// <param name="SaveName"></param>
    //    /// <returns></returns>
    //    public KACAlarmList BySaveName(String SaveName)
    //    {
    //        KACAlarmList lstreturn = new KACAlarmList();

    //        foreach (KACAlarm tmpAlarm in this)
    //        {
    //            if (tmpAlarm.SaveName.ToLower() == SaveName.ToLower())
    //                lstreturn.Add(tmpAlarm);
    //        }

    //        return lstreturn;
    //    }

    //    /// <summary>
    //    /// Get the Alarm object from the Unity Window ID
    //    /// </summary>
    //    /// <param name="windowID"></param>
    //    /// <returns></returns>
    //    public KACAlarm GetByWindowID(Int32 windowID)
    //    {
    //        KACAlarm alarmReturn=null;
    //        foreach (KACAlarm tmpAlarm in this)
    //        {
    //            if (tmpAlarm.AlarmWindowID == windowID)
    //                alarmReturn=tmpAlarm;
    //        }
    //        return alarmReturn;
    //    }

    //    public Boolean PauseAlarmOnScreen(String SaveName)
    //    {
    //        Boolean blnReturn = false;
    //        foreach (KACAlarm tmpAlarm in this)
    //        {
    //            if ((tmpAlarm.SaveName.ToLower() == SaveName.ToLower()) && tmpAlarm.AlarmWindowID!=0 && !tmpAlarm.AlarmWindowClosed )
    //            {
    //                blnReturn = true;
    //                break;
    //            }
    //        }
    //        return blnReturn;
    //    }
    //}

    public class KACVesselSOI
    {
        public String Name;
        public String SOIName;
        //public String SOINew;
        //public Boolean SOIChanged { get { return (SOILast != SOINew); } }

        //public KACVesselSOI() { }
        public KACVesselSOI(String VesselName, String SOIBody)
        {
            Name = VesselName;
            SOIName = SOIBody;
        }
    }

    public class KACXFerTarget
        {
            private CelestialBody _Origin;

            public CelestialBody Origin
            {
                get { return _Origin; }
                set {
                    _Origin = value;
                    if (_Target != null)
                    {
                        CalcPhaseAngleTarget();
                        CalcPhaseAngleCurrent();
                    }
                }
            }
            private CelestialBody _Target;

            public CelestialBody Target
            {
                get { return _Target; }
                set {
                    _Target = value;
                    if (_Target != null)
                    {
                        CalcPhaseAngleTarget();
                        CalcPhaseAngleCurrent();
                    }
                }
            }

            private double _PhaseAngleTarget;
            private double _PhaseAngleCurrent;
            public double PhaseAngleTarget
            {
                get
                {
                    CalcPhaseAngleTarget();
                    return KACUtils.clampDegrees(_PhaseAngleTarget); }
                }

            private void CalcPhaseAngleTarget()
            {
                _PhaseAngleTarget = KACUtils.clampDegrees360(180 * (1 - Math.Pow((Origin.orbit.semiMajorAxis + Target.orbit.semiMajorAxis) / (2 * Target.orbit.semiMajorAxis), 1.5)));
            }
            public double PhaseAngleCurrent
            {
                get
                {
                    CalcPhaseAngleCurrent2();
                    return KACUtils.clampDegrees(_PhaseAngleCurrent);
                }
            }

            private void CalcPhaseAngleCurrent()
            {
                _PhaseAngleCurrent = KACUtils.clampDegrees360(Target.orbit.trueAnomaly + Target.orbit.argumentOfPeriapsis + Target.orbit.LAN
                    - (Origin.orbit.trueAnomaly + Origin.orbit.argumentOfPeriapsis + Origin.orbit.LAN));
            }
            private void CalcPhaseAngleCurrent2()
            {
                _PhaseAngleCurrent = KACUtils.clampDegrees360((Target.orbit.trueAnomaly * Mathf.Rad2Deg) + Target.orbit.argumentOfPeriapsis + Target.orbit.LAN
                    - ((Origin.orbit.trueAnomaly * Mathf.Rad2Deg ) + Origin.orbit.argumentOfPeriapsis + Origin.orbit.LAN));
            }

        public double PhaseAngleTarget360 {get{return KACUtils.clampDegrees360(_PhaseAngleTarget); }}
            public double PhaseAngleCurrent360 {get{return KACUtils.clampDegrees360(_PhaseAngleCurrent); }}

            //private KSPDateTime _AlignmentTime = new KSPDateTime(0);
            public KSPTimeSpan AlignmentTime
            {
                get
                {
                    double angleChangepersec = (360 / Target.orbit.period) - (360 / Origin.orbit.period);
                    double angleToMakeUp =PhaseAngleCurrent360-PhaseAngleTarget360;
                    if (angleToMakeUp > 0 && angleChangepersec > 0)
                        angleToMakeUp -= 360;
                    if (angleToMakeUp < 0 && angleChangepersec < 0)
                        angleToMakeUp += 360;

                    double UTToTarget = Math.Floor(Math.Abs(angleToMakeUp / angleChangepersec));
                    KSPTimeSpan tmeReturn = new KSPTimeSpan(UTToTarget);
                    return tmeReturn;
                }
            }

        }

    public class KACXFerModelPoint
    {
        public Double UT;
        public Int32 Origin;
        public Int32 Target;
        public Double PhaseAngle;

        public KACXFerModelPoint(Double NewUT, Int32 NewOrigin, Int32 NewTarget, Double NewPhase)
        {
            UT = NewUT;
            PhaseAngle = NewPhase;
            Origin = NewOrigin;
            Target = NewTarget;
        }
    }

    public class EarthTime
    {
        static DateTime EarthTimeRoot = new DateTime(2013, 1, 1);

        public static Double EarthTimeEncode(DateTime Input)
        {
            Double dblReturn;

            dblReturn = (Input - EarthTimeRoot).TotalSeconds;

            return dblReturn;
        }

        public static DateTime EarthTimeDecode(Double Input)
        {
            DateTime dteReturn;

            dteReturn = EarthTimeRoot.AddSeconds(Input);

            return dteReturn;
        }
    }
}


text:
package amu.roboclub.ui.fragments;

import android.os.Bundle;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import amu.roboclub.R;
import butterknife.BindView;
import butterknife.ButterKnife;

public class FeedbackDialogFragment extends BottomSheetDialogFragment {

    @BindView(R.id.feedbackEdt)
    EditText edt;
    @BindView(R.id.send)
    ImageView send;

    public static FeedbackDialogFragment newInstance() {
        return new FeedbackDialogFragment();
    }

    private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("feedback");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.bottomsheet_feedback, container, false);

        ButterKnife.bind(this, root);

        final FeedbackDialogFragment current = this;

        send.setOnClickListener(view -> {
            String feedback = edt.getText().toString();
            if (feedback.isEmpty()) {
                Toast.makeText(getContext(), R.string.empty_feedback, Toast.LENGTH_SHORT).show();
                return;
            }

            databaseReference.push().setValue(feedback, (databaseError, databaseReference1) -> {
                if(databaseError != null)
                    Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(getContext(), R.string.feedback_posted, Toast.LENGTH_SHORT).show();
            });

            current.dismiss();

        });
        return root;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Azure::Compute::Mgmt::V2018_06_01
  module Models
    #
    # The List Galleries operation response.
    #
    class GalleryList

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<Gallery>] A list of galleries.
      attr_accessor :value

      # @return [String] The uri to fetch the next page of galleries. Call
      # ListNext() with this to fetch the next page of galleries.
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<Gallery>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [GalleryList] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for GalleryList class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'GalleryList',
          type: {
            name: 'Composite',
            class_name: 'GalleryList',
            model_properties: {
              value: {
                client_side_validation: true,
                required: true,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'GalleryElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Gallery'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
require 'pry'
RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.disable_monkey_patching!
  config.profile_examples = 10
  config.order = :random
  Kernel.srand config.seed
end


text:
<?php
/**
 *Credits : Konstantin Kovshenin
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/

class Quick_Flickr_Widget extends WP_Widget {
	public function __construct() {
		parent::__construct( 'quick-flickr-widget', 'Vibe Flickr Widget', array(
			'description' => 'Display up to 20 of your latest Flickr submissions in your sidebar.',
		) );
	}

	/**
	 * Displays the widget contents.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		$title = apply_filters( 'widget_title', $instance['title'] );

		echo $args['before_widget'];
		if ( ! empty( $title ) )
			echo $args['before_title'] . $title . $args['after_title'];

		$photos = $this->get_photos( array(
			'username' => $instance['username'],
			'count' => $instance['count'],
			'tags' => $instance['tags'],
		) );

		if ( is_wp_error( $photos ) ) {
			echo $photos->get_error_message();
		} else {
			foreach ( $photos as $photo ) {
				$link = esc_url( $photo->link );
				$src = esc_url( $photo->media->m );
				$title = esc_attr( $photo->title );

				$item = sprintf( '', $link, $src, $title );
				$item = sprintf( '
%s
', $item );
				echo $item;
			}
		}

		echo $args['after_widget'];
	}

	/**
	 * Returns an array of photos on a WP_Error.
	 */
	private function get_photos( $args = array() ) {
		$transient_key = md5( 'aquick-flickr-cache-' . print_r( $args, true ) );
		$cached = get_transient( $transient_key );
		if ( $cached )
			return $cached;

		$username = isset( $args['username'] ) ? $args['username'] : '';
		$tags = isset( $args['tags'] ) ? $args['tags'] : '';
		$count = isset( $args['count'] ) ? absint( $args['count'] ) : 10;
		$query = array(
			'tagmode' => 'any',
			'tags' => $tags,
		);

		// If username is an RSS feed
		if ( preg_match( '#^https?://api\.flickr\.com/services/feeds/photos_public\.gne#', $username ) ) {
			$url = parse_url( $username );
			$url_query = array();
			wp_parse_str( $url['query'], $url_query );
			$query = array_merge( $query, $url_query );
		} else {
			$user = $this->request( 'flickr.people.findByUsername', array( 'username' => $username ) );
			if ( is_wp_error( $user ) )
				return $user;

			$user_id = $user->user->id;
			$query['id'] = $user_id;
		}

		$photos = $this->request_feed( 'photos_public', $query );

		if ( ! $photos )
			return new WP_Error( 'error', 'Could not fetch photos.' );

		$photos = array_slice( $photos, 0, $count );
		set_transient( $transient_key, $photos, apply_filters( 'quick_flickr_widget_cache_timeout', 3600 ) );
		return $photos;
	}

	/**
	 * Make a request to the Flickr API.
	 */
	private function request( $method, $args ) {
		$args['method'] = $method;
		$args['format'] = 'json';
		$args['api_key'] = 'd348e6e1216a46f2a4c9e28f93d75a48';
		$args['nojsoncallback'] = 1;
		$url = esc_url_raw( add_query_arg( $args, 'http://api.flickr.com/services/rest/' ) );

		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) )
			return false;

		$body = wp_remote_retrieve_body( $response );
 		$obj = json_decode( $body );

		if ( $obj && $obj->stat == 'fail' )
			return new WP_Error( 'error', $obj->message );

		return $obj ? $obj : false;
	}

	/**
	 * Fetch items from the Flickr Feed API.
	 */
	private function request_feed( $feed = 'photos_public', $args = array() ) {
		$args['format'] = 'json';
		$args['nojsoncallback'] = 1;
		$url = sprintf( 'http://api.flickr.com/services/feeds/%s.gne', $feed );
		$url = esc_url_raw( add_query_arg( $args, $url ) );

		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) )
			return false;

		$body = wp_remote_retrieve_body( $response );
		$body = preg_replace( "#\\\\'#", "\\\\\\'", $body );
 		$obj = json_decode( $body );

		return $obj ? $obj->items : false;

	}

	/**
	 * Validate and update widget options.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['username'] = strip_tags( $new_instance['username'] );
		$instance['tags'] = strip_tags( $new_instance['tags'] );
		$instance['count'] = absint( $new_instance['count'] );
		return $new_instance;
	}

	/**
	 * Render widget controls.
	 */
	public function form( $instance ) {
		$title = isset( $instance['title'] ) ? $instance['title'] : 'Photostream';
		$username = isset( $instance['username'] ) ? $instance['username'] : '';
		$tags = isset( $instance['tags'] ) ? $instance['tags'] : '';
		$count = isset( $instance['count'] ) ? absint( $instance['count'] ) : 10;
		?>

			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:','vibe'  ); ?>
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />

			<label for="<?php echo $this->get_field_id( 'username' ); ?>"><?php _e( 'Username or RSS:','vibe' ); ?>
			<input class="widefat" id="<?php echo $this->get_field_id( 'username' ); ?>" name="<?php echo $this->get_field_name( 'username' ); ?>" type="text" value="<?php echo esc_attr( $username ); ?>" />

			<label for="<?php echo $this->get_field_id( 'tags' ); ?>"><?php _e( 'Tags:','vibe' ); ?>
			<input class="widefat" id="<?php echo $this->get_field_id( 'tags' ); ?>" name="<?php echo $this->get_field_name( 'tags' ); ?>" type="text" value="<?php echo esc_attr( $tags ); ?>" />

			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Count:','vibe'  ); ?>

			<input type="number" min="1" max="20" value="<?php echo esc_attr( $count ); ?>" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" />

		<?php
	}
}

// Register the widget.
add_action( 'widgets_init', 'quick_flickr_widget_init' );
function quick_flickr_widget_init() {
	register_widget( 'Quick_Flickr_Widget' );
}


text:
<?php

namespace App\Providers;

use Destiny\Destiny;
use Destiny\DestinyClient;
use Destiny\DestinyManifest;
use Destiny\DestinyPlatform;
use Illuminate\Support\ServiceProvider;

class DestinyServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton('destiny.client', function () {
            $apiKey = config('destiny.key');

            return new DestinyClient($apiKey);
        });

        $this->app->singleton('destiny.manifest', function () {
            return new DestinyManifest();
        });

        $this->app->singleton('destiny.platform', function () {
            return new DestinyPlatform();
        });

        $this->app->singleton('destiny', function ($app) {
            return new Destiny($app['destiny.client'], $app['destiny.platform']);
        });
    }
}


text:
namespace {
using ::i18n::addressinput::Source;
using ::i18n::addressinput::Storage;
using ::i18n::addressinput::NullStorage;
using ::i18n::addressinput::TestdataSource;

}  // namespace

namespace autofill {

namespace {

std::unique_ptr<::i18n::addressinput::Source> GetInputSource() {
  base::FilePath file_path;
  CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path));
  file_path = file_path.Append(FILE_PATH_LITERAL("third_party"))
                  .Append(FILE_PATH_LITERAL("libaddressinput"))
                  .Append(FILE_PATH_LITERAL("src"))
                  .Append(FILE_PATH_LITERAL("testdata"))
                  .Append(FILE_PATH_LITERAL("countryinfo.txt"));
  return std::make_unique<TestdataSource>(true, file_path.AsUTF8Unsafe());
}

std::unique_ptr<::i18n::addressinput::Storage> GetInputStorage() {
  return std::unique_ptr<Storage>(new NullStorage);
}

}  // namespace

// static
AutofillProfileValidator* TestAutofillProfileValidator::GetInstance() {
  static base::LazyInstance<TestAutofillProfileValidator>::DestructorAtExit
      instance = LAZY_INSTANCE_INITIALIZER;
  return &(instance.Get().autofill_profile_validator_);
}

// static
TestAutofillProfileValidatorDelayed*
TestAutofillProfileValidator::GetDelayedInstance() {
  static base::LazyInstance<TestAutofillProfileValidator>::DestructorAtExit
      instance = LAZY_INSTANCE_INITIALIZER;
  return &(instance.Get().autofill_profile_validator_delayed_);
}

TestAutofillProfileValidator::TestAutofillProfileValidator()
    : autofill_profile_validator_(GetInputSource(), GetInputStorage()),
      autofill_profile_validator_delayed_(GetInputSource(), GetInputStorage()) {
}

TestAutofillProfileValidator::~TestAutofillProfileValidator() {}

}  // namespace autofill


text:
package za.co.wstoop.jatalog;

import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import za.co.wstoop.jatalog.statement.Statement;
import za.co.wstoop.jatalog.statement.StatementFactory;

/**
 * Internal class that encapsulates the parser for the Datalog language.
 */
class Parser {

	/* Parses a Datalog statement.
     * A statement can be:
     * - a fact, like parent(alice, bob).
     * - a rule, like ancestor(A, B) :- ancestor(A, C), parent(C, B).
     * - a query, like ancestor(X, bob)?
     * - a delete clause, like delete parent(alice, bob).
     */
    static Statement parseStmt(StreamTokenizer scan) throws DatalogException {

    	List<Expr> goals = new ArrayList<>();
        try {
            Expr head = parseExpr(scan);
            if(scan.nextToken() == ':') {
                // We're dealing with a rule
                if(scan.nextToken() != '-') {
                    throw new DatalogException("[line " + scan.lineno() + "] Expected ':-'");
                }
                List<Expr> body = new ArrayList<>();
                do {
                    Expr arg = parseExpr(scan);
                    body.add(arg);
                } while(scan.nextToken() == ',');

                if(scan.ttype != '.') {
                    throw new DatalogException("[line " + scan.lineno() + "] Expected '.' after rule");
                }
				Rule newRule = new Rule(head, body);
				return StatementFactory.insertRule(newRule);
            } else {
                // We're dealing with a fact, or a query
                if(scan.ttype == '.') {
                    // It's a fact
                    return StatementFactory.insertFact(head);
                } else {
                    // It's a query
                    goals.clear();
                    goals.add(head);
                    if (scan.ttype != '.' && scan.ttype != '?' && scan.ttype != ',') {
                        /* You _can_ write facts like `a = 5 .` but I recommend against it; if you do then you *must* have the space between the
                        5 and the '.' otherwise the parser sees it as 5.0 and the error message can be a bit confusing. */
                        throw new DatalogException("[line " + scan.lineno() + "] Expected one of '.', ',' or '?' after fact/query expression");
                    }
                    while(scan.ttype == ',') {
                        goals.add(parseExpr(scan));
                        scan.nextToken();
                    }

                    if (scan.ttype == '?') {
						return StatementFactory.query(goals);
					} else if (scan.ttype == '~') {
						return StatementFactory.deleteFacts(goals);
					} else {
						throw new DatalogException("[line " + scan.lineno() + "] Expected '?' or '~' after query");
					}
                }
            }
        } catch (IOException e) {
            throw new DatalogException(e);
        }
    }

    /* parses an expression */
    static Expr parseExpr(StreamTokenizer scan) throws DatalogException {
        try {
            scan.nextToken();

            boolean negated = false;
            if(scan.ttype == StreamTokenizer.TT_WORD && scan.sval.equalsIgnoreCase("not")) {
                negated = true;
                scan.nextToken();
            }

            String lhs = null;
            boolean builtInExpected = false;
            if(scan.ttype == StreamTokenizer.TT_WORD) {
                lhs = scan.sval;
            } else if(scan.ttype == '"' || scan.ttype == '\'') {
                lhs = scan.sval;
                builtInExpected = true;
            } else if(scan.ttype == StreamTokenizer.TT_NUMBER) {
                lhs = numberToString(scan.nval);
                builtInExpected = true;
            } else
                throw new DatalogException("[line " + scan.lineno() + "] Predicate or start of expression expected");

            scan.nextToken();
            if(scan.ttype == StreamTokenizer.TT_WORD || scan.ttype == '=' || scan.ttype == '!' || scan.ttype == '<' || scan.ttype == '>') {
                scan.pushBack();
                Expr e = parseBuiltInPredicate(lhs, scan);
                e.negated = negated;
                return e;
            }

            if(builtInExpected) {
                // LHS was a number or a quoted string but we didn't get an operator
                throw new DatalogException("[line " + scan.lineno() + "] Built-in predicate expected");
            } else if(scan.ttype != '(') {
                throw new DatalogException("[line " + scan.lineno() + "] Expected '(' after predicate or an operator");
            }

            List<String> terms = new ArrayList<>();
            if(scan.nextToken() != ')') {
                scan.pushBack();
                do {
                    if(scan.nextToken() == StreamTokenizer.TT_WORD) {
                        terms.add(scan.sval);
                    } else if(scan.ttype == '"' || scan.ttype == '\'') {
                        terms.add("\"" + scan.sval);
                    } else if(scan.ttype == StreamTokenizer.TT_NUMBER) {
                        terms.add(numberToString(scan.nval));
                    } else {
                        throw new DatalogException("[line " + scan.lineno() + "] Expected term in expression");
                    }
                } while(scan.nextToken() == ',');
                if(scan.ttype != ')') {
                    throw new DatalogException("[line " + scan.lineno() + "] Expected ')'");
                }
            }
            Expr e = new Expr(lhs, terms);
            e.negated = negated;
            return e;
        } catch (IOException e) {
            throw new DatalogException(e);
        }
    }

    private static final List<String> validOperators = Arrays.asList(new String[] {"=", "!=", "<>", "<", "<=", ">", ">="});

    /* Parses one of the built-in predicates, eg X <> Y
     * It is represented internally as a Expr with the operator as the predicate and the
     * operands as its terms, eg. <>(X, Y)
     */
    private static Expr parseBuiltInPredicate(String lhs, StreamTokenizer scan) throws DatalogException {
        try {
            String operator;
            scan.nextToken();
            if(scan.ttype == StreamTokenizer.TT_WORD) {
                // At some point I was going to have "eq" and "ne" for string comparisons, but it wasn't a good idea.
                operator = scan.sval;
            } else {
                operator = Character.toString((char)scan.ttype);
                scan.nextToken();
                if(scan.ttype == '=' || scan.ttype == '>') {
                    operator = operator + Character.toString((char)scan.ttype);
                } else {
                    scan.pushBack();
                }
            }

            if(!validOperators.contains(operator)) {
                throw new DatalogException("Invalid operator '" + operator + "'");
            }

            String rhs = null;
            scan.nextToken();
            if(scan.ttype == StreamTokenizer.TT_WORD) {
                rhs = scan.sval;
            } else if(scan.ttype == '"' || scan.ttype == '\'') {
                rhs = scan.sval;
            } else if(scan.ttype == StreamTokenizer.TT_NUMBER) {
                rhs = numberToString(scan.nval);
            } else {
                throw new DatalogException("[line " + scan.lineno() + "] Right hand side of expression expected");
            }

            return new Expr(operator, lhs, rhs);

        } catch (IOException e) {
            throw new DatalogException(e);
        }
    }

    /* Converts a number to a string - The StreamTokenizer returns numbers as doubles by default
     * so we need to convert them back to strings to store them in the expressions */
    private static String numberToString(double nval) {
        // Remove trailing zeros; http://stackoverflow.com/a/14126736/115589
        if(nval == (long) nval)
            return String.format("%d",(long)nval);
        else
            return String.format("%s",nval);
    }

    // Regex for tryParseDouble()
    // There are several suggestions at http://stackoverflow.com/q/1102891/115589, but I chose to roll my own.
    private static final Pattern numberPattern = Pattern.compile("[+-]?\\d+(\\.\\d*)?([Ee][+-]?\\d+)?");

    /* Checks, via regex, if a String can be parsed as a Double */
    static boolean tryParseDouble(String str) {
        return numberPattern.matcher(str).matches();
    }
}


text:
LevelUpCommand::LevelUpCommand()
{
	Requires(Robot::elevator);
	// Use Requires() here to declare subsystem dependencies
	// eg. Requires(chassis);
}

// Called just before this Command runs the first time
void LevelUpCommand::Initialize()
{

}

// Called repeatedly when this Command is scheduled to run
void LevelUpCommand::Execute()
{

	if(Robot::elevator->snapsToLevel())
	{
		Robot::elevator->SetSetpoint((Robot::elevator->closestLevel()+1.0)*Elevator::kLevelInterval);
	}
	else
	{
		int nextHighest = ((int)Robot::elevator->GetPosition()/Elevator::kLevelInterval)+1;
		Robot::elevator->SetSetpoint(nextHighest*Elevator::kLevelInterval);
	}
}

// Make this return true when this Command no longer needs to run execute()
bool LevelUpCommand::IsFinished()
{
	return true;
}

// Called once after isFinished returns true
void LevelUpCommand::End()
{

}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void LevelUpCommand::Interrupted()
{

}


text:
<?php

include '../config.php';
include '../functions.php';

doc_header($titleprefix, "Export");

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed.");
}

echo "
Export
\n";

$res = $conn->query("select d.date, d.name, d.rank, d.pos, d.donations, d.trophies, d.crowns, d.excused, d.pos, d.cfwins, d.id from ${table_name_prefix}data d where d.date=(select max(date) from ${table_name_prefix}data)");

display_result($res);

echo "Back to top\n";

$conn->close();

doc_end();

?>


text:
from os import sep
from os.path import join, realpath, dirname
from fabric.api import cd, env, local, run, sudo, require, settings
from fabric.contrib.project import rsync_project
from fabric.context_managers import hide
from fabric.operations import _prefix_commands, _prefix_env_vars

env.disable_known_hosts = True # always fails for me without this
env.root = '/opt/webapps/example_project'
env.proj_root = env.root + '/src/chef-cookbooks/example_project'
env.proj_repo = 'git@github.com:lincolnloop/chef-cookbooks.git'
env.pip_file = env.proj_root + '/requirements.pip'
env.chef_executable = '/var/lib/gems/1.8/bin/chef-solo'
env.cookbook_repo = 'git://github.com/lincolnloop/chef-cookbooks.git'
env.cookbook_rev = 'HEAD'
env.config_root = join(realpath(dirname(__file__)), 'config')

env.roledefs = {
    'dev': ['exampleproject'],
}

# Default to the dev role if no role was specified
if not env.get('roles') and not env.get('hosts'):
    env.roles = ['dev']

def deploy():
    """Update source, update pip requirements, syncdb, restart server"""
    update()
    update_reqs()
    syncdb()
    restart()

def switch(branch):
    """Switch the repo branch which the server is using"""
    with cd(env.proj_root):
        ve_run('git checkout %s' % branch)
    restart()

def version():
    """Show last commit to repo on server"""
    with cd(env.proj_root):
        sshagent_run('git log -1')

def restart():
    """Restart Apache process"""
    run('touch %s/etc/apache/django.wsgi' % env.root)

def update_reqs():
    """Update pip requirements"""
    ve_run('yes w | pip install -r %s' % env.pip_file)

def update():
    """Updates project source"""
    with cd(env.proj_root):
        sshagent_run('git pull')

def syncdb():
    """Run syncdb (along with any pending south migrations)"""
    ve_run('manage.py syncdb --migrate --noinput')

def clone():
    """Clone the repository for the first time"""
    with cd('%s/src' % env.root):
        sshagent_run('git clone %s' % env.proj_repo)
    ve_run('pip install -e %s' % env.proj_root)

    with cd('%s/myapp/conf/local' % env.proj_root):
        run('ln -s ../dev/__init__.py')
        run('ln -s ../dev/settings.py')

def sync_config():
    """
    Synchronizes the local configuration files to the server, and runs
    chef-solo to update the server.
    """
    rsync_project(remote_dir='~/.chefconfig/',
                  local_dir=env.config_root + sep, delete=True)
    sudo('rsync -az ~/.chefconfig/ /etc/chef/')
    sudo('sudo chown -R root:root /etc/chef/')
    with cd("/etc/chef/cookbooks"):
        sudo('git reset %s --hard && git pull' % env.cookbook_rev)

    sudo('%s -j /etc/chef/nodes/%s.json' % (env.chef_executable, env.host))

def bootstrap_chef():
    """
    Installs the necessary dependencies for chef-solo, and run an initial
    synchronization of the config.
    """
    with settings(user='root'):
        # Install the necessary packages
        run('apt-get update')
        run('apt-get -y dist-upgrade')
        run('apt-get install -y git-core rubygems ruby ruby-dev')
        run('gem install --no-rdoc --no-ri chef')

        # Copy the local configuration to the server
        rsync_project(remote_dir='/etc/chef/', local_dir=env.config_root + sep)

        with settings(warn_only=True):
            with hide('everything'):
                test_cookbook_dir = run('test -d /etc/chef/cookbooks')

        # If the /etc/chef/cookbooks directory already exists, then make
        # sure the cookbook repo is up to date.  Otherwise, clone it.
        if not test_cookbook_dir.return_code == 0:
            sshagent_run('git clone %s /etc/chef/cookbooks'
                         % env.cookbook_repo)

        with cd('/etc/chef/cookbooks'):
            sshagent_run('git reset %s --hard && git pull' % env.cookbook_rev)

        run('%s -j /etc/chef/nodes/%s.json' % (env.chef_executable, env.host))

def ve_run(cmd):
    """
    Helper function.
    Runs a command using the virtualenv environment
    """
    require('root')
    return sshagent_run('source %s/bin/activate; %s' % (env.root, cmd))

def sshagent_run(cmd):
    """
    Helper function.
    Runs a command with SSH agent forwarding enabled.

    Note:: Fabric (and paramiko) can't forward your SSH agent.
    This helper uses your system's ssh to do so.
    """
    # Handle context manager modifications
    wrapped_cmd = _prefix_commands(_prefix_env_vars(cmd), 'remote')
    try:
        host, port = env.host_string.split(':')
        return local(
            "ssh -p %s -A %s@%s '%s'" % (port, env.user, host, wrapped_cmd)
        )
    except ValueError:
        return local(
            "ssh -A %s@%s '%s'" % (env.user, env.host_string, wrapped_cmd)
        )


text:
ALTER TABLE modifications
ADD COLUMN materialId INTEGER;

-- associate modifications with materials

update modifications
SET materialId=
    (SELECT materials.id
    FROM materials
    JOIN pipelines
    ON materials.pipelineId=pipelines.id
    AND pipelines.id=modifications.pipelineId
    LIMIT 1);

CREATE INDEX idx_modifications_materialId ON modifications(materialId);
CREATE INDEX idx_modifications_modifiedtime ON modifications(modifiedtime);

-- copy modifications onto new materials for svn repos with multiple materials
-- this is for some number of historical pipelines that were created when
-- multiple materials support was not complete

INSERT INTO modifications(TYPE, USERNAME, COMMENT, EMAILADDRESS, REVISION, MODIFIEDTIME, PIPELINEID, FROMEXTERNAL, MATERIALID )
SELECT m1.TYPE, m1.USERNAME, m1.COMMENT, m1.EMAILADDRESS, m1.REVISION, m1.MODIFIEDTIME, m1.PIPELINEID, m1.FROMEXTERNAL, materials.ID
FROM modifications m1
JOIN materials on  m1.pipelineid = materials.pipelineid
WHERE not exists(select 1 from modifications where modifications.materialId = materials.id);

ALTER TABLE modifications
ALTER COLUMN materialId SET NOT NULL;

ALTER TABLE modifications
ADD CONSTRAINT fk_modifications_materials
FOREIGN KEY (materialId)
REFERENCES materials(id) ON DELETE CASCADE;

--//@UNDO

ALTER TABLE modifications DROP COLUMN materialId;


text:
package org.hisp.dhis.reporting.document.action;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.document.Document;
import org.hisp.dhis.document.DocumentService;
import org.hisp.dhis.external.location.LocationManager;
import org.hisp.dhis.external.location.LocationManagerException;

import com.opensymphony.xwork2.Action;

/**
 * @author Lars Helge Overland
 */
public class RemoveDocumentAction
    implements Action
{
    private static final Log log = LogFactory.getLog( RemoveDocumentAction.class );

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private LocationManager locationManager;

    public void setLocationManager( LocationManager locationManager )
    {
        this.locationManager = locationManager;
    }

    private DocumentService documentService;

    public void setDocumentService( DocumentService documentService )
    {
        this.documentService = documentService;
    }

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private Integer id;

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

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
    {
        if ( id != null )
        {
            Document document = documentService.getDocument( id );

            if ( !document.isExternal() )
            {
                try
                {
                    File file = locationManager.getFileForReading( document.getUrl(), DocumentService.DIR );

                    if ( file.delete() )
                    {
                        log.info( "Document " + document.getUrl() + " successfully deleted" );
                    }
                    else
                    {
                        log.warn( "Document " + document.getUrl() + " could not be deleted" );
                    }
                }
                catch ( LocationManagerException ex )
                {
                    log.warn( "An error occured while deleting " + document.getUrl() );
                }
            }

            documentService.deleteDocument( document );
        }

        return SUCCESS;
    }
}


text:
package org.xlrnet.metadict.core.services.query;

import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.xlrnet.metadict.api.language.Language;

import java.io.Serializable;

/**
 * Query step for executing a Monolingual query.
 */
public class MonolingualQueryStep extends AbstractQueryStep implements Serializable {

    private static final long serialVersionUID = -9136988588523162829L;

    private Language requestLanguage;

    public Language getRequestLanguage() {
        return this.requestLanguage;
    }

    public MonolingualQueryStep setRequestLanguage(Language requestLanguage) {
        this.requestLanguage = requestLanguage;
        return this;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.searchEngineName, this.queryString, this.searchEngine, this.requestLanguage);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("searchEngineName", this.searchEngineName)
                .add("queryString", this.queryString)
                .add("requestLanguage", this.requestLanguage)
                .toString();
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) return true;
        if (!(o instanceof MonolingualQueryStep)) return false;
        MonolingualQueryStep queryStep = (MonolingualQueryStep) o;
        return Objects.equal(this.requestLanguage, queryStep.requestLanguage) &&
                Objects.equal(this.searchEngineName, queryStep.searchEngineName) &&
                Objects.equal(this.queryString, queryStep.queryString) &&
                Objects.equal(this.searchEngine, queryStep.searchEngine);
    }
}


text:
#ifndef _PLUGIN_H_
#define _PLUGIN_H_

#include "bfd.h"

void bfd_plugin_set_program_name (const char *);
void bfd_plugin_set_plugin (const char *);

typedef struct plugin_data_struct
{
  int nsyms;
  const struct ld_plugin_symbol *syms;
}
plugin_data_struct;

#endif


text:
from subprocess import call

import platform

def say(what):
    command = {
        "Darwin": "say",
        "Linux": "espeak"
    }[platform.system()]

    call([command, what])


text:
#include "Tree.h"
#include "Particle.h"

class ParticleSystem {
protected:
	float timeStep;
	vector<Particle> particles;
	Tree* tree;

public:
	ParticleSystem();

	void setTimeStep(float timeStep);

	void add(Particle& p);
	vector<Particle*> getNeighbors(float x, float y, float radius) const;
	unsigned size() const;
	Particle& operator[](unsigned i);

	void setupForces();
	void addRepulsionForce(const Particle& particle, float radius, float scale);
	void addRepulsionForce(float x, float y, float radius, float scale);
	void addAttractionForce(const Particle& particle, float radius, float scale);
	void addAttractionForce(float x, float y, float radius, float scale);
	void addForce(const Particle& particle, float radius, float scale);
	void addForce(float x, float y, float radius, float scale);
	void update();

	void draw();
    vector<Particle>& getParticles();
};


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
  <title>Test For Show Promise That Resolves With Empty Dictionary</title>
  <link rel="stylesheet" type="text/css" href="../style.css">
  <link rel="manifest" href="app.json">

<button onclick="buy()" id="buy">Buy</button>

<button onclick="buyWithCurrentUrlMethod()" id="buyWithCurrentUrlMethod">Buy using the current URL as the method</button>

<button onclick="buyWithUrlMethod()" id="buyWithUrlMethod">Buy with URL method</button>


text:
package com.project.module.main;

import android.os.Bundle;
import android.support.v4.view.ViewPager;

import com.code.base.activity.BaseActivity;
import com.code.listener.ItemHandle;
import com.code.listener.PageChange;
import com.code.view.TabLayout;
import com.study.niu.niustudydemo.R;

import butterknife.BindView;

public class MainActivity extends BaseActivity {

    private long exitTime;
    @BindView(R.id.tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.main_viewpager)
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViewPager();
    }

    private void initViewPager() {
        mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager(), this));
        mViewPager.addOnPageChangeListener(new PageChange() {
            @Override
            public void onPageSelected(int position) {
                mTabLayout.selectItem(position);
            }
        });
        mTabLayout.setOnItemHandleListener(new ItemHandle() {
            @Override
            public void onItemClick(int position) {
                mViewPager.setCurrentItem(position);
            }
        });
    }

    @Override
    public void doActivityStateChange(boolean isForeground) {
        if (isForeground) {
            showToast("前台");
        } else {
            showToast("后台");
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast(getString(R.string.exit_app), true);
            exitTime = System.currentTimeMillis();
        } else {
            isExitApp = true;
            finish();
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.galagosearch.core.retrieval.extents;

import org.galagosearch.core.retrieval.structured.ScoreCombinationIterator;
import org.galagosearch.core.retrieval.structured.UnfilteredCombinationIterator;
import java.io.IOException;
import junit.framework.TestCase;
import org.galagosearch.tupleflow.Parameters;

/**
 *
 * @author trevor
 */
public class UnfilteredCombinationIteratorTest extends TestCase {
    public UnfilteredCombinationIteratorTest(String testName) {
        super(testName);
    }
    int[] docsA = new int[]{5, 10, 15, 20};
    double[] scoresA = new double[]{1.0, 2.0, 3.0, 4.0};
    int[] docsB = new int[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    double[] scoresB = new double[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int[] docsTogether = new int[]{2, 4, 5, 6, 8, 10, 12, 14, 15, 16, 18, 20};
    double[] scoresTogether = new double[]{2, 4, 1, 6, 8, 12, 12, 14, 3, 16, 18, 24};

    public void testNextCandidateAny() throws IOException {
        FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
        FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
        FakeScoreIterator[] iterators = { one, two };

        Parameters anyParameters = new Parameters();
        UnfilteredCombinationIterator instance = new UnfilteredCombinationIterator(anyParameters,
                                                                                iterators);

        assertEquals(2, instance.nextCandidate());
        instance.movePast(2);
        assertEquals(4, instance.nextCandidate());
        instance.movePast(4);
        assertEquals(5, instance.nextCandidate());
        instance.movePast(5);
        assertEquals(6, instance.nextCandidate());
    }

    public void testHasMatch() {
        FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
        FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
        FakeScoreIterator[] iterators = { one, two };

        Parameters anyParameters = new Parameters();
        ScoreCombinationIterator instance = new UnfilteredCombinationIterator(anyParameters,
                                                                              iterators);

        assertFalse(instance.hasMatch(1));
        assertTrue(instance.hasMatch(2));
        assertFalse(instance.hasMatch(3));
    }

    public void testScore() throws IOException {
        FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
        FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
        FakeScoreIterator[] iterators = { one, two };

        Parameters anyParameters = new Parameters();
        UnfilteredCombinationIterator instance = new UnfilteredCombinationIterator(anyParameters,
                                                                                iterators);

        for (int i = 0; i < 12; i++) {
            assertFalse(instance.isDone());
            assertTrue(instance.hasMatch(docsTogether[i]));
            assertEquals(scoresTogether[i], instance.score(docsTogether[i], 100));

            instance.movePast(docsTogether[i]);
        }

        assertTrue(instance.isDone());
    }

    public void testMovePast() throws Exception {
        FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
        FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
        FakeScoreIterator[] iterators = { one, two };

        Parameters anyParameters = new Parameters();
        UnfilteredCombinationIterator instance = new UnfilteredCombinationIterator(anyParameters,
                                                                                iterators);

        instance.movePast(5);
        assertEquals(6, instance.nextCandidate());
    }

    public void testMoveTo() throws Exception {
        FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
        FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
        FakeScoreIterator[] iterators = { one, two };

        Parameters anyParameters = new Parameters();
        UnfilteredCombinationIterator instance = new UnfilteredCombinationIterator(anyParameters,
                                                                                iterators);

        instance.moveTo(5);
        assertEquals(5, instance.nextCandidate());
    }
}


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

<title>G-Index</title>
<meta name="date" content="2015-07-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I M N O P R S T U V

G

GenericBankNowException - Exception in pl.garciapl.banknow.service.exceptions

GenericBankNowException

GenericBankNowException(String) - Constructor for exception pl.garciapl.banknow.service.exceptions.GenericBankNowException

getAccount(Model) - Method in class pl.garciapl.banknow.controller.AccountController

Returns view with form to creation of account

getAccountByIban(BigInteger) - Method in interface pl.garciapl.banknow.dao.AccountDAO

getAccountByIban() - Method in class pl.garciapl.banknow.dao.AccountDAOTest

getAccountByIban(BigInteger) - Method in class pl.garciapl.banknow.dao.impl.AccountDAOImpl

Fetches account for particular iban

getAccountByIbanReturnsNull() - Method in class pl.garciapl.banknow.dao.AccountDAOTest

getAccountByNameSurname(String, String) - Method in interface pl.garciapl.banknow.dao.AccountDAO

getAccountByNameSurname() - Method in class pl.garciapl.banknow.dao.AccountDAOTest

getAccountByNameSurname(String, String) - Method in class pl.garciapl.banknow.dao.impl.AccountDAOImpl

Fetches account with particular name and surname

getAccountByNameSurnameReturnsNull() - Method in class pl.garciapl.banknow.dao.AccountDAOTest

getAccountTest() - Method in class pl.garciapl.banknow.controller.AccountControllerTest

getAddress() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getAddress() - Method in class pl.garciapl.banknow.model.Account

getAllAccounts() - Method in interface pl.garciapl.banknow.dao.AccountDAO

getAllAccounts() - Method in class pl.garciapl.banknow.dao.impl.AccountDAOImpl

Fetches all accounts

getAllAccounts() - Method in interface pl.garciapl.banknow.service.AccountService

getAllAccounts() - Method in class pl.garciapl.banknow.service.impl.AccountServiceImpl

Fetches all accounts

getAllAccountsTest() - Method in class pl.garciapl.banknow.dao.AccountDAOTest

getAllAccountsTest() - Method in class pl.garciapl.banknow.service.AccountServiceTest

getAllTransactions() - Method in class pl.garciapl.banknow.dao.impl.TransactionDAOImpl

Fetches all transactions

getAllTransactions() - Method in interface pl.garciapl.banknow.dao.TransactionDAO

getAllTransactions() - Method in class pl.garciapl.banknow.service.impl.TransactionServiceImpl

Fetches all transactions

getAllTransactions() - Method in interface pl.garciapl.banknow.service.TransactionService

getAllTransactionsTest() - Method in class pl.garciapl.banknow.dao.TransactionDAOTest

getAllTransactionsTest() - Method in class pl.garciapl.banknow.service.TransactionServiceTest

getAmount() - Method in class pl.garciapl.banknow.controller.domain.DepositForm

getAmount() - Method in class pl.garciapl.banknow.controller.domain.TransferForm

getAmount() - Method in class pl.garciapl.banknow.model.Transaction

getBalance() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getBalance() - Method in class pl.garciapl.banknow.model.Account

getCurrency() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getCurrency() - Method in class pl.garciapl.banknow.model.Account

getDeposit(Model) - Method in class pl.garciapl.banknow.controller.OperationsController

Returns view for performing deposit operations

getDepositTest() - Method in class pl.garciapl.banknow.controller.OperationsControllerTest

getIban() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getIban() - Method in class pl.garciapl.banknow.model.Account

getId() - Method in class pl.garciapl.banknow.model.Account

getId() - Method in class pl.garciapl.banknow.model.Transaction

getIndexTest() - Method in class pl.garciapl.banknow.controller.HomeControllerTest

getMainTest() - Method in class pl.garciapl.banknow.controller.HomeControllerTest

getName() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getName() - Method in class pl.garciapl.banknow.model.Account

getPhone() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getPhone() - Method in class pl.garciapl.banknow.model.Account

getRecipient() - Method in class pl.garciapl.banknow.controller.domain.DepositForm

getRecipient() - Method in class pl.garciapl.banknow.controller.domain.TransferForm

getRecipient() - Method in class pl.garciapl.banknow.model.Transaction

getSender() - Method in class pl.garciapl.banknow.controller.domain.TransferForm

getSender() - Method in class pl.garciapl.banknow.model.Transaction

getSurname() - Method in class pl.garciapl.banknow.controller.domain.AccountForm

getSurname() - Method in class pl.garciapl.banknow.model.Account

getTest() - Method in class pl.garciapl.banknow.controller.HomeControllerTest

getTransactionsTest() - Method in class pl.garciapl.banknow.controller.TransactionsControllerTest

getTransfer(Model) - Method in class pl.garciapl.banknow.controller.OperationsController

Returns view for performing transfer operations

getTransferTest() - Method in class pl.garciapl.banknow.controller.OperationsControllerTest

getType() - Method in class pl.garciapl.banknow.model.Transaction

A B C D E F G H I M N O P R S T U V

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
unset CDPATH
cd "$( dirname "${BASH_SOURCE[0]}" )"

source ../../bashbooster.sh

bb-flag? 'flag' || bb-log-info "Flag is not set"
bb-flag-set 'flag'
bb-flag? 'flag' && bb-log-info "Flag is set"
bb-flag-unset 'flag'
bb-flag? 'flag' || bb-log-info "Flag is not set"
bb-flag-set 'flag'
bb-flag-clean


text:
package com.jason.json_examples;

import static java.lang.System.out;

import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonExamples {
	public static void main(String[] args) {
		JSONObject response = new JSONObject();

		/*Json array from ArrayList */
		List<String> list1 = Arrays.asList("1","2","3");
		response.put("example1",JSONArray.fromObject(list1) );
		out.println(response);

		/*Json array from javabean */
		Bean bean = new Bean();
		response.put("example2", JSONObject.fromObject(bean));
		out.println(response);
	}
}


text:
var _ = require("underscore");
var express = require("express");

module.exports = function (app, mongoose) {

    // Add an API endpoint to be used internally by this module
    app.get('/api-docs', function (req, res) {
        try {
            if (app.routes) {
                // Extract all API routes in one array  in case of express3
                var routes = _.flatten(app.routes);
            }
            else {
                // Extract all API routes in one array  in case of express4
                var arr = [];
                _.each(app._router.stack, function (route) {
                    if (!_.isUndefined(route.route)) {
                        route.route.method = Object.keys(route.route.methods).toString();
                        arr.push(route.route);
                    } else if(route.handle.stack) {
                        // Extract routes from middlewere installed Router
                        _.each(route.handle.stack, function (route) {
                            if (!_.isUndefined(route.route)) {
                                route.route.method = Object.keys(route.route.methods).toString();
                                arr.push(route.route);
                            }
                        });
                    }
                });
                routes = arr;
            }
            // Group routes by resource name
            routes = _.groupBy(routes, function (route) {
                return route.path.split("/")[1];
            });

            // Skip the routes to be used internally by this module
            delete routes['api-docs'];

            // Transform route groups object to an array of group/routes pairs
            routes = _.pairs(routes);

            var schemas;

            if (mongoose)
                schemas = generateSchemaDocs(mongoose);

            res.send({routes: routes, schemas: schemas});
        } catch (e) {
            res.status(400).send(e)
            // res.send(400,e);
        }
    });

    // Configure the directory which holds html docs template
    app.use(express.static(__dirname + '/html'));
};

var nestedSchemas;

// Transform mongoose model schemas into a readable format
function generateSchemaDocs(mongoose) {

    nestedSchemas = [];
    // Transform models object to an array
    var schemas = _.pairs(mongoose.modelSchemas);

    // Map each schema to a readable format
    schemas = _.map(schemas, function (schema) {
        var info = getSchemaInfo(schema);
        return info;
    });

    // Add nested schemas
    schemas = schemas.concat(nestedSchemas);
    return schemas;
}

function getSchemaInfo(schema) {

    // Extract schema info for all fields of a schema
    var paths = _.map(schema[1].paths, function (path) {

        // Extract field info like type, required, enum etc.
        var info = getFieldInfo(path);

        // If field is a nested array with a custom, add it's schema to nested schemas
        if (info && info.schema)
            nestedSchemas.push(info.schema);

        return info;
    });

    // Add virtual fields to schema info
    _.each(schema[1].virtuals, function (virtual) {
        if (virtual.path != "id")
            paths.push({name: virtual.path, type: "Unknown"});
    });

    return {name: schema[0], fields: paths};
}

function getFieldInfo(path) {

    var field = {name: path.path, type: path.instance};

    if (path.options.type) {
        field.type = path.options.type.name;

        if (path.options.type instanceof Array && !path.schema){
            if(path.options.type[0])
            field.type = path.options.type[0].schemaName + " []";
        }
    }

    field.min = path.options.min;
    field.max = path.options.max;

    if (path.enumValues && path.enumValues.length > 0)
        field.enumValues = path.enumValues;

    if (path.schema) {
        // This field is a nested array with a custom schema
        field.type = field.name;
        // Get schema info for the array item schema
        field.schema = getSchemaInfo([field.name, path.schema]);
    }

    if (path.isRequired)
        field.required = true;

    return field;
}