text:
set -euxo pipefail
setup_ssh_for_user() {
  local user="${1}"
  local home_dir
  home_dir=$(eval echo "~${user}")

  mkdir -p "${home_dir}"/.ssh
  touch "${home_dir}/.ssh/authorized_keys" "${home_dir}/.ssh/known_hosts" "${home_dir}/.ssh/config"
  ssh-keygen -t rsa -N "" -f "${home_dir}/.ssh/id_rsa"
  cat "${home_dir}/.ssh/id_rsa.pub" >> "${home_dir}/.ssh/authorized_keys"
  chmod 0600 "${home_dir}/.ssh/authorized_keys"
  cat << 'NOROAMING' >> "${home_dir}/.ssh/config"
Host *
  UseRoaming no
NOROAMING
  chown -R "${user}" "${home_dir}/.ssh"
}

ssh_keyscan_for_user() {
  local user="${1}"
  local home_dir
  home_dir=$(eval echo "~${user}")

  {
    ssh-keyscan localhost
    ssh-keyscan 0.0.0.0
    ssh-keyscan github.com
  } >> "${home_dir}/.ssh/known_hosts"
}

transfer_ownership() {
  chown -R gpadmin:gpadmin gpdb_src
  [ -d /usr/local/gpdb ] && chown -R gpadmin:gpadmin /usr/local/gpdb
  [ -d /usr/local/greenplum-db-devel ] && chown -R gpadmin:gpadmin /usr/local/greenplum-db-devel
  chown -R gpadmin:gpadmin /home/gpadmin
}

set_limits() {
  # Currently same as what's recommended in install guide
  if [ -d /etc/security/limits.d ]; then
    cat > /etc/security/limits.d/gpadmin-limits.conf <<-EOF
		gpadmin soft core unlimited
		gpadmin soft nproc 131072
		gpadmin soft nofile 65536
	EOF
  fi
  # Print now effective limits for gpadmin
  su gpadmin -c 'ulimit -a'
}

setup_gpadmin_user() {
  groupadd supergroup
  case "$TEST_OS" in
    sles)
      groupadd gpadmin
      /usr/sbin/useradd -G gpadmin,supergroup,tty gpadmin
      ;;
    centos)
      /usr/sbin/useradd -G supergroup,tty gpadmin
      ;;
    *) echo "Unknown OS: $TEST_OS"; exit 1 ;;
  esac
  echo -e "password\npassword" | passwd gpadmin
  setup_ssh_for_user gpadmin
  transfer_ownership
  set_limits
}

setup_sshd() {
  test -e /etc/ssh/ssh_host_key || ssh-keygen -f /etc/ssh/ssh_host_key -N '' -t rsa1
  test -e /etc/ssh/ssh_host_rsa_key || ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
  test -e /etc/ssh/ssh_host_dsa_key || ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa

  # For Centos 7, disable looking for host key types that older Centos versions don't support.
  sed -ri 's@^HostKey /etc/ssh/ssh_host_ecdsa_key$@#&@' /etc/ssh/sshd_config
  sed -ri 's@^HostKey /etc/ssh/ssh_host_ed25519_key$@#&@' /etc/ssh/sshd_config

  # See https://gist.github.com/gasi/5691565
  sed -ri 's/UsePAM yes/UsePAM no/g' /etc/ssh/sshd_config
  # Disable password authentication so builds never hang given bad keys
  sed -ri 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config

  setup_ssh_for_user root

  /usr/sbin/sshd

  ssh_keyscan_for_user root
  ssh_keyscan_for_user gpadmin
}

determine_os() {
  if [ -f /etc/redhat-release ] ; then
    echo "centos"
    return
  fi
  if [ -f /etc/os-release ] && grep -q '^NAME=.*SLES' /etc/os-release ; then
    echo "sles"
    return
  fi
  echo "Could not determine operating system type" >/dev/stderr
  exit 1
}

_main() {
  TEST_OS=$(determine_os)
  setup_gpadmin_user
  setup_sshd
}

_main "$@"


text:
package org.assertj.core.api.comparable;

import static org.mockito.Mockito.verify;

import org.assertj.core.api.GenericComparableAssert;
import org.assertj.core.api.GenericComparableAssertBaseTest;

/**
 * Tests for <code>{@link org.assertj.core.api.AbstractComparableAssert#isLessThan(Comparable)}</code>.
 */
class GenericComparableAssert_isLessThan_Test extends GenericComparableAssertBaseTest {

  @Override
  protected GenericComparableAssert<Integer> invoke_api_method() {
    return assertions.isLessThan(8);
  }

  @Override
  protected void verify_internal_effects() {
    verify(comparables).assertLessThan(getInfo(assertions), getActual(assertions), 8);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.darkhouse.gdefence.Level.Ability.Tower;

import com.badlogic.gdx.utils.Array;
import com.darkhouse.gdefence.GDefence;
import com.darkhouse.gdefence.Helpers.AssetLoader;
import com.darkhouse.gdefence.Helpers.FontLoader;
import com.darkhouse.gdefence.Level.Ability.Tools.DamageType;
import com.darkhouse.gdefence.Level.Ability.Tools.Effect;
import com.darkhouse.gdefence.Level.Ability.Tools.Chance;
import com.darkhouse.gdefence.Level.Mob.Mob;
import com.darkhouse.gdefence.Model.Level.Map;
import com.darkhouse.gdefence.User;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class Bash extends Ability implements Ability.IOnHit{

    private class BashEffect extends Effect<Mob>{
//        private float startSpeed;

        public BashEffect(float duration) {
            super(false, true, duration, "bash");
        }

        @Override
        public void apply() {
//            startSpeed = owner.getSpeed();//bad idea
//            owner.changeSpeed(0);
            owner.setState(Mob.State.stunned);
        }

        @Override
        public void dispell() {
//            owner.changeSpeed(startSpeed);
            if(owner.getState() == Mob.State.stunned) owner.setState(Mob.State.normal); //dont dispell other effects, but dispell stuns
            super.dispell();
        }
    }
    public static class P extends AbilityPrototype {
        private G g;
        private S s;
        private AtomicReference<Float> chance;
        private AtomicReference<Float> duration;
        private AtomicReference<Integer> bonusDmg;

        public P(float chance, float duration, int bonusDmg, G grader) {
            super(0, "bash", grader.gemCap, IOnHit.class);
            this.chance = new AtomicReference<Float>(chance);
            this.duration = new AtomicReference<Float>(duration);
            this.bonusDmg = new AtomicReference<Integer>(bonusDmg);
            this.g = grader;
            s = new S(chance, duration, bonusDmg);
        }

//        USE IT FOR NEW ABILITY PROTOTYPE
        public P copy(){
            AssetLoader l = GDefence.getInstance().assetLoader;
            P p = new P(chance.get(), duration.get(), bonusDmg.get(), g);
            p.gemBoost[0] = new BoostInteger(p.bonusDmg, g.bonusDmgUp, l.getWord("bashGrade3"),
                    true, BoostInteger.IntegerGradeFieldType.NONE);
            p.gemBoost[1] = new BoostFloat(p.duration,   g.durationUp, l.getWord("bashGrade2"),
                    true, BoostFloat.FloatGradeFieldType.TIME);
            p.gemBoost[2] = new BoostFloat(p.chance,     g.chanceUp,   l.getWord("bashGrade1"),
                    true, BoostFloat.FloatGradeFieldType.PERCENT);
            p.s = new S(chance.get(), duration.get(), bonusDmg.get());
            return p;
        }
        @Override
        public void flush() {
            AssetLoader l = GDefence.getInstance().assetLoader;
            this.bonusDmg = new AtomicReference<Integer>(s.bonusDmg);
            this.duration = new AtomicReference<Float>(s.duration);
            this.chance = new AtomicReference<Float>(s.chance);
            gemBoost[0] = new BoostInteger(bonusDmg, g.bonusDmgUp, l.getWord("bashGrade3"),
                    true, BoostInteger.IntegerGradeFieldType.NONE);
            gemBoost[1] = new BoostFloat(duration,   g.durationUp, l.getWord("bashGrade2"),
                    true, BoostFloat.FloatGradeFieldType.TIME);
            gemBoost[2] = new BoostFloat(chance,     g.chanceUp,   l.getWord("bashGrade1"),
                    true, BoostFloat.FloatGradeFieldType.PERCENT);
        }

        @Override
        public Ability getAbility() {
            return new Bash(this);
        }

        @Override
        public String getTooltip() {
            AssetLoader l = GDefence.getInstance().assetLoader; ///*FontLoader.colorCode(0) + chance.get()*100 + "%[] "*/
            return l.getWord("bashTooltip1") + " " + FontLoader.colorString(chance.get()*100 + "%", User.GEM_TYPE.WHITE) + " " + l.getWord("bashTooltip2") + System.getProperty("line.separator") +
                   l.getWord("bashTooltip3") + " " + FontLoader.colorString(duration.get().toString(), User.GEM_TYPE.GREEN) + " " +
                   l.getWord("bashTooltip4") + " " + FontLoader.colorString(bonusDmg.get().toString(), User.GEM_TYPE.BLACK) + " " + l.getWord("bashTooltip5");
        }

        @Override
        public Array<Class<? extends AbilityPrototype>> getAbilitiesToSaveOnCraft() {
            return new Array<Class<? extends AbilityPrototype>>();
        }

//        @Override
//        public String getSaveCode() {
//            return super.getSaveCode() + "z" + chance + ";" + duration + ";" + bonusDmg + ";" + g.chanceUp + ";" + g.durationUp + ";" + g.bonusDmgUp;
//        }

//        protected String getBoostName(User.GEM_TYPE gemType){
//            switch (gemType) {
//                case BLACK: return "bash chance";
//                case GREEN: return "stun duration";
//                case WHITE: return "bonus stun damage";
//                default: return "error";
//            }
//        }
//        protected String getBoostValue(User.GEM_TYPE gemType){
//            G g = ((G) grader);//
//            switch (gemType) {
//                case BLACK: return "+ " + /*new DecimalFormat("##").format*/(g.chanceUp * 100) + "%";
//                case GREEN: return "+ " + new DecimalFormat("##.#").format(g.durationUp) + "s";
//                case WHITE: return "+ " + g.bonusDmgUp + "";
//                default: return "error";
//            }
//        }
//        protected String getCurrentValue(User.GEM_TYPE gemType){
//            switch (gemType) {
//                case BLACK: return new DecimalFormat("##").format(chance * 100) + "%";
//                case GREEN: return new DecimalFormat("##.#").format(duration) + "s";
//                case WHITE: return bonusDmg + "";
//                default: return "error";
//            }
//        }
//        protected String getBoostedValue(User.GEM_TYPE gemType){
//            G g = ((G) grader);//
//            switch (gemType) {
//                case BLACK: return new DecimalFormat("##").format(chance * 100 + g.chanceUp * 100) + "%";
//                case GREEN: return new DecimalFormat("##.#").format(duration + g.durationUp);
//                case WHITE: return (bonusDmg + g.bonusDmgUp) + "";
//                default: return "error";
//            }
//        }

    }
    public static class G extends AbilityGrader{
        protected float chanceUp;
        protected float durationUp;
        protected int bonusDmgUp;

        public G(float chanceUp, float durationUp, int bonusDmgUp, int[] gemCap) {
            super(gemCap);
            this.chanceUp = chanceUp;
            this.durationUp = durationUp;
            this.bonusDmgUp = bonusDmgUp;
        }
    }
    public static class S extends AbilitySaverStat{
        private float chance;
        private float duration;
        private int bonusDmg;

        public S(float chance, float duration, int bonusDmg) {
            this.chance = chance;
            this.duration = duration;
            this.bonusDmg = bonusDmg;
        }
    }

    private float chance;
    private float duration;
    private int bonusDmg;

    public Bash(P prototype) {
        this.chance = prototype.chance.get();
        this.duration = prototype.duration.get();
        this.bonusDmg = prototype.bonusDmg.get();
    }

    @Override
    public int getDmg(Mob target, int startDmg) {
        if(Chance.proc(chance)) {
            target.addEffect(new BashEffect(duration).setOwner(target));
            target.hit(bonusDmg, DamageType.Magic, owner);
        }
        return startDmg;
    }

    @Override
    protected void init(Map map) {

    }
}


text:
#include "phd.h"

#include "socket_server.h"
#include "cam_simulator.h"

#include <algorithm>
#include <functional>

static std::set<wxSocketBase *> s_clients;

enum {
    MSG_PAUSE = 1,
    MSG_RESUME,
    MSG_MOVE1,
    MSG_MOVE2,
    MSG_MOVE3,
    MSG_IMAGE,
    MSG_GUIDE,
    MSG_CAMCONNECT,
    MSG_CAMDISCONNECT,
    MSG_REQDIST,
    MSG_REQFRAME,
    MSG_MOVE4,
    MSG_MOVE5,
    MSG_AUTOFINDSTAR,
    MSG_SETLOCKPOSITION,    //15
    MSG_FLIPRACAL,          //16
    MSG_GETSTATUS,          //17
    MSG_STOP,               //18
    MSG_LOOP,               //19
    MSG_STARTGUIDING,       //20
    MSG_LOOPFRAMECOUNT,     //21
    MSG_CLEARCAL,           //22
    MSG_FLIP_SIM_CAMERA,    //23
    MSG_DESELECT,           //24
};

void MyFrame::OnServerMenu(wxCommandEvent &evt)
{
    SetServerMode(evt.IsChecked());
    StartServer(GetServerMode());
}

bool MyFrame::StartServer(bool state)
{
    if (state)
    {
        // Create the SocketServer socket
        unsigned int port = 4300 + m_instanceNumber - 1;
        wxIPV4address sockServerAddr;
        sockServerAddr.Service(port);
        SocketServer = new wxSocketServer(sockServerAddr);

        // We use Ok() here to see if the server is really listening
        if (!SocketServer->Ok())
        {
            Debug.AddLine(wxString::Format("Socket server failed to start - Could not listen at port %u", port));
            delete SocketServer;
            SocketServer = NULL;
            return true;
        }
        SocketServer->SetEventHandler(*this, SOCK_SERVER_ID);
        SocketServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
        SocketServer->Notify(true);

        // start the event server
        if (EvtServer.EventServerStart(m_instanceNumber))
        {
            delete SocketServer;
            SocketServer = NULL;
            return true;
        }

        SetStatusText(_("Server started"));
        Debug.AddLine(wxString::Format("Server started, listening on port %u", port));
    }
    else {
        Debug.AddLine("Server stopped");
        std::for_each(s_clients.begin(), s_clients.end(), std::mem_fun(&wxSocketBase::Destroy));
        s_clients.empty();
        EvtServer.EventServerStop();
        delete SocketServer;
        SocketServer = NULL;
        SetStatusText(_("Server stopped"));
    }

    return false;
}

void MyFrame::OnSockServerEvent(wxSocketEvent& event)
{
    wxSocketServer *server = static_cast<wxSocketServer *>(event.GetSocket());

    if (server == NULL)
        return;

    if (event.GetSocketEvent() != wxSOCKET_CONNECTION)
    {
        Debug.AddLine(wxString::Format("socket server event expected %d, got %d. ignoring it.",
            wxSOCKET_CONNECTION, event.GetSocketEvent()));
        return;
    }

    wxSocketBase *client = server->Accept(false);

    if (client)
    {
        pFrame->SetStatusText("New connection");
        Debug.AddLine("SOCKSVR: New connection");
    }
    else
    {
        Debug.AddLine("SOCKSVR: connection error");
        return;
    }

    client->SetEventHandler(*this, SOCK_SERVER_CLIENT_ID);
    client->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
    client->Notify(true);

    s_clients.insert(client);
}

double MyFrame::GetDitherAmount(int ditherType)
{
    switch (ditherType) {
    case 1: return 0.5;
    case 2: return 1.0;
    case 3: return 2.0;
    case 4: return 3.0;
    case 5: return 5.0;
    }
    return 1.0;
}

void MyFrame::HandleSockServerInput(wxSocketBase *sock)
{
    unsigned char rval = 0;

    try
    {
        // We disable input events, so that the test doesn't trigger
        // wxSocketEvent again.
        sock->SetNotify(wxSOCKET_LOST_FLAG);

        // Which command is coming in?
        unsigned char c;

        sock->Read(&c, 1);

        Debug.AddLine("read socket command %d", c);

        switch (c)
        {
            case MSG_PAUSE:
            case 'p':
                Debug.AddLine("processing socket request PAUSE");
                SetPaused(PAUSE_GUIDING);
                break;

            case MSG_RESUME:
            case 'r':
                Debug.AddLine("processing socket request RESUME");
                SetPaused(PAUSE_NONE);
                break;

            case MSG_MOVE1:  // +/- 0.5
            case MSG_MOVE2:  // +/- 1.0
            case MSG_MOVE3:  // +/- 2.0
            case MSG_MOVE4:  // +/- 3.0
            case MSG_MOVE5:  // +/- 5.0
            {
                Debug.AddLine("processing socket request MOVEn");

                int ditherType = 3;
                switch (c)
                {
                    case MSG_MOVE1: ditherType = 1; break;
                    case MSG_MOVE2: ditherType = 2; break;
                    case MSG_MOVE3: ditherType = 3; break;
                    case MSG_MOVE4: ditherType = 4; break;
                    case MSG_MOVE5: ditherType = 5; break;
                }

                double size = GetDitherAmount(ditherType);

                bool error = Dither(size, m_ditherRaOnly);
                if (error)
                {
                    throw ERROR_INFO("dither failed");
                }

                rval = RequestedExposureDuration() / 1000;
                if (rval < 1)
                {
                    rval = 1;
                }
                break;
            }

            case MSG_REQDIST:
            {
                Debug.AddLine("processing socket request REQDIST");
                if (!pGuider->IsGuiding())
                {
                    throw ERROR_INFO("cannot request distance if not guiding");
                }

                double currentError = pGuider->CurrentError();

                if (currentError > 2.55)
                {
                    rval = 255;
                }
                else
                {
                    rval = (unsigned char) (currentError * 100);
                }

                Debug.AddLine(wxString::Format("SOCKSVR: Sending pixel error of %.2f", (float) rval / 100.0));
                break;
            }

            case MSG_AUTOFINDSTAR:
                Debug.AddLine("processing socket request AUTOFINDSTAR");
                bool error;
                error = pFrame->pGuider->AutoSelect();
                rval = error ? 0 : 1;
                if (!error)
                {
                    StartLooping();
                }
                GuideLog.ServerCommand(pGuider, "AUTO FIND STAR");
                break;

            case MSG_SETLOCKPOSITION:
            {
                // Sets LockX and LockY to be user-specified
                unsigned short x,y;
                sock->Read(&x, 2);
                sock->Read(&y, 2);
                sock->Discard();  // Clean out anything else

                if (!pFrame->pGuider->SetLockPosToStarAtPosition(PHD_Point(x,y)))
                {
                    Debug.AddLine("processing socket request SETLOCKPOSITION for (%d, %d) succeeded", x, y);
                    pFrame->SetStatusText(wxString::Format("Lock set to %d,%d",x,y));
                    GuideLog.NotifySetLockPosition(pGuider);
                }
                else
                {
                    Debug.AddLine("processing socket request SETLOCKPOSITION for (%d, %d) failed", x, y);
                }
                break;
            }

            case MSG_FLIPRACAL:
            {
                Debug.AddLine("processing socket request FLIPRACAL");
                PauseType prev = pGuider->SetPaused(PAUSE_GUIDING);
                // return 1 for success, 0 for failure
                rval = 1;
                if (FlipRACal())
                {
                    rval = 0;
                }
                pGuider->SetPaused(prev);
                GuideLog.ServerCommand(pGuider, "FLIP RA CAL");
                break;
            }

            case MSG_GETSTATUS:
                Debug.AddLine("processing socket request GETSTATUS");
                rval = Guider::GetExposedState();
                break;

            case MSG_LOOP:
            {
                Debug.AddLine("processing socket request LOOP");
                StartLooping();
                GuideLog.ServerCommand(pGuider, "LOOP");
                break;
            }

            case MSG_STOP:
            {
                Debug.AddLine("processing socket request STOP");
                StopCapturing();
                GuideLog.ServerCommand(pGuider, "STOP");
                break;
            }

            case MSG_STARTGUIDING:
            {
                Debug.AddLine("processing socket request STARTGUIDING");
                bool err = StartGuiding();
                Debug.AddLine(wxString::Format("StartGuiding returned %d, guider state is %d", err, pFrame->pGuider->GetState()));
                GuideLog.ServerCommand(pGuider, "START GUIDING");
                break;
            }

            case MSG_LOOPFRAMECOUNT:
                Debug.AddLine("processing socket request LOOPFRAMECOUNT");
                if (!CaptureActive)
                {
                    rval = 0;
                }
                else if (m_frameCounter > UCHAR_MAX)
                {
                    rval = UCHAR_MAX;
                }
                else
                {
                    rval = m_frameCounter;
                }
                break;

            case MSG_CLEARCAL:
                Debug.AddLine("processing socket request CLEARCAL");

                if (pMount)
                    pMount->ClearCalibration();
                if (pSecondaryMount)
                    pSecondaryMount->ClearCalibration();

                GuideLog.ServerCommand(pGuider, "CLEAR CAL");
                break;

            case MSG_FLIP_SIM_CAMERA:
                Debug.AddLine("processing socket request flip camera simulator");
                if (pCamera && pCamera->Name == _T("Simulator"))
                {
                    Camera_SimClass *simcam = static_cast<Camera_SimClass *>(pCamera);
                    simcam->FlipPierSide();
                }
                break;

            case MSG_DESELECT:
                Debug.AddLine("processing socket request deselect");
                pFrame->pGuider->Reset(true);
                break;

            default:
                Debug.AddLine(wxString::Format("SOCKSVR: Unknown command char received from client: %d"), (int) c);
                rval = 1;
                break;
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
    }

    Debug.AddLine("Sending socket response %d (0x%x)", rval, rval);

    // Send response
    sock->Write(&rval,1);

    // Enable input events again.
    sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
}

void MyFrame::OnSockServerClientEvent(wxSocketEvent& event)
{
    try
    {
        wxSocketBase *sock = event.GetSocket();

        if (SocketServer == NULL)
        {
            throw ERROR_INFO("socket command when SocketServer == NULL");
        }

        // Now we process the event
        switch (event.GetSocketEvent())
        {
            case wxSOCKET_INPUT:
                HandleSockServerInput(sock);
                break;
            case wxSOCKET_LOST:
                Debug.AddLine("SOCKSVR: Client disconnected, deleting socket");
                size_t n;
                n = s_clients.erase(sock);
                assert(n > 0);
                sock->Destroy();
                break;
            default:
                break;
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
    }
}

#ifdef NEB_SBIG

// this code only works when there is a single socket connection from Nebulosity

static int SocketConnections;
static wxSocketBase *ServerEndpoint;

bool ServerSendGuideCommand (int direction, int duration) {
    // Sends a guide command to Nebulosity
    if (!pFrame->SocketServer || !SocketConnections)
        return true;

    unsigned char cmd = MSG_GUIDE;
    unsigned char rval = 0;
    Debug.AddLine(wxString::Format("Sending guide: %d %d", direction, duration));
//  cmd = 'Z';
    ServerEndpoint->Write(&cmd, 1);
    if (pFrame->SocketServer->Error())
        Debug.AddLine(_T("Error sending Neb command"));
    else {
        Debug.AddLine(_T("Cmd done - sending data"));
        ServerEndpoint->Write(&direction, sizeof(int));
        ServerEndpoint->Write(&duration, sizeof(int));
        ServerEndpoint->Read(&rval,1);
        Debug.AddLine(_T("Sent guide command - returned %d"), (int) rval);
    }
    return false;
}

bool ServerSendCamConnect(int& xsize, int& ysize) {
    if (!pFrame->SocketServer || !SocketConnections)
        return true;
    Debug.AddLine(_T("Sending cam connect request"));
    unsigned char cmd = MSG_CAMCONNECT;
    unsigned char rval = 0;

    ServerEndpoint->Write(&cmd, 1);
    if (pFrame->SocketServer->Error()) {
        Debug.AddLine(_T("Error sending Neb command"));
        return true;
    }
    else {
//      unsigned char c;
        ServerEndpoint->Read(&rval, 1);
        Debug.AddLine(_T("Cmd done - returned %d"), (int) rval);
    }
    if (rval)
        return true;
    else {  // cam connected OK
        // Should get x and y size back
        ServerEndpoint->Read(&xsize,sizeof(int));
        ServerEndpoint->Read(&ysize,sizeof(int));
        Debug.AddLine(_T("Guide chip reported as %d x %d"),xsize,ysize);
        return false;
    }
}

bool ServerSendCamDisconnect() {
    if (!pFrame->SocketServer || !SocketConnections)
        return true;

    Debug.AddLine(_T("Sending cam disconnect request"));
    unsigned char cmd = MSG_CAMDISCONNECT;
    unsigned char rval = 0;

    ServerEndpoint->Write(&cmd, 1);
    if (pFrame->SocketServer->Error()) {
        Debug.AddLine(_T("Error sending Neb command"));
        return true;
    }
    else {
//      unsigned char c;
        ServerEndpoint->Read(&rval, 1);
        Debug.AddLine(_T("Cmd done - returned %d"), (int) rval);
    }
    if (rval)
        return true;
    else
        return false;  // cam disconnected OK
}

bool ServerReqFrame(int duration, usImage& img) {
    if (!pFrame->SocketServer || !SocketConnections)
        return true;
    Debug.AddLine(_T("Sending guide frame request"));
    unsigned char cmd = MSG_REQFRAME;
    unsigned char rval = 0;

    ServerEndpoint->Write(&cmd, 1);
    if (pFrame->SocketServer->Error()) {
        Debug.AddLine(_T("Error sending Neb command"));
        return true;
    }
    else {
//      unsigned char c;
        ServerEndpoint->Read(&rval, 1);
        Debug.AddLine(_T("Cmd done - returned %d"), (int) rval);
    }
    if (rval)
        return true;
    else { // grab frame data
        // Send duration request
        ServerEndpoint->Write(&duration,sizeof(int));
        Debug.AddLine(_T("Starting %d ms frame"),duration);
        wxMilliSleep(duration); // might as well wait here nicely at least this long
        Debug.AddLine(_T("Reading frame - looking for %d pixels (%d bytes)"),img.NPixels,img.NPixels*2);
        unsigned short *dataptr;
        dataptr = img.ImageData;
        unsigned short buffer[512];
        int i, xsize, ysize, pixels_left, packet_size;
        xsize = img.Size.GetWidth();
        ysize = img.Size.GetHeight();
        pixels_left = img.NPixels;
        packet_size = 256;  // # pixels to get
        int j=0;
        while (pixels_left > 0) {
            ServerEndpoint->Read(&buffer,packet_size * 2);
            pixels_left -= packet_size;
            if ((j%100) == 0)
                Debug.AddLine(_T("%d left"),pixels_left);
            for (i=0; i<packet_size; i++, dataptr++)
                *dataptr = buffer[i];
            if (pixels_left < 256)
                packet_size = 256;
            ServerEndpoint->Write(&cmd,1);
            j++;
        }
        int min = 9999999;
        int max = -999999;
        dataptr = img.ImageData;
        for (i=0; i<(xsize * ysize); i++, dataptr++) {
            if (*dataptr > max) max = (int) *dataptr;
            else if (*dataptr < min) min = (int) *dataptr;
        }
        Debug.AddLine(_T("Frame received min=%d max=%d"),min,max);

//      ServerEndpoint->ReadMsg(img.ImageData,(xsize * ysize * 2));
        Debug.AddLine(_T("Frame read"));
    }

    return false;
}

#endif // NEB_SBIG


text:
Puppet::Type.type(:mysql_sql).provide(:mysql) do

  def run_unless_sql_command(sql)
    # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT',
    # which makes it easier to parse and process the output.
    run_sql_command('SELECT COUNT(*) FROM (' <<  sql << ') count')
  end

  def run_sql_command(sql)

    # mysql --defaults-group-suffix=slave

    command = [resource[:mysql_path]]
    command.push("--defaults-group-suffix=" + resource[:instance_name]) if resource[:instance_name]
    command.push("-S", resource[:socket]) if resource[:socket]
    command.push("-p" + resource[:password]) if resource[:password]
    command.push("-BN")
    command.push("-e", '"' + sql.gsub('"', '\"') + '"')
    command.push(resource[:db]) if resource[:db]

    if resource[:cwd]
      Dir.chdir resource[:cwd] do
        run_command(command)
      end
    else
      run_command(command)
    end
  end

  private

  def run_command(command)
    command = command.join ' '
    output = Puppet::Util::Execution.execute(command, {
      :uid                => 'root',
      :gid                => 'root',
      :failonfail         => false,
      :combine            => true,
      :override_locale    => true,
    })
    [output, $CHILD_STATUS.dup]
  end

end


text:
var Module = require('module')
  , fs = require('fs')
  , os = require('os')
  , path = require('path')
  , util = require('util');

var _resolveFilename = Module._resolveFilename;
var DEFAULT_STARTUP_FILE = path.normalize('./node_modules/module-locations-startup.json');
var DEFAULT_CACHE_FILE = path.join(os.tmpdir(), 'module-locations-cache.json') ;
var options = {
  startupFile: DEFAULT_STARTUP_FILE,
  cacheFile: DEFAULT_CACHE_FILE,
  cacheKiller: versionNumber(),
  statusCallback: function(message) {}
};
var filenameLookup = newFilenameLookup();
var cwd = process.cwd();
var stats = {
  cacheHit: 0,
  cacheMiss: 0,
  notCached: 0,
  loading: {
    startupFile: "did not attempted to load startup file",
    cacheFile: "did not attempted to load cache file"
  }
};

function toCanonicalPath(filename) {
  var relative = path.relative(cwd, filename);
  // do not cache files outside of the process.cwd() scope
  if (relative.indexOf("..") == 0)
    return undefined;

  return relative.replace("\\\\", "/")
}

function toAbsolutePath(filename) {
  return path.join(cwd, filename);
}

function resolveFilenameOptimized(request, parent) {
  var key = (toCanonicalPath(parent.id) + ":" + request );
  var canonical = filenameLookup[key];
  var filename = undefined;
  if (canonical)
    filename = toAbsolutePath(canonical);

  if (filename && fs.existsSync(filename)) {
    stats.cacheHit++;
    options.statusCallback(util.format("cache hit on module [%s]", filename));
    return filename;
  }
  else {
    filename = _resolveFilename.apply(Module, arguments);
    canonical = toCanonicalPath(filename);
    if (canonical && canonical.indexOf("node_modules") > -1) {
      filenameLookup[key] = canonical;
      scheduleSaveCache();
      options.statusCallback(util.format("cache miss on module [%s]", filename));
      stats.cacheMiss++;
    }
    else {
      options.statusCallback(util.format("module [%s] not cached", filename));
      stats.notCached++;
    }
    return filename;
  }
}

function loadModuleList() {

  stats.loading = {
    startupFile: "did not attempted to load startup file",
    cacheFile: "did not attempted to load cache file"
  };

  function tryLoadingFile(file, fileCaption, statsMember, fileLocation) {

    function report(message) {
      stats.loading[statsMember] = message;
      options.statusCallback(message);
    }

    try {
      if (fs.existsSync(file)) {
        var readFileNameLookup = JSON.parse(fs.readFileSync(file, 'utf-8'));
        if ((!options.cacheKiller) || (readFileNameLookup._cacheKiller === options.cacheKiller)) {
          filenameLookup = readFileNameLookup;
          report(util.format("loaded %s file from [%s]", fileCaption, fileLocation));
        }
        else
          report(util.format("dismissed %s file from [%s] because of different cache killer", fileCaption, fileLocation));
        return true;
      }
      report(util.format("%s file not found at [%s]", fileCaption, fileLocation));
      return false;
    }
    catch (e) {
      report(util.format("failed to load or parse %s file from [%s] with error [%s]", fileCaption, fileLocation, e));
      return false;
    }
  }

  tryLoadingFile(options.cacheFile, "cache", "cacheFile", options.cacheFile) ||
    tryLoadingFile(options.startupFile, "startup", "startupFile", options.startupFile) ||
    (filenameLookup = newFilenameLookup());
}

function start(opts) {
  if (opts) {
    if (opts.cacheFile)
      options.cacheFile = opts.cacheFile;
    if (opts.startupFile)
      options.startupFile = opts.startupFile;
    if (opts.cacheKiller) {
      options.cacheKiller = opts.cacheKiller;
      filenameLookup._cacheKiller = options.cacheKiller;
    }
    if (opts.statusCallback && typeof opts.statusCallback === 'function')
      options.statusCallback = opts.statusCallback;
  }
  Module._resolveFilename = resolveFilenameOptimized;
  loadModuleList();
}

function stop() {
  Module._resolveFilename = _resolveFilename;
  saveCache();
}

function saveCache(cb) {
  fs.writeFile(options.cacheFile, JSON.stringify(filenameLookup), onSaveError(cb, "cache", options.cacheFile));
  clearSaveCacheTimer();
}

function saveStartupList(cb) {
  fs.writeFile(options.startupFile, JSON.stringify(filenameLookup), onSaveError(cb));
}

function onSaveError(other, fileCaption, fileLocation) {
  return function handleSaveError(err) {
    if (err)
      options.statusCallback(util.format("failed to save %s file to [%s] with error [%s]", fileCaption, fileLocation, err));

    options.statusCallback(util.format("saved %s file to [%s]", fileCaption, fileLocation));

    if (other)
      other(err);
  }
}

var saveCacheTimer;
function clearSaveCacheTimer() {
  if (saveCacheTimer) {
    clearTimeout(saveCacheTimer);
    saveCacheTimer = null;
  }
}
function scheduleSaveCache() {
  clearSaveCacheTimer();
  saveCacheTimer = setTimeout(saveCache, 10*1000);
}

function versionNumber() {
  try {
    return require('./package.json').version.toString();
  }
  catch (e) {
    return undefined;                           }
}

function newFilenameLookup() {
  return {_cacheKiller: options.cacheKiller}
}

module.exports.loadModuleList = loadModuleList;
module.exports.start = start;
module.exports.stop = stop;
module.exports.saveCache = saveCache;
module.exports.saveStartupList = saveStartupList;
module.exports.DEFAULT_CACHE_FILE = DEFAULT_CACHE_FILE;
module.exports.DEFAULT_STARTUP_FILE = DEFAULT_STARTUP_FILE;
module.exports.stats = function () {
  return {
    cacheHit: stats.cacheHit,
    cacheMiss: stats.cacheMiss,
    notCached: stats.notCached,
    cacheKiller: filenameLookup._cacheKiller,
    loading: {
      startupFile: stats.loading.startupFile,
      cacheFile: stats.loading.cacheFile
    }
  }
};


text:
Object.defineProperty(Object.prototype, 'spawn', {
    value: function() {
        return Object.create(this, descriptors.apply(this, arguments));
    }
});

Object.defineProperty(Object.prototype, 'extend', {
    value: function() {
        return Object.defineProperties(this, descriptors.apply(this, arguments));
    }
});

var descriptors = function() {
    var d = {};
    [].slice.call(arguments).forEach(function(o) {
        if (o instanceof Object) {
            Object.keys(o).forEach(function(k) {
                d[k] = {
                    configurable: true,
                    enumerable: true,
                    value: o[k],
                    writeable: true
                };
            });
        }
    });
    return d;
};


text:
<?php

##|+PRIV
##|*IDENT=page-firewall-schedules-edit
##|*NAME=Firewall: Schedules: Edit
##|*DESCR=Allow access to the 'Firewall: Schedules: Edit' page.
##|*MATCH=firewall_schedule_edit.php*
##|-PRIV

function schedulecmp($a, $b) {
	return strcmp($a['name'], $b['name']);
}

function schedule_sort() {
	global $g, $config;

	if (!is_array($config['schedules']['schedule'])) {
		return;
	}

	usort($config['schedules']['schedule'], "schedulecmp");
}

require_once("guiconfig.inc");
require_once("functions.inc");
require_once("filter.inc");
require_once("shaper.inc");

$pgtitle = array(gettext("Firewall"), gettext("Schedules"), gettext("Edit"));
$pglinks = array("", "firewall_schedule.php", "@self");

$referer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/firewall_schedule.php');

$dayArray = array (gettext('Mon'), gettext('Tues'), gettext('Wed'), gettext('Thur'), gettext('Fri'), gettext('Sat'), gettext('Sun'));
$monthArray = array (gettext('January'), gettext('February'), gettext('March'), gettext('April'), gettext('May'), gettext('June'), gettext('July'), gettext('August'), gettext('September'), gettext('October'), gettext('November'), gettext('December'));

init_config_arr(array('schedules', 'schedule'));
$a_schedules = &$config['schedules']['schedule'];

if (isset($_REQUEST['id']) && is_numericint($_REQUEST['id'])) {
	$id = $_REQUEST['id'];
}

if (isset($id) && $a_schedules[$id]) {
	$pconfig['name'] = $a_schedules[$id]['name'];
	$pconfig['descr'] = html_entity_decode($a_schedules[$id]['descr']);
	$pconfig['timerange'] = $a_schedules[$id]['timerange'];
	$pconfig['schedlabel'] = $a_schedules[$id]['schedlabel'];
	$getSchedule = true;
}

if ($_POST['save']) {

	if (strtolower($_POST['name']) == "lan") {
		$input_errors[] = gettext("Schedule may not be named LAN.");
	}

	if (strtolower($_POST['name']) == "wan") {
		$input_errors[] = gettext("Schedule may not be named WAN.");
	}

	if (strtolower($_POST['name']) == "") {
		$input_errors[] = gettext("Schedule name cannot be blank.");
	}

	if (!is_validaliasname($_POST['name'])) {
		$input_errors[] = invalidaliasnamemsg($_POST['name'], gettext("schedule"));
	}

	/* check for name conflicts */
	foreach ($a_schedules as $schedule) {
		if (isset($id) && ($a_schedules[$id]) && ($a_schedules[$id] === $schedule)) {
			continue;
		}

		if ($schedule['name'] == $_POST['name']) {
			$input_errors[] = gettext("A Schedule with this name already exists.");
			break;
		}
	}

	$schedule = array();

	$schedule['name'] = $_POST['name'];
	$schedule['descr'] = $_POST['descr'];

	$timerangeFound = false;

	for ($x = 0; $x < 99; $x++) {
		if ($_POST['schedule' . $x]) {
			if (!preg_match('/^[0-9]+:[0-9]+$/', $_POST['starttime' . $x])) {
				$input_errors[] = sprintf(gettext("Invalid start time - '%s'"), $_POST['starttime' . $x]);
				continue;
			}

			if (!preg_match('/^[0-9]+:[0-9]+$/', $_POST['stoptime' . $x])) {
				$input_errors[] = sprintf(gettext("Invalid stop time - '%s'"), $_POST['stoptime' . $x]);
				continue;
			}

			$timerangeFound = true;
			$timeparts = array();
			$firstprint = false;
			$timestr = $_POST['schedule' . $x];
			$timehourstr = $_POST['starttime' . $x];
			$timehourstr .= "-";
			$timehourstr .= $_POST['stoptime' . $x];
			$timedescrstr = $_POST['timedescr' . $x];
			$dashpos = strpos($timestr, '-');

			if ($dashpos === false) {
				$timeparts['position'] = $timestr;
			} else {
				$tempindarray = array();
				$monthstr = "";
				$daystr = "";
				$tempindarray = explode(",", $timestr);
				foreach ($tempindarray as $currentselection) {
					if ($currentselection) {
						if ($firstprint) {
							$monthstr .= ",";
							$daystr .= ",";
						}
						$tempstr = "";
						$monthpos = strpos($currentselection, "m");
						$daypos = strpos($currentselection, "d");
						$monthstr .= substr($currentselection, $monthpos+1, $daypos-$monthpos-1);
						$daystr .=	substr($currentselection, $daypos+1);
						$firstprint = true;
					}
				}

				$timeparts['month'] = $monthstr;
				$timeparts['day'] = $daystr;
			}

			$timeparts['hour'] = $timehourstr;
			$timeparts['rangedescr'] = $timedescrstr;
			$schedule['timerange'][$x] = $timeparts;
		}
	}

	if (!$timerangeFound) {
		$input_errors[] = gettext("The schedule must have at least one time range configured.");
	}

	if (!$input_errors) {

		if (!empty($pconfig['schedlabel'])) {
			$schedule['schedlabel'] = $pconfig['schedlabel'];
		} else {
			$schedule['schedlabel'] = uniqid();
		}

		if (isset($id) && $a_schedules[$id]) {
			$a_schedules[$id] = $schedule;
		} else {
			$a_schedules[] = $schedule;
		}

		schedule_sort();

		if (write_config(gettext("Firewall schedule configured."))) {
			filter_configure();
		}

		header("Location: firewall_schedule.php");
		exit;

	}
	//we received input errors, copy data to prevent retype
	else {
		if (!$_POST['schedule0']) {
			$getSchedule = false;
		} else {
			$getSchedule = true;
		}

		$pconfig['name'] = $schedule['name'];
		$pconfig['descr'] = $schedule['descr'];
		$pconfig['timerange'] = $schedule['timerange'];
	}

}

include("head.inc");

// Returns a string containing the HTML to display a calendar table
function build_date_table() {
	$tblstr = "";

	$firstmonth = TRUE;
	$monthcounter = date("n");
	$yearcounter = date("Y");

	for ($k = 0; $k < 12; $k++) {
		$firstdayofmonth = date("w", mktime(0, 0, 0, date($monthcounter), 1, date($yearcounter)));

		if ($firstdayofmonth == 0) {
			$firstdayofmonth = 7;
		}

		$daycounter = 1;
		//number of day in month
		$numberofdays = date("t", mktime(0, 0, 0, date($monthcounter), 1, date($yearcounter)));
		$firstdayprinted = FALSE;
		$lasttr = FALSE;
		$positioncounter = 1;//7 for Sun, 1 for Mon, 2 for Tues, etc

		$mostr = '
';

		$mostr .=
			'

' . date("F_Y", mktime(0, 0, 0, date($monthcounter), 1, date($yearcounter))) . '

					' . gettext("Mon") . '
					' . gettext("Tue") . '
					' . gettext("Wed") . '
					' . gettext("Thu") . '
					' . gettext("Fri") . '
					' . gettext("Sat") . '
					' . gettext("Sun") . '

' . "\r\n";

				$firstmonth = FALSE;

				while ($daycounter<=$numberofdays) {
					$weekcounter =	date("W", mktime(0, 0, 0, date($monthcounter), date($daycounter), date($yearcounter)));
					$weekcounter = ltrim($weekcounter, "0");
					if ($positioncounter == 1) {
						$mostr .= "
";
					}

					if ($firstdayofmonth == $positioncounter) {

						$mostr .= '' . $daycounter . "\r\n";

						$daycounter++;
						$firstdayprinted = TRUE;
						$mostr .= "	";
					} elseif ($firstdayprinted == TRUE && $daycounter <= $numberofdays) {
						$mostr .= '' . $daycounter . "\r\n";
						$daycounter++;
						$mostr .= "	";
					} else {
						$mostr .= '	';
					}

					if ($daycounter > $numberofdays) {
						while ($positioncounter < 7) {
							$mostr .= '	';
							$positioncounter++;
						}
					}

					if ($positioncounter == 7) {
						$positioncounter = 1;
						$mostr .= "
";
					} else {
						$positioncounter++;
					}

				}

			$mostr .= '

';
			$mostr .= gettext('Click individual date to select that date only. Click the appropriate weekday Header to select all occurrences of that weekday. ');
			$mostr .= '

';

		if ($monthcounter == 12) {
			$monthcounter = 1;
			$yearcounter++;
		} else {
			$monthcounter++;
		}

	$tblstr .= $mostr;
	} //end for loop

	return($tblstr);
}

function build_month_list() {

	$list = array();

	$monthcounter = date("n");
	$monthlimit = $monthcounter + 12;
	$yearcounter = date("Y");

	for ($k = 0; $k < 12; $k++) {
		$list[$monthcounter] = date("F_y", mktime(0, 0, 0, date($monthcounter), 1, date($yearcounter)));

		if ($monthcounter == 12) {
			$monthcounter = 1;
			$yearcounter++;
		} else {
			$monthcounter++;
		}
	}

	return($list);
}

if ($input_errors) {
	print_input_errors($input_errors);
}

$form = new Form();

$section = new Form_Section('Schedule Information');

$input = new Form_Input(
	'name',
	'*Schedule Name',
	'text',
	$pconfig['name']
);

if (is_schedule_inuse($pconfig['name']) != true) {
	$input->setHelp('The name of the schedule may only consist of the characters "a-z, A-Z, 0-9 and _".');
} else {
	$input->setHelp('This schedule is in use so the name may not be modified!');
}

if (is_schedule_inuse($pconfig['name']) == true) {
	$input->setReadonly();
}

$section->addInput($input);

$section->addInput(new Form_Input(
	'descr',
	'Description',
	'text',
	$pconfig['descr']
))->setHelp('A description may be entered here for administrative reference (not parsed). ');

$section->addInput(new Form_Select(
	'monthsel',
	'Month',
	null,
	build_month_list()
));

$section->addInput(new Form_StaticText(
	'*Date',
	 build_date_table()
));

$group = new Form_Group('*Time');

$group->add(new Form_Select(
	'starttimehour',
	null,
	null,
	array_combine(range(0, 23, 1), range(0, 23, 1))
))->setHelp('Start Hrs');

$group->add(new Form_Select(
	'starttimemin',
	null,
	null,
	array('00' => '00', '15' => '15', '30' => '30', '45' => '45', '59' => '59')
))->setHelp('Start Mins');

$group->add(new Form_Select(
	'stoptimehour',
	null,
	'23',
	array_combine(range(0, 23, 1), range(0, 23, 1))
))->setHelp('Stop Hrs');

$group->add(new Form_Select(
	'stoptimemin',
	null,
	'59',
	array('00' => '00', '15' => '15', '30' => '30', '45' => '45', '59' => '59')
))->setHelp('Stop Mins');

$group->setHelp('Select the time range for the day(s) selected on the Month(s) above. A full day is 0:00-23:59.');

$section->add($group);

$section->addInput(new Form_Input(
	'timerangedescr',
	'Time range description',
	'text',
	$pconfig['timerangedescr']
))->setHelp('A description may be entered here for administrative reference (not parsed). ');

$group = new Form_Group(null);

$group->add(new Form_Button(
	'btnaddtime',
	'Add Time',
	null,
	'fa-plus'
))->setAttribute('type','button')->addClass('btn-success btn-sm');

$group->add(new Form_Button(
	'btnclrsel',
	'Clear selection',
	null,
	'fa-undo'
))->setAttribute('type','button')->addClass('btn-info btn-sm');

$section->add($group);

if (isset($id) && $a_schedules[$id]) {
	$form->addGlobal(new Form_Input(
		'id',
		null,
		'hidden',
		$id
	));
}

$form->add($section);

$section = new Form_Section('Configured Ranges');
$counter = 0;

if ($getSchedule && !empty($pconfig['timerange'])) {
	$maxrows = count($pconfig['timerange']) -1;

	foreach ($pconfig['timerange'] as $timerange) {
		$tempFriendlyTime = "";
		$tempID = "";
		if ($timerange) {
			$dayFriendly = "";
			$tempFriendlyTime = "";
			$timedescr = $timerange['rangedescr'];

			//get hours
			$temptimerange = $timerange['hour'];
			$temptimeseparator = strrpos($temptimerange, "-");

			$starttime = substr ($temptimerange, 0, $temptimeseparator);
			$stoptime = substr ($temptimerange, $temptimeseparator+1);
			$currentDay = "";
			$firstDay = "";
			$nextDay = "";
			$foundEnd = false;
			$firstDayFound = false;
			$firstPrint = false;
			$firstprint2 = false;

			if ($timerange['month']) {
				$tempmontharray = explode(",", $timerange['month']);
				$tempdayarray = explode(",", $timerange['day']);
				$arraycounter = 0;
				foreach ($tempmontharray as $monthtmp) {
					$month = $tempmontharray[$arraycounter];
					$day = $tempdayarray[$arraycounter];
					$daypos = date("w", mktime(0, 0, 0, date($month), date($day), date("Y")));
					//if sunday, set position to 7 to get correct week number. This is due to php limitations on ISO-8601. When we move to php5.1 we can change this.
					if ($daypos == 0) {
						$daypos = 7;
					}

					$weeknumber = date("W", mktime(0, 0, 0, date($month), date($day), date("Y")));
					$weeknumber = ltrim($weeknumber, "0");

					if ($firstPrint) {
						$tempID .= ",";
					}

					$tempID .= "w" . $weeknumber . "p" . $daypos . "-m" .  $month . "d" . $day;
					$firstPrint = true;

					if (!$firstDayFound) {
						$firstDay = $day;
						$firstmonth = $month;
						$firstDayFound = true;
					}

					$currentDay = $day;
					$nextDay = $tempdayarray[$arraycounter+1];
					$currentDay++;
					if (($currentDay != $nextDay) || ($tempmontharray[$arraycounter] != $tempmontharray[$arraycounter+1])) {
						if ($firstprint2) {
							$tempFriendlyTime .= ", ";
						}

						$currentDay--;

						if ($currentDay != $firstDay) {
							$tempFriendlyTime .= $monthArray[$firstmonth-1] . " " . $firstDay . " - " . $currentDay ;
						} else {
							$tempFriendlyTime .=  $monthArray[$month-1] . " " . $day;
						}

						$firstDayFound = false;
						$firstprint2 = true;
					}
					$arraycounter++;
				}

			} else {
				$dayFriendly = $timerange['position'];
				$tempID = $dayFriendly;
			}

			$tempTime = $tempID . "||" . $starttime . "-" . $stoptime . "||" . $timedescr;

			//following code makes the days friendly appearing, IE instead of Mon, Tues, Wed it will show Mon - Wed
			$foundEnd = false;
			$firstDayFound = false;
			$firstprint = false;
			$tempFriendlyDayArray = explode(",", $dayFriendly);
			$currentDay = "";
			$firstDay = "";
			$nextDay = "";
			$i = 0;

			if (!$timerange['month']) {
				foreach ($tempFriendlyDayArray as $day) {
					if ($day != "") {
						if (!$firstDayFound) {
							$firstDay = $tempFriendlyDayArray[$i];
							$firstDayFound = true;
						}

						$currentDay =$tempFriendlyDayArray[$i];
						//get next day
						$nextDay = $tempFriendlyDayArray[$i+1];
						$currentDay++;

						if ($currentDay != $nextDay) {
							if ($firstprint) {
								$tempFriendlyTime .= ", ";
							}

							$currentDay--;

							if ($currentDay != $firstDay) {
								$tempFriendlyTime .= $dayArray[$firstDay-1] . " - " . $dayArray[$currentDay-1];
							} else {
								$tempFriendlyTime .= $dayArray[$firstDay-1];
							}

							$firstDayFound = false;
							$firstprint = true;
						}
						$i++;
					}
				}
			}

			$group = new Form_Group('');
			$group->add(new Form_Input(
				'tempFriendlyTime' . $counter,
				null,
				'text',
				$tempFriendlyTime
			))->setWidth(2)->setReadonly()->setHelp($counter == $maxrows ? 'Day(s)':'');

			$group->add(new Form_Input(
				'starttime' . $counter,
				null,
				'text',
				$starttime
			))->setWidth(2)->setReadonly()->setHelp($counter == $maxrows ? 'Start time':'');

			$group->add(new Form_Input(
				'stoptime' . $counter,
				null,
				'text',
				$stoptime
			))->setWidth(2)->setReadonly()->setHelp($counter == $maxrows ? 'Stop time':'');

			$group->add(new Form_Input(
				'timedescr' . $counter,
				null,
				'text',
				$timedescr
			))->setWidth(2)->setHelp($counter == $maxrows ? 'Description':'');

			$group->add(new Form_Button(
				'Delete' . $counter,
				'Delete',
				null,
				'fa-trash'
			))->setAttribute('type','button')->addClass('btn-xs btn-warning');

			$group->add(new Form_Input(
				'schedule' . $counter,
				null,
				'hidden',
				$tempID
			));

			$group->addClass('schedulegrp' . $counter);

			$counter++;
			$section->add($group);
		}
	}
}

// This is just a marker that the javascript can use to insertBefore() when adding new rows
$section->addInput(new Form_Input(
	'marker',
	null,
	'hidden'
))->addClass('noranges');

$form->add($section);

print($form);
?>

<?php

include("foot.inc");


text:
import makeFloatSlider from "../../toolbox/makeFloatSlider";

export const title = "Desert Shadertoy + CRT effect + snapshot()";

export const toolbox = [
  {
    prop: "distortion",
    title: "Distortion",
    Editor: makeFloatSlider(0, 1, 0.01),
  },
];


text:
{% extends 'main.html' %}

{% block content %}

Account Information:

    <form action="{% url 'website:edit_settings' %}" method="post">
        {% csrf_token %}

First Name:
<input type="text" name="first_name" value="{{customer.user.first_name}}">

Last Name:
<input type="text" name="last_name" value="{{customer.user.last_name}}">

Email:
<input type="text" name="email" value="{{customer.user.email}}">

Phone:
<input type="text" name="phone" value="{{customer.phone}}">

Street address:
<input type="text" name="street_address" value="{{customer.street_address}}">

        <input type="submit" class="btn btn-success btn-small" value="Update" />
    </form>

{% endblock content %}


text:
// Copyright (C) 2014 Domenic Denicola. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
description: Array.prototype.includes should terminate if an exception occurs converting the fromIndex to a number
includes: [Test262Error.js]
---*/

var fromIndex = {
    valueOf: function () {
        throw new Test262Error('This error should be re-thrown');
    }
};

var trappedZero = {
    length: 1,
    get 0() {
        $ERROR('Should not try to get the zeroth element');
    }
};

assert.throws(Test262Error, function () {
    Array.prototype.includes.call(trappedZero, 'a', fromIndex);
});


text:
@echo off

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

echo Start - Building the Snow Site
echo Running Snow.exe config=%DEPLOYMENT_SOURCE%\Snow\

pushd %DEPLOYMENT_SOURCE%
call  .\Snow\_compiler\Snow.exe config=.\Snow\

IF !ERRORLEVEL! NEQ 0 goto error

mkdir %DEPLOYMENT_SOURCE%\Website\feed
copy %DEPLOYMENT_SOURCE%\Website\feed.xml %DEPLOYMENT_SOURCE%\Website\feed\index.xml

mkdir %DEPLOYMENT_SOURCE%\Website\rss
copy %DEPLOYMENT_SOURCE%\Website\rss.xml %DEPLOYMENT_SOURCE%\Website\rss\index.xml

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

echo Setting up Kudu Sync

IF NOT DEFINED KUDU_SYNC_COMMAND (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_COMMAND=node "%appdata%\npm\node_modules\kuduSync\bin\kuduSync"
)

echo Kudu Sync from "%DEPLOYMENT_SOURCE%\Website" to "%DEPLOYMENT_TARGET%"
call %KUDU_SYNC_COMMAND% -q -f "%DEPLOYMENT_SOURCE%\Website" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.deployment;deploy.cmd" 2>nul
IF !ERRORLEVEL! NEQ 0 goto error

goto end

:error
echo An error has occured during web site deployment.
exit /b 1

:end
echo Finished successfully.


text: Universal iOS 9.1 app demo written in Swift featuring a card-based TableView and SFSafariViewController


text:
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage
import matplotlib.patches

plt.figure(figsize=(10,10))
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)

size        = 1000 #width and height of image in pixels
peak_height = 150 # define the height of the peaks
num_peaks   = 100
noise_level = 65
threshold   = 70

np.random.seed(3)

#set up a simple, blank image (Z)
x = np.linspace(0,size,size)
y = np.linspace(0,size,size)

X,Y = np.meshgrid(x,y)
Z = X*0

#now add some peaks
def gaussian(X,Y,xo,yo,amp=100,sigmax=4,sigmay=4):
    return amp*np.exp(-(X-xo)**2/(2*sigmax**2) - (Y-yo)**2/(2*sigmay**2))

for xo,yo in size*np.random.rand(num_peaks,2):
    widthx = 5 + np.random.randn(1)
    widthy = 5 + np.random.randn(1)
    Z += gaussian(X,Y,xo,yo,amp=peak_height,sigmax=widthx,sigmay=widthy)

#of course, add some noise:
Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=5)
Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=1)

t = time.time() #Start timing the peak-finding algorithm

#Set everything below the threshold to zero:
Z_thresh = np.copy(Z)
Z_thresh[Z_thresh<threshold] = 0
print 'Time after thresholding: %.5f seconds'%(time.time()-t)

#now find the objects
labeled_image, number_of_objects = scipy.ndimage.label(Z_thresh)
print 'Time after labeling: %.5f seconds'%(time.time()-t)

peak_slices = scipy.ndimage.find_objects(labeled_image)
print 'Time after finding objects: %.5f seconds'%(time.time()-t)

def centroid(data):
    h,w = np.shape(data)
    x = np.arange(0,w)
    y = np.arange(0,h)

    X,Y = np.meshgrid(x,y)

    cx = np.sum(X*data)/np.sum(data)
    cy = np.sum(Y*data)/np.sum(data)

    return cx,cy

centroids = []

for peak_slice in peak_slices:
    dy,dx  = peak_slice
    x,y = dx.start, dy.start
    cx,cy = centroid(Z_thresh[peak_slice])
    centroids.append((x+cx,y+cy))

print 'Total time: %.5f seconds\n'%(time.time()-t)

###########################################
#Now make the plots:
for ax in (ax1,ax2,ax3,ax4): ax.clear()
ax1.set_title('Original image')
ax1.imshow(Z,origin='lower')

ax2.set_title('Thresholded image')
ax2.imshow(Z_thresh,origin='lower')

ax3.set_title('Labeled image')
ax3.imshow(labeled_image,origin='lower') #display the color-coded regions

for peak_slice in peak_slices:  #Draw some rectangles around the objects
    dy,dx  = peak_slice
    xy     = (dx.start, dy.start)
    width  = (dx.stop - dx.start + 1)
    height = (dy.stop - dy.start + 1)
    rect = matplotlib.patches.Rectangle(xy,width,height,fc='none',ec='red')
    ax3.add_patch(rect,)

ax4.set_title('Centroids on original image')
ax4.imshow(Z,origin='lower')

for x,y in centroids:
    ax4.plot(x,y,'kx',ms=10)

ax4.set_xlim(0,size)
ax4.set_ylim(0,size)

plt.tight_layout
plt.show()


text:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { DragulaService } from 'ng2-dragula';
import { TestStepFactory } from '../../../../../../../factory/test-step-factory';
import { IContainer } from '../../../../../../../model/IContainer';
import { IContentElement } from '../../../../../../../model/IContentElement';
import { IPositionable } from '../../../../../../../model/IPositionable';
import { TestParameter } from '../../../../../../../model/TestParameter';
import { TestProcedure } from '../../../../../../../model/TestProcedure';
import { Type } from '../../../../../../../util/type';
import { Url } from '../../../../../../../util/url';
import { SpecmateDataService } from '../../../../../../data/modules/data-service/services/specmate-data.service';
import { NavigatorService } from '../../../../../../navigation/modules/navigator/services/navigator.service';
import { ConfirmationModal } from '../../../../../../notification/modules/modals/services/confirmation-modal.service';
import { DraggableSupportingViewBase } from '../../../base/draggable-supporting-view-base';

@Component({
    moduleId: module.id.toString(),
    selector: 'test-procedure-editor',
    templateUrl: 'test-procedure-editor.component.html',
    styleUrls: ['test-procedure-editor.component.css']
})
export class TestProcedureEditor extends DraggableSupportingViewBase {

    /** The test procedure being edited */
    public testProcedure: TestProcedure;

    public get relevantElements(): (IContentElement & IPositionable)[] {
        return this.contents as (IContentElement & IPositionable)[];
    }

    /** The contents of the parent test specification */
    private testSpecContents: IContainer[];

    /** getter for the input parameters of the parent test specification */
    public get inputParameters(): IContentElement[] {
        return this.allParameters.filter((param: TestParameter) => param.type === 'INPUT');
    }

    /** getter for the output parameters of the parent test specification */
    public get outputParameters(): IContentElement[] {
        return this.allParameters.filter((param: TestParameter) => param.type === 'OUTPUT');
    }

    /** getter for all test parameters */
    private get allParameters(): IContentElement[] {
        if (!this.testSpecContents) {
            return [];
        }
        return this.testSpecContents.filter((element: IContainer) => Type.is(element, TestParameter));
    }

    /** Constructor */
    constructor(dataService: SpecmateDataService,
        navigator: NavigatorService,
        route: ActivatedRoute,
        modal: ConfirmationModal,
        dragulaService: DragulaService,
        translate: TranslateService) {
            super(dataService, navigator, route, modal, dragulaService, translate);
    }

    public onElementResolved(element: IContainer): Promise<void> {
        return super.onElementResolved(element)
            .then(() => Type.is(element, TestProcedure) ? Promise.resolve() : Promise.reject('Not a test procedure'))
            .then(() => this.readParentTestSpec(element as TestProcedure))
            .then(() => this.testProcedure = element as TestProcedure)
            .then(() => Promise.resolve());
    }

    /** Reads the parent test specification */
    private readParentTestSpec(testProcedure: TestProcedure): Promise<void> {
        let testSpecificationUrl: string = Url.parent(testProcedure.url);
        return this.dataService.readContents(testSpecificationUrl)
            .then((contents: IContainer[]) => this.testSpecContents = contents)
            .then((contents: IContainer[]) => this.sanitizeContentPositions(true))
            .then(() => Promise.resolve());
    }

    /** Creates a new test case */
    private createNewTestStep() {
        let factory: TestStepFactory = new TestStepFactory(this.dataService);
        factory.create(this.testProcedure, false);
    }

    /** Return true if all user inputs are valid  */
    protected get isValid(): boolean {
        return true;
    }
}


text:
@class MWMViewController;

@protocol MWMActionBarProtocol<NSObject>

- (void)routeFrom;
- (void)routeTo;
- (void)routeAddStop;
- (void)routeRemoveStop;

- (void)share;

- (void)addBookmark;
- (void)removeBookmark;

- (void)call;
- (void)book;
- (void)searchBookingHotels;

- (void)openPartner;
- (void)downloadSelectedArea;
- (void)avoidToll;
- (void)avoidDirty;
- (void)avoidFerry;

@end

struct FeatureID;

@protocol MWMFeatureHolder<NSObject>

- (FeatureID const &)featureId;

@end

namespace booking
{
struct HotelFacility;
}

@protocol MWMBookingInfoHolder<NSObject>

- (std::vector<booking::HotelFacility> const &)hotelFacilities;
- (NSString *)hotelName;

@end

@protocol MWMPlacePageProtocol<MWMActionBarProtocol, MWMPlacePageButtonsProtocol, MWMFeatureHolder, MWMBookingInfoHolder>

- (void)show:(place_page::Info const &)info;
- (void)showReview:(place_page::Info const &)info;
- (void)dismiss;
- (void)mwm_refreshUI;

@end


text:
cask 'ipass' do
  version :latest
  sha256 :no_check

  # d18uyicgt51j26.cloudfront.net/packages was verified as official when first introduced to the cask
  url 'https://d18uyicgt51j26.cloudfront.net/packages/iPass_Mac.dmg'
  name 'iPass'
  homepage 'https://www.ipass.com/'

  pkg 'iPass.pkg'

  uninstall pkgutil: 'com.ipass.ipass.pkg'
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/******************************************************************************
 * This file is auto-generated from a template file by the GenerateTests.csx  *
 * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make    *
 * changes, please update the corresponding template and run according to the *
 * directions listed in the file.                                             *
 ******************************************************************************/

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;

namespace JIT.HardwareIntrinsics.X86
{
    public static partial class Program
    {
        private static void AndNotUInt64()
        {
            var test = new ScalarBinaryOpTest__AndNotUInt64();

            if (test.IsSupported)
            {
                // Validates basic functionality works, using Unsafe.ReadUnaligned
                test.RunBasicScenario_UnsafeRead();

                // Validates calling via reflection works, using Unsafe.ReadUnaligned
                test.RunReflectionScenario_UnsafeRead();

                // Validates passing a static member works
                test.RunClsVarScenario();

                // Validates passing a local works, using Unsafe.ReadUnaligned
                test.RunLclVarScenario_UnsafeRead();

                // Validates passing the field of a local class works
                test.RunClassLclFldScenario();

                // Validates passing an instance member of a class works
                test.RunClassFldScenario();

                // Validates passing the field of a local struct works
                test.RunStructLclFldScenario();

                // Validates passing an instance member of a struct works
                test.RunStructFldScenario();
            }
            else
            {
                // Validates we throw on unsupported hardware
                test.RunUnsupportedScenario();
            }

            if (!test.Succeeded)
            {
                throw new Exception("One or more scenarios did not complete as expected.");
            }
        }
    }

    public sealed unsafe class ScalarBinaryOpTest__AndNotUInt64
    {
        private struct TestStruct
        {
            public UInt64 _fld1;
            public UInt64 _fld2;

            public static TestStruct Create()
            {
                var testStruct = new TestStruct();

                testStruct._fld1 = TestLibrary.Generator.GetUInt64();
                testStruct._fld2 = TestLibrary.Generator.GetUInt64();

                return testStruct;
            }

            public void RunStructFldScenario(ScalarBinaryOpTest__AndNotUInt64 testClass)
            {
                var result = Bmi1.X64.AndNot(_fld1, _fld2);
                testClass.ValidateResult(_fld1, _fld2, result);
            }
        }

        private static UInt64 _data1;
        private static UInt64 _data2;

        private static UInt64 _clsVar1;
        private static UInt64 _clsVar2;

        private UInt64 _fld1;
        private UInt64 _fld2;

        static ScalarBinaryOpTest__AndNotUInt64()
        {
            _clsVar1 = TestLibrary.Generator.GetUInt64();
            _clsVar2 = TestLibrary.Generator.GetUInt64();
        }

        public ScalarBinaryOpTest__AndNotUInt64()
        {
            Succeeded = true;

            _fld1 = TestLibrary.Generator.GetUInt64();
            _fld2 = TestLibrary.Generator.GetUInt64();

            _data1 = TestLibrary.Generator.GetUInt64();
            _data2 = TestLibrary.Generator.GetUInt64();
        }

        public bool IsSupported => Bmi1.X64.IsSupported;

        public bool Succeeded { get; set; }

        public void RunBasicScenario_UnsafeRead()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));

            var result = Bmi1.X64.AndNot(
                Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
                Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2))
            );

            ValidateResult(_data1, _data2, result);
        }

        public void RunReflectionScenario_UnsafeRead()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));

            var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.AndNot), new Type[] { typeof(UInt64), typeof(UInt64) })
                                     .Invoke(null, new object[] {
                                        Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
                                        Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2))
                                     });

            ValidateResult(_data1, _data2, (UInt64)result);
        }

        public void RunClsVarScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));

            var result = Bmi1.X64.AndNot(
                _clsVar1,
                _clsVar2
            );

            ValidateResult(_clsVar1, _clsVar2, result);
        }

        public void RunLclVarScenario_UnsafeRead()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));

            var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1));
            var data2 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2));
            var result = Bmi1.X64.AndNot(data1, data2);

            ValidateResult(data1, data2, result);
        }

        public void RunClassLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));

            var test = new ScalarBinaryOpTest__AndNotUInt64();
            var result = Bmi1.X64.AndNot(test._fld1, test._fld2);

            ValidateResult(test._fld1, test._fld2, result);
        }

        public void RunClassFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));

            var result = Bmi1.X64.AndNot(_fld1, _fld2);
            ValidateResult(_fld1, _fld2, result);
        }

        public void RunStructLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));

            var test = TestStruct.Create();
            var result = Bmi1.X64.AndNot(test._fld1, test._fld2);

            ValidateResult(test._fld1, test._fld2, result);
        }

        public void RunStructFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));

            var test = TestStruct.Create();
            test.RunStructFldScenario(this);
        }

        public void RunUnsupportedScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));

            bool succeeded = false;

            try
            {
                RunBasicScenario_UnsafeRead();
            }
            catch (PlatformNotSupportedException)
            {
                succeeded = true;
            }

            if (!succeeded)
            {
                Succeeded = false;
            }
        }

        private void ValidateResult(UInt64 left, UInt64 right, UInt64 result, [CallerMemberName] string method = "")
        {
            var isUnexpectedResult = false;

            isUnexpectedResult = ((~left & right) != result);

            if (isUnexpectedResult)
            {
                TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.AndNot)}<UInt64>(UInt64, UInt64): AndNot failed:");
                TestLibrary.TestFramework.LogInformation($"    left: {left}");
                TestLibrary.TestFramework.LogInformation($"   right: {right}");
                TestLibrary.TestFramework.LogInformation($"  result: {result}");
                TestLibrary.TestFramework.LogInformation(string.Empty);

                Succeeded = false;
            }
        }
    }
}


text:
package checkpoint

import (
	"path/filepath"
	"strings"

	"github.com/golang/glog"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/serializer/json"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/pkg/api"
	"k8s.io/client-go/pkg/api/v1"
)

var (
	// podSerializer is an encoder for writing checkpointed pods.
	//
	// Perfer this instead of json.Marshal because it corrects metadata before
	// serializing. For example it automatically fills in the "apiVersion" field.
	podSerializer = scheme.Codecs.EncoderForVersion(
		json.NewSerializer(
			json.DefaultMetaFactory,
			scheme.Scheme, // client-go's default scheme.
			scheme.Scheme,
			false, // don't pretty print.
		),
		v1.SchemeGroupVersion,
	)
)

func sanitizeCheckpointPod(cp *v1.Pod) *v1.Pod {
	trueVar := true

	// Check if this is already sanitized, i.e. it was read back from a checkpoint on disk.
	if _, ok := cp.Annotations[checkpointParentAnnotation]; ok {
		return cp
	}

	// Keep same name, namespace, and labels as parent.
	cp.ObjectMeta = metav1.ObjectMeta{
		Name:        cp.Name,
		Namespace:   cp.Namespace,
		Annotations: make(map[string]string),
		Labels:      cp.Labels,
		// Set the ownerRef to the parent pod. We do this because:
		// If the ownerRef stays the same (e.g. the original deployment), then the deployment controller will try to manage the static/mirror pod.
		// If we clear the ownerRef, then a higher-level object will adopt this pod based on the label selector (e.g. the original deployment).
		OwnerReferences: []metav1.OwnerReference{
			{
				APIVersion: cp.APIVersion,
				Kind:       cp.Kind,
				Name:       cp.Name,
				UID:        cp.UID,
				Controller: &trueVar,
			},
		},
	}

	// Track this checkpoint's parent pod
	cp.Annotations[checkpointParentAnnotation] = cp.Name

	// Remove Service Account
	cp.Spec.ServiceAccountName = ""
	cp.Spec.DeprecatedServiceAccount = ""

	// Sanitize the volumes
	for i := range cp.Spec.Volumes {
		v := &cp.Spec.Volumes[i]
		if v.Secret != nil {
			v.HostPath = &v1.HostPathVolumeSource{Path: secretPath(cp.Namespace, cp.Name, v.Secret.SecretName)}
			v.Secret = nil
		} else if v.ConfigMap != nil {
			v.HostPath = &v1.HostPathVolumeSource{Path: configMapPath(cp.Namespace, cp.Name, v.ConfigMap.Name)}
			v.ConfigMap = nil
		}
	}

	// Clear pod status
	cp.Status.Reset()

	return cp
}

// isPodCheckpointer returns true if the manifest is the pod checkpointer (has the same name as the parent).
// For example, the pod.Name would be "pod-checkpointer".
// The podName would be "pod-checkpointer" or "pod-checkpointer-172.17.4.201" where
// "172.17.4.201" is the nodeName.
func isPodCheckpointer(pod *v1.Pod, cp CheckpointerPod) bool {
	if pod.Namespace != cp.PodNamespace {
		return false
	}
	return pod.Name == strings.TrimSuffix(cp.PodName, "-"+cp.NodeName)
}

func podListToParentPods(pl *v1.PodList) map[string]*v1.Pod {
	return podListToMap(pl, isValidParent)
}

func filterNone(p *v1.Pod) bool {
	return true
}

type filterFn func(*v1.Pod) bool

func podListToMap(pl *v1.PodList, filter filterFn) map[string]*v1.Pod {
	pods := make(map[string]*v1.Pod)
	for i := range pl.Items {
		if !filter(&pl.Items[i]) {
			continue
		}

		pod := &pl.Items[i]
		id := podFullName(pod)

		if _, ok := pods[id]; ok { // TODO(aaron): likely not be necessary (shouldn't ever happen) - but sanity check
			glog.Warningf("Found multiple local parent pods with same id: %s", id)
		}

		// Pods from Kubelet API do not have TypeMeta populated - set it here either way.
		pods[id] = pod
		pods[id].TypeMeta = metav1.TypeMeta{
			APIVersion: "v1",
			Kind:       "Pod",
		}
	}
	return pods
}

// A valid checkpoint parent:
//    has the checkpoint=true annotation
//    is not a static pod itself
//    is not a checkpoint pod itself
func isValidParent(pod *v1.Pod) bool {
	if pod.Annotations == nil {
		return false
	}
	shouldCheckpoint := pod.Annotations[shouldCheckpointAnnotation] == shouldCheckpoint
	isStatic := pod.Annotations[podSourceAnnotation] == podSourceFile
	return shouldCheckpoint && !isStatic && !isCheckpoint(pod)
}

func isCheckpoint(pod *v1.Pod) bool {
	if pod.Annotations == nil {
		return false
	}
	_, ok := pod.Annotations[checkpointParentAnnotation]
	return ok
}

func copyPod(pod *v1.Pod) (*v1.Pod, error) {
	obj, err := api.Scheme.Copy(pod)
	if err != nil {
		return nil, err
	}
	return obj.(*v1.Pod), nil
}

func podFullName(pod *v1.Pod) string {
	return pod.Namespace + "/" + pod.Name
}

func podFullNameToInactiveCheckpointPath(id string) string {
	return filepath.Join(inactiveCheckpointPath, strings.Replace(id, "/", "-", -1)+".json")
}

func podFullNameToActiveCheckpointPath(id string) string {
	return filepath.Join(activeCheckpointPath, strings.Replace(id, "/", "-", -1)+".json")
}


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

package com.google.devtools.j2objc.pipeline;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.file.InputFile;
import com.google.devtools.j2objc.file.RegularInputFile;
import com.google.devtools.j2objc.gen.GenerationUnit;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.FileUtil;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * A set of input files for J2ObjC to process,
 * together with behavior for scanning input files and adding more files.
 * This class also contains a queue that can be used by processors that dynamically
 * add more files while they process.
 *
 * @author Tom Ball, Keith Stanger, Mike Thvedt
 */
public class GenerationBatch {

  private static final Logger logger = Logger.getLogger(GenerationBatch.class.getName());
  private static final String J2OBJC_TEMP_DIR_PREFIX = "J2ObjCTempDir";
  private final Options options;

  private final List<ProcessingContext> inputs = Lists.newArrayList();

  private GenerationUnit globalCombinedUnit = null;

  public GenerationBatch(Options options){
    this.options = options;
    if (options.globalCombinedOutput() != null) {
      globalCombinedUnit = options.globalCombinedOutput().globalGenerationUnit();
    }
  }

  public List<ProcessingContext> getInputs() {
    return inputs;
  }

  public void processFileArgs(Iterable<String> args) {
    for (String arg : args) {
      processSourceFile(arg);
    }
  }

  private void processSourceFile(String filename) {
    logger.finest("processing " + filename);
    if (filename.endsWith(".java")
        || (options.translateClassfiles() && filename.endsWith(".class"))) {
      processJavaFile(filename);
    } else {
      processJarFile(filename);
    }
  }

  private void processJavaFile(String filename) {
    InputFile inputFile;

    try {
      inputFile = new RegularInputFile(filename, filename);

      if (!inputFile.exists()) {
        // Check source path for regular file.
        inputFile = options.fileUtil().findFileOnSourcePath(filename);
        if (inputFile == null) {
          ErrorUtil.error("No such file: " + filename);
          return;
        }
      }
    } catch (IOException e) {
      ErrorUtil.warning(e.getMessage());
      return;
    }

    addSource(inputFile);
  }

  private File findJarFile(String filename) {
    File f = new File(filename);
    if (f.exists() && f.isFile()) {
      return f;
    }
    // Checking the sourcepath is helpful for our unit tests where the source
    // jars aren't relative to the current working directory.
    for (String path : options.fileUtil().getSourcePathEntries()) {
      File dir = new File(path);
      if (dir.isDirectory()) {
        f = new File(dir, filename);
        if (f.exists() && f.isFile()) {
          return f;
        }
      }
    }
    return null;
  }

  private void processJarFile(String filename) {
    File f = findJarFile(filename);
    if (f == null) {
      ErrorUtil.error("No such file: " + filename);
      return;
    }

    // Warn if source debugging is specified for a jar file, since native debuggers
    // don't support Java-like source paths.
    if (options.emitLineDirectives()) {
      ErrorUtil.warning("source debugging of jar files is not supported: " + filename);
    }

    GenerationUnit combinedUnit = null;
    if (globalCombinedUnit != null) {
      combinedUnit = globalCombinedUnit;
    } else if (options.getHeaderMap().combineSourceJars()) {
      combinedUnit = GenerationUnit.newCombinedJarUnit(filename, options);
    }
    try {
      ZipFile zfile = new ZipFile(f);
      try {
        Enumeration<? extends ZipEntry> enumerator = zfile.entries();
        File tempDir = FileUtil.createTempDir(J2OBJC_TEMP_DIR_PREFIX);
        String tempDirPath = tempDir.getAbsolutePath();
        options.fileUtil().addTempDir(tempDirPath);
        options.fileUtil().appendSourcePath(tempDirPath);

        while (enumerator.hasMoreElements()) {
          ZipEntry entry = enumerator.nextElement();
          String internalPath = entry.getName();
          if (internalPath.endsWith(".java")
              || (options.translateClassfiles() && internalPath.endsWith(".class"))) {
            // Extract JAR file to a temporary directory
            File outputFile = options.fileUtil().extractZipEntry(tempDir, zfile, entry);
            InputFile newFile = new RegularInputFile(outputFile.getAbsolutePath(), internalPath);
            if (combinedUnit != null) {
              inputs.add(new ProcessingContext(newFile, combinedUnit));
            } else {
              addExtractedJarSource(newFile, filename, internalPath);
            }
          }
        }
      } finally {
        zfile.close();  // Also closes input stream.
      }
    } catch (ZipException e) { // Also catches JarExceptions
      logger.fine(e.getMessage());
      ErrorUtil.error("Error reading file " + filename + " as a zip or jar file.");
    } catch (IOException e) {
      ErrorUtil.error(e.getMessage());
    }
  }

  private void addExtractedJarSource(InputFile file, String jarFileName, String internalPath) {
    String sourceName = "jar:file:" + jarFileName + "!" + internalPath;
    inputs.add(ProcessingContext.fromExtractedJarEntry(file, sourceName, options));
  }

  /**
   * Adds the given InputFile to this GenerationBatch,
   * creating GenerationUnits and inferring unit names/output paths as necessary.
   */
  @VisibleForTesting
  public void addSource(InputFile file) {
    if (globalCombinedUnit != null) {
      inputs.add(new ProcessingContext(file, globalCombinedUnit));
    } else {
      inputs.add(ProcessingContext.fromFile(file, options));
    }
  }
}


text:
package daemon

import (
	"fmt"
	"github.com/Sirupsen/logrus"
	"github.com/rancher/convoy/api"
	"github.com/rancher/convoy/convoydriver"
	"github.com/rancher/convoy/objectstore"
	"github.com/rancher/convoy/util"
	"net/http"
	"net/url"
	"strings"

	. "github.com/rancher/convoy/logging"
)

func (s *daemon) doBackupList(version string, w http.ResponseWriter, r *http.Request, objs map[string]string) error {
	s.GlobalLock.RLock()
	defer s.GlobalLock.RUnlock()

	request := &api.BackupListRequest{}
	if err := decodeRequest(r, request); err != nil {
		return err
	}
	request.URL = util.UnescapeURL(request.URL)

	opts := map[string]string{
		convoydriver.OPT_VOLUME_UUID: request.VolumeUUID,
	}
	result := make(map[string]map[string]string)
	for _, driver := range s.ConvoyDrivers {
		backupOps, err := driver.BackupOps()
		if err != nil {
			// Not support backup ops
			continue
		}
		infos, err := backupOps.ListBackup(request.URL, opts)
		if err != nil {
			return err
		}
		for k, v := range infos {
			result[k] = v
		}
	}

	data, err := api.ResponseOutput(result)
	if err != nil {
		return err
	}
	_, err = w.Write(data)
	return err
}

func (s *daemon) doBackupInspect(version string, w http.ResponseWriter, r *http.Request, objs map[string]string) error {
	s.GlobalLock.RLock()
	defer s.GlobalLock.RUnlock()

	request := &api.BackupListRequest{}
	if err := decodeRequest(r, request); err != nil {
		return err
	}
	request.URL = util.UnescapeURL(request.URL)
	backupOps, err := s.getBackupOpsForBackup(request.URL)
	if err != nil {
		return err
	}

	info, err := backupOps.GetBackupInfo(request.URL)
	if err != nil {
		return err
	}

	data, err := api.ResponseOutput(info)
	if err != nil {
		return err
	}
	_, err = w.Write(data)
	return err
}

func (s *daemon) doBackupCreate(version string, w http.ResponseWriter, r *http.Request, objs map[string]string) error {
	request := &api.BackupCreateRequest{}
	if err := decodeRequest(r, request); err != nil {
		return err
	}
	request.URL = util.UnescapeURL(request.URL)

	snapshotUUID := request.SnapshotUUID
	volumeUUID := s.SnapshotVolumeIndex.Get(snapshotUUID)
	if volumeUUID == "" {
		return fmt.Errorf("Cannot find volume of snapshot %v", snapshotUUID)
	}

	if !s.snapshotExists(volumeUUID, snapshotUUID) {
		return fmt.Errorf("snapshot %v of volume %v doesn't exist", snapshotUUID, volumeUUID)
	}

	volume := s.loadVolume(volumeUUID)
	backupOps, err := s.getBackupOpsForVolume(volume)
	if err != nil {
		return err
	}

	opts := map[string]string{
		convoydriver.OPT_VOLUME_NAME:           volume.Name,
		convoydriver.OPT_FILESYSTEM:            volume.FileSystem,
		convoydriver.OPT_VOLUME_CREATED_TIME:   volume.CreatedTime,
		convoydriver.OPT_SNAPSHOT_NAME:         volume.Snapshots[snapshotUUID].Name,
		convoydriver.OPT_SNAPSHOT_CREATED_TIME: volume.Snapshots[snapshotUUID].CreatedTime,
	}

	log.WithFields(logrus.Fields{
		LOG_FIELD_REASON:   LOG_REASON_PREPARE,
		LOG_FIELD_EVENT:    LOG_EVENT_BACKUP,
		LOG_FIELD_OBJECT:   LOG_OBJECT_SNAPSHOT,
		LOG_FIELD_SNAPSHOT: snapshotUUID,
		LOG_FIELD_VOLUME:   volumeUUID,
		LOG_FIELD_DRIVER:   backupOps.Name(),
		LOG_FIELD_DEST_URL: request.URL,
	}).Debug()
	backupURL, err := backupOps.CreateBackup(snapshotUUID, volumeUUID, request.URL, opts)
	if err != nil {
		return err
	}
	log.WithFields(logrus.Fields{
		LOG_FIELD_REASON:   LOG_REASON_COMPLETE,
		LOG_FIELD_EVENT:    LOG_EVENT_BACKUP,
		LOG_FIELD_OBJECT:   LOG_OBJECT_SNAPSHOT,
		LOG_FIELD_SNAPSHOT: snapshotUUID,
		LOG_FIELD_VOLUME:   volumeUUID,
		LOG_FIELD_DRIVER:   backupOps.Name(),
		LOG_FIELD_DEST_URL: request.URL,
	}).Debug()

	backup := &api.BackupURLResponse{
		URL: backupURL,
	}
	if request.Verbose {
		return sendResponse(w, backup)
	}
	escapedURL := strings.Replace(backupURL, "&", "\\u0026", 1)
	return writeStringResponse(w, escapedURL)
}

func (s *daemon) doBackupDelete(version string, w http.ResponseWriter, r *http.Request, objs map[string]string) error {
	s.GlobalLock.Lock()
	defer s.GlobalLock.Unlock()

	request := &api.BackupDeleteRequest{}
	if err := decodeRequest(r, request); err != nil {
		return err
	}
	request.URL = util.UnescapeURL(request.URL)

	backupOps, err := s.getBackupOpsForBackup(request.URL)
	if err != nil {
		return err
	}

	log.WithFields(logrus.Fields{
		LOG_FIELD_REASON:   LOG_REASON_PREPARE,
		LOG_FIELD_EVENT:    LOG_EVENT_REMOVE,
		LOG_FIELD_OBJECT:   LOG_OBJECT_SNAPSHOT,
		LOG_FIELD_DEST_URL: request.URL,
		LOG_FIELD_DRIVER:   backupOps.Name(),
	}).Debug()
	if err := backupOps.DeleteBackup(request.URL); err != nil {
		return err
	}
	log.WithFields(logrus.Fields{
		LOG_FIELD_REASON:   LOG_REASON_COMPLETE,
		LOG_FIELD_EVENT:    LOG_EVENT_REMOVE,
		LOG_FIELD_OBJECT:   LOG_OBJECT_SNAPSHOT,
		LOG_FIELD_DEST_URL: request.URL,
		LOG_FIELD_DRIVER:   backupOps.Name(),
	}).Debug()
	return nil
}

func (s *daemon) getBackupOpsForBackup(requestURL string) (convoydriver.BackupOperations, error) {
	driverName := ""

	if _, err := objectstore.GetObjectStoreDriver(requestURL); err == nil {
		// Known objectstore driver
		objVolume, err := objectstore.LoadVolume(requestURL)
		if err != nil {
			return nil, err
		}
		driverName = objVolume.Driver
	} else {
		// Try Convoy driver
		u, err := url.Parse(requestURL)
		if err != nil {
			return nil, err
		}
		driverName = u.Scheme
	}
	driver := s.ConvoyDrivers[driverName]
	if driver == nil {
		return nil, fmt.Errorf("Cannot find driver %v for restoring", driverName)
	}
	return driver.BackupOps()
}


text:
<?php

namespace Jb\Bundle\TagCloudBundle\Component\Manager;

use Sculpin\Core\DataProvider\DataProviderInterface;
use Jb\Bundle\TagCloudBundle\Component\Strategy\StrategyInterface;
use Jb\Bundle\TagCloudBundle\Component\Factory\TagCloudFactory;

/**
 * Description of TagCloudGenerator
 *
 * @author Jonathan Bouzekri <jonathan.bouzekri@gmail.com>
 */
class TagCloudManager
{
    /**
     * @var \Jb\Bundle\TagCloudBundle\Model\TagCloud
     */
    protected $tagCloud = false;

    /**
     * @var \Sculpin\Core\DataProvider\DataProviderInterface
     */
    protected $tagDataProvider;

    /**
     * @var \Jb\Bundle\TagCloudBundle\Component\Factory\TagCloudFactory
     */
    protected $factory;

    /**
     * @var string
     */
    protected $permalinkPattern;

    /**
     * @var array
     */
    protected $strategies = array();

    /**
     * Constructor
     *
     * @param \Sculpin\Core\DataProvider\DataProviderInterface $dataProvider
     * @param \Jb\Bundle\TagCloudBundle\Component\Factory\TagCloudFactory $factory
     * @param string $permalinkPattern
     */
    public function __construct(
        DataProviderInterface $dataProvider,
        TagCloudFactory $factory,
        $permalinkPattern
    ) {
        $this->tagDataProvider = $dataProvider;
        $this->factory = $factory;
        $this->permalinkPattern = $permalinkPattern;
    }

    /**
     * Generate a tag cloud (or return the one already generated)
     *
     * @return \Jb\Bundle\TagCloudBundle\Model\TagCloud
     */
    public function generateTagCloud()
    {
        if ($this->tagCloud !== false) {
            return $this->tagCloud;
        }

        $this->tagCloud = $this->factory->buildTagCloud();

        $tags = $this->tagDataProvider->provideData();
        foreach ($tags as $tag => $source) {
            $tagObject = $this->factory->buildTag(
                $tag,
                count($source),
                $this->getPermalink($tag)
            );

            $this->tagCloud->addTag($tagObject);
        }

        $this->applyStrategies($this->tagCloud);

        return $this->tagCloud;
    }

    /**
     * Register a strategy
     *
     * @param \Jb\Bundle\TagCloudBundle\Component\Strategy\StrategyInterface $strategy
     *
     * @return \Jb\Bundle\TagCloudBundle\Component\Manager\TagCloudManager
     */
    public function addStrategy(StrategyInterface $strategy)
    {
        $this->strategies[] = $strategy;

        return $this;
    }

    /**
     * Apply all registered strategies
     *
     * @param \Jb\Bundle\TagCloudBundle\Model\TagCloud $tagCloud
     */
    protected function applyStrategies(\Jb\Bundle\TagCloudBundle\Model\TagCloud $tagCloud)
    {
        foreach ($this->strategies as $strategy) {
            $strategy->process($tagCloud);
        }
    }

    /**
     * Generate a permalink
     *
     * @param string $tag
     *
     * @return string
     */
    protected function getPermalink($tag)
    {
        return str_replace(':taxon', $tag, $this->permalinkPattern);;
    }
}